1 /*
   2  * Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "jvm.h"
  27 #include "cds/archiveBuilder.hpp"
  28 #include "cds/archiveUtils.inline.hpp"
  29 #include "cds/dynamicArchive.hpp"
  30 #include "cds/filemap.hpp"
  31 #include "cds/heapShared.inline.hpp"
  32 #include "cds/metaspaceShared.hpp"
  33 #include "classfile/altHashing.hpp"
  34 #include "classfile/classFileStream.hpp"
  35 #include "classfile/classLoader.inline.hpp"
  36 #include "classfile/classLoaderData.inline.hpp"
  37 #include "classfile/classLoaderExt.hpp"
  38 #include "classfile/symbolTable.hpp"
  39 #include "classfile/systemDictionaryShared.hpp"
  40 #include "classfile/vmClasses.hpp"
  41 #include "classfile/vmSymbols.hpp"
  42 #include "logging/log.hpp"
  43 #include "logging/logStream.hpp"
  44 #include "logging/logMessage.hpp"
  45 #include "memory/iterator.inline.hpp"
  46 #include "memory/metadataFactory.hpp"
  47 #include "memory/metaspaceClosure.hpp"
  48 #include "memory/oopFactory.hpp"
  49 #include "memory/universe.hpp"
  50 #include "oops/compressedOops.hpp"
  51 #include "oops/compressedOops.inline.hpp"
  52 #include "oops/objArrayOop.hpp"
  53 #include "oops/oop.inline.hpp"
  54 #include "prims/jvmtiExport.hpp"
  55 #include "runtime/arguments.hpp"
  56 #include "runtime/java.hpp"
  57 #include "runtime/mutexLocker.hpp"
  58 #include "runtime/os.hpp"
  59 #include "runtime/vm_version.hpp"
  60 #include "services/memTracker.hpp"
  61 #include "utilities/align.hpp"
  62 #include "utilities/bitMap.inline.hpp"
  63 #include "utilities/classpathStream.hpp"
  64 #include "utilities/defaultStream.hpp"
  65 #include "utilities/ostream.hpp"
  66 #if INCLUDE_G1GC
  67 #include "gc/g1/g1CollectedHeap.hpp"
  68 #include "gc/g1/heapRegion.hpp"
  69 #endif
  70 
  71 # include <sys/stat.h>
  72 # include <errno.h>
  73 
  74 #ifndef O_BINARY       // if defined (Win32) use binary files.
  75 #define O_BINARY 0     // otherwise do nothing.
  76 #endif
  77 
  78 // Complain and stop. All error conditions occurring during the writing of
  79 // an archive file should stop the process.  Unrecoverable errors during
  80 // the reading of the archive file should stop the process.
  81 
  82 static void fail_exit(const char *msg, va_list ap) {
  83   // This occurs very early during initialization: tty is not initialized.
  84   jio_fprintf(defaultStream::error_stream(),
  85               "An error has occurred while processing the"
  86               " shared archive file.\n");
  87   jio_vfprintf(defaultStream::error_stream(), msg, ap);
  88   jio_fprintf(defaultStream::error_stream(), "\n");
  89   // Do not change the text of the below message because some tests check for it.
  90   vm_exit_during_initialization("Unable to use shared archive.", NULL);
  91 }
  92 
  93 
  94 void FileMapInfo::fail_stop(const char *msg, ...) {
  95         va_list ap;
  96   va_start(ap, msg);
  97   fail_exit(msg, ap);   // Never returns.
  98   va_end(ap);           // for completeness.
  99 }
 100 
 101 
 102 // Complain and continue.  Recoverable errors during the reading of the
 103 // archive file may continue (with sharing disabled).
 104 //
 105 // If we continue, then disable shared spaces and close the file.
 106 
 107 void FileMapInfo::fail_continue(const char *msg, ...) {
 108   va_list ap;
 109   va_start(ap, msg);
 110   if (PrintSharedArchiveAndExit && _validating_shared_path_table) {
 111     // If we are doing PrintSharedArchiveAndExit and some of the classpath entries
 112     // do not validate, we can still continue "limping" to validate the remaining
 113     // entries. No need to quit.
 114     tty->print("[");
 115     tty->vprint(msg, ap);
 116     tty->print_cr("]");
 117   } else {
 118     if (RequireSharedSpaces) {
 119       fail_exit(msg, ap);
 120     } else {
 121       if (log_is_enabled(Info, cds)) {
 122         ResourceMark rm;
 123         LogStream ls(Log(cds)::info());
 124         ls.print("UseSharedSpaces: ");
 125         ls.vprint_cr(msg, ap);
 126       }
 127     }
 128   }
 129   va_end(ap);
 130 }
 131 
 132 // Fill in the fileMapInfo structure with data about this VM instance.
 133 
 134 // This method copies the vm version info into header_version.  If the version is too
 135 // long then a truncated version, which has a hash code appended to it, is copied.
 136 //
 137 // Using a template enables this method to verify that header_version is an array of
 138 // length JVM_IDENT_MAX.  This ensures that the code that writes to the CDS file and
 139 // the code that reads the CDS file will both use the same size buffer.  Hence, will
 140 // use identical truncation.  This is necessary for matching of truncated versions.
 141 template <int N> static void get_header_version(char (&header_version) [N]) {
 142   assert(N == JVM_IDENT_MAX, "Bad header_version size");
 143 
 144   const char *vm_version = VM_Version::internal_vm_info_string();
 145   const int version_len = (int)strlen(vm_version);
 146 
 147   memset(header_version, 0, JVM_IDENT_MAX);
 148 
 149   if (version_len < (JVM_IDENT_MAX-1)) {
 150     strcpy(header_version, vm_version);
 151 
 152   } else {
 153     // Get the hash value.  Use a static seed because the hash needs to return the same
 154     // value over multiple jvm invocations.
 155     uint32_t hash = AltHashing::halfsiphash_32(8191, (const uint8_t*)vm_version, version_len);
 156 
 157     // Truncate the ident, saving room for the 8 hex character hash value.
 158     strncpy(header_version, vm_version, JVM_IDENT_MAX-9);
 159 
 160     // Append the hash code as eight hex digits.
 161     sprintf(&header_version[JVM_IDENT_MAX-9], "%08x", hash);
 162     header_version[JVM_IDENT_MAX-1] = 0;  // Null terminate.
 163   }
 164 
 165   assert(header_version[JVM_IDENT_MAX-1] == 0, "must be");
 166 }
 167 
 168 FileMapInfo::FileMapInfo(bool is_static) :
 169   _is_static(is_static), _file_open(false), _is_mapped(false), _fd(-1), _file_offset(0),
 170   _full_path(nullptr), _base_archive_name(nullptr), _header(nullptr) {
 171   size_t header_size;
 172   if (is_static) {
 173     assert(_current_info == NULL, "must be singleton"); // not thread safe
 174     _current_info = this;
 175     header_size = sizeof(FileMapHeader);
 176   } else {
 177     assert(_dynamic_archive_info == NULL, "must be singleton"); // not thread safe
 178     _dynamic_archive_info = this;
 179     header_size = sizeof(DynamicArchiveHeader);
 180   }
 181   _header = (FileMapHeader*)os::malloc(header_size, mtInternal);
 182   memset((void*)_header, 0, header_size);
 183   _header->set_header_size(header_size);
 184   _header->set_version(INVALID_CDS_ARCHIVE_VERSION);
 185   _header->set_has_platform_or_app_classes(true);
 186 }
 187 
 188 FileMapInfo::~FileMapInfo() {
 189   if (_is_static) {
 190     assert(_current_info == this, "must be singleton"); // not thread safe
 191     _current_info = NULL;
 192   } else {
 193     assert(_dynamic_archive_info == this, "must be singleton"); // not thread safe
 194     _dynamic_archive_info = NULL;
 195   }
 196 
 197   if (_header != nullptr) {
 198     os::free(_header);
 199   }
 200 
 201   if (_file_open) {
 202     ::close(_fd);
 203   }
 204 }
 205 
 206 void FileMapInfo::populate_header(size_t core_region_alignment) {
 207   header()->populate(this, core_region_alignment);
 208 }
 209 
 210 void FileMapHeader::populate(FileMapInfo* mapinfo, size_t core_region_alignment) {
 211   if (DynamicDumpSharedSpaces) {
 212     _magic = CDS_DYNAMIC_ARCHIVE_MAGIC;
 213   } else {
 214     _magic = CDS_ARCHIVE_MAGIC;
 215   }
 216   _version = CURRENT_CDS_ARCHIVE_VERSION;
 217   _core_region_alignment = core_region_alignment;
 218   _obj_alignment = ObjectAlignmentInBytes;
 219   _compact_strings = CompactStrings;
 220   _compact_headers = UseCompactObjectHeaders;
 221   if (HeapShared::is_heap_object_archiving_allowed()) {
 222     _narrow_oop_mode = CompressedOops::mode();
 223     _narrow_oop_base = CompressedOops::base();
 224     _narrow_oop_shift = CompressedOops::shift();
 225     _heap_begin = CompressedOops::begin();
 226     _heap_end = CompressedOops::end();
 227   }
 228   _compressed_oops = UseCompressedOops;
 229   _compressed_class_ptrs = UseCompressedClassPointers;
 230   _max_heap_size = MaxHeapSize;
 231   _narrow_klass_shift = CompressedKlassPointers::shift();
 232   _use_optimized_module_handling = MetaspaceShared::use_optimized_module_handling();
 233   _use_full_module_graph = MetaspaceShared::use_full_module_graph();
 234 
 235   // The following fields are for sanity checks for whether this archive
 236   // will function correctly with this JVM and the bootclasspath it's
 237   // invoked with.
 238 
 239   // JVM version string ... changes on each build.
 240   get_header_version(_jvm_ident);
 241 
 242   _app_class_paths_start_index = ClassLoaderExt::app_class_paths_start_index();
 243   _app_module_paths_start_index = ClassLoaderExt::app_module_paths_start_index();
 244   _num_module_paths = ClassLoader::num_module_path_entries();
 245   _max_used_path_index = ClassLoaderExt::max_used_path_index();
 246 
 247   _verify_local = BytecodeVerificationLocal;
 248   _verify_remote = BytecodeVerificationRemote;
 249   _has_platform_or_app_classes = ClassLoaderExt::has_platform_or_app_classes();
 250   _requested_base_address = (char*)SharedBaseAddress;
 251   _mapped_base_address = (char*)SharedBaseAddress;
 252   _allow_archiving_with_java_agent = AllowArchivingWithJavaAgent;
 253   // the following 2 fields will be set in write_header for dynamic archive header
 254   _base_archive_name_size = 0;
 255   _base_archive_is_default = false;
 256 
 257   if (!DynamicDumpSharedSpaces) {
 258     set_shared_path_table(mapinfo->_shared_path_table);
 259     CDS_JAVA_HEAP_ONLY(_heap_obj_roots = CompressedOops::encode(HeapShared::roots());)
 260   }
 261 }
 262 
 263 void FileMapHeader::print(outputStream* st) {
 264   ResourceMark rm;
 265 
 266   st->print_cr("- magic:                          0x%08x", _magic);
 267   st->print_cr("- crc:                            0x%08x", _crc);
 268   st->print_cr("- version:                        %d", _version);
 269 
 270   for (int i = 0; i < NUM_CDS_REGIONS; i++) {
 271     FileMapRegion* si = space_at(i);
 272     si->print(st, i);
 273   }
 274   st->print_cr("============ end regions ======== ");
 275 
 276   st->print_cr("- header_size:                    " SIZE_FORMAT, _header_size);
 277   st->print_cr("- core_region_alignment:          " SIZE_FORMAT, _core_region_alignment);
 278   st->print_cr("- obj_alignment:                  %d", _obj_alignment);
 279   st->print_cr("- narrow_oop_base:                " INTPTR_FORMAT, p2i(_narrow_oop_base));
 280   st->print_cr("- narrow_oop_base:                " INTPTR_FORMAT, p2i(_narrow_oop_base));
 281   st->print_cr("- narrow_oop_shift                %d", _narrow_oop_shift);
 282   st->print_cr("- compact_strings:                %d", _compact_strings);
 283   st->print_cr("- compact_headers:                %d", _compact_headers);
 284   st->print_cr("- max_heap_size:                  " UINTX_FORMAT, _max_heap_size);
 285   st->print_cr("- narrow_oop_mode:                %d", _narrow_oop_mode);
 286   st->print_cr("- narrow_klass_shift:             %d", _narrow_klass_shift);
 287   st->print_cr("- compressed_oops:                %d", _compressed_oops);
 288   st->print_cr("- compressed_class_ptrs:          %d", _compressed_class_ptrs);
 289   st->print_cr("- cloned_vtables_offset:          " SIZE_FORMAT_HEX, _cloned_vtables_offset);
 290   st->print_cr("- serialized_data_offset:         " SIZE_FORMAT_HEX, _serialized_data_offset);
 291   st->print_cr("- heap_end:                       " INTPTR_FORMAT, p2i(_heap_end));
 292   st->print_cr("- base_archive_is_default:        %d", _base_archive_is_default);
 293   st->print_cr("- jvm_ident:                      %s", _jvm_ident);
 294   st->print_cr("- base_archive_name_size:         " SIZE_FORMAT, _base_archive_name_size);
 295   st->print_cr("- shared_path_table_offset:       " SIZE_FORMAT_HEX, _shared_path_table_offset);
 296   st->print_cr("- shared_path_table_size:         %d", _shared_path_table_size);
 297   st->print_cr("- app_class_paths_start_index:    %d", _app_class_paths_start_index);
 298   st->print_cr("- app_module_paths_start_index:   %d", _app_module_paths_start_index);
 299   st->print_cr("- num_module_paths:               %d", _num_module_paths);
 300   st->print_cr("- max_used_path_index:            %d", _max_used_path_index);
 301   st->print_cr("- verify_local:                   %d", _verify_local);
 302   st->print_cr("- verify_remote:                  %d", _verify_remote);
 303   st->print_cr("- has_platform_or_app_classes:    %d", _has_platform_or_app_classes);
 304   st->print_cr("- requested_base_address:         " INTPTR_FORMAT, p2i(_requested_base_address));
 305   st->print_cr("- mapped_base_address:            " INTPTR_FORMAT, p2i(_mapped_base_address));
 306   st->print_cr("- allow_archiving_with_java_agent:%d", _allow_archiving_with_java_agent);
 307   st->print_cr("- use_optimized_module_handling:  %d", _use_optimized_module_handling);
 308   st->print_cr("- use_full_module_graph           %d", _use_full_module_graph);
 309   st->print_cr("- ptrmap_size_in_bits:            " SIZE_FORMAT, _ptrmap_size_in_bits);
 310 }
 311 
 312 void SharedClassPathEntry::init_as_non_existent(const char* path, TRAPS) {
 313   _type = non_existent_entry;
 314   set_name(path, CHECK);
 315 }
 316 
 317 void SharedClassPathEntry::init(bool is_modules_image,
 318                                 bool is_module_path,
 319                                 ClassPathEntry* cpe, TRAPS) {
 320   Arguments::assert_is_dumping_archive();
 321   _timestamp = 0;
 322   _filesize  = 0;
 323   _from_class_path_attr = false;
 324 
 325   struct stat st;
 326   if (os::stat(cpe->name(), &st) == 0) {
 327     if ((st.st_mode & S_IFMT) == S_IFDIR) {
 328       _type = dir_entry;
 329     } else {
 330       // The timestamp of the modules_image is not checked at runtime.
 331       if (is_modules_image) {
 332         _type = modules_image_entry;
 333       } else {
 334         _type = jar_entry;
 335         _timestamp = st.st_mtime;
 336         _from_class_path_attr = cpe->from_class_path_attr();
 337       }
 338       _filesize = st.st_size;
 339       _is_module_path = is_module_path;
 340     }
 341   } else {
 342     // The file/dir must exist, or it would not have been added
 343     // into ClassLoader::classpath_entry().
 344     //
 345     // If we can't access a jar file in the boot path, then we can't
 346     // make assumptions about where classes get loaded from.
 347     FileMapInfo::fail_stop("Unable to open file %s.", cpe->name());
 348   }
 349 
 350   // No need to save the name of the module file, as it will be computed at run time
 351   // to allow relocation of the JDK directory.
 352   const char* name = is_modules_image  ? "" : cpe->name();
 353   set_name(name, CHECK);
 354 }
 355 
 356 void SharedClassPathEntry::set_name(const char* name, TRAPS) {
 357   size_t len = strlen(name) + 1;
 358   _name = MetadataFactory::new_array<char>(ClassLoaderData::the_null_class_loader_data(), (int)len, CHECK);
 359   strcpy(_name->data(), name);
 360 }
 361 
 362 void SharedClassPathEntry::copy_from(SharedClassPathEntry* ent, ClassLoaderData* loader_data, TRAPS) {
 363   _type = ent->_type;
 364   _is_module_path = ent->_is_module_path;
 365   _timestamp = ent->_timestamp;
 366   _filesize = ent->_filesize;
 367   _from_class_path_attr = ent->_from_class_path_attr;
 368   set_name(ent->name(), CHECK);
 369 
 370   if (ent->is_jar() && ent->manifest() != NULL) {
 371     Array<u1>* buf = MetadataFactory::new_array<u1>(loader_data,
 372                                                     ent->manifest_size(),
 373                                                     CHECK);
 374     char* p = (char*)(buf->data());
 375     memcpy(p, ent->manifest(), ent->manifest_size());
 376     set_manifest(buf);
 377   }
 378 }
 379 
 380 const char* SharedClassPathEntry::name() const {
 381   if (UseSharedSpaces && is_modules_image()) {
 382     // In order to validate the runtime modules image file size against the archived
 383     // size information, we need to obtain the runtime modules image path. The recorded
 384     // dump time modules image path in the archive may be different from the runtime path
 385     // if the JDK image has beed moved after generating the archive.
 386     return ClassLoader::get_jrt_entry()->name();
 387   } else {
 388     return _name->data();
 389   }
 390 }
 391 
 392 bool SharedClassPathEntry::validate(bool is_class_path) const {
 393   assert(UseSharedSpaces, "runtime only");
 394 
 395   struct stat st;
 396   const char* name = this->name();
 397 
 398   bool ok = true;
 399   log_info(class, path)("checking shared classpath entry: %s", name);
 400   if (os::stat(name, &st) != 0 && is_class_path) {
 401     // If the archived module path entry does not exist at runtime, it is not fatal
 402     // (no need to invalid the shared archive) because the shared runtime visibility check
 403     // filters out any archived module classes that do not have a matching runtime
 404     // module path location.
 405     FileMapInfo::fail_continue("Required classpath entry does not exist: %s", name);
 406     ok = false;
 407   } else if (is_dir()) {
 408     if (!os::dir_is_empty(name)) {
 409       FileMapInfo::fail_continue("directory is not empty: %s", name);
 410       ok = false;
 411     }
 412   } else if ((has_timestamp() && _timestamp != st.st_mtime) ||
 413              _filesize != st.st_size) {
 414     ok = false;
 415     if (PrintSharedArchiveAndExit) {
 416       FileMapInfo::fail_continue(_timestamp != st.st_mtime ?
 417                                  "Timestamp mismatch" :
 418                                  "File size mismatch");
 419     } else {
 420       FileMapInfo::fail_continue("A jar file is not the one used while building"
 421                                  " the shared archive file: %s", name);
 422     }
 423   }
 424 
 425   if (PrintSharedArchiveAndExit && !ok) {
 426     // If PrintSharedArchiveAndExit is enabled, don't report failure to the
 427     // caller. Please see above comments for more details.
 428     ok = true;
 429     MetaspaceShared::set_archive_loading_failed();
 430   }
 431   return ok;
 432 }
 433 
 434 bool SharedClassPathEntry::check_non_existent() const {
 435   assert(_type == non_existent_entry, "must be");
 436   log_info(class, path)("should be non-existent: %s", name());
 437   struct stat st;
 438   if (os::stat(name(), &st) != 0) {
 439     log_info(class, path)("ok");
 440     return true; // file doesn't exist
 441   } else {
 442     return false;
 443   }
 444 }
 445 
 446 
 447 void SharedClassPathEntry::metaspace_pointers_do(MetaspaceClosure* it) {
 448   it->push(&_name);
 449   it->push(&_manifest);
 450 }
 451 
 452 void SharedPathTable::metaspace_pointers_do(MetaspaceClosure* it) {
 453   it->push(&_table);
 454   for (int i=0; i<_size; i++) {
 455     path_at(i)->metaspace_pointers_do(it);
 456   }
 457 }
 458 
 459 void SharedPathTable::dumptime_init(ClassLoaderData* loader_data, TRAPS) {
 460   size_t entry_size = sizeof(SharedClassPathEntry);
 461   int num_entries = 0;
 462   num_entries += ClassLoader::num_boot_classpath_entries();
 463   num_entries += ClassLoader::num_app_classpath_entries();
 464   num_entries += ClassLoader::num_module_path_entries();
 465   num_entries += FileMapInfo::num_non_existent_class_paths();
 466   size_t bytes = entry_size * num_entries;
 467 
 468   _table = MetadataFactory::new_array<u8>(loader_data, (int)bytes, CHECK);
 469   _size = num_entries;
 470 }
 471 
 472 // Make a copy of the _shared_path_table for use during dynamic CDS dump.
 473 // It is needed because some Java code continues to execute after dynamic dump has finished.
 474 // However, during dynamic dump, we have modified FileMapInfo::_shared_path_table so
 475 // FileMapInfo::shared_path(i) returns incorrect information in ClassLoader::record_result().
 476 void FileMapInfo::copy_shared_path_table(ClassLoaderData* loader_data, TRAPS) {
 477   size_t entry_size = sizeof(SharedClassPathEntry);
 478   size_t bytes = entry_size * _shared_path_table.size();
 479 
 480   Array<u8>* array = MetadataFactory::new_array<u8>(loader_data, (int)bytes, CHECK);
 481   _saved_shared_path_table = SharedPathTable(array, _shared_path_table.size());
 482 
 483   for (int i = 0; i < _shared_path_table.size(); i++) {
 484     _saved_shared_path_table.path_at(i)->copy_from(shared_path(i), loader_data, CHECK);
 485   }
 486 }
 487 
 488 void FileMapInfo::allocate_shared_path_table(TRAPS) {
 489   Arguments::assert_is_dumping_archive();
 490 
 491   ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data();
 492   ClassPathEntry* jrt = ClassLoader::get_jrt_entry();
 493 
 494   assert(jrt != NULL,
 495          "No modular java runtime image present when allocating the CDS classpath entry table");
 496 
 497   _shared_path_table.dumptime_init(loader_data, CHECK);
 498 
 499   // 1. boot class path
 500   int i = 0;
 501   i = add_shared_classpaths(i, "boot",   jrt, CHECK);
 502   i = add_shared_classpaths(i, "app",    ClassLoader::app_classpath_entries(), CHECK);
 503   i = add_shared_classpaths(i, "module", ClassLoader::module_path_entries(), CHECK);
 504 
 505   for (int x = 0; x < num_non_existent_class_paths(); x++, i++) {
 506     const char* path = _non_existent_class_paths->at(x);
 507     shared_path(i)->init_as_non_existent(path, CHECK);
 508   }
 509 
 510   assert(i == _shared_path_table.size(), "number of shared path entry mismatch");
 511 
 512   copy_shared_path_table(loader_data, CHECK);
 513 }
 514 
 515 int FileMapInfo::add_shared_classpaths(int i, const char* which, ClassPathEntry *cpe, TRAPS) {
 516   while (cpe != NULL) {
 517     bool is_jrt = (cpe == ClassLoader::get_jrt_entry());
 518     bool is_module_path = i >= ClassLoaderExt::app_module_paths_start_index();
 519     const char* type = (is_jrt ? "jrt" : (cpe->is_jar_file() ? "jar" : "dir"));
 520     log_info(class, path)("add %s shared path (%s) %s", which, type, cpe->name());
 521     SharedClassPathEntry* ent = shared_path(i);
 522     ent->init(is_jrt, is_module_path, cpe, CHECK_0);
 523     if (cpe->is_jar_file()) {
 524       update_jar_manifest(cpe, ent, CHECK_0);
 525     }
 526     if (is_jrt) {
 527       cpe = ClassLoader::get_next_boot_classpath_entry(cpe);
 528     } else {
 529       cpe = cpe->next();
 530     }
 531     i++;
 532   }
 533 
 534   return i;
 535 }
 536 
 537 void FileMapInfo::check_nonempty_dir_in_shared_path_table() {
 538   Arguments::assert_is_dumping_archive();
 539 
 540   bool has_nonempty_dir = false;
 541 
 542   int last = _shared_path_table.size() - 1;
 543   if (last > ClassLoaderExt::max_used_path_index()) {
 544      // no need to check any path beyond max_used_path_index
 545      last = ClassLoaderExt::max_used_path_index();
 546   }
 547 
 548   for (int i = 0; i <= last; i++) {
 549     SharedClassPathEntry *e = shared_path(i);
 550     if (e->is_dir()) {
 551       const char* path = e->name();
 552       if (!os::dir_is_empty(path)) {
 553         log_error(cds)("Error: non-empty directory '%s'", path);
 554         has_nonempty_dir = true;
 555       }
 556     }
 557   }
 558 
 559   if (has_nonempty_dir) {
 560     ClassLoader::exit_with_path_failure("Cannot have non-empty directory in paths", NULL);
 561   }
 562 }
 563 
 564 void FileMapInfo::record_non_existent_class_path_entry(const char* path) {
 565   Arguments::assert_is_dumping_archive();
 566   log_info(class, path)("non-existent Class-Path entry %s", path);
 567   if (_non_existent_class_paths == NULL) {
 568     _non_existent_class_paths = new (ResourceObj::C_HEAP, mtClass)GrowableArray<const char*>(10, mtClass);
 569   }
 570   _non_existent_class_paths->append(os::strdup(path));
 571 }
 572 
 573 int FileMapInfo::num_non_existent_class_paths() {
 574   Arguments::assert_is_dumping_archive();
 575   if (_non_existent_class_paths != NULL) {
 576     return _non_existent_class_paths->length();
 577   } else {
 578     return 0;
 579   }
 580 }
 581 
 582 int FileMapInfo::get_module_shared_path_index(Symbol* location) {
 583   if (location->starts_with("jrt:", 4) && get_number_of_shared_paths() > 0) {
 584     assert(shared_path(0)->is_modules_image(), "first shared_path must be the modules image");
 585     return 0;
 586   }
 587 
 588   if (ClassLoaderExt::app_module_paths_start_index() >= get_number_of_shared_paths()) {
 589     // The archive(s) were created without --module-path option
 590     return -1;
 591   }
 592 
 593   if (!location->starts_with("file:", 5)) {
 594     return -1;
 595   }
 596 
 597   // skip_uri_protocol was also called during dump time -- see ClassLoaderExt::process_module_table()
 598   ResourceMark rm;
 599   const char* file = ClassLoader::skip_uri_protocol(location->as_C_string());
 600   for (int i = ClassLoaderExt::app_module_paths_start_index(); i < get_number_of_shared_paths(); i++) {
 601     SharedClassPathEntry* ent = shared_path(i);
 602     assert(ent->in_named_module(), "must be");
 603     bool cond = strcmp(file, ent->name()) == 0;
 604     log_debug(class, path)("get_module_shared_path_index (%d) %s : %s = %s", i,
 605                            location->as_C_string(), ent->name(), cond ? "same" : "different");
 606     if (cond) {
 607       return i;
 608     }
 609   }
 610 
 611   return -1;
 612 }
 613 
 614 class ManifestStream: public ResourceObj {
 615   private:
 616   u1*   _buffer_start; // Buffer bottom
 617   u1*   _buffer_end;   // Buffer top (one past last element)
 618   u1*   _current;      // Current buffer position
 619 
 620  public:
 621   // Constructor
 622   ManifestStream(u1* buffer, int length) : _buffer_start(buffer),
 623                                            _current(buffer) {
 624     _buffer_end = buffer + length;
 625   }
 626 
 627   static bool is_attr(u1* attr, const char* name) {
 628     return strncmp((const char*)attr, name, strlen(name)) == 0;
 629   }
 630 
 631   static char* copy_attr(u1* value, size_t len) {
 632     char* buf = NEW_RESOURCE_ARRAY(char, len + 1);
 633     strncpy(buf, (char*)value, len);
 634     buf[len] = 0;
 635     return buf;
 636   }
 637 };
 638 
 639 void FileMapInfo::update_jar_manifest(ClassPathEntry *cpe, SharedClassPathEntry* ent, TRAPS) {
 640   ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data();
 641   ResourceMark rm(THREAD);
 642   jint manifest_size;
 643 
 644   assert(cpe->is_jar_file() && ent->is_jar(), "the shared class path entry is not a JAR file");
 645   char* manifest = ClassLoaderExt::read_manifest(THREAD, cpe, &manifest_size);
 646   if (manifest != NULL) {
 647     ManifestStream* stream = new ManifestStream((u1*)manifest,
 648                                                 manifest_size);
 649     // Copy the manifest into the shared archive
 650     manifest = ClassLoaderExt::read_raw_manifest(THREAD, cpe, &manifest_size);
 651     Array<u1>* buf = MetadataFactory::new_array<u1>(loader_data,
 652                                                     manifest_size,
 653                                                     CHECK);
 654     char* p = (char*)(buf->data());
 655     memcpy(p, manifest, manifest_size);
 656     ent->set_manifest(buf);
 657   }
 658 }
 659 
 660 char* FileMapInfo::skip_first_path_entry(const char* path) {
 661   size_t path_sep_len = strlen(os::path_separator());
 662   char* p = strstr((char*)path, os::path_separator());
 663   if (p != NULL) {
 664     debug_only( {
 665       size_t image_name_len = strlen(MODULES_IMAGE_NAME);
 666       assert(strncmp(p - image_name_len, MODULES_IMAGE_NAME, image_name_len) == 0,
 667              "first entry must be the modules image");
 668     } );
 669     p += path_sep_len;
 670   } else {
 671     debug_only( {
 672       assert(ClassLoader::string_ends_with(path, MODULES_IMAGE_NAME),
 673              "first entry must be the modules image");
 674     } );
 675   }
 676   return p;
 677 }
 678 
 679 int FileMapInfo::num_paths(const char* path) {
 680   if (path == NULL) {
 681     return 0;
 682   }
 683   int npaths = 1;
 684   char* p = (char*)path;
 685   while (p != NULL) {
 686     char* prev = p;
 687     p = strstr((char*)p, os::path_separator());
 688     if (p != NULL) {
 689       p++;
 690       // don't count empty path
 691       if ((p - prev) > 1) {
 692        npaths++;
 693       }
 694     }
 695   }
 696   return npaths;
 697 }
 698 
 699 GrowableArray<const char*>* FileMapInfo::create_path_array(const char* paths) {
 700   GrowableArray<const char*>* path_array = new GrowableArray<const char*>(10);
 701 
 702   ClasspathStream cp_stream(paths);
 703   while (cp_stream.has_next()) {
 704     const char* path = cp_stream.get_next();
 705     struct stat st;
 706     if (os::stat(path, &st) == 0) {
 707       path_array->append(path);
 708     }
 709   }
 710   return path_array;
 711 }
 712 
 713 bool FileMapInfo::classpath_failure(const char* msg, const char* name) {
 714   ClassLoader::trace_class_path(msg, name);
 715   if (PrintSharedArchiveAndExit) {
 716     MetaspaceShared::set_archive_loading_failed();
 717   }
 718   return false;
 719 }
 720 
 721 bool FileMapInfo::check_paths(int shared_path_start_idx, int num_paths, GrowableArray<const char*>* rp_array) {
 722   int i = 0;
 723   int j = shared_path_start_idx;
 724   bool mismatch = false;
 725   while (i < num_paths && !mismatch) {
 726     while (shared_path(j)->from_class_path_attr()) {
 727       // shared_path(j) was expanded from the JAR file attribute "Class-Path:"
 728       // during dump time. It's not included in the -classpath VM argument.
 729       j++;
 730     }
 731     if (!os::same_files(shared_path(j)->name(), rp_array->at(i))) {
 732       mismatch = true;
 733     }
 734     i++;
 735     j++;
 736   }
 737   return mismatch;
 738 }
 739 
 740 bool FileMapInfo::validate_boot_class_paths() {
 741   //
 742   // - Archive contains boot classes only - relaxed boot path check:
 743   //   Extra path elements appended to the boot path at runtime are allowed.
 744   //
 745   // - Archive contains application or platform classes - strict boot path check:
 746   //   Validate the entire runtime boot path, which must be compatible
 747   //   with the dump time boot path. Appending boot path at runtime is not
 748   //   allowed.
 749   //
 750 
 751   // The first entry in boot path is the modules_image (guaranteed by
 752   // ClassLoader::setup_boot_search_path()). Skip the first entry. The
 753   // path of the runtime modules_image may be different from the dump
 754   // time path (e.g. the JDK image is copied to a different location
 755   // after generating the shared archive), which is acceptable. For most
 756   // common cases, the dump time boot path might contain modules_image only.
 757   char* runtime_boot_path = Arguments::get_sysclasspath();
 758   char* rp = skip_first_path_entry(runtime_boot_path);
 759   assert(shared_path(0)->is_modules_image(), "first shared_path must be the modules image");
 760   int dp_len = header()->app_class_paths_start_index() - 1; // ignore the first path to the module image
 761   bool mismatch = false;
 762 
 763   bool relaxed_check = !header()->has_platform_or_app_classes();
 764   if (dp_len == 0 && rp == NULL) {
 765     return true;   // ok, both runtime and dump time boot paths have modules_images only
 766   } else if (dp_len == 0 && rp != NULL) {
 767     if (relaxed_check) {
 768       return true;   // ok, relaxed check, runtime has extra boot append path entries
 769     } else {
 770       mismatch = true;
 771     }
 772   } else if (dp_len > 0 && rp != NULL) {
 773     int num;
 774     ResourceMark rm;
 775     GrowableArray<const char*>* rp_array = create_path_array(rp);
 776     int rp_len = rp_array->length();
 777     if (rp_len >= dp_len) {
 778       if (relaxed_check) {
 779         // only check the leading entries in the runtime boot path, up to
 780         // the length of the dump time boot path
 781         num = dp_len;
 782       } else {
 783         // check the full runtime boot path, must match with dump time
 784         num = rp_len;
 785       }
 786       mismatch = check_paths(1, num, rp_array);
 787     } else {
 788       // create_path_array() ignores non-existing paths. Although the dump time and runtime boot classpath lengths
 789       // are the same initially, after the call to create_path_array(), the runtime boot classpath length could become
 790       // shorter. We consider boot classpath mismatch in this case.
 791       mismatch = true;
 792     }
 793   }
 794 
 795   if (mismatch) {
 796     // The paths are different
 797     return classpath_failure("[BOOT classpath mismatch, actual =", runtime_boot_path);
 798   }
 799   return true;
 800 }
 801 
 802 bool FileMapInfo::validate_app_class_paths(int shared_app_paths_len) {
 803   const char *appcp = Arguments::get_appclasspath();
 804   assert(appcp != NULL, "NULL app classpath");
 805   int rp_len = num_paths(appcp);
 806   bool mismatch = false;
 807   if (rp_len < shared_app_paths_len) {
 808     return classpath_failure("Run time APP classpath is shorter than the one at dump time: ", appcp);
 809   }
 810   if (shared_app_paths_len != 0 && rp_len != 0) {
 811     // Prefix is OK: E.g., dump with -cp foo.jar, but run with -cp foo.jar:bar.jar.
 812     ResourceMark rm;
 813     GrowableArray<const char*>* rp_array = create_path_array(appcp);
 814     if (rp_array->length() == 0) {
 815       // None of the jar file specified in the runtime -cp exists.
 816       return classpath_failure("None of the jar file specified in the runtime -cp exists: -Djava.class.path=", appcp);
 817     }
 818     if (rp_array->length() < shared_app_paths_len) {
 819       // create_path_array() ignores non-existing paths. Although the dump time and runtime app classpath lengths
 820       // are the same initially, after the call to create_path_array(), the runtime app classpath length could become
 821       // shorter. We consider app classpath mismatch in this case.
 822       return classpath_failure("[APP classpath mismatch, actual: -Djava.class.path=", appcp);
 823     }
 824 
 825     // Handling of non-existent entries in the classpath: we eliminate all the non-existent
 826     // entries from both the dump time classpath (ClassLoader::update_class_path_entry_list)
 827     // and the runtime classpath (FileMapInfo::create_path_array), and check the remaining
 828     // entries. E.g.:
 829     //
 830     // dump : -cp a.jar:NE1:NE2:b.jar  -> a.jar:b.jar -> recorded in archive.
 831     // run 1: -cp NE3:a.jar:NE4:b.jar  -> a.jar:b.jar -> matched
 832     // run 2: -cp x.jar:NE4:b.jar      -> x.jar:b.jar -> mismatched
 833 
 834     int j = header()->app_class_paths_start_index();
 835     mismatch = check_paths(j, shared_app_paths_len, rp_array);
 836     if (mismatch) {
 837       return classpath_failure("[APP classpath mismatch, actual: -Djava.class.path=", appcp);
 838     }
 839   }
 840   return true;
 841 }
 842 
 843 void FileMapInfo::log_paths(const char* msg, int start_idx, int end_idx) {
 844   LogTarget(Info, class, path) lt;
 845   if (lt.is_enabled()) {
 846     LogStream ls(lt);
 847     ls.print("%s", msg);
 848     const char* prefix = "";
 849     for (int i = start_idx; i < end_idx; i++) {
 850       ls.print("%s%s", prefix, shared_path(i)->name());
 851       prefix = os::path_separator();
 852     }
 853     ls.cr();
 854   }
 855 }
 856 
 857 bool FileMapInfo::validate_shared_path_table() {
 858   assert(UseSharedSpaces, "runtime only");
 859 
 860   _validating_shared_path_table = true;
 861 
 862   // Load the shared path table info from the archive header
 863   _shared_path_table = header()->shared_path_table();
 864   if (DynamicDumpSharedSpaces) {
 865     // Only support dynamic dumping with the usage of the default CDS archive
 866     // or a simple base archive.
 867     // If the base layer archive contains additional path component besides
 868     // the runtime image and the -cp, dynamic dumping is disabled.
 869     //
 870     // When dynamic archiving is enabled, the _shared_path_table is overwritten
 871     // to include the application path and stored in the top layer archive.
 872     assert(shared_path(0)->is_modules_image(), "first shared_path must be the modules image");
 873     if (header()->app_class_paths_start_index() > 1) {
 874       DynamicDumpSharedSpaces = false;
 875       warning(
 876         "Dynamic archiving is disabled because base layer archive has appended boot classpath");
 877     }
 878     if (header()->num_module_paths() > 0) {
 879       DynamicDumpSharedSpaces = false;
 880       warning(
 881         "Dynamic archiving is disabled because base layer archive has module path");
 882     }
 883   }
 884 
 885   log_paths("Expecting BOOT path=", 0, header()->app_class_paths_start_index());
 886   log_paths("Expecting -Djava.class.path=", header()->app_class_paths_start_index(), header()->app_module_paths_start_index());
 887 
 888   int module_paths_start_index = header()->app_module_paths_start_index();
 889   int shared_app_paths_len = 0;
 890 
 891   // validate the path entries up to the _max_used_path_index
 892   for (int i=0; i < header()->max_used_path_index() + 1; i++) {
 893     if (i < module_paths_start_index) {
 894       if (shared_path(i)->validate()) {
 895         // Only count the app class paths not from the "Class-path" attribute of a jar manifest.
 896         if (!shared_path(i)->from_class_path_attr() && i >= header()->app_class_paths_start_index()) {
 897           shared_app_paths_len++;
 898         }
 899         log_info(class, path)("ok");
 900       } else {
 901         if (_dynamic_archive_info != NULL && _dynamic_archive_info->_is_static) {
 902           assert(!UseSharedSpaces, "UseSharedSpaces should be disabled");
 903         }
 904         return false;
 905       }
 906     } else if (i >= module_paths_start_index) {
 907       if (shared_path(i)->validate(false /* not a class path entry */)) {
 908         log_info(class, path)("ok");
 909       } else {
 910         if (_dynamic_archive_info != NULL && _dynamic_archive_info->_is_static) {
 911           assert(!UseSharedSpaces, "UseSharedSpaces should be disabled");
 912         }
 913         return false;
 914       }
 915     }
 916   }
 917 
 918   if (header()->max_used_path_index() == 0) {
 919     // default archive only contains the module image in the bootclasspath
 920     assert(shared_path(0)->is_modules_image(), "first shared_path must be the modules image");
 921   } else {
 922     if (!validate_boot_class_paths() || !validate_app_class_paths(shared_app_paths_len)) {
 923       fail_continue("shared class paths mismatch (hint: enable -Xlog:class+path=info to diagnose the failure)");
 924       return false;
 925     }
 926   }
 927 
 928   validate_non_existent_class_paths();
 929 
 930   _validating_shared_path_table = false;
 931 
 932 #if INCLUDE_JVMTI
 933   if (_classpath_entries_for_jvmti != NULL) {
 934     os::free(_classpath_entries_for_jvmti);
 935   }
 936   size_t sz = sizeof(ClassPathEntry*) * get_number_of_shared_paths();
 937   _classpath_entries_for_jvmti = (ClassPathEntry**)os::malloc(sz, mtClass);
 938   memset((void*)_classpath_entries_for_jvmti, 0, sz);
 939 #endif
 940 
 941   return true;
 942 }
 943 
 944 void FileMapInfo::validate_non_existent_class_paths() {
 945   // All of the recorded non-existent paths came from the Class-Path: attribute from the JAR
 946   // files on the app classpath. If any of these are found to exist during runtime,
 947   // it will change how classes are loading for the app loader. For safety, disable
 948   // loading of archived platform/app classes (currently there's no way to disable just the
 949   // app classes).
 950 
 951   assert(UseSharedSpaces, "runtime only");
 952   for (int i = header()->app_module_paths_start_index() + header()->num_module_paths();
 953        i < get_number_of_shared_paths();
 954        i++) {
 955     SharedClassPathEntry* ent = shared_path(i);
 956     if (!ent->check_non_existent()) {
 957       warning("Archived non-system classes are disabled because the "
 958               "file %s exists", ent->name());
 959       header()->set_has_platform_or_app_classes(false);
 960     }
 961   }
 962 }
 963 
 964 bool FileMapInfo::check_archive(const char* archive_name, bool is_static) {
 965   int fd = os::open(archive_name, O_RDONLY | O_BINARY, 0);
 966   if (fd < 0) {
 967     // do not vm_exit_during_initialization here because Arguments::init_shared_archive_paths()
 968     // requires a shared archive name. The open_for_read() function will log a message regarding
 969     // failure in opening a shared archive.
 970     return false;
 971   }
 972 
 973   size_t sz = is_static ? sizeof(FileMapHeader) : sizeof(DynamicArchiveHeader);
 974   void* header = os::malloc(sz, mtInternal);
 975   memset(header, 0, sz);
 976   size_t n = os::read(fd, header, (unsigned int)sz);
 977   if (n != sz) {
 978     os::free(header);
 979     os::close(fd);
 980     vm_exit_during_initialization("Unable to read header from shared archive", archive_name);
 981     return false;
 982   }
 983   if (is_static) {
 984     FileMapHeader* static_header = (FileMapHeader*)header;
 985     if (static_header->magic() != CDS_ARCHIVE_MAGIC) {
 986       os::free(header);
 987       os::close(fd);
 988       vm_exit_during_initialization("Not a base shared archive", archive_name);
 989       return false;
 990     }
 991   } else {
 992     DynamicArchiveHeader* dynamic_header = (DynamicArchiveHeader*)header;
 993     if (dynamic_header->magic() != CDS_DYNAMIC_ARCHIVE_MAGIC) {
 994       os::free(header);
 995       os::close(fd);
 996       vm_exit_during_initialization("Not a top shared archive", archive_name);
 997       return false;
 998     }
 999   }
1000   os::free(header);
1001   os::close(fd);
1002   return true;
1003 }
1004 
1005 bool FileMapInfo::get_base_archive_name_from_header(const char* archive_name,
1006                                                     int* size, char** base_archive_name) {
1007   int fd = os::open(archive_name, O_RDONLY | O_BINARY, 0);
1008   if (fd < 0) {
1009     *size = 0;
1010     return false;
1011   }
1012 
1013   // read the header as a dynamic archive header
1014   size_t sz = sizeof(DynamicArchiveHeader);
1015   DynamicArchiveHeader* dynamic_header = (DynamicArchiveHeader*)os::malloc(sz, mtInternal);
1016   size_t n = os::read(fd, dynamic_header, (unsigned int)sz);
1017   if (n != sz) {
1018     fail_continue("Unable to read the file header.");
1019     os::free(dynamic_header);
1020     os::close(fd);
1021     return false;
1022   }
1023   if (dynamic_header->magic() != CDS_DYNAMIC_ARCHIVE_MAGIC) {
1024     // Not a dynamic header, no need to proceed further.
1025     *size = 0;
1026     os::free(dynamic_header);
1027     os::close(fd);
1028     return false;
1029   }
1030   if (dynamic_header->base_archive_is_default()) {
1031     *base_archive_name = Arguments::get_default_shared_archive_path();
1032   } else {
1033     // read the base archive name
1034     size_t name_size = dynamic_header->base_archive_name_size();
1035     if (name_size == 0) {
1036       os::free(dynamic_header);
1037       os::close(fd);
1038       return false;
1039     }
1040     *base_archive_name = NEW_C_HEAP_ARRAY(char, name_size, mtInternal);
1041     n = os::read(fd, *base_archive_name, (unsigned int)name_size);
1042     if (n != name_size) {
1043       fail_continue("Unable to read the base archive name from the header.");
1044       FREE_C_HEAP_ARRAY(char, *base_archive_name);
1045       *base_archive_name = NULL;
1046       os::free(dynamic_header);
1047       os::close(fd);
1048       return false;
1049     }
1050   }
1051 
1052   os::free(dynamic_header);
1053   os::close(fd);
1054   return true;
1055 }
1056 
1057 // Read the FileMapInfo information from the file.
1058 
1059 bool FileMapInfo::init_from_file(int fd) {
1060   size_t sz = is_static() ? sizeof(FileMapHeader) : sizeof(DynamicArchiveHeader);
1061   size_t n = os::read(fd, header(), (unsigned int)sz);
1062   if (n != sz) {
1063     fail_continue("Unable to read the file header.");
1064     return false;
1065   }
1066 
1067   if (!Arguments::has_jimage()) {
1068     FileMapInfo::fail_continue("The shared archive file cannot be used with an exploded module build.");
1069     return false;
1070   }
1071 
1072   unsigned int expected_magic = is_static() ? CDS_ARCHIVE_MAGIC : CDS_DYNAMIC_ARCHIVE_MAGIC;
1073   if (header()->magic() != expected_magic) {
1074     log_info(cds)("_magic expected: 0x%08x", expected_magic);
1075     log_info(cds)("         actual: 0x%08x", header()->magic());
1076     FileMapInfo::fail_continue("The shared archive file has a bad magic number.");
1077     return false;
1078   }
1079 
1080   if (header()->version() != CURRENT_CDS_ARCHIVE_VERSION) {
1081     log_info(cds)("_version expected: %d", CURRENT_CDS_ARCHIVE_VERSION);
1082     log_info(cds)("           actual: %d", header()->version());
1083     fail_continue("The shared archive file has the wrong version.");
1084     return false;
1085   }
1086 
1087   if (header()->header_size() != sz) {
1088     log_info(cds)("_header_size expected: " SIZE_FORMAT, sz);
1089     log_info(cds)("               actual: " SIZE_FORMAT, header()->header_size());
1090     FileMapInfo::fail_continue("The shared archive file has an incorrect header size.");
1091     return false;
1092   }
1093 
1094   const char* actual_ident = header()->jvm_ident();
1095 
1096   if (actual_ident[JVM_IDENT_MAX-1] != 0) {
1097     FileMapInfo::fail_continue("JVM version identifier is corrupted.");
1098     return false;
1099   }
1100 
1101   char expected_ident[JVM_IDENT_MAX];
1102   get_header_version(expected_ident);
1103   if (strncmp(actual_ident, expected_ident, JVM_IDENT_MAX-1) != 0) {
1104     log_info(cds)("_jvm_ident expected: %s", expected_ident);
1105     log_info(cds)("             actual: %s", actual_ident);
1106     FileMapInfo::fail_continue("The shared archive file was created by a different"
1107                   " version or build of HotSpot");
1108     return false;
1109   }
1110 
1111   if (VerifySharedSpaces) {
1112     int expected_crc = header()->compute_crc();
1113     if (expected_crc != header()->crc()) {
1114       log_info(cds)("_crc expected: %d", expected_crc);
1115       log_info(cds)("       actual: %d", header()->crc());
1116       FileMapInfo::fail_continue("Header checksum verification failed.");
1117       return false;
1118     }
1119   }
1120 
1121   _file_offset = n + header()->base_archive_name_size(); // accounts for the size of _base_archive_name
1122 
1123   if (is_static()) {
1124     // just checking the last region is sufficient since the archive is written
1125     // in sequential order
1126     size_t len = lseek(fd, 0, SEEK_END);
1127     FileMapRegion* si = space_at(MetaspaceShared::last_valid_region);
1128     // The last space might be empty
1129     if (si->file_offset() > len || len - si->file_offset() < si->used()) {
1130       fail_continue("The shared archive file has been truncated.");
1131       return false;
1132     }
1133   }
1134 
1135   return true;
1136 }
1137 
1138 void FileMapInfo::seek_to_position(size_t pos) {
1139   if (lseek(_fd, (long)pos, SEEK_SET) < 0) {
1140     fail_stop("Unable to seek to position " SIZE_FORMAT, pos);
1141   }
1142 }
1143 
1144 // Read the FileMapInfo information from the file.
1145 bool FileMapInfo::open_for_read() {
1146   if (_file_open) {
1147     return true;
1148   }
1149   if (is_static()) {
1150     _full_path = Arguments::GetSharedArchivePath();
1151   } else {
1152     _full_path = Arguments::GetSharedDynamicArchivePath();
1153   }
1154   log_info(cds)("trying to map %s", _full_path);
1155   int fd = os::open(_full_path, O_RDONLY | O_BINARY, 0);
1156   if (fd < 0) {
1157     if (errno == ENOENT) {
1158       fail_continue("Specified shared archive not found (%s).", _full_path);
1159     } else {
1160       fail_continue("Failed to open shared archive file (%s).",
1161                     os::strerror(errno));
1162     }
1163     return false;
1164   } else {
1165     log_info(cds)("Opened archive %s.", _full_path);
1166   }
1167 
1168   _fd = fd;
1169   _file_open = true;
1170   return true;
1171 }
1172 
1173 // Write the FileMapInfo information to the file.
1174 
1175 void FileMapInfo::open_for_write(const char* path) {
1176   if (path == NULL) {
1177     _full_path = Arguments::GetSharedArchivePath();
1178   } else {
1179     _full_path = path;
1180   }
1181   LogMessage(cds) msg;
1182   if (msg.is_info()) {
1183     msg.info("Dumping shared data to file: ");
1184     msg.info("   %s", _full_path);
1185   }
1186 
1187 #ifdef _WINDOWS  // On Windows, need WRITE permission to remove the file.
1188     chmod(_full_path, _S_IREAD | _S_IWRITE);
1189 #endif
1190 
1191   // Use remove() to delete the existing file because, on Unix, this will
1192   // allow processes that have it open continued access to the file.
1193   remove(_full_path);
1194   int fd = os::open(_full_path, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0444);
1195   if (fd < 0) {
1196     fail_stop("Unable to create shared archive file %s: (%s).", _full_path,
1197               os::strerror(errno));
1198   }
1199   _fd = fd;
1200   _file_open = true;
1201 
1202   // Seek past the header. We will write the header after all regions are written
1203   // and their CRCs computed.
1204   size_t header_bytes = header()->header_size();
1205   if (header()->magic() == CDS_DYNAMIC_ARCHIVE_MAGIC) {
1206     header_bytes += strlen(Arguments::GetSharedArchivePath()) + 1;
1207   }
1208 
1209   header_bytes = align_up(header_bytes, MetaspaceShared::core_region_alignment());
1210   _file_offset = header_bytes;
1211   seek_to_position(_file_offset);
1212 }
1213 
1214 
1215 // Write the header to the file, seek to the next allocation boundary.
1216 
1217 void FileMapInfo::write_header() {
1218   _file_offset = 0;
1219   seek_to_position(_file_offset);
1220   assert(is_file_position_aligned(), "must be");
1221   write_bytes(header(), header()->header_size());
1222 
1223   if (header()->magic() == CDS_DYNAMIC_ARCHIVE_MAGIC) {
1224     char* base_archive_name = (char*)Arguments::GetSharedArchivePath();
1225     if (base_archive_name != NULL) {
1226       write_bytes(base_archive_name, header()->base_archive_name_size());
1227     }
1228   }
1229 }
1230 
1231 size_t FileMapRegion::used_aligned() const {
1232   return align_up(used(), MetaspaceShared::core_region_alignment());
1233 }
1234 
1235 void FileMapRegion::init(int region_index, size_t mapping_offset, size_t size, bool read_only,
1236                          bool allow_exec, int crc) {
1237   _is_heap_region = HeapShared::is_heap_region(region_index);
1238   _is_bitmap_region = (region_index == MetaspaceShared::bm);
1239   _mapping_offset = mapping_offset;
1240   _used = size;
1241   _read_only = read_only;
1242   _allow_exec = allow_exec;
1243   _crc = crc;
1244   _mapped_from_file = false;
1245   _mapped_base = NULL;
1246 }
1247 
1248 
1249 static const char* region_name(int region_index) {
1250   static const char* names[] = {
1251     "rw", "ro", "bm", "ca0", "ca1", "oa0", "oa1"
1252   };
1253   const int num_regions = sizeof(names)/sizeof(names[0]);
1254   assert(0 <= region_index && region_index < num_regions, "sanity");
1255 
1256   return names[region_index];
1257 }
1258 
1259 void FileMapRegion::print(outputStream* st, int region_index) {
1260   st->print_cr("============ region ============= %d \"%s\"", region_index, region_name(region_index));
1261   st->print_cr("- crc:                            0x%08x", _crc);
1262   st->print_cr("- read_only:                      %d", _read_only);
1263   st->print_cr("- allow_exec:                     %d", _allow_exec);
1264   st->print_cr("- is_heap_region:                 %d", _is_heap_region);
1265   st->print_cr("- is_bitmap_region:               %d", _is_bitmap_region);
1266   st->print_cr("- mapped_from_file:               %d", _mapped_from_file);
1267   st->print_cr("- file_offset:                    " SIZE_FORMAT_HEX, _file_offset);
1268   st->print_cr("- mapping_offset:                 " SIZE_FORMAT_HEX, _mapping_offset);
1269   st->print_cr("- used:                           " SIZE_FORMAT, _used);
1270   st->print_cr("- oopmap_offset:                  " SIZE_FORMAT_HEX, _oopmap_offset);
1271   st->print_cr("- oopmap_size_in_bits:            " SIZE_FORMAT, _oopmap_size_in_bits);
1272   st->print_cr("- mapped_base:                    " INTPTR_FORMAT, p2i(_mapped_base));
1273 }
1274 
1275 void FileMapInfo::write_region(int region, char* base, size_t size,
1276                                bool read_only, bool allow_exec) {
1277   Arguments::assert_is_dumping_archive();
1278 
1279   FileMapRegion* si = space_at(region);
1280   char* requested_base;
1281   size_t mapping_offset = 0;
1282 
1283   if (region == MetaspaceShared::bm) {
1284     requested_base = NULL; // always NULL for bm region
1285   } else if (size == 0) {
1286     // This is an unused region (e.g., a heap region when !INCLUDE_CDS_JAVA_HEAP)
1287     requested_base = NULL;
1288   } else if (HeapShared::is_heap_region(region)) {
1289     assert(!DynamicDumpSharedSpaces, "must be");
1290     requested_base = base;
1291     mapping_offset = (size_t)CompressedOops::encode_not_null(cast_to_oop(base));
1292     assert(mapping_offset == (size_t)(uint32_t)mapping_offset, "must be 32-bit only");
1293   } else {
1294     char* requested_SharedBaseAddress = (char*)MetaspaceShared::requested_base_address();
1295     requested_base = ArchiveBuilder::current()->to_requested(base);
1296     assert(requested_base >= requested_SharedBaseAddress, "must be");
1297     mapping_offset = requested_base - requested_SharedBaseAddress;
1298   }
1299 
1300   si->set_file_offset(_file_offset);
1301   int crc = ClassLoader::crc32(0, base, (jint)size);
1302   if (size > 0) {
1303     log_info(cds)("Shared file region (%-3s)  %d: " SIZE_FORMAT_W(8)
1304                    " bytes, addr " INTPTR_FORMAT " file offset " SIZE_FORMAT_HEX_W(08)
1305                    " crc 0x%08x",
1306                    region_name(region), region, size, p2i(requested_base), _file_offset, crc);
1307   }
1308   si->init(region, mapping_offset, size, read_only, allow_exec, crc);
1309 
1310   if (base != NULL) {
1311     write_bytes_aligned(base, size);
1312   }
1313 }
1314 
1315 size_t FileMapInfo::set_oopmaps_offset(GrowableArray<ArchiveHeapOopmapInfo>* oopmaps, size_t curr_size) {
1316   for (int i = 0; i < oopmaps->length(); i++) {
1317     oopmaps->at(i)._offset = curr_size;
1318     curr_size += oopmaps->at(i)._oopmap_size_in_bytes;
1319   }
1320   return curr_size;
1321 }
1322 
1323 size_t FileMapInfo::write_oopmaps(GrowableArray<ArchiveHeapOopmapInfo>* oopmaps, size_t curr_offset, char* buffer) {
1324   for (int i = 0; i < oopmaps->length(); i++) {
1325     memcpy(buffer + curr_offset, oopmaps->at(i)._oopmap, oopmaps->at(i)._oopmap_size_in_bytes);
1326     curr_offset += oopmaps->at(i)._oopmap_size_in_bytes;
1327   }
1328   return curr_offset;
1329 }
1330 
1331 char* FileMapInfo::write_bitmap_region(const CHeapBitMap* ptrmap,
1332                                        GrowableArray<ArchiveHeapOopmapInfo>* closed_oopmaps,
1333                                        GrowableArray<ArchiveHeapOopmapInfo>* open_oopmaps,
1334                                        size_t &size_in_bytes) {
1335   size_t size_in_bits = ptrmap->size();
1336   size_in_bytes = ptrmap->size_in_bytes();
1337 
1338   if (closed_oopmaps != NULL && open_oopmaps != NULL) {
1339     size_in_bytes = set_oopmaps_offset(closed_oopmaps, size_in_bytes);
1340     size_in_bytes = set_oopmaps_offset(open_oopmaps, size_in_bytes);
1341   }
1342 
1343   char* buffer = NEW_C_HEAP_ARRAY(char, size_in_bytes, mtClassShared);
1344   ptrmap->write_to((BitMap::bm_word_t*)buffer, ptrmap->size_in_bytes());
1345   header()->set_ptrmap_size_in_bits(size_in_bits);
1346 
1347   if (closed_oopmaps != NULL && open_oopmaps != NULL) {
1348     size_t curr_offset = write_oopmaps(closed_oopmaps, ptrmap->size_in_bytes(), buffer);
1349     write_oopmaps(open_oopmaps, curr_offset, buffer);
1350   }
1351 
1352   write_region(MetaspaceShared::bm, (char*)buffer, size_in_bytes, /*read_only=*/true, /*allow_exec=*/false);
1353   return buffer;
1354 }
1355 
1356 // Write out the given archive heap memory regions.  GC code combines multiple
1357 // consecutive archive GC regions into one MemRegion whenever possible and
1358 // produces the 'heap_mem' array.
1359 //
1360 // If the archive heap memory size is smaller than a single dump time GC region
1361 // size, there is only one MemRegion in the array.
1362 //
1363 // If the archive heap memory size is bigger than one dump time GC region size,
1364 // the 'heap_mem' array may contain more than one consolidated MemRegions. When
1365 // the first/bottom archive GC region is a partial GC region (with the empty
1366 // portion at the higher address within the region), one MemRegion is used for
1367 // the bottom partial archive GC region. The rest of the consecutive archive
1368 // GC regions are combined into another MemRegion.
1369 //
1370 // Here's the mapping from (archive heap GC regions) -> (GrowableArray<MemRegion> *regions).
1371 //   + We have 1 or more archive heap regions: ah0, ah1, ah2 ..... ahn
1372 //   + We have 1 or 2 consolidated heap memory regions: r0 and r1
1373 //
1374 // If there's a single archive GC region (ah0), then r0 == ah0, and r1 is empty.
1375 // Otherwise:
1376 //
1377 // "X" represented space that's occupied by heap objects.
1378 // "_" represented unused spaced in the heap region.
1379 //
1380 //
1381 //    |ah0       | ah1 | ah2| ...... | ahn|
1382 //    |XXXXXX|__ |XXXXX|XXXX|XXXXXXXX|XXXX|
1383 //    |<-r0->|   |<- r1 ----------------->|
1384 //            ^^^
1385 //             |
1386 //             +-- gap
1387 size_t FileMapInfo::write_archive_heap_regions(GrowableArray<MemRegion> *heap_mem,
1388                                                GrowableArray<ArchiveHeapOopmapInfo> *oopmaps,
1389                                                int first_region_id, int max_num_regions) {
1390   assert(max_num_regions <= 2, "Only support maximum 2 memory regions");
1391 
1392   int arr_len = heap_mem == NULL ? 0 : heap_mem->length();
1393   if(arr_len > max_num_regions) {
1394     fail_stop("Unable to write archive heap memory regions: "
1395               "number of memory regions exceeds maximum due to fragmentation. "
1396               "Please increase java heap size "
1397               "(current MaxHeapSize is " SIZE_FORMAT ", InitialHeapSize is " SIZE_FORMAT ").",
1398               MaxHeapSize, InitialHeapSize);
1399   }
1400 
1401   size_t total_size = 0;
1402   for (int i = 0; i < max_num_regions; i++) {
1403     char* start = NULL;
1404     size_t size = 0;
1405     if (i < arr_len) {
1406       start = (char*)heap_mem->at(i).start();
1407       size = heap_mem->at(i).byte_size();
1408       total_size += size;
1409     }
1410 
1411     int region_idx = i + first_region_id;
1412     write_region(region_idx, start, size, false, false);
1413     if (size > 0) {
1414       space_at(region_idx)->init_oopmap(oopmaps->at(i)._offset,
1415                                         oopmaps->at(i)._oopmap_size_in_bits);
1416     }
1417   }
1418   return total_size;
1419 }
1420 
1421 // Dump bytes to file -- at the current file position.
1422 
1423 void FileMapInfo::write_bytes(const void* buffer, size_t nbytes) {
1424   assert(_file_open, "must be");
1425   size_t n = os::write(_fd, buffer, (unsigned int)nbytes);
1426   if (n != nbytes) {
1427     // If the shared archive is corrupted, close it and remove it.
1428     close();
1429     remove(_full_path);
1430     fail_stop("Unable to write to shared archive file.");
1431   }
1432   _file_offset += nbytes;
1433 }
1434 
1435 bool FileMapInfo::is_file_position_aligned() const {
1436   return _file_offset == align_up(_file_offset,
1437                                   MetaspaceShared::core_region_alignment());
1438 }
1439 
1440 // Align file position to an allocation unit boundary.
1441 
1442 void FileMapInfo::align_file_position() {
1443   assert(_file_open, "must be");
1444   size_t new_file_offset = align_up(_file_offset,
1445                                     MetaspaceShared::core_region_alignment());
1446   if (new_file_offset != _file_offset) {
1447     _file_offset = new_file_offset;
1448     // Seek one byte back from the target and write a byte to insure
1449     // that the written file is the correct length.
1450     _file_offset -= 1;
1451     seek_to_position(_file_offset);
1452     char zero = 0;
1453     write_bytes(&zero, 1);
1454   }
1455 }
1456 
1457 
1458 // Dump bytes to file -- at the current file position.
1459 
1460 void FileMapInfo::write_bytes_aligned(const void* buffer, size_t nbytes) {
1461   align_file_position();
1462   write_bytes(buffer, nbytes);
1463   align_file_position();
1464 }
1465 
1466 // Close the shared archive file.  This does NOT unmap mapped regions.
1467 
1468 void FileMapInfo::close() {
1469   if (_file_open) {
1470     if (::close(_fd) < 0) {
1471       fail_stop("Unable to close the shared archive file.");
1472     }
1473     _file_open = false;
1474     _fd = -1;
1475   }
1476 }
1477 
1478 
1479 // JVM/TI RedefineClasses() support:
1480 // Remap the shared readonly space to shared readwrite, private.
1481 bool FileMapInfo::remap_shared_readonly_as_readwrite() {
1482   int idx = MetaspaceShared::ro;
1483   FileMapRegion* si = space_at(idx);
1484   if (!si->read_only()) {
1485     // the space is already readwrite so we are done
1486     return true;
1487   }
1488   size_t size = si->used_aligned();
1489   if (!open_for_read()) {
1490     return false;
1491   }
1492   char *addr = region_addr(idx);
1493   char *base = os::remap_memory(_fd, _full_path, si->file_offset(),
1494                                 addr, size, false /* !read_only */,
1495                                 si->allow_exec());
1496   close();
1497   // These have to be errors because the shared region is now unmapped.
1498   if (base == NULL) {
1499     log_error(cds)("Unable to remap shared readonly space (errno=%d).", errno);
1500     vm_exit(1);
1501   }
1502   if (base != addr) {
1503     log_error(cds)("Unable to remap shared readonly space (errno=%d).", errno);
1504     vm_exit(1);
1505   }
1506   si->set_read_only(false);
1507   return true;
1508 }
1509 
1510 // Memory map a region in the address space.
1511 static const char* shared_region_name[] = { "ReadWrite", "ReadOnly", "Bitmap",
1512                                             "String1", "String2", "OpenArchive1", "OpenArchive2" };
1513 
1514 MapArchiveResult FileMapInfo::map_regions(int regions[], int num_regions, char* mapped_base_address, ReservedSpace rs) {
1515   DEBUG_ONLY(FileMapRegion* last_region = NULL);
1516   intx addr_delta = mapped_base_address - header()->requested_base_address();
1517 
1518   // Make sure we don't attempt to use header()->mapped_base_address() unless
1519   // it's been successfully mapped.
1520   DEBUG_ONLY(header()->set_mapped_base_address((char*)(uintptr_t)0xdeadbeef);)
1521 
1522   for (int r = 0; r < num_regions; r++) {
1523     int idx = regions[r];
1524     MapArchiveResult result = map_region(idx, addr_delta, mapped_base_address, rs);
1525     if (result != MAP_ARCHIVE_SUCCESS) {
1526       return result;
1527     }
1528     FileMapRegion* si = space_at(idx);
1529     DEBUG_ONLY(if (last_region != NULL) {
1530         // Ensure that the OS won't be able to allocate new memory spaces between any mapped
1531         // regions, or else it would mess up the simple comparision in MetaspaceObj::is_shared().
1532         assert(si->mapped_base() == last_region->mapped_end(), "must have no gaps");
1533       }
1534       last_region = si;)
1535     log_info(cds)("Mapped %s region #%d at base " INTPTR_FORMAT " top " INTPTR_FORMAT " (%s)", is_static() ? "static " : "dynamic",
1536                   idx, p2i(si->mapped_base()), p2i(si->mapped_end()),
1537                   shared_region_name[idx]);
1538 
1539   }
1540 
1541   header()->set_mapped_base_address(header()->requested_base_address() + addr_delta);
1542   if (addr_delta != 0 && !relocate_pointers_in_core_regions(addr_delta)) {
1543     return MAP_ARCHIVE_OTHER_FAILURE;
1544   }
1545 
1546   return MAP_ARCHIVE_SUCCESS;
1547 }
1548 
1549 bool FileMapInfo::read_region(int i, char* base, size_t size) {
1550   assert(MetaspaceShared::use_windows_memory_mapping(), "used by windows only");
1551   FileMapRegion* si = space_at(i);
1552   log_info(cds)("Commit %s region #%d at base " INTPTR_FORMAT " top " INTPTR_FORMAT " (%s)%s",
1553                 is_static() ? "static " : "dynamic", i, p2i(base), p2i(base + size),
1554                 shared_region_name[i], si->allow_exec() ? " exec" : "");
1555   if (!os::commit_memory(base, size, si->allow_exec())) {
1556     log_error(cds)("Failed to commit %s region #%d (%s)", is_static() ? "static " : "dynamic",
1557                    i, shared_region_name[i]);
1558     return false;
1559   }
1560   if (lseek(_fd, (long)si->file_offset(), SEEK_SET) != (int)si->file_offset() ||
1561       read_bytes(base, size) != size) {
1562     return false;
1563   }
1564   return true;
1565 }
1566 
1567 MapArchiveResult FileMapInfo::map_region(int i, intx addr_delta, char* mapped_base_address, ReservedSpace rs) {
1568   assert(!HeapShared::is_heap_region(i), "sanity");
1569   FileMapRegion* si = space_at(i);
1570   size_t size = si->used_aligned();
1571   char *requested_addr = mapped_base_address + si->mapping_offset();
1572   assert(si->mapped_base() == NULL, "must be not mapped yet");
1573   assert(requested_addr != NULL, "must be specified");
1574 
1575   si->set_mapped_from_file(false);
1576 
1577   if (MetaspaceShared::use_windows_memory_mapping()) {
1578     // Windows cannot remap read-only shared memory to read-write when required for
1579     // RedefineClasses, which is also used by JFR.  Always map windows regions as RW.
1580     si->set_read_only(false);
1581   } else if (JvmtiExport::can_modify_any_class() || JvmtiExport::can_walk_any_space() ||
1582              Arguments::has_jfr_option()) {
1583     // If a tool agent is in use (debugging enabled), or JFR, we must map the address space RW
1584     si->set_read_only(false);
1585   } else if (addr_delta != 0) {
1586     si->set_read_only(false); // Need to patch the pointers
1587   }
1588 
1589   if (MetaspaceShared::use_windows_memory_mapping() && rs.is_reserved()) {
1590     // This is the second time we try to map the archive(s). We have already created a ReservedSpace
1591     // that covers all the FileMapRegions to ensure all regions can be mapped. However, Windows
1592     // can't mmap into a ReservedSpace, so we just os::read() the data. We're going to patch all the
1593     // regions anyway, so there's no benefit for mmap anyway.
1594     if (!read_region(i, requested_addr, size)) {
1595       log_info(cds)("Failed to read %s shared space into reserved space at " INTPTR_FORMAT,
1596                     shared_region_name[i], p2i(requested_addr));
1597       return MAP_ARCHIVE_OTHER_FAILURE; // oom or I/O error.
1598     }
1599   } else {
1600     // Note that this may either be a "fresh" mapping into unreserved address
1601     // space (Windows, first mapping attempt), or a mapping into pre-reserved
1602     // space (Posix). See also comment in MetaspaceShared::map_archives().
1603     char* base = os::map_memory(_fd, _full_path, si->file_offset(),
1604                                 requested_addr, size, si->read_only(),
1605                                 si->allow_exec(), mtClassShared);
1606     if (base != requested_addr) {
1607       log_info(cds)("Unable to map %s shared space at " INTPTR_FORMAT,
1608                     shared_region_name[i], p2i(requested_addr));
1609       _memory_mapping_failed = true;
1610       return MAP_ARCHIVE_MMAP_FAILURE;
1611     }
1612     si->set_mapped_from_file(true);
1613   }
1614   si->set_mapped_base(requested_addr);
1615 
1616   if (VerifySharedSpaces && !verify_region_checksum(i)) {
1617     return MAP_ARCHIVE_OTHER_FAILURE;
1618   }
1619 
1620   return MAP_ARCHIVE_SUCCESS;
1621 }
1622 
1623 // The return value is the location of the archive relocation bitmap.
1624 char* FileMapInfo::map_bitmap_region() {
1625   FileMapRegion* si = space_at(MetaspaceShared::bm);
1626   if (si->mapped_base() != NULL) {
1627     return si->mapped_base();
1628   }
1629   bool read_only = true, allow_exec = false;
1630   char* requested_addr = NULL; // allow OS to pick any location
1631   char* bitmap_base = os::map_memory(_fd, _full_path, si->file_offset(),
1632                                      requested_addr, si->used_aligned(), read_only, allow_exec, mtClassShared);
1633   if (bitmap_base == NULL) {
1634     log_info(cds)("failed to map relocation bitmap");
1635     return NULL;
1636   }
1637 
1638   if (VerifySharedSpaces && !region_crc_check(bitmap_base, si->used(), si->crc())) {
1639     log_error(cds)("relocation bitmap CRC error");
1640     if (!os::unmap_memory(bitmap_base, si->used_aligned())) {
1641       fatal("os::unmap_memory of relocation bitmap failed");
1642     }
1643     return NULL;
1644   }
1645 
1646   si->set_mapped_base(bitmap_base);
1647   si->set_mapped_from_file(true);
1648   log_info(cds)("Mapped %s region #%d at base " INTPTR_FORMAT " top " INTPTR_FORMAT " (%s)",
1649                 is_static() ? "static " : "dynamic",
1650                 MetaspaceShared::bm, p2i(si->mapped_base()), p2i(si->mapped_end()),
1651                 shared_region_name[MetaspaceShared::bm]);
1652   return bitmap_base;
1653 }
1654 
1655 // This is called when we cannot map the archive at the requested[ base address (usually 0x800000000).
1656 // We relocate all pointers in the 2 core regions (ro, rw).
1657 bool FileMapInfo::relocate_pointers_in_core_regions(intx addr_delta) {
1658   log_debug(cds, reloc)("runtime archive relocation start");
1659   char* bitmap_base = map_bitmap_region();
1660 
1661   if (bitmap_base == NULL) {
1662     return false; // OOM, or CRC check failure
1663   } else {
1664     size_t ptrmap_size_in_bits = header()->ptrmap_size_in_bits();
1665     log_debug(cds, reloc)("mapped relocation bitmap @ " INTPTR_FORMAT " (" SIZE_FORMAT " bits)",
1666                           p2i(bitmap_base), ptrmap_size_in_bits);
1667 
1668     BitMapView ptrmap((BitMap::bm_word_t*)bitmap_base, ptrmap_size_in_bits);
1669 
1670     // Patch all pointers in the the mapped region that are marked by ptrmap.
1671     address patch_base = (address)mapped_base();
1672     address patch_end  = (address)mapped_end();
1673 
1674     // the current value of the pointers to be patched must be within this
1675     // range (i.e., must be between the requesed base address, and the of the current archive).
1676     // Note: top archive may point to objects in the base archive, but not the other way around.
1677     address valid_old_base = (address)header()->requested_base_address();
1678     address valid_old_end  = valid_old_base + mapping_end_offset();
1679 
1680     // after patching, the pointers must point inside this range
1681     // (the requested location of the archive, as mapped at runtime).
1682     address valid_new_base = (address)header()->mapped_base_address();
1683     address valid_new_end  = (address)mapped_end();
1684 
1685     SharedDataRelocator patcher((address*)patch_base, (address*)patch_end, valid_old_base, valid_old_end,
1686                                 valid_new_base, valid_new_end, addr_delta);
1687     ptrmap.iterate(&patcher);
1688 
1689     // The MetaspaceShared::bm region will be unmapped in MetaspaceShared::initialize_shared_spaces().
1690 
1691     log_debug(cds, reloc)("runtime archive relocation done");
1692     return true;
1693   }
1694 }
1695 
1696 size_t FileMapInfo::read_bytes(void* buffer, size_t count) {
1697   assert(_file_open, "Archive file is not open");
1698   size_t n = os::read(_fd, buffer, (unsigned int)count);
1699   if (n != count) {
1700     // Close the file if there's a problem reading it.
1701     close();
1702     return 0;
1703   }
1704   _file_offset += count;
1705   return count;
1706 }
1707 
1708 address FileMapInfo::decode_start_address(FileMapRegion* spc, bool with_current_oop_encoding_mode) {
1709   size_t offset = spc->mapping_offset();
1710   narrowOop n = CompressedOops::narrow_oop_cast(offset);
1711   if (with_current_oop_encoding_mode) {
1712     return cast_from_oop<address>(CompressedOops::decode_raw_not_null(n));
1713   } else {
1714     return cast_from_oop<address>(HeapShared::decode_from_archive(n));
1715   }
1716 }
1717 
1718 static MemRegion *closed_archive_heap_ranges = NULL;
1719 static MemRegion *open_archive_heap_ranges = NULL;
1720 static int num_closed_archive_heap_ranges = 0;
1721 static int num_open_archive_heap_ranges = 0;
1722 
1723 #if INCLUDE_CDS_JAVA_HEAP
1724 bool FileMapInfo::has_heap_regions() {
1725   return (space_at(MetaspaceShared::first_closed_archive_heap_region)->used() > 0);
1726 }
1727 
1728 // Returns the address range of the archived heap regions computed using the
1729 // current oop encoding mode. This range may be different than the one seen at
1730 // dump time due to encoding mode differences. The result is used in determining
1731 // if/how these regions should be relocated at run time.
1732 MemRegion FileMapInfo::get_heap_regions_range_with_current_oop_encoding_mode() {
1733   address start = (address) max_uintx;
1734   address end   = NULL;
1735 
1736   for (int i = MetaspaceShared::first_closed_archive_heap_region;
1737            i <= MetaspaceShared::last_valid_region;
1738            i++) {
1739     FileMapRegion* si = space_at(i);
1740     size_t size = si->used();
1741     if (size > 0) {
1742       address s = start_address_as_decoded_with_current_oop_encoding_mode(si);
1743       address e = s + size;
1744       if (start > s) {
1745         start = s;
1746       }
1747       if (end < e) {
1748         end = e;
1749       }
1750     }
1751   }
1752   assert(end != NULL, "must have at least one used heap region");
1753   return MemRegion((HeapWord*)start, (HeapWord*)end);
1754 }
1755 
1756 //
1757 // Map the closed and open archive heap objects to the runtime java heap.
1758 //
1759 // The shared objects are mapped at (or close to ) the java heap top in
1760 // closed archive regions. The mapped objects contain no out-going
1761 // references to any other java heap regions. GC does not write into the
1762 // mapped closed archive heap region.
1763 //
1764 // The open archive heap objects are mapped below the shared objects in
1765 // the runtime java heap. The mapped open archive heap data only contains
1766 // references to the shared objects and open archive objects initially.
1767 // During runtime execution, out-going references to any other java heap
1768 // regions may be added. GC may mark and update references in the mapped
1769 // open archive objects.
1770 void FileMapInfo::map_heap_regions_impl() {
1771   if (!HeapShared::is_heap_object_archiving_allowed()) {
1772     log_info(cds)("CDS heap data is being ignored. UseG1GC, "
1773                   "UseCompressedOops and UseCompressedClassPointers are required.");
1774     return;
1775   }
1776 
1777   if (JvmtiExport::should_post_class_file_load_hook() && JvmtiExport::has_early_class_hook_env()) {
1778     ShouldNotReachHere(); // CDS should have been disabled.
1779     // The archived objects are mapped at JVM start-up, but we don't know if
1780     // j.l.String or j.l.Class might be replaced by the ClassFileLoadHook,
1781     // which would make the archived String or mirror objects invalid. Let's be safe and not
1782     // use the archived objects. These 2 classes are loaded during the JVMTI "early" stage.
1783     //
1784     // If JvmtiExport::has_early_class_hook_env() is false, the classes of some objects
1785     // in the archived subgraphs may be replaced by the ClassFileLoadHook. But that's OK
1786     // because we won't install an archived object subgraph if the klass of any of the
1787     // referenced objects are replaced. See HeapShared::initialize_from_archived_subgraph().
1788   }
1789 
1790   log_info(cds)("CDS archive was created with max heap size = " SIZE_FORMAT "M, and the following configuration:",
1791                 max_heap_size()/M);
1792   log_info(cds)("    narrow_klass_base = " PTR_FORMAT ", narrow_klass_shift = %d",
1793                 p2i(narrow_klass_base()), narrow_klass_shift());
1794   log_info(cds)("    narrow_oop_mode = %d, narrow_oop_base = " PTR_FORMAT ", narrow_oop_shift = %d",
1795                 narrow_oop_mode(), p2i(narrow_oop_base()), narrow_oop_shift());
1796   log_info(cds)("    heap range = [" PTR_FORMAT " - "  PTR_FORMAT "]",
1797                 p2i(header()->heap_begin()), p2i(header()->heap_end()));
1798 
1799   log_info(cds)("The current max heap size = " SIZE_FORMAT "M, HeapRegion::GrainBytes = " SIZE_FORMAT,
1800                 MaxHeapSize/M, HeapRegion::GrainBytes);
1801   log_info(cds)("    narrow_klass_base = " PTR_FORMAT ", narrow_klass_shift = %d",
1802                 p2i(CompressedKlassPointers::base()), CompressedKlassPointers::shift());
1803   log_info(cds)("    narrow_oop_mode = %d, narrow_oop_base = " PTR_FORMAT ", narrow_oop_shift = %d",
1804                 CompressedOops::mode(), p2i(CompressedOops::base()), CompressedOops::shift());
1805   log_info(cds)("    heap range = [" PTR_FORMAT " - "  PTR_FORMAT "]",
1806                 p2i(CompressedOops::begin()), p2i(CompressedOops::end()));
1807 
1808   if (narrow_klass_base() != CompressedKlassPointers::base() ||
1809       narrow_klass_shift() != CompressedKlassPointers::shift()) {
1810     log_info(cds)("CDS heap data cannot be used because the archive was created with an incompatible narrow klass encoding mode.");
1811     return;
1812   }
1813 
1814   if (narrow_oop_mode() != CompressedOops::mode() ||
1815       narrow_oop_base() != CompressedOops::base() ||
1816       narrow_oop_shift() != CompressedOops::shift()) {
1817     log_info(cds)("CDS heap data needs to be relocated because the archive was created with an incompatible oop encoding mode.");
1818     _heap_pointers_need_patching = true;
1819   } else {
1820     MemRegion range = get_heap_regions_range_with_current_oop_encoding_mode();
1821     if (!CompressedOops::is_in(range)) {
1822       log_info(cds)("CDS heap data needs to be relocated because");
1823       log_info(cds)("the desired range " PTR_FORMAT " - "  PTR_FORMAT, p2i(range.start()), p2i(range.end()));
1824       log_info(cds)("is outside of the heap " PTR_FORMAT " - "  PTR_FORMAT, p2i(CompressedOops::begin()), p2i(CompressedOops::end()));
1825       _heap_pointers_need_patching = true;
1826     } else if (header()->heap_end() != CompressedOops::end()) {
1827       log_info(cds)("CDS heap data needs to be relocated to the end of the runtime heap to reduce fragmentation");
1828       _heap_pointers_need_patching = true;
1829     }
1830   }
1831 
1832   ptrdiff_t delta = 0;
1833   if (_heap_pointers_need_patching) {
1834     //   dumptime heap end  ------------v
1835     //   [      |archived heap regions| ]         runtime heap end ------v
1836     //                                       [   |archived heap regions| ]
1837     //                                  |<-----delta-------------------->|
1838     //
1839     // At dump time, the archived heap regions were near the top of the heap.
1840     // At run time, they may not be inside the heap, so we move them so
1841     // that they are now near the top of the runtime time. This can be done by
1842     // the simple math of adding the delta as shown above.
1843     address dumptime_heap_end = header()->heap_end();
1844     address runtime_heap_end = CompressedOops::end();
1845     delta = runtime_heap_end - dumptime_heap_end;
1846   }
1847 
1848   log_info(cds)("CDS heap data relocation delta = " INTX_FORMAT " bytes", delta);
1849   HeapShared::init_narrow_oop_decoding(narrow_oop_base() + delta, narrow_oop_shift());
1850 
1851   FileMapRegion* si = space_at(MetaspaceShared::first_closed_archive_heap_region);
1852   address relocated_closed_heap_region_bottom = start_address_as_decoded_from_archive(si);
1853   if (!is_aligned(relocated_closed_heap_region_bottom, HeapRegion::GrainBytes)) {
1854     // Align the bottom of the closed archive heap regions at G1 region boundary.
1855     // This will avoid the situation where the highest open region and the lowest
1856     // closed region sharing the same G1 region. Otherwise we will fail to map the
1857     // open regions.
1858     size_t align = size_t(relocated_closed_heap_region_bottom) % HeapRegion::GrainBytes;
1859     delta -= align;
1860     log_info(cds)("CDS heap data needs to be relocated lower by a further " SIZE_FORMAT
1861                   " bytes to " INTX_FORMAT " to be aligned with HeapRegion::GrainBytes",
1862                   align, delta);
1863     HeapShared::init_narrow_oop_decoding(narrow_oop_base() + delta, narrow_oop_shift());
1864     _heap_pointers_need_patching = true;
1865     relocated_closed_heap_region_bottom = start_address_as_decoded_from_archive(si);
1866   }
1867   assert(is_aligned(relocated_closed_heap_region_bottom, HeapRegion::GrainBytes),
1868          "must be");
1869 
1870   // Map the closed_archive_heap regions, GC does not write into the regions.
1871   if (map_heap_data(&closed_archive_heap_ranges,
1872                     MetaspaceShared::first_closed_archive_heap_region,
1873                     MetaspaceShared::max_closed_archive_heap_region,
1874                     &num_closed_archive_heap_ranges)) {
1875     HeapShared::set_closed_archive_heap_region_mapped();
1876 
1877     // Now, map open_archive heap regions, GC can write into the regions.
1878     if (map_heap_data(&open_archive_heap_ranges,
1879                       MetaspaceShared::first_open_archive_heap_region,
1880                       MetaspaceShared::max_open_archive_heap_region,
1881                       &num_open_archive_heap_ranges,
1882                       true /* open */)) {
1883       HeapShared::set_open_archive_heap_region_mapped();
1884       HeapShared::set_roots(header()->heap_obj_roots());
1885     }
1886   }
1887 }
1888 
1889 void FileMapInfo::map_heap_regions() {
1890   if (has_heap_regions()) {
1891     map_heap_regions_impl();
1892   }
1893 
1894   if (!HeapShared::closed_archive_heap_region_mapped()) {
1895     assert(closed_archive_heap_ranges == NULL &&
1896            num_closed_archive_heap_ranges == 0, "sanity");
1897   }
1898 
1899   if (!HeapShared::open_archive_heap_region_mapped()) {
1900     assert(open_archive_heap_ranges == NULL && num_open_archive_heap_ranges == 0, "sanity");
1901     MetaspaceShared::disable_full_module_graph();
1902   }
1903 }
1904 
1905 bool FileMapInfo::map_heap_data(MemRegion **heap_mem, int first,
1906                                 int max, int* num, bool is_open_archive) {
1907   MemRegion* regions = MemRegion::create_array(max, mtInternal);
1908 
1909   struct Cleanup {
1910     MemRegion* _regions;
1911     uint _length;
1912     bool _aborted;
1913     Cleanup(MemRegion* regions, uint length) : _regions(regions), _length(length), _aborted(true) { }
1914     ~Cleanup() { if (_aborted) { MemRegion::destroy_array(_regions, _length); } }
1915   } cleanup(regions, max);
1916 
1917   FileMapRegion* si;
1918   int region_num = 0;
1919 
1920   for (int i = first;
1921            i < first + max; i++) {
1922     si = space_at(i);
1923     size_t size = si->used();
1924     if (size > 0) {
1925       HeapWord* start = (HeapWord*)start_address_as_decoded_from_archive(si);
1926       regions[region_num] = MemRegion(start, size / HeapWordSize);
1927       region_num ++;
1928       log_info(cds)("Trying to map heap data: region[%d] at " INTPTR_FORMAT ", size = " SIZE_FORMAT_W(8) " bytes",
1929                     i, p2i(start), size);
1930     }
1931   }
1932 
1933   if (region_num == 0) {
1934     return false; // no archived java heap data
1935   }
1936 
1937   // Check that ranges are within the java heap
1938   if (!G1CollectedHeap::heap()->check_archive_addresses(regions, region_num)) {
1939     log_info(cds)("UseSharedSpaces: Unable to allocate region, range is not within java heap.");
1940     return false;
1941   }
1942 
1943   // allocate from java heap
1944   if (!G1CollectedHeap::heap()->alloc_archive_regions(
1945              regions, region_num, is_open_archive)) {
1946     log_info(cds)("UseSharedSpaces: Unable to allocate region, java heap range is already in use.");
1947     return false;
1948   }
1949 
1950   // Map the archived heap data. No need to call MemTracker::record_virtual_memory_type()
1951   // for mapped regions as they are part of the reserved java heap, which is
1952   // already recorded.
1953   for (int i = 0; i < region_num; i++) {
1954     si = space_at(first + i);
1955     char* addr = (char*)regions[i].start();
1956     char* base = os::map_memory(_fd, _full_path, si->file_offset(),
1957                                 addr, regions[i].byte_size(), si->read_only(),
1958                                 si->allow_exec());
1959     if (base == NULL || base != addr) {
1960       // dealloc the regions from java heap
1961       dealloc_archive_heap_regions(regions, region_num);
1962       log_info(cds)("UseSharedSpaces: Unable to map at required address in java heap. "
1963                     INTPTR_FORMAT ", size = " SIZE_FORMAT " bytes",
1964                     p2i(addr), regions[i].byte_size());
1965       return false;
1966     }
1967 
1968     if (VerifySharedSpaces && !region_crc_check(addr, regions[i].byte_size(), si->crc())) {
1969       // dealloc the regions from java heap
1970       dealloc_archive_heap_regions(regions, region_num);
1971       log_info(cds)("UseSharedSpaces: mapped heap regions are corrupt");
1972       return false;
1973     }
1974   }
1975 
1976   cleanup._aborted = false;
1977   // the shared heap data is mapped successfully
1978   *heap_mem = regions;
1979   *num = region_num;
1980   return true;
1981 }
1982 
1983 void FileMapInfo::patch_archived_heap_embedded_pointers() {
1984   if (!_heap_pointers_need_patching) {
1985     return;
1986   }
1987 
1988   log_info(cds)("patching heap embedded pointers");
1989   patch_archived_heap_embedded_pointers(closed_archive_heap_ranges,
1990                                         num_closed_archive_heap_ranges,
1991                                         MetaspaceShared::first_closed_archive_heap_region);
1992 
1993   patch_archived_heap_embedded_pointers(open_archive_heap_ranges,
1994                                         num_open_archive_heap_ranges,
1995                                         MetaspaceShared::first_open_archive_heap_region);
1996 }
1997 
1998 void FileMapInfo::patch_archived_heap_embedded_pointers(MemRegion* ranges, int num_ranges,
1999                                                         int first_region_idx) {
2000   char* bitmap_base = map_bitmap_region();
2001   if (bitmap_base == NULL) {
2002     return;
2003   }
2004   for (int i=0; i<num_ranges; i++) {
2005     FileMapRegion* si = space_at(i + first_region_idx);
2006     HeapShared::patch_archived_heap_embedded_pointers(
2007       ranges[i],
2008       (address)(space_at(MetaspaceShared::bm)->mapped_base()) + si->oopmap_offset(),
2009       si->oopmap_size_in_bits());
2010   }
2011 }
2012 
2013 // This internally allocates objects using vmClasses::Object_klass(), so it
2014 // must be called after the Object_klass is loaded
2015 void FileMapInfo::fixup_mapped_heap_regions() {
2016   assert(vmClasses::Object_klass_loaded(), "must be");
2017   // If any closed regions were found, call the fill routine to make them parseable.
2018   // Note that closed_archive_heap_ranges may be non-NULL even if no ranges were found.
2019   if (num_closed_archive_heap_ranges != 0) {
2020     assert(closed_archive_heap_ranges != NULL,
2021            "Null closed_archive_heap_ranges array with non-zero count");
2022     G1CollectedHeap::heap()->fill_archive_regions(closed_archive_heap_ranges,
2023                                                   num_closed_archive_heap_ranges);
2024   }
2025 
2026   // do the same for mapped open archive heap regions
2027   if (num_open_archive_heap_ranges != 0) {
2028     assert(open_archive_heap_ranges != NULL, "NULL open_archive_heap_ranges array with non-zero count");
2029     G1CollectedHeap::heap()->fill_archive_regions(open_archive_heap_ranges,
2030                                                   num_open_archive_heap_ranges);
2031 
2032     // Populate the open archive regions' G1BlockOffsetTableParts. That ensures
2033     // fast G1BlockOffsetTablePart::block_start operations for any given address
2034     // within the open archive regions when trying to find start of an object
2035     // (e.g. during card table scanning).
2036     //
2037     // This is only needed for open archive regions but not the closed archive
2038     // regions, because objects in closed archive regions never reference objects
2039     // outside the closed archive regions and they are immutable. So we never
2040     // need their BOT during garbage collection.
2041     G1CollectedHeap::heap()->populate_archive_regions_bot_part(open_archive_heap_ranges,
2042                                                                num_open_archive_heap_ranges);
2043   }
2044 }
2045 
2046 // dealloc the archive regions from java heap
2047 void FileMapInfo::dealloc_archive_heap_regions(MemRegion* regions, int num) {
2048   if (num > 0) {
2049     assert(regions != NULL, "Null archive ranges array with non-zero count");
2050     G1CollectedHeap::heap()->dealloc_archive_regions(regions, num);
2051   }
2052 }
2053 #endif // INCLUDE_CDS_JAVA_HEAP
2054 
2055 bool FileMapInfo::region_crc_check(char* buf, size_t size, int expected_crc) {
2056   int crc = ClassLoader::crc32(0, buf, (jint)size);
2057   if (crc != expected_crc) {
2058     fail_continue("Checksum verification failed.");
2059     return false;
2060   }
2061   return true;
2062 }
2063 
2064 bool FileMapInfo::verify_region_checksum(int i) {
2065   assert(VerifySharedSpaces, "sanity");
2066   size_t sz = space_at(i)->used();
2067 
2068   if (sz == 0) {
2069     return true; // no data
2070   } else {
2071     return region_crc_check(region_addr(i), sz, space_at(i)->crc());
2072   }
2073 }
2074 
2075 void FileMapInfo::unmap_regions(int regions[], int num_regions) {
2076   for (int r = 0; r < num_regions; r++) {
2077     int idx = regions[r];
2078     unmap_region(idx);
2079   }
2080 }
2081 
2082 // Unmap a memory region in the address space.
2083 
2084 void FileMapInfo::unmap_region(int i) {
2085   assert(!HeapShared::is_heap_region(i), "sanity");
2086   FileMapRegion* si = space_at(i);
2087   char* mapped_base = si->mapped_base();
2088   size_t size = si->used_aligned();
2089 
2090   if (mapped_base != NULL) {
2091     if (size > 0 && si->mapped_from_file()) {
2092       log_info(cds)("Unmapping region #%d at base " INTPTR_FORMAT " (%s)", i, p2i(mapped_base),
2093                     shared_region_name[i]);
2094       if (!os::unmap_memory(mapped_base, size)) {
2095         fatal("os::unmap_memory failed");
2096       }
2097     }
2098     si->set_mapped_base(NULL);
2099   }
2100 }
2101 
2102 void FileMapInfo::assert_mark(bool check) {
2103   if (!check) {
2104     fail_stop("Mark mismatch while restoring from shared file.");
2105   }
2106 }
2107 
2108 void FileMapInfo::metaspace_pointers_do(MetaspaceClosure* it, bool use_copy) {
2109   if (use_copy) {
2110     _saved_shared_path_table.metaspace_pointers_do(it);
2111   } else {
2112     _shared_path_table.metaspace_pointers_do(it);
2113   }
2114 }
2115 
2116 FileMapInfo* FileMapInfo::_current_info = NULL;
2117 FileMapInfo* FileMapInfo::_dynamic_archive_info = NULL;
2118 bool FileMapInfo::_heap_pointers_need_patching = false;
2119 SharedPathTable FileMapInfo::_shared_path_table;
2120 SharedPathTable FileMapInfo::_saved_shared_path_table;
2121 bool FileMapInfo::_validating_shared_path_table = false;
2122 bool FileMapInfo::_memory_mapping_failed = false;
2123 GrowableArray<const char*>* FileMapInfo::_non_existent_class_paths = NULL;
2124 
2125 // Open the shared archive file, read and validate the header
2126 // information (version, boot classpath, etc.).  If initialization
2127 // fails, shared spaces are disabled and the file is closed. [See
2128 // fail_continue.]
2129 //
2130 // Validation of the archive is done in two steps:
2131 //
2132 // [1] validate_header() - done here.
2133 // [2] validate_shared_path_table - this is done later, because the table is in the RW
2134 //     region of the archive, which is not mapped yet.
2135 bool FileMapInfo::initialize() {
2136   assert(UseSharedSpaces, "UseSharedSpaces expected.");
2137 
2138   if (JvmtiExport::should_post_class_file_load_hook() && JvmtiExport::has_early_class_hook_env()) {
2139     // CDS assumes that no classes resolved in vmClasses::resolve_all()
2140     // are replaced at runtime by JVMTI ClassFileLoadHook. All of those classes are resolved
2141     // during the JVMTI "early" stage, so we can still use CDS if
2142     // JvmtiExport::has_early_class_hook_env() is false.
2143     FileMapInfo::fail_continue("CDS is disabled because early JVMTI ClassFileLoadHook is in use.");
2144     return false;
2145   }
2146 
2147   if (!open_for_read()) {
2148     return false;
2149   }
2150   if (!init_from_file(_fd)) {
2151     return false;
2152   }
2153   if (!validate_header()) {
2154     return false;
2155   }
2156   return true;
2157 }
2158 
2159 char* FileMapInfo::region_addr(int idx) {
2160   FileMapRegion* si = space_at(idx);
2161   if (HeapShared::is_heap_region(idx)) {
2162     assert(DumpSharedSpaces, "The following doesn't work at runtime");
2163     return si->used() > 0 ?
2164           (char*)start_address_as_decoded_with_current_oop_encoding_mode(si) : NULL;
2165   } else {
2166     return si->mapped_base();
2167   }
2168 }
2169 
2170 // The 2 core spaces are RW->RO
2171 FileMapRegion* FileMapInfo::first_core_space() const {
2172   return space_at(MetaspaceShared::rw);
2173 }
2174 
2175 FileMapRegion* FileMapInfo::last_core_space() const {
2176   return space_at(MetaspaceShared::ro);
2177 }
2178 
2179 void FileMapHeader::set_as_offset(char* p, size_t *offset) {
2180   *offset = ArchiveBuilder::current()->any_to_offset((address)p);
2181 }
2182 
2183 int FileMapHeader::compute_crc() {
2184   char* start = (char*)this;
2185   // start computing from the field after _crc
2186   char* buf = (char*)&_crc + sizeof(_crc);
2187   size_t sz = _header_size - (buf - start);
2188   int crc = ClassLoader::crc32(0, buf, (jint)sz);
2189   return crc;
2190 }
2191 
2192 // This function should only be called during run time with UseSharedSpaces enabled.
2193 bool FileMapHeader::validate() {
2194   if (_obj_alignment != ObjectAlignmentInBytes) {
2195     FileMapInfo::fail_continue("The shared archive file's ObjectAlignmentInBytes of %d"
2196                   " does not equal the current ObjectAlignmentInBytes of " INTX_FORMAT ".",
2197                   _obj_alignment, ObjectAlignmentInBytes);
2198     return false;
2199   }
2200   if (_compact_strings != CompactStrings) {
2201     FileMapInfo::fail_continue("The shared archive file's CompactStrings setting (%s)"
2202                   " does not equal the current CompactStrings setting (%s).",
2203                   _compact_strings ? "enabled" : "disabled",
2204                   CompactStrings   ? "enabled" : "disabled");
2205     return false;
2206   }
2207 
2208   // This must be done after header validation because it might change the
2209   // header data
2210   const char* prop = Arguments::get_property("java.system.class.loader");
2211   if (prop != NULL) {
2212     warning("Archived non-system classes are disabled because the "
2213             "java.system.class.loader property is specified (value = \"%s\"). "
2214             "To use archived non-system classes, this property must not be set", prop);
2215     _has_platform_or_app_classes = false;
2216   }
2217 
2218 
2219   if (!_verify_local && BytecodeVerificationLocal) {
2220     //  we cannot load boot classes, so there's no point of using the CDS archive
2221     FileMapInfo::fail_continue("The shared archive file's BytecodeVerificationLocal setting (%s)"
2222                                " does not equal the current BytecodeVerificationLocal setting (%s).",
2223                                _verify_local ? "enabled" : "disabled",
2224                                BytecodeVerificationLocal ? "enabled" : "disabled");
2225     return false;
2226   }
2227 
2228   // For backwards compatibility, we don't check the BytecodeVerificationRemote setting
2229   // if the archive only contains system classes.
2230   if (_has_platform_or_app_classes
2231       && !_verify_remote // we didn't verify the archived platform/app classes
2232       && BytecodeVerificationRemote) { // but we want to verify all loaded platform/app classes
2233     FileMapInfo::fail_continue("The shared archive file was created with less restrictive "
2234                                "verification setting than the current setting.");
2235     // Pretend that we didn't have any archived platform/app classes, so they won't be loaded
2236     // by SystemDictionaryShared.
2237     _has_platform_or_app_classes = false;
2238   }
2239 
2240   // Java agents are allowed during run time. Therefore, the following condition is not
2241   // checked: (!_allow_archiving_with_java_agent && AllowArchivingWithJavaAgent)
2242   // Note: _allow_archiving_with_java_agent is set in the shared archive during dump time
2243   // while AllowArchivingWithJavaAgent is set during the current run.
2244   if (_allow_archiving_with_java_agent && !AllowArchivingWithJavaAgent) {
2245     FileMapInfo::fail_continue("The setting of the AllowArchivingWithJavaAgent is different "
2246                                "from the setting in the shared archive.");
2247     return false;
2248   }
2249 
2250   if (_allow_archiving_with_java_agent) {
2251     warning("This archive was created with AllowArchivingWithJavaAgent. It should be used "
2252             "for testing purposes only and should not be used in a production environment");
2253   }
2254 
2255   log_info(cds)("Archive was created with UseCompressedOops = %d, UseCompressedClassPointers = %d",
2256                           compressed_oops(), compressed_class_pointers());
2257   if (compressed_oops() != UseCompressedOops || compressed_class_pointers() != UseCompressedClassPointers) {
2258     FileMapInfo::fail_continue("Unable to use shared archive.\nThe saved state of UseCompressedOops and UseCompressedClassPointers is "
2259                                "different from runtime, CDS will be disabled.");
2260     return false;
2261   }
2262 
2263   if (compact_headers() != UseCompactObjectHeaders) {
2264     log_info(cds)("The shared archive file's UseCompactObjectHeaders setting (%s)"
2265                   " does not equal the current UseCompactObjectHeaders setting (%s).",
2266                   _compact_headers          ? "enabled" : "disabled",
2267                   UseCompactObjectHeaders   ? "enabled" : "disabled");
2268     return false;
2269   }
2270 
2271   if (!_use_optimized_module_handling) {
2272     MetaspaceShared::disable_optimized_module_handling();
2273     log_info(cds)("optimized module handling: disabled because archive was created without optimized module handling");
2274   }
2275 
2276   if (!_use_full_module_graph) {
2277     MetaspaceShared::disable_full_module_graph();
2278     log_info(cds)("full module graph: disabled because archive was created without full module graph");
2279   }
2280 
2281   return true;
2282 }
2283 
2284 bool FileMapInfo::validate_header() {
2285   if (!header()->validate()) {
2286     return false;
2287   }
2288   if (_is_static) {
2289     return true;
2290   } else {
2291     return DynamicArchive::validate(this);
2292   }
2293 }
2294 
2295 // Check if a given address is within one of the shared regions
2296 bool FileMapInfo::is_in_shared_region(const void* p, int idx) {
2297   assert(idx == MetaspaceShared::ro ||
2298          idx == MetaspaceShared::rw, "invalid region index");
2299   char* base = region_addr(idx);
2300   if (p >= base && p < base + space_at(idx)->used()) {
2301     return true;
2302   }
2303   return false;
2304 }
2305 
2306 // Unmap mapped regions of shared space.
2307 void FileMapInfo::stop_sharing_and_unmap(const char* msg) {
2308   MetaspaceShared::set_shared_metaspace_range(NULL, NULL, NULL);
2309 
2310   FileMapInfo *map_info = FileMapInfo::current_info();
2311   if (map_info) {
2312     map_info->fail_continue("%s", msg);
2313     for (int i = 0; i < MetaspaceShared::num_non_heap_spaces; i++) {
2314       if (!HeapShared::is_heap_region(i)) {
2315         map_info->unmap_region(i);
2316       }
2317     }
2318     // Dealloc the archive heap regions only without unmapping. The regions are part
2319     // of the java heap. Unmapping of the heap regions are managed by GC.
2320     map_info->dealloc_archive_heap_regions(open_archive_heap_ranges,
2321                                            num_open_archive_heap_ranges);
2322     map_info->dealloc_archive_heap_regions(closed_archive_heap_ranges,
2323                                            num_closed_archive_heap_ranges);
2324   } else if (DumpSharedSpaces) {
2325     fail_stop("%s", msg);
2326   }
2327 }
2328 
2329 #if INCLUDE_JVMTI
2330 ClassPathEntry** FileMapInfo::_classpath_entries_for_jvmti = NULL;
2331 
2332 ClassPathEntry* FileMapInfo::get_classpath_entry_for_jvmti(int i, TRAPS) {
2333   if (i == 0) {
2334     // index 0 corresponds to the ClassPathImageEntry which is a globally shared object
2335     // and should never be deleted.
2336     return ClassLoader::get_jrt_entry();
2337   }
2338   ClassPathEntry* ent = _classpath_entries_for_jvmti[i];
2339   if (ent == NULL) {
2340     SharedClassPathEntry* scpe = shared_path(i);
2341     assert(scpe->is_jar(), "must be"); // other types of scpe will not produce archived classes
2342 
2343     const char* path = scpe->name();
2344     struct stat st;
2345     if (os::stat(path, &st) != 0) {
2346       char *msg = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, strlen(path) + 128);
2347       jio_snprintf(msg, strlen(path) + 127, "error in finding JAR file %s", path);
2348       THROW_MSG_(vmSymbols::java_io_IOException(), msg, NULL);
2349     } else {
2350       ent = ClassLoader::create_class_path_entry(THREAD, path, &st, false, false);
2351       if (ent == NULL) {
2352         char *msg = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, strlen(path) + 128);
2353         jio_snprintf(msg, strlen(path) + 127, "error in opening JAR file %s", path);
2354         THROW_MSG_(vmSymbols::java_io_IOException(), msg, NULL);
2355       }
2356     }
2357 
2358     MutexLocker mu(THREAD, CDSClassFileStream_lock);
2359     if (_classpath_entries_for_jvmti[i] == NULL) {
2360       _classpath_entries_for_jvmti[i] = ent;
2361     } else {
2362       // Another thread has beat me to creating this entry
2363       delete ent;
2364       ent = _classpath_entries_for_jvmti[i];
2365     }
2366   }
2367 
2368   return ent;
2369 }
2370 
2371 ClassFileStream* FileMapInfo::open_stream_for_jvmti(InstanceKlass* ik, Handle class_loader, TRAPS) {
2372   int path_index = ik->shared_classpath_index();
2373   assert(path_index >= 0, "should be called for shared built-in classes only");
2374   assert(path_index < (int)get_number_of_shared_paths(), "sanity");
2375 
2376   ClassPathEntry* cpe = get_classpath_entry_for_jvmti(path_index, CHECK_NULL);
2377   assert(cpe != NULL, "must be");
2378 
2379   Symbol* name = ik->name();
2380   const char* const class_name = name->as_C_string();
2381   const char* const file_name = ClassLoader::file_name_for_class_name(class_name,
2382                                                                       name->utf8_length());
2383   ClassLoaderData* loader_data = ClassLoaderData::class_loader_data(class_loader());
2384   ClassFileStream* cfs = cpe->open_stream_for_loader(THREAD, file_name, loader_data);
2385   assert(cfs != NULL, "must be able to read the classfile data of shared classes for built-in loaders.");
2386   log_debug(cds, jvmti)("classfile data for %s [%d: %s] = %d bytes", class_name, path_index,
2387                         cfs->source(), cfs->length());
2388   return cfs;
2389 }
2390 
2391 #endif