1 /*
   2  * Copyright (c) 2003, 2025, 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 "cds/archiveBuilder.hpp"
  26 #include "cds/archiveHeapLoader.inline.hpp"
  27 #include "cds/archiveHeapWriter.hpp"
  28 #include "cds/archiveUtils.inline.hpp"
  29 #include "cds/cds_globals.hpp"
  30 #include "cds/cdsConfig.hpp"
  31 #include "cds/dynamicArchive.hpp"
  32 #include "cds/filemap.hpp"
  33 #include "cds/heapShared.hpp"
  34 #include "cds/metaspaceShared.hpp"
  35 #include "classfile/altHashing.hpp"
  36 #include "classfile/classFileStream.hpp"
  37 #include "classfile/classLoader.hpp"
  38 #include "classfile/classLoader.inline.hpp"
  39 #include "classfile/classLoaderData.inline.hpp"
  40 #include "classfile/classLoaderExt.hpp"
  41 #include "classfile/symbolTable.hpp"
  42 #include "classfile/systemDictionaryShared.hpp"
  43 #include "classfile/vmClasses.hpp"
  44 #include "classfile/vmSymbols.hpp"
  45 #include "jvm.h"
  46 #include "logging/log.hpp"
  47 #include "logging/logMessage.hpp"
  48 #include "logging/logStream.hpp"
  49 #include "memory/iterator.inline.hpp"
  50 #include "memory/metadataFactory.hpp"
  51 #include "memory/metaspaceClosure.hpp"
  52 #include "memory/oopFactory.hpp"
  53 #include "memory/universe.hpp"
  54 #include "nmt/memTracker.hpp"
  55 #include "oops/access.hpp"
  56 #include "oops/compressedOops.hpp"
  57 #include "oops/compressedOops.inline.hpp"
  58 #include "oops/compressedKlass.hpp"
  59 #include "oops/objArrayOop.hpp"
  60 #include "oops/oop.inline.hpp"
  61 #include "oops/typeArrayKlass.hpp"
  62 #include "prims/jvmtiExport.hpp"
  63 #include "runtime/arguments.hpp"
  64 #include "runtime/globals_extension.hpp"
  65 #include "runtime/java.hpp"
  66 #include "runtime/javaCalls.hpp"
  67 #include "runtime/mutexLocker.hpp"
  68 #include "runtime/os.hpp"
  69 #include "runtime/vm_version.hpp"
  70 #include "utilities/align.hpp"
  71 #include "utilities/bitMap.inline.hpp"
  72 #include "utilities/classpathStream.hpp"
  73 #include "utilities/defaultStream.hpp"
  74 #include "utilities/ostream.hpp"
  75 #if INCLUDE_G1GC
  76 #include "gc/g1/g1CollectedHeap.hpp"
  77 #include "gc/g1/g1HeapRegion.hpp"
  78 #endif
  79 
  80 # include <sys/stat.h>
  81 # include <errno.h>
  82 
  83 #ifndef O_BINARY       // if defined (Win32) use binary files.
  84 #define O_BINARY 0     // otherwise do nothing.
  85 #endif
  86 
  87 // Fill in the fileMapInfo structure with data about this VM instance.
  88 
  89 // This method copies the vm version info into header_version.  If the version is too
  90 // long then a truncated version, which has a hash code appended to it, is copied.
  91 //
  92 // Using a template enables this method to verify that header_version is an array of
  93 // length JVM_IDENT_MAX.  This ensures that the code that writes to the CDS file and
  94 // the code that reads the CDS file will both use the same size buffer.  Hence, will
  95 // use identical truncation.  This is necessary for matching of truncated versions.
  96 template <int N> static void get_header_version(char (&header_version) [N]) {
  97   assert(N == JVM_IDENT_MAX, "Bad header_version size");
  98 
  99   const char *vm_version = VM_Version::internal_vm_info_string();
 100   const int version_len = (int)strlen(vm_version);
 101 
 102   memset(header_version, 0, JVM_IDENT_MAX);
 103 
 104   if (version_len < (JVM_IDENT_MAX-1)) {
 105     strcpy(header_version, vm_version);
 106 
 107   } else {
 108     // Get the hash value.  Use a static seed because the hash needs to return the same
 109     // value over multiple jvm invocations.
 110     uint32_t hash = AltHashing::halfsiphash_32(8191, (const uint8_t*)vm_version, version_len);
 111 
 112     // Truncate the ident, saving room for the 8 hex character hash value.
 113     strncpy(header_version, vm_version, JVM_IDENT_MAX-9);
 114 
 115     // Append the hash code as eight hex digits.
 116     os::snprintf_checked(&header_version[JVM_IDENT_MAX-9], 9, "%08x", hash);
 117     header_version[JVM_IDENT_MAX-1] = 0;  // Null terminate.
 118   }
 119 
 120   assert(header_version[JVM_IDENT_MAX-1] == 0, "must be");
 121 }
 122 
 123 FileMapInfo::FileMapInfo(const char* full_path, bool is_static) :
 124   _is_static(is_static), _file_open(false), _is_mapped(false), _fd(-1), _file_offset(0),
 125   _full_path(full_path), _base_archive_name(nullptr), _header(nullptr) {
 126   if (_is_static) {
 127     assert(_current_info == nullptr, "must be singleton"); // not thread safe
 128     _current_info = this;
 129   } else {
 130     assert(_dynamic_archive_info == nullptr, "must be singleton"); // not thread safe
 131     _dynamic_archive_info = this;
 132   }
 133 }
 134 
 135 FileMapInfo::~FileMapInfo() {
 136   if (_is_static) {
 137     assert(_current_info == this, "must be singleton"); // not thread safe
 138     _current_info = nullptr;
 139   } else {
 140     assert(_dynamic_archive_info == this, "must be singleton"); // not thread safe
 141     _dynamic_archive_info = nullptr;
 142   }
 143 
 144   if (_header != nullptr) {
 145     os::free(_header);
 146   }
 147 
 148   if (_file_open) {
 149     ::close(_fd);
 150   }
 151 }
 152 
 153 void FileMapInfo::populate_header(size_t core_region_alignment) {
 154   assert(_header == nullptr, "Sanity check");
 155   size_t c_header_size;
 156   size_t header_size;
 157   size_t base_archive_name_size = 0;
 158   size_t base_archive_name_offset = 0;
 159   size_t longest_common_prefix_size = 0;
 160   if (is_static()) {
 161     c_header_size = sizeof(FileMapHeader);
 162     header_size = c_header_size;
 163   } else {
 164     // dynamic header including base archive name for non-default base archive
 165     c_header_size = sizeof(DynamicArchiveHeader);
 166     header_size = c_header_size;
 167 
 168     const char* default_base_archive_name = CDSConfig::default_archive_path();
 169     const char* current_base_archive_name = CDSConfig::static_archive_path();
 170     if (!os::same_files(current_base_archive_name, default_base_archive_name)) {
 171       base_archive_name_size = strlen(current_base_archive_name) + 1;
 172       header_size += base_archive_name_size;
 173       base_archive_name_offset = c_header_size;
 174     }
 175   }
 176   ResourceMark rm;
 177   GrowableArray<const char*>* app_cp_array = create_dumptime_app_classpath_array();
 178   int len = app_cp_array->length();
 179   longest_common_prefix_size = longest_common_app_classpath_prefix_len(len, app_cp_array);
 180   _header = (FileMapHeader*)os::malloc(header_size, mtInternal);
 181   memset((void*)_header, 0, header_size);
 182   _header->populate(this,
 183                     core_region_alignment,
 184                     header_size,
 185                     base_archive_name_size,
 186                     base_archive_name_offset,
 187                     longest_common_prefix_size);
 188 }
 189 
 190 void FileMapHeader::populate(FileMapInfo *info, size_t core_region_alignment,
 191                              size_t header_size, size_t base_archive_name_size,
 192                              size_t base_archive_name_offset, size_t common_app_classpath_prefix_size) {
 193   // 1. We require _generic_header._magic to be at the beginning of the file
 194   // 2. FileMapHeader also assumes that _generic_header is at the beginning of the file
 195   assert(offset_of(FileMapHeader, _generic_header) == 0, "must be");
 196   set_header_size((unsigned int)header_size);
 197   set_base_archive_name_offset((unsigned int)base_archive_name_offset);
 198   set_base_archive_name_size((unsigned int)base_archive_name_size);
 199   set_common_app_classpath_prefix_size((unsigned int)common_app_classpath_prefix_size);
 200   set_magic(CDSConfig::is_dumping_dynamic_archive() ? CDS_DYNAMIC_ARCHIVE_MAGIC : CDS_ARCHIVE_MAGIC);
 201   set_version(CURRENT_CDS_ARCHIVE_VERSION);
 202 
 203   if (!info->is_static() && base_archive_name_size != 0) {
 204     // copy base archive name
 205     copy_base_archive_name(CDSConfig::static_archive_path());
 206   }
 207   _core_region_alignment = core_region_alignment;
 208   _obj_alignment = ObjectAlignmentInBytes;
 209   _compact_strings = CompactStrings;
 210   _compact_headers = UseCompactObjectHeaders;
 211   if (CDSConfig::is_dumping_heap()) {
 212     _narrow_oop_mode = CompressedOops::mode();
 213     _narrow_oop_base = CompressedOops::base();
 214     _narrow_oop_shift = CompressedOops::shift();
 215   }
 216   _compressed_oops = UseCompressedOops;
 217   _compressed_class_ptrs = UseCompressedClassPointers;
 218   if (UseCompressedClassPointers) {
 219 #ifdef _LP64
 220     _narrow_klass_pointer_bits = CompressedKlassPointers::narrow_klass_pointer_bits();
 221     _narrow_klass_shift = ArchiveBuilder::precomputed_narrow_klass_shift();
 222 #endif
 223   } else {
 224     _narrow_klass_pointer_bits = _narrow_klass_shift = -1;
 225   }
 226   _max_heap_size = MaxHeapSize;
 227   _use_optimized_module_handling = CDSConfig::is_using_optimized_module_handling();
 228   _has_aot_linked_classes = CDSConfig::is_dumping_aot_linked_classes();
 229   _has_full_module_graph = CDSConfig::is_dumping_full_module_graph();
 230   _has_archived_invokedynamic = CDSConfig::is_dumping_invokedynamic();
 231 
 232   // The following fields are for sanity checks for whether this archive
 233   // will function correctly with this JVM and the bootclasspath it's
 234   // invoked with.
 235 
 236   // JVM version string ... changes on each build.
 237   get_header_version(_jvm_ident);
 238 
 239   _app_class_paths_start_index = ClassLoaderExt::app_class_paths_start_index();
 240   _app_module_paths_start_index = ClassLoaderExt::app_module_paths_start_index();
 241   _max_used_path_index = ClassLoaderExt::max_used_path_index();
 242   _num_module_paths = ClassLoader::num_module_path_entries();
 243 
 244   _verify_local = BytecodeVerificationLocal;
 245   _verify_remote = BytecodeVerificationRemote;
 246   _has_platform_or_app_classes = ClassLoaderExt::has_platform_or_app_classes();
 247   _has_non_jar_in_classpath = ClassLoaderExt::has_non_jar_in_classpath();
 248   _requested_base_address = (char*)SharedBaseAddress;
 249   _mapped_base_address = (char*)SharedBaseAddress;
 250   _allow_archiving_with_java_agent = AllowArchivingWithJavaAgent;
 251 
 252   if (!CDSConfig::is_dumping_dynamic_archive()) {
 253     set_shared_path_table(info->_shared_path_table);
 254   }
 255 }
 256 
 257 void FileMapHeader::copy_base_archive_name(const char* archive) {
 258   assert(base_archive_name_size() != 0, "_base_archive_name_size not set");
 259   assert(base_archive_name_offset() != 0, "_base_archive_name_offset not set");
 260   assert(header_size() > sizeof(*this), "_base_archive_name_size not included in header size?");
 261   memcpy((char*)this + base_archive_name_offset(), archive, base_archive_name_size());
 262 }
 263 
 264 void FileMapHeader::print(outputStream* st) {
 265   ResourceMark rm;
 266 
 267   st->print_cr("- magic:                          0x%08x", magic());
 268   st->print_cr("- crc:                            0x%08x", crc());
 269   st->print_cr("- version:                        0x%x", version());
 270   st->print_cr("- header_size:                    " UINT32_FORMAT, header_size());
 271   st->print_cr("- common_app_classpath_size:      " UINT32_FORMAT, common_app_classpath_prefix_size());
 272   st->print_cr("- base_archive_name_offset:       " UINT32_FORMAT, base_archive_name_offset());
 273   st->print_cr("- base_archive_name_size:         " UINT32_FORMAT, base_archive_name_size());
 274 
 275   for (int i = 0; i < NUM_CDS_REGIONS; i++) {
 276     FileMapRegion* r = region_at(i);
 277     r->print(st, i);
 278   }
 279   st->print_cr("============ end regions ======== ");
 280 
 281   st->print_cr("- core_region_alignment:          %zu", _core_region_alignment);
 282   st->print_cr("- obj_alignment:                  %d", _obj_alignment);
 283   st->print_cr("- narrow_oop_base:                " INTPTR_FORMAT, p2i(_narrow_oop_base));
 284   st->print_cr("- narrow_oop_shift                %d", _narrow_oop_shift);
 285   st->print_cr("- compact_strings:                %d", _compact_strings);
 286   st->print_cr("- compact_headers:                %d", _compact_headers);
 287   st->print_cr("- max_heap_size:                  %zu", _max_heap_size);
 288   st->print_cr("- narrow_oop_mode:                %d", _narrow_oop_mode);
 289   st->print_cr("- compressed_oops:                %d", _compressed_oops);
 290   st->print_cr("- compressed_class_ptrs:          %d", _compressed_class_ptrs);
 291   st->print_cr("- narrow_klass_pointer_bits:      %d", _narrow_klass_pointer_bits);
 292   st->print_cr("- narrow_klass_shift:             %d", _narrow_klass_shift);
 293   st->print_cr("- cloned_vtables_offset:          0x%zx", _cloned_vtables_offset);
 294   st->print_cr("- early_serialized_data_offset:   0x%zx", _early_serialized_data_offset);
 295   st->print_cr("- serialized_data_offset:         0x%zx", _serialized_data_offset);
 296   st->print_cr("- jvm_ident:                      %s", _jvm_ident);
 297   st->print_cr("- shared_path_table_offset:       0x%zx", _shared_path_table_offset);
 298   st->print_cr("- app_class_paths_start_index:    %d", _app_class_paths_start_index);
 299   st->print_cr("- app_module_paths_start_index:   %d", _app_module_paths_start_index);
 300   st->print_cr("- num_module_paths:               %d", _num_module_paths);
 301   st->print_cr("- max_used_path_index:            %d", _max_used_path_index);
 302   st->print_cr("- verify_local:                   %d", _verify_local);
 303   st->print_cr("- verify_remote:                  %d", _verify_remote);
 304   st->print_cr("- has_platform_or_app_classes:    %d", _has_platform_or_app_classes);
 305   st->print_cr("- has_non_jar_in_classpath:       %d", _has_non_jar_in_classpath);
 306   st->print_cr("- requested_base_address:         " INTPTR_FORMAT, p2i(_requested_base_address));
 307   st->print_cr("- mapped_base_address:            " INTPTR_FORMAT, p2i(_mapped_base_address));
 308   st->print_cr("- heap_root_segments.roots_count: %d" , _heap_root_segments.roots_count());
 309   st->print_cr("- heap_root_segments.base_offset: 0x%zx", _heap_root_segments.base_offset());
 310   st->print_cr("- heap_root_segments.count:       %zu", _heap_root_segments.count());
 311   st->print_cr("- heap_root_segments.max_size_elems: %d", _heap_root_segments.max_size_in_elems());
 312   st->print_cr("- heap_root_segments.max_size_bytes: %d", _heap_root_segments.max_size_in_bytes());
 313   st->print_cr("- _heap_oopmap_start_pos:         %zu", _heap_oopmap_start_pos);
 314   st->print_cr("- _heap_ptrmap_start_pos:         %zu", _heap_ptrmap_start_pos);
 315   st->print_cr("- _rw_ptrmap_start_pos:           %zu", _rw_ptrmap_start_pos);
 316   st->print_cr("- _ro_ptrmap_start_pos:           %zu", _ro_ptrmap_start_pos);
 317   st->print_cr("- allow_archiving_with_java_agent:%d", _allow_archiving_with_java_agent);
 318   st->print_cr("- use_optimized_module_handling:  %d", _use_optimized_module_handling);
 319   st->print_cr("- has_full_module_graph           %d", _has_full_module_graph);
 320   st->print_cr("- has_aot_linked_classes          %d", _has_aot_linked_classes);
 321   st->print_cr("- has_archived_invokedynamic      %d", _has_archived_invokedynamic);
 322 }
 323 
 324 void SharedClassPathEntry::init_as_non_existent(const char* path, TRAPS) {
 325   _type = non_existent_entry;
 326   set_name(path, CHECK);
 327 }
 328 
 329 void SharedClassPathEntry::init(bool is_modules_image,
 330                                 bool is_module_path,
 331                                 ClassPathEntry* cpe, TRAPS) {
 332   assert(CDSConfig::is_dumping_archive(), "sanity");
 333   _timestamp = 0;
 334   _filesize  = 0;
 335   _from_class_path_attr = false;
 336 
 337   struct stat st;
 338   if (os::stat(cpe->name(), &st) == 0) {
 339     if ((st.st_mode & S_IFMT) == S_IFDIR) {
 340       _type = dir_entry;
 341     } else {
 342       // The timestamp of the modules_image is not checked at runtime.
 343       if (is_modules_image) {
 344         _type = modules_image_entry;
 345       } else {
 346         _type = jar_entry;
 347         _timestamp = st.st_mtime;
 348         _from_class_path_attr = cpe->from_class_path_attr();
 349         _is_multi_release = cpe->is_multi_release_jar();
 350       }
 351       _filesize = st.st_size;
 352       _is_module_path = is_module_path;
 353     }
 354   } else {
 355     // The file/dir must exist, or it would not have been added
 356     // into ClassLoader::classpath_entry().
 357     //
 358     // If we can't access a jar file in the boot path, then we can't
 359     // make assumptions about where classes get loaded from.
 360     log_error(cds)("Unable to open file %s.", cpe->name());
 361     MetaspaceShared::unrecoverable_loading_error();
 362   }
 363 
 364   // No need to save the name of the module file, as it will be computed at run time
 365   // to allow relocation of the JDK directory.
 366   const char* name = is_modules_image  ? "" : cpe->name();
 367   set_name(name, CHECK);
 368 }
 369 
 370 void SharedClassPathEntry::set_name(const char* name, TRAPS) {
 371   size_t len = strlen(name) + 1;
 372   _name = MetadataFactory::new_array<char>(ClassLoaderData::the_null_class_loader_data(), (int)len, CHECK);
 373   strcpy(_name->data(), name);
 374 }
 375 
 376 void SharedClassPathEntry::copy_from(SharedClassPathEntry* ent, ClassLoaderData* loader_data, TRAPS) {
 377   assert(ent != nullptr, "sanity");
 378   _type = ent->_type;
 379   _is_module_path = ent->_is_module_path;
 380   _timestamp = ent->_timestamp;
 381   _filesize = ent->_filesize;
 382   _from_class_path_attr = ent->_from_class_path_attr;
 383   set_name(ent->name(), CHECK);
 384 
 385   if (ent->is_jar() && ent->manifest() != nullptr) {
 386     Array<u1>* buf = MetadataFactory::new_array<u1>(loader_data,
 387                                                     ent->manifest_size(),
 388                                                     CHECK);
 389     char* p = (char*)(buf->data());
 390     memcpy(p, ent->manifest(), ent->manifest_size());
 391     set_manifest(buf);
 392   }
 393 }
 394 
 395 const char* SharedClassPathEntry::name() const {
 396   if (CDSConfig::is_using_archive() && is_modules_image()) {
 397     // In order to validate the runtime modules image file size against the archived
 398     // size information, we need to obtain the runtime modules image path. The recorded
 399     // dump time modules image path in the archive may be different from the runtime path
 400     // if the JDK image has beed moved after generating the archive.
 401     return ClassLoader::get_jrt_entry()->name();
 402   } else {
 403     return _name->data();
 404   }
 405 }
 406 
 407 bool SharedClassPathEntry::validate(bool is_class_path) const {
 408   assert(CDSConfig::is_using_archive(), "runtime only");
 409 
 410   struct stat st;
 411   const char* name = this->name();
 412 
 413   bool ok = true;
 414   log_info(class, path)("checking shared classpath entry: %s", name);
 415   if (os::stat(name, &st) != 0 && is_class_path) {
 416     // If the archived module path entry does not exist at runtime, it is not fatal
 417     // (no need to invalid the shared archive) because the shared runtime visibility check
 418     // filters out any archived module classes that do not have a matching runtime
 419     // module path location.
 420     log_warning(cds)("Required classpath entry does not exist: %s", name);
 421     ok = false;
 422   } else if (is_dir()) {
 423     if (!os::dir_is_empty(name)) {
 424       log_warning(cds)("directory is not empty: %s", name);
 425       ok = false;
 426     }
 427   } else {
 428     bool size_differs = _filesize != st.st_size;
 429     bool time_differs = has_timestamp() && _timestamp != st.st_mtime;
 430     if (time_differs || size_differs) {
 431       ok = false;
 432       if (PrintSharedArchiveAndExit) {
 433         log_warning(cds)(time_differs ? "Timestamp mismatch" : "File size mismatch");
 434       } else {
 435         const char* bad_file_msg = "This file is not the one used while building the shared archive file:";
 436         log_warning(cds)("%s %s", bad_file_msg, name);
 437         if (!log_is_enabled(Info, cds)) {
 438           log_warning(cds)("%s %s", bad_file_msg, name);
 439         }
 440         if (time_differs) {
 441           log_warning(cds)("%s timestamp has changed.", name);
 442         }
 443         if (size_differs) {
 444           log_warning(cds)("%s size has changed.", name);
 445         }
 446       }
 447     }
 448   }
 449 
 450   if (PrintSharedArchiveAndExit && !ok) {
 451     // If PrintSharedArchiveAndExit is enabled, don't report failure to the
 452     // caller. Please see above comments for more details.
 453     ok = true;
 454     MetaspaceShared::set_archive_loading_failed();
 455   }
 456   return ok;
 457 }
 458 
 459 bool SharedClassPathEntry::check_non_existent() const {
 460   assert(_type == non_existent_entry, "must be");
 461   log_info(class, path)("should be non-existent: %s", name());
 462   struct stat st;
 463   if (os::stat(name(), &st) != 0) {
 464     log_info(class, path)("ok");
 465     return true; // file doesn't exist
 466   } else {
 467     return false;
 468   }
 469 }
 470 
 471 void SharedClassPathEntry::metaspace_pointers_do(MetaspaceClosure* it) {
 472   it->push(&_name);
 473   it->push(&_manifest);
 474 }
 475 
 476 void SharedPathTable::metaspace_pointers_do(MetaspaceClosure* it) {
 477   it->push(&_entries);
 478 }
 479 
 480 void SharedPathTable::dumptime_init(ClassLoaderData* loader_data, TRAPS) {
 481   const int num_entries =
 482     ClassLoader::num_boot_classpath_entries() +
 483     ClassLoader::num_app_classpath_entries() +
 484     ClassLoader::num_module_path_entries() +
 485     FileMapInfo::num_non_existent_class_paths();
 486   _entries = MetadataFactory::new_array<SharedClassPathEntry*>(loader_data, num_entries, CHECK);
 487   for (int i = 0; i < num_entries; i++) {
 488     SharedClassPathEntry* ent =
 489       new (loader_data, SharedClassPathEntry::size(), MetaspaceObj::SharedClassPathEntryType, THREAD) SharedClassPathEntry;
 490     _entries->at_put(i, ent);
 491   }
 492 }
 493 
 494 void FileMapInfo::allocate_shared_path_table(TRAPS) {
 495   assert(CDSConfig::is_dumping_archive(), "sanity");
 496 
 497   ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data();
 498   ClassPathEntry* jrt = ClassLoader::get_jrt_entry();
 499 
 500   assert(jrt != nullptr,
 501          "No modular java runtime image present when allocating the CDS classpath entry table");
 502 
 503   _shared_path_table.dumptime_init(loader_data, CHECK);
 504 
 505   // 1. boot class path
 506   int i = 0;
 507   i = add_shared_classpaths(i, "boot",   jrt, CHECK);
 508   i = add_shared_classpaths(i, "app",    ClassLoader::app_classpath_entries(), CHECK);
 509   i = add_shared_classpaths(i, "module", ClassLoader::module_path_entries(), CHECK);
 510 
 511   for (int x = 0; x < num_non_existent_class_paths(); x++, i++) {
 512     const char* path = _non_existent_class_paths->at(x);
 513     shared_path(i)->init_as_non_existent(path, CHECK);
 514   }
 515 
 516   assert(i == _shared_path_table.size(), "number of shared path entry mismatch");
 517 }
 518 
 519 int FileMapInfo::add_shared_classpaths(int i, const char* which, ClassPathEntry *cpe, TRAPS) {
 520   while (cpe != nullptr) {
 521     bool is_jrt = (cpe == ClassLoader::get_jrt_entry());
 522     bool is_module_path = i >= ClassLoaderExt::app_module_paths_start_index();
 523     const char* type = (is_jrt ? "jrt" : (cpe->is_jar_file() ? "jar" : "dir"));
 524     log_info(class, path)("add %s shared path (%s) %s", which, type, cpe->name());
 525     SharedClassPathEntry* ent = shared_path(i);
 526     ent->init(is_jrt, is_module_path, cpe, CHECK_0);
 527     if (cpe->is_jar_file()) {
 528       update_jar_manifest(cpe, ent, CHECK_0);
 529     }
 530     if (is_jrt) {
 531       cpe = ClassLoader::get_next_boot_classpath_entry(cpe);
 532     } else {
 533       cpe = cpe->next();
 534     }
 535     i++;
 536   }
 537 
 538   return i;
 539 }
 540 
 541 void FileMapInfo::check_nonempty_dir_in_shared_path_table() {
 542   assert(CDSConfig::is_dumping_archive(), "sanity");
 543 
 544   bool has_nonempty_dir = false;
 545 
 546   int last = _shared_path_table.size() - 1;
 547   if (last > ClassLoaderExt::max_used_path_index()) {
 548      // no need to check any path beyond max_used_path_index
 549      last = ClassLoaderExt::max_used_path_index();
 550   }
 551 
 552   for (int i = 0; i <= last; i++) {
 553     SharedClassPathEntry *e = shared_path(i);
 554     if (e->is_dir()) {
 555       const char* path = e->name();
 556       if (!os::dir_is_empty(path)) {
 557         log_error(cds)("Error: non-empty directory '%s'", path);
 558         has_nonempty_dir = true;
 559       }
 560     }
 561   }
 562 
 563   if (has_nonempty_dir) {
 564     ClassLoader::exit_with_path_failure("Cannot have non-empty directory in paths", nullptr);
 565   }
 566 }
 567 
 568 void FileMapInfo::record_non_existent_class_path_entry(const char* path) {
 569   assert(CDSConfig::is_dumping_archive(), "sanity");
 570   log_info(class, path)("non-existent Class-Path entry %s", path);
 571   if (_non_existent_class_paths == nullptr) {
 572     _non_existent_class_paths = new (mtClass) GrowableArray<const char*>(10, mtClass);
 573   }
 574   _non_existent_class_paths->append(os::strdup(path));
 575 }
 576 
 577 int FileMapInfo::num_non_existent_class_paths() {
 578   assert(CDSConfig::is_dumping_archive(), "sanity");
 579   if (_non_existent_class_paths != nullptr) {
 580     return _non_existent_class_paths->length();
 581   } else {
 582     return 0;
 583   }
 584 }
 585 
 586 int FileMapInfo::get_module_shared_path_index(Symbol* location) {
 587   if (location->starts_with("jrt:", 4) && get_number_of_shared_paths() > 0) {
 588     assert(shared_path(0)->is_modules_image(), "first shared_path must be the modules image");
 589     return 0;
 590   }
 591 
 592   if (ClassLoaderExt::app_module_paths_start_index() >= get_number_of_shared_paths()) {
 593     // The archive(s) were created without --module-path option
 594     return -1;
 595   }
 596 
 597   if (!location->starts_with("file:", 5)) {
 598     return -1;
 599   }
 600 
 601   // skip_uri_protocol was also called during dump time -- see ClassLoaderExt::process_module_table()
 602   ResourceMark rm;
 603   const char* file = ClassLoader::uri_to_path(location->as_C_string());
 604   for (int i = ClassLoaderExt::app_module_paths_start_index(); i < get_number_of_shared_paths(); i++) {
 605     SharedClassPathEntry* ent = shared_path(i);
 606     if (!ent->is_non_existent()) {
 607       assert(ent->in_named_module(), "must be");
 608       bool cond = strcmp(file, ent->name()) == 0;
 609       log_debug(class, path)("get_module_shared_path_index (%d) %s : %s = %s", i,
 610                              location->as_C_string(), ent->name(), cond ? "same" : "different");
 611       if (cond) {
 612         return i;
 613       }
 614     }
 615   }
 616 
 617   return -1;
 618 }
 619 
 620 class ManifestStream: public ResourceObj {
 621   private:
 622   u1*   _buffer_start; // Buffer bottom
 623   u1*   _buffer_end;   // Buffer top (one past last element)
 624   u1*   _current;      // Current buffer position
 625 
 626  public:
 627   // Constructor
 628   ManifestStream(u1* buffer, int length) : _buffer_start(buffer),
 629                                            _current(buffer) {
 630     _buffer_end = buffer + length;
 631   }
 632 
 633   static bool is_attr(u1* attr, const char* name) {
 634     return strncmp((const char*)attr, name, strlen(name)) == 0;
 635   }
 636 
 637   static char* copy_attr(u1* value, size_t len) {
 638     char* buf = NEW_RESOURCE_ARRAY(char, len + 1);
 639     strncpy(buf, (char*)value, len);
 640     buf[len] = 0;
 641     return buf;
 642   }
 643 };
 644 
 645 void FileMapInfo::update_jar_manifest(ClassPathEntry *cpe, SharedClassPathEntry* ent, TRAPS) {
 646   ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data();
 647   ResourceMark rm(THREAD);
 648   jint manifest_size;
 649 
 650   assert(cpe->is_jar_file() && ent->is_jar(), "the shared class path entry is not a JAR file");
 651   char* manifest = ClassLoaderExt::read_manifest(THREAD, cpe, &manifest_size);
 652   if (manifest != nullptr) {
 653     ManifestStream* stream = new ManifestStream((u1*)manifest,
 654                                                 manifest_size);
 655     // Copy the manifest into the shared archive
 656     manifest = ClassLoaderExt::read_raw_manifest(THREAD, cpe, &manifest_size);
 657     Array<u1>* buf = MetadataFactory::new_array<u1>(loader_data,
 658                                                     manifest_size,
 659                                                     CHECK);
 660     char* p = (char*)(buf->data());
 661     memcpy(p, manifest, manifest_size);
 662     ent->set_manifest(buf);
 663   }
 664 }
 665 
 666 char* FileMapInfo::skip_first_path_entry(const char* path) {
 667   size_t path_sep_len = strlen(os::path_separator());
 668   char* p = strstr((char*)path, os::path_separator());
 669   if (p != nullptr) {
 670     debug_only( {
 671       size_t image_name_len = strlen(MODULES_IMAGE_NAME);
 672       assert(strncmp(p - image_name_len, MODULES_IMAGE_NAME, image_name_len) == 0,
 673              "first entry must be the modules image");
 674     } );
 675     p += path_sep_len;
 676   } else {
 677     debug_only( {
 678       assert(ClassLoader::string_ends_with(path, MODULES_IMAGE_NAME),
 679              "first entry must be the modules image");
 680     } );
 681   }
 682   return p;
 683 }
 684 
 685 int FileMapInfo::num_paths(const char* path) {
 686   if (path == nullptr) {
 687     return 0;
 688   }
 689   int npaths = 1;
 690   char* p = (char*)path;
 691   while (p != nullptr) {
 692     char* prev = p;
 693     p = strstr((char*)p, os::path_separator());
 694     if (p != nullptr) {
 695       p++;
 696       // don't count empty path
 697       if ((p - prev) > 1) {
 698        npaths++;
 699       }
 700     }
 701   }
 702   return npaths;
 703 }
 704 
 705 // Returns true if a path within the paths exists and has non-zero size.
 706 bool FileMapInfo::check_paths_existence(const char* paths) {
 707   ClasspathStream cp_stream(paths);
 708   bool exist = false;
 709   struct stat st;
 710   while (cp_stream.has_next()) {
 711     const char* path = cp_stream.get_next();
 712     if (os::stat(path, &st) == 0 && st.st_size > 0) {
 713       exist = true;
 714       break;
 715     }
 716   }
 717   return exist;
 718 }
 719 
 720 GrowableArray<const char*>* FileMapInfo::create_dumptime_app_classpath_array() {
 721   assert(CDSConfig::is_dumping_archive(), "sanity");
 722   GrowableArray<const char*>* path_array = new GrowableArray<const char*>(10);
 723   ClassPathEntry* cpe = ClassLoader::app_classpath_entries();
 724   while (cpe != nullptr) {
 725     path_array->append(cpe->name());
 726     cpe = cpe->next();
 727   }
 728   return path_array;
 729 }
 730 
 731 GrowableArray<const char*>* FileMapInfo::create_path_array(const char* paths) {
 732   GrowableArray<const char*>* path_array = new GrowableArray<const char*>(10);
 733   JavaThread* current = JavaThread::current();
 734   ClasspathStream cp_stream(paths);
 735   bool non_jar_in_cp = header()->has_non_jar_in_classpath();
 736   while (cp_stream.has_next()) {
 737     const char* path = cp_stream.get_next();
 738     if (!non_jar_in_cp) {
 739       struct stat st;
 740       if (os::stat(path, &st) == 0) {
 741         path_array->append(path);
 742       }
 743     } else {
 744       const char* canonical_path = ClassLoader::get_canonical_path(path, current);
 745       if (canonical_path != nullptr) {
 746         char* error_msg = nullptr;
 747         jzfile* zip = ClassLoader::open_zip_file(canonical_path, &error_msg, current);
 748         if (zip != nullptr && error_msg == nullptr) {
 749           path_array->append(path);
 750         }
 751       }
 752     }
 753   }
 754   return path_array;
 755 }
 756 
 757 bool FileMapInfo::classpath_failure(const char* msg, const char* name) {
 758   ClassLoader::trace_class_path(msg, name);
 759   if (PrintSharedArchiveAndExit) {
 760     MetaspaceShared::set_archive_loading_failed();
 761   }
 762   return false;
 763 }
 764 
 765 unsigned int FileMapInfo::longest_common_app_classpath_prefix_len(int num_paths,
 766                                                                   GrowableArray<const char*>* rp_array) {
 767   if (num_paths == 0) {
 768     return 0;
 769   }
 770   unsigned int pos;
 771   for (pos = 0; ; pos++) {
 772     for (int i = 0; i < num_paths; i++) {
 773       if (rp_array->at(i)[pos] != '\0' && rp_array->at(i)[pos] == rp_array->at(0)[pos]) {
 774         continue;
 775       }
 776       // search backward for the pos before the file separator char
 777       while (pos > 0) {
 778         if (rp_array->at(0)[--pos] == *os::file_separator()) {
 779           return pos + 1;
 780         }
 781       }
 782       return 0;
 783     }
 784   }
 785   return 0;
 786 }
 787 
 788 bool FileMapInfo::check_paths(int shared_path_start_idx, int num_paths, GrowableArray<const char*>* rp_array,
 789                               unsigned int dumptime_prefix_len, unsigned int runtime_prefix_len) {
 790   int i = 0;
 791   int j = shared_path_start_idx;
 792   while (i < num_paths) {
 793     while (shared_path(j)->from_class_path_attr()) {
 794       // shared_path(j) was expanded from the JAR file attribute "Class-Path:"
 795       // during dump time. It's not included in the -classpath VM argument.
 796       j++;
 797     }
 798     assert(strlen(shared_path(j)->name()) > (size_t)dumptime_prefix_len, "sanity");
 799     const char* dumptime_path = shared_path(j)->name() + dumptime_prefix_len;
 800     assert(strlen(rp_array->at(i)) > (size_t)runtime_prefix_len, "sanity");
 801     const char* runtime_path = rp_array->at(i)  + runtime_prefix_len;
 802     if (!os::same_files(dumptime_path, runtime_path)) {
 803       return false;
 804     }
 805     i++;
 806     j++;
 807   }
 808   return true;
 809 }
 810 
 811 bool FileMapInfo::validate_boot_class_paths() {
 812   //
 813   // - Archive contains boot classes only - relaxed boot path check:
 814   //   Extra path elements appended to the boot path at runtime are allowed.
 815   //
 816   // - Archive contains application or platform classes - strict boot path check:
 817   //   Validate the entire runtime boot path, which must be compatible
 818   //   with the dump time boot path. Appending boot path at runtime is not
 819   //   allowed.
 820   //
 821 
 822   // The first entry in boot path is the modules_image (guaranteed by
 823   // ClassLoader::setup_boot_search_path()). Skip the first entry. The
 824   // path of the runtime modules_image may be different from the dump
 825   // time path (e.g. the JDK image is copied to a different location
 826   // after generating the shared archive), which is acceptable. For most
 827   // common cases, the dump time boot path might contain modules_image only.
 828   char* runtime_boot_path = Arguments::get_boot_class_path();
 829   char* rp = skip_first_path_entry(runtime_boot_path);
 830   assert(shared_path(0)->is_modules_image(), "first shared_path must be the modules image");
 831   int dp_len = header()->app_class_paths_start_index() - 1; // ignore the first path to the module image
 832   bool match = true;
 833 
 834   bool relaxed_check = !header()->has_platform_or_app_classes();
 835   if (dp_len == 0 && rp == nullptr) {
 836     return true;   // ok, both runtime and dump time boot paths have modules_images only
 837   } else if (dp_len == 0 && rp != nullptr) {
 838     if (relaxed_check) {
 839       return true;   // ok, relaxed check, runtime has extra boot append path entries
 840     } else {
 841       ResourceMark rm;
 842       if (check_paths_existence(rp)) {
 843         // If a path exists in the runtime boot paths, it is considered a mismatch
 844         // since there's no boot path specified during dump time.
 845         match = false;
 846       }
 847     }
 848   } else if (dp_len > 0 && rp != nullptr) {
 849     int num;
 850     ResourceMark rm;
 851     GrowableArray<const char*>* rp_array = create_path_array(rp);
 852     int rp_len = rp_array->length();
 853     if (rp_len >= dp_len) {
 854       if (relaxed_check) {
 855         // only check the leading entries in the runtime boot path, up to
 856         // the length of the dump time boot path
 857         num = dp_len;
 858       } else {
 859         // check the full runtime boot path, must match with dump time
 860         num = rp_len;
 861       }
 862       match = check_paths(1, num, rp_array, 0, 0);
 863     } else {
 864       // create_path_array() ignores non-existing paths. Although the dump time and runtime boot classpath lengths
 865       // are the same initially, after the call to create_path_array(), the runtime boot classpath length could become
 866       // shorter. We consider boot classpath mismatch in this case.
 867       match = false;
 868     }
 869   }
 870 
 871   if (!match) {
 872     // The paths are different
 873     return classpath_failure("[BOOT classpath mismatch, actual =", runtime_boot_path);
 874   }
 875   return true;
 876 }
 877 
 878 bool FileMapInfo::validate_app_class_paths(int shared_app_paths_len) {
 879   const char *appcp = Arguments::get_appclasspath();
 880   assert(appcp != nullptr, "null app classpath");
 881   int rp_len = num_paths(appcp);
 882   bool match = false;
 883   if (rp_len < shared_app_paths_len) {
 884     return classpath_failure("Run time APP classpath is shorter than the one at dump time: ", appcp);
 885   }
 886   if (shared_app_paths_len != 0 && rp_len != 0) {
 887     // Prefix is OK: E.g., dump with -cp foo.jar, but run with -cp foo.jar:bar.jar.
 888     ResourceMark rm;
 889     GrowableArray<const char*>* rp_array = create_path_array(appcp);
 890     if (rp_array->length() == 0) {
 891       // None of the jar file specified in the runtime -cp exists.
 892       return classpath_failure("None of the jar file specified in the runtime -cp exists: -Djava.class.path=", appcp);
 893     }
 894     if (rp_array->length() < shared_app_paths_len) {
 895       // create_path_array() ignores non-existing paths. Although the dump time and runtime app classpath lengths
 896       // are the same initially, after the call to create_path_array(), the runtime app classpath length could become
 897       // shorter. We consider app classpath mismatch in this case.
 898       return classpath_failure("[APP classpath mismatch, actual: -Djava.class.path=", appcp);
 899     }
 900 
 901     // Handling of non-existent entries in the classpath: we eliminate all the non-existent
 902     // entries from both the dump time classpath (ClassLoader::update_class_path_entry_list)
 903     // and the runtime classpath (FileMapInfo::create_path_array), and check the remaining
 904     // entries. E.g.:
 905     //
 906     // dump : -cp a.jar:NE1:NE2:b.jar  -> a.jar:b.jar -> recorded in archive.
 907     // run 1: -cp NE3:a.jar:NE4:b.jar  -> a.jar:b.jar -> matched
 908     // run 2: -cp x.jar:NE4:b.jar      -> x.jar:b.jar -> mismatched
 909 
 910     int j = header()->app_class_paths_start_index();
 911     match = check_paths(j, shared_app_paths_len, rp_array, 0, 0);
 912     if (!match) {
 913       // To facilitate app deployment, we allow the JAR files to be moved *together* to
 914       // a different location, as long as they are still stored under the same directory
 915       // structure. E.g., the following is OK.
 916       //     java -Xshare:dump -cp /a/Foo.jar:/a/b/Bar.jar  ...
 917       //     java -Xshare:auto -cp /x/y/Foo.jar:/x/y/b/Bar.jar  ...
 918       unsigned int dumptime_prefix_len = header()->common_app_classpath_prefix_size();
 919       unsigned int runtime_prefix_len = longest_common_app_classpath_prefix_len(shared_app_paths_len, rp_array);
 920       if (dumptime_prefix_len != 0 || runtime_prefix_len != 0) {
 921         log_info(class, path)("LCP length for app classpath (dumptime: %u, runtime: %u)",
 922                               dumptime_prefix_len, runtime_prefix_len);
 923         match = check_paths(j, shared_app_paths_len, rp_array,
 924                                dumptime_prefix_len, runtime_prefix_len);
 925       }
 926       if (!match) {
 927         return classpath_failure("[APP classpath mismatch, actual: -Djava.class.path=", appcp);
 928       }
 929     }
 930   }
 931   return true;
 932 }
 933 
 934 void FileMapInfo::log_paths(const char* msg, int start_idx, int end_idx) {
 935   LogTarget(Info, class, path) lt;
 936   if (lt.is_enabled()) {
 937     LogStream ls(lt);
 938     ls.print("%s", msg);
 939     const char* prefix = "";
 940     for (int i = start_idx; i < end_idx; i++) {
 941       ls.print("%s%s", prefix, shared_path(i)->name());
 942       prefix = os::path_separator();
 943     }
 944     ls.cr();
 945   }
 946 }
 947 
 948 void FileMapInfo::extract_module_paths(const char* runtime_path, GrowableArray<const char*>* module_paths) {
 949   GrowableArray<const char*>* path_array = create_path_array(runtime_path);
 950   int num_paths = path_array->length();
 951   for (int i = 0; i < num_paths; i++) {
 952     const char* name = path_array->at(i);
 953     ClassLoaderExt::extract_jar_files_from_path(name, module_paths);
 954   }
 955   // module paths are stored in sorted order in the CDS archive.
 956   module_paths->sort(ClassLoaderExt::compare_module_names);
 957 }
 958 
 959 bool FileMapInfo::check_module_paths() {
 960   const char* runtime_path = Arguments::get_property("jdk.module.path");
 961   int archived_num_module_paths = header()->num_module_paths();
 962   if (runtime_path == nullptr && archived_num_module_paths == 0) {
 963     return true;
 964   }
 965   if ((runtime_path == nullptr && archived_num_module_paths > 0) ||
 966       (runtime_path != nullptr && archived_num_module_paths == 0)) {
 967     return false;
 968   }
 969   ResourceMark rm;
 970   GrowableArray<const char*>* module_paths = new GrowableArray<const char*>(3);
 971   extract_module_paths(runtime_path, module_paths);
 972   int num_paths = module_paths->length();
 973   if (num_paths != archived_num_module_paths) {
 974     return false;
 975   }
 976   return check_paths(header()->app_module_paths_start_index(), num_paths, module_paths, 0, 0);
 977 }
 978 
 979 bool FileMapInfo::validate_shared_path_table() {
 980   assert(CDSConfig::is_using_archive(), "runtime only");
 981 
 982   _validating_shared_path_table = true;
 983 
 984   // Load the shared path table info from the archive header
 985   _shared_path_table = header()->shared_path_table();
 986 
 987   bool matched_module_paths = true;
 988   if (CDSConfig::is_dumping_dynamic_archive() || header()->has_full_module_graph()) {
 989     matched_module_paths = check_module_paths();
 990   }
 991   if (header()->has_full_module_graph() && !matched_module_paths) {
 992     CDSConfig::stop_using_optimized_module_handling();
 993     log_info(cds)("optimized module handling: disabled because of mismatched module paths");
 994   }
 995 
 996   if (CDSConfig::is_dumping_dynamic_archive()) {
 997     // Only support dynamic dumping with the usage of the default CDS archive
 998     // or a simple base archive.
 999     // If the base layer archive contains additional path component besides
1000     // the runtime image and the -cp, dynamic dumping is disabled.
1001     //
1002     // When dynamic archiving is enabled, the _shared_path_table is overwritten
1003     // to include the application path and stored in the top layer archive.
1004     assert(shared_path(0)->is_modules_image(), "first shared_path must be the modules image");
1005     if (header()->app_class_paths_start_index() > 1) {
1006       CDSConfig::disable_dumping_dynamic_archive();
1007       log_warning(cds)(
1008         "Dynamic archiving is disabled because base layer archive has appended boot classpath");
1009     }
1010     if (header()->num_module_paths() > 0) {
1011       if (!matched_module_paths) {
1012         CDSConfig::disable_dumping_dynamic_archive();
1013         log_warning(cds)(
1014           "Dynamic archiving is disabled because base layer archive has a different module path");
1015       }
1016     }
1017   }
1018 
1019   log_paths("Expecting BOOT path=", 0, header()->app_class_paths_start_index());
1020   log_paths("Expecting -Djava.class.path=", header()->app_class_paths_start_index(), header()->app_module_paths_start_index());
1021 
1022   int module_paths_start_index = header()->app_module_paths_start_index();
1023   int shared_app_paths_len = 0;
1024 
1025   // validate the path entries up to the _max_used_path_index
1026   for (int i=0; i < header()->max_used_path_index() + 1; i++) {
1027     if (i < module_paths_start_index) {
1028       if (shared_path(i)->validate()) {
1029         // Only count the app class paths not from the "Class-path" attribute of a jar manifest.
1030         if (!shared_path(i)->from_class_path_attr() && i >= header()->app_class_paths_start_index()) {
1031           shared_app_paths_len++;
1032         }
1033         log_info(class, path)("ok");
1034       } else {
1035         if (_dynamic_archive_info != nullptr && _dynamic_archive_info->_is_static) {
1036           assert(!CDSConfig::is_using_archive(), "UseSharedSpaces should be disabled");
1037         }
1038         return false;
1039       }
1040     } else if (i >= module_paths_start_index) {
1041       if (shared_path(i)->validate(false /* not a class path entry */)) {
1042         log_info(class, path)("ok");
1043       } else {
1044         if (_dynamic_archive_info != nullptr && _dynamic_archive_info->_is_static) {
1045           assert(!CDSConfig::is_using_archive(), "UseSharedSpaces should be disabled");
1046         }
1047         return false;
1048       }
1049     }
1050   }
1051 
1052   if (header()->max_used_path_index() == 0) {
1053     // default archive only contains the module image in the bootclasspath
1054     assert(shared_path(0)->is_modules_image(), "first shared_path must be the modules image");
1055   } else {
1056     if (!validate_boot_class_paths() || !validate_app_class_paths(shared_app_paths_len)) {
1057       const char* mismatch_msg = "shared class paths mismatch";
1058       const char* hint_msg = log_is_enabled(Info, class, path) ?
1059           "" : " (hint: enable -Xlog:class+path=info to diagnose the failure)";
1060       if (RequireSharedSpaces) {
1061         log_error(cds)("%s%s", mismatch_msg, hint_msg);
1062         MetaspaceShared::unrecoverable_loading_error();
1063       } else {
1064         log_warning(cds)("%s%s", mismatch_msg, hint_msg);
1065       }
1066       return false;
1067     }
1068   }
1069 
1070   if (!validate_non_existent_class_paths()) {
1071     return false;
1072   }
1073 
1074   _validating_shared_path_table = false;
1075 
1076 #if INCLUDE_JVMTI
1077   if (_classpath_entries_for_jvmti != nullptr) {
1078     os::free(_classpath_entries_for_jvmti);
1079   }
1080   size_t sz = sizeof(ClassPathEntry*) * get_number_of_shared_paths();
1081   _classpath_entries_for_jvmti = (ClassPathEntry**)os::malloc(sz, mtClass);
1082   memset((void*)_classpath_entries_for_jvmti, 0, sz);
1083 #endif
1084 
1085   return true;
1086 }
1087 
1088 bool FileMapInfo::validate_non_existent_class_paths() {
1089   // All of the recorded non-existent paths came from the Class-Path: attribute from the JAR
1090   // files on the app classpath. If any of these are found to exist during runtime,
1091   // it will change how classes are loading for the app loader. For safety, disable
1092   // loading of archived platform/app classes (currently there's no way to disable just the
1093   // app classes).
1094 
1095   assert(CDSConfig::is_using_archive(), "runtime only");
1096   for (int i = header()->app_module_paths_start_index() + header()->num_module_paths();
1097        i < get_number_of_shared_paths();
1098        i++) {
1099     SharedClassPathEntry* ent = shared_path(i);
1100     if (!ent->check_non_existent()) {
1101       if (header()->has_aot_linked_classes()) {
1102         log_error(cds)("CDS archive has aot-linked classes. It cannot be used because the "
1103                        "file %s exists", ent->name());
1104         return false;
1105       } else {
1106         log_warning(cds)("Archived non-system classes are disabled because the "
1107                          "file %s exists", ent->name());
1108         header()->set_has_platform_or_app_classes(false);
1109       }
1110     }
1111   }
1112 
1113   return true;
1114 }
1115 
1116 // A utility class for reading/validating the GenericCDSFileMapHeader portion of
1117 // a CDS archive's header. The file header of all CDS archives with versions from
1118 // CDS_GENERIC_HEADER_SUPPORTED_MIN_VERSION (12) are guaranteed to always start
1119 // with GenericCDSFileMapHeader. This makes it possible to read important information
1120 // from a CDS archive created by a different version of HotSpot, so that we can
1121 // automatically regenerate the archive as necessary (JDK-8261455).
1122 class FileHeaderHelper {
1123   int _fd;
1124   bool _is_valid;
1125   bool _is_static;
1126   GenericCDSFileMapHeader* _header;
1127   const char* _archive_name;
1128   const char* _base_archive_name;
1129 
1130 public:
1131   FileHeaderHelper(const char* archive_name, bool is_static) {
1132     _fd = -1;
1133     _is_valid = false;
1134     _header = nullptr;
1135     _base_archive_name = nullptr;
1136     _archive_name = archive_name;
1137     _is_static = is_static;
1138   }
1139 
1140   ~FileHeaderHelper() {
1141     if (_header != nullptr) {
1142       FREE_C_HEAP_ARRAY(char, _header);
1143     }
1144     if (_fd != -1) {
1145       ::close(_fd);
1146     }
1147   }
1148 
1149   bool initialize() {
1150     assert(_archive_name != nullptr, "Archive name is null");
1151     _fd = os::open(_archive_name, O_RDONLY | O_BINARY, 0);
1152     if (_fd < 0) {
1153       log_info(cds)("Specified shared archive not found (%s)", _archive_name);
1154       return false;
1155     }
1156     return initialize(_fd);
1157   }
1158 
1159   // for an already opened file, do not set _fd
1160   bool initialize(int fd) {
1161     assert(_archive_name != nullptr, "Archive name is null");
1162     assert(fd != -1, "Archive must be opened already");
1163     // First read the generic header so we know the exact size of the actual header.
1164     GenericCDSFileMapHeader gen_header;
1165     size_t size = sizeof(GenericCDSFileMapHeader);
1166     os::lseek(fd, 0, SEEK_SET);
1167     size_t n = ::read(fd, (void*)&gen_header, (unsigned int)size);
1168     if (n != size) {
1169       log_warning(cds)("Unable to read generic CDS file map header from shared archive");
1170       return false;
1171     }
1172 
1173     if (gen_header._magic != CDS_ARCHIVE_MAGIC &&
1174         gen_header._magic != CDS_DYNAMIC_ARCHIVE_MAGIC) {
1175       log_warning(cds)("The shared archive file has a bad magic number: %#x", gen_header._magic);
1176       return false;
1177     }
1178 
1179     if (gen_header._version < CDS_GENERIC_HEADER_SUPPORTED_MIN_VERSION) {
1180       log_warning(cds)("Cannot handle shared archive file version 0x%x. Must be at least 0x%x.",
1181                                  gen_header._version, CDS_GENERIC_HEADER_SUPPORTED_MIN_VERSION);
1182       return false;
1183     }
1184 
1185     if (gen_header._version !=  CURRENT_CDS_ARCHIVE_VERSION) {
1186       log_warning(cds)("The shared archive file version 0x%x does not match the required version 0x%x.",
1187                                  gen_header._version, CURRENT_CDS_ARCHIVE_VERSION);
1188     }
1189 
1190     size_t filelen = os::lseek(fd, 0, SEEK_END);
1191     if (gen_header._header_size >= filelen) {
1192       log_warning(cds)("Archive file header larger than archive file");
1193       return false;
1194     }
1195 
1196     // Read the actual header and perform more checks
1197     size = gen_header._header_size;
1198     _header = (GenericCDSFileMapHeader*)NEW_C_HEAP_ARRAY(char, size, mtInternal);
1199     os::lseek(fd, 0, SEEK_SET);
1200     n = ::read(fd, (void*)_header, (unsigned int)size);
1201     if (n != size) {
1202       log_warning(cds)("Unable to read actual CDS file map header from shared archive");
1203       return false;
1204     }
1205 
1206     if (!check_header_crc()) {
1207       return false;
1208     }
1209 
1210     if (!check_and_init_base_archive_name()) {
1211       return false;
1212     }
1213 
1214     // All fields in the GenericCDSFileMapHeader has been validated.
1215     _is_valid = true;
1216     return true;
1217   }
1218 
1219   GenericCDSFileMapHeader* get_generic_file_header() {
1220     assert(_header != nullptr && _is_valid, "must be a valid archive file");
1221     return _header;
1222   }
1223 
1224   const char* base_archive_name() {
1225     assert(_header != nullptr && _is_valid, "must be a valid archive file");
1226     return _base_archive_name;
1227   }
1228 
1229  private:
1230   bool check_header_crc() const {
1231     if (VerifySharedSpaces) {
1232       FileMapHeader* header = (FileMapHeader*)_header;
1233       int actual_crc = header->compute_crc();
1234       if (actual_crc != header->crc()) {
1235         log_info(cds)("_crc expected: %d", header->crc());
1236         log_info(cds)("       actual: %d", actual_crc);
1237         log_warning(cds)("Header checksum verification failed.");
1238         return false;
1239       }
1240     }
1241     return true;
1242   }
1243 
1244   bool check_and_init_base_archive_name() {
1245     unsigned int name_offset = _header->_base_archive_name_offset;
1246     unsigned int name_size   = _header->_base_archive_name_size;
1247     unsigned int header_size = _header->_header_size;
1248 
1249     if (name_offset + name_size < name_offset) {
1250       log_warning(cds)("base_archive_name offset/size overflow: " UINT32_FORMAT "/" UINT32_FORMAT,
1251                                  name_offset, name_size);
1252       return false;
1253     }
1254     if (_header->_magic == CDS_ARCHIVE_MAGIC) {
1255       if (name_offset != 0) {
1256         log_warning(cds)("static shared archive must have zero _base_archive_name_offset");
1257         return false;
1258       }
1259       if (name_size != 0) {
1260         log_warning(cds)("static shared archive must have zero _base_archive_name_size");
1261         return false;
1262       }
1263     } else {
1264       assert(_header->_magic == CDS_DYNAMIC_ARCHIVE_MAGIC, "must be");
1265       if ((name_size == 0 && name_offset != 0) ||
1266           (name_size != 0 && name_offset == 0)) {
1267         // If either is zero, both must be zero. This indicates that we are using the default base archive.
1268         log_warning(cds)("Invalid base_archive_name offset/size: " UINT32_FORMAT "/" UINT32_FORMAT,
1269                                    name_offset, name_size);
1270         return false;
1271       }
1272       if (name_size > 0) {
1273         if (name_offset + name_size > header_size) {
1274           log_warning(cds)("Invalid base_archive_name offset/size (out of range): "
1275                                      UINT32_FORMAT " + " UINT32_FORMAT " > " UINT32_FORMAT ,
1276                                      name_offset, name_size, header_size);
1277           return false;
1278         }
1279         const char* name = ((const char*)_header) + _header->_base_archive_name_offset;
1280         if (name[name_size - 1] != '\0' || strlen(name) != name_size - 1) {
1281           log_warning(cds)("Base archive name is damaged");
1282           return false;
1283         }
1284         if (!os::file_exists(name)) {
1285           log_warning(cds)("Base archive %s does not exist", name);
1286           return false;
1287         }
1288         _base_archive_name = name;
1289       }
1290     }
1291 
1292     return true;
1293   }
1294 };
1295 
1296 // Return value:
1297 // false:
1298 //      <archive_name> is not a valid archive. *base_archive_name is set to null.
1299 // true && (*base_archive_name) == nullptr:
1300 //      <archive_name> is a valid static archive.
1301 // true && (*base_archive_name) != nullptr:
1302 //      <archive_name> is a valid dynamic archive.
1303 bool FileMapInfo::get_base_archive_name_from_header(const char* archive_name,
1304                                                     char** base_archive_name) {
1305   FileHeaderHelper file_helper(archive_name, false);
1306   *base_archive_name = nullptr;
1307 
1308   if (!file_helper.initialize()) {
1309     return false;
1310   }
1311   GenericCDSFileMapHeader* header = file_helper.get_generic_file_header();
1312   if (header->_magic != CDS_DYNAMIC_ARCHIVE_MAGIC) {
1313     assert(header->_magic == CDS_ARCHIVE_MAGIC, "must be");
1314     if (AutoCreateSharedArchive) {
1315      log_warning(cds)("AutoCreateSharedArchive is ignored because %s is a static archive", archive_name);
1316     }
1317     return true;
1318   }
1319 
1320   const char* base = file_helper.base_archive_name();
1321   if (base == nullptr) {
1322     *base_archive_name = CDSConfig::default_archive_path();
1323   } else {
1324     *base_archive_name = os::strdup_check_oom(base);
1325   }
1326 
1327   return true;
1328 }
1329 
1330 // Read the FileMapInfo information from the file.
1331 
1332 bool FileMapInfo::init_from_file(int fd) {
1333   FileHeaderHelper file_helper(_full_path, _is_static);
1334   if (!file_helper.initialize(fd)) {
1335     log_warning(cds)("Unable to read the file header.");
1336     return false;
1337   }
1338   GenericCDSFileMapHeader* gen_header = file_helper.get_generic_file_header();
1339 
1340   if (_is_static) {
1341     if (gen_header->_magic != CDS_ARCHIVE_MAGIC) {
1342       log_warning(cds)("Not a base shared archive: %s", _full_path);
1343       return false;
1344     }
1345   } else {
1346     if (gen_header->_magic != CDS_DYNAMIC_ARCHIVE_MAGIC) {
1347       log_warning(cds)("Not a top shared archive: %s", _full_path);
1348       return false;
1349     }
1350   }
1351 
1352   _header = (FileMapHeader*)os::malloc(gen_header->_header_size, mtInternal);
1353   os::lseek(fd, 0, SEEK_SET); // reset to begin of the archive
1354   size_t size = gen_header->_header_size;
1355   size_t n = ::read(fd, (void*)_header, (unsigned int)size);
1356   if (n != size) {
1357     log_warning(cds)("Failed to read file header from the top archive file\n");
1358     return false;
1359   }
1360 
1361   if (header()->version() != CURRENT_CDS_ARCHIVE_VERSION) {
1362     log_info(cds)("_version expected: 0x%x", CURRENT_CDS_ARCHIVE_VERSION);
1363     log_info(cds)("           actual: 0x%x", header()->version());
1364     log_warning(cds)("The shared archive file has the wrong version.");
1365     return false;
1366   }
1367 
1368   int common_path_size = header()->common_app_classpath_prefix_size();
1369   if (common_path_size < 0) {
1370       log_warning(cds)("common app classpath prefix len < 0");
1371       return false;
1372   }
1373 
1374   unsigned int base_offset = header()->base_archive_name_offset();
1375   unsigned int name_size = header()->base_archive_name_size();
1376   unsigned int header_size = header()->header_size();
1377   if (base_offset != 0 && name_size != 0) {
1378     if (header_size != base_offset + name_size) {
1379       log_info(cds)("_header_size: " UINT32_FORMAT, header_size);
1380       log_info(cds)("common_app_classpath_size: " UINT32_FORMAT, header()->common_app_classpath_prefix_size());
1381       log_info(cds)("base_archive_name_size: " UINT32_FORMAT, header()->base_archive_name_size());
1382       log_info(cds)("base_archive_name_offset: " UINT32_FORMAT, header()->base_archive_name_offset());
1383       log_warning(cds)("The shared archive file has an incorrect header size.");
1384       return false;
1385     }
1386   }
1387 
1388   const char* actual_ident = header()->jvm_ident();
1389 
1390   if (actual_ident[JVM_IDENT_MAX-1] != 0) {
1391     log_warning(cds)("JVM version identifier is corrupted.");
1392     return false;
1393   }
1394 
1395   char expected_ident[JVM_IDENT_MAX];
1396   get_header_version(expected_ident);
1397   if (strncmp(actual_ident, expected_ident, JVM_IDENT_MAX-1) != 0) {
1398     log_info(cds)("_jvm_ident expected: %s", expected_ident);
1399     log_info(cds)("             actual: %s", actual_ident);
1400     log_warning(cds)("The shared archive file was created by a different"
1401                   " version or build of HotSpot");
1402     return false;
1403   }
1404 
1405   _file_offset = header()->header_size(); // accounts for the size of _base_archive_name
1406 
1407   size_t len = os::lseek(fd, 0, SEEK_END);
1408 
1409   for (int i = 0; i < MetaspaceShared::n_regions; i++) {
1410     FileMapRegion* r = region_at(i);
1411     if (r->file_offset() > len || len - r->file_offset() < r->used()) {
1412       log_warning(cds)("The shared archive file has been truncated.");
1413       return false;
1414     }
1415   }
1416 
1417   return true;
1418 }
1419 
1420 void FileMapInfo::seek_to_position(size_t pos) {
1421   if (os::lseek(_fd, (long)pos, SEEK_SET) < 0) {
1422     log_error(cds)("Unable to seek to position %zu", pos);
1423     MetaspaceShared::unrecoverable_loading_error();
1424   }
1425 }
1426 
1427 // Read the FileMapInfo information from the file.
1428 bool FileMapInfo::open_for_read() {
1429   if (_file_open) {
1430     return true;
1431   }
1432   log_info(cds)("trying to map %s", _full_path);
1433   int fd = os::open(_full_path, O_RDONLY | O_BINARY, 0);
1434   if (fd < 0) {
1435     if (errno == ENOENT) {
1436       log_info(cds)("Specified shared archive not found (%s)", _full_path);
1437     } else {
1438       log_warning(cds)("Failed to open shared archive file (%s)",
1439                     os::strerror(errno));
1440     }
1441     return false;
1442   } else {
1443     log_info(cds)("Opened archive %s.", _full_path);
1444   }
1445 
1446   _fd = fd;
1447   _file_open = true;
1448   return true;
1449 }
1450 
1451 // Write the FileMapInfo information to the file.
1452 
1453 void FileMapInfo::open_for_write() {
1454   LogMessage(cds) msg;
1455   if (msg.is_info()) {
1456     msg.info("Dumping shared data to file: ");
1457     msg.info("   %s", _full_path);
1458   }
1459 
1460 #ifdef _WINDOWS  // On Windows, need WRITE permission to remove the file.
1461     chmod(_full_path, _S_IREAD | _S_IWRITE);
1462 #endif
1463 
1464   // Use remove() to delete the existing file because, on Unix, this will
1465   // allow processes that have it open continued access to the file.
1466   remove(_full_path);
1467   int fd = os::open(_full_path, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0444);
1468   if (fd < 0) {
1469     log_error(cds)("Unable to create shared archive file %s: (%s).", _full_path,
1470                    os::strerror(errno));
1471     MetaspaceShared::writing_error();
1472     return;
1473   }
1474   _fd = fd;
1475   _file_open = true;
1476 
1477   // Seek past the header. We will write the header after all regions are written
1478   // and their CRCs computed.
1479   size_t header_bytes = header()->header_size();
1480 
1481   header_bytes = align_up(header_bytes, MetaspaceShared::core_region_alignment());
1482   _file_offset = header_bytes;
1483   seek_to_position(_file_offset);
1484 }
1485 
1486 // Write the header to the file, seek to the next allocation boundary.
1487 
1488 void FileMapInfo::write_header() {
1489   _file_offset = 0;
1490   seek_to_position(_file_offset);
1491   assert(is_file_position_aligned(), "must be");
1492   write_bytes(header(), header()->header_size());
1493 }
1494 
1495 size_t FileMapRegion::used_aligned() const {
1496   return align_up(used(), MetaspaceShared::core_region_alignment());
1497 }
1498 
1499 void FileMapRegion::init(int region_index, size_t mapping_offset, size_t size, bool read_only,
1500                          bool allow_exec, int crc) {
1501   _is_heap_region = HeapShared::is_heap_region(region_index);
1502   _is_bitmap_region = (region_index == MetaspaceShared::bm);
1503   _mapping_offset = mapping_offset;
1504   _used = size;
1505   _read_only = read_only;
1506   _allow_exec = allow_exec;
1507   _crc = crc;
1508   _mapped_from_file = false;
1509   _mapped_base = nullptr;
1510   _in_reserved_space = false;
1511 }
1512 
1513 void FileMapRegion::init_oopmap(size_t offset, size_t size_in_bits) {
1514   _oopmap_offset = offset;
1515   _oopmap_size_in_bits = size_in_bits;
1516 }
1517 
1518 void FileMapRegion::init_ptrmap(size_t offset, size_t size_in_bits) {
1519   _ptrmap_offset = offset;
1520   _ptrmap_size_in_bits = size_in_bits;
1521 }
1522 
1523 bool FileMapRegion::check_region_crc(char* base) const {
1524   // This function should be called after the region has been properly
1525   // loaded into memory via FileMapInfo::map_region() or FileMapInfo::read_region().
1526   // I.e., this->mapped_base() must be valid.
1527   size_t sz = used();
1528   if (sz == 0) {
1529     return true;
1530   }
1531 
1532   assert(base != nullptr, "must be initialized");
1533   int crc = ClassLoader::crc32(0, base, (jint)sz);
1534   if (crc != this->crc()) {
1535     log_warning(cds)("Checksum verification failed.");
1536     return false;
1537   }
1538   return true;
1539 }
1540 
1541 static const char* region_name(int region_index) {
1542   static const char* names[] = {
1543     "rw", "ro", "bm", "hp"
1544   };
1545   const int num_regions = sizeof(names)/sizeof(names[0]);
1546   assert(0 <= region_index && region_index < num_regions, "sanity");
1547 
1548   return names[region_index];
1549 }
1550 
1551 BitMapView FileMapInfo::bitmap_view(int region_index, bool is_oopmap) {
1552   FileMapRegion* r = region_at(region_index);
1553   char* bitmap_base = is_static() ? FileMapInfo::current_info()->map_bitmap_region() : FileMapInfo::dynamic_info()->map_bitmap_region();
1554   bitmap_base += is_oopmap ? r->oopmap_offset() : r->ptrmap_offset();
1555   size_t size_in_bits = is_oopmap ? r->oopmap_size_in_bits() : r->ptrmap_size_in_bits();
1556 
1557   log_debug(cds, reloc)("mapped %s relocation %smap @ " INTPTR_FORMAT " (%zu bits)",
1558                         region_name(region_index), is_oopmap ? "oop" : "ptr",
1559                         p2i(bitmap_base), size_in_bits);
1560 
1561   return BitMapView((BitMap::bm_word_t*)(bitmap_base), size_in_bits);
1562 }
1563 
1564 BitMapView FileMapInfo::oopmap_view(int region_index) {
1565     return bitmap_view(region_index, /*is_oopmap*/true);
1566   }
1567 
1568 BitMapView FileMapInfo::ptrmap_view(int region_index) {
1569   return bitmap_view(region_index, /*is_oopmap*/false);
1570 }
1571 
1572 void FileMapRegion::print(outputStream* st, int region_index) {
1573   st->print_cr("============ region ============= %d \"%s\"", region_index, region_name(region_index));
1574   st->print_cr("- crc:                            0x%08x", _crc);
1575   st->print_cr("- read_only:                      %d", _read_only);
1576   st->print_cr("- allow_exec:                     %d", _allow_exec);
1577   st->print_cr("- is_heap_region:                 %d", _is_heap_region);
1578   st->print_cr("- is_bitmap_region:               %d", _is_bitmap_region);
1579   st->print_cr("- mapped_from_file:               %d", _mapped_from_file);
1580   st->print_cr("- file_offset:                    0x%zx", _file_offset);
1581   st->print_cr("- mapping_offset:                 0x%zx", _mapping_offset);
1582   st->print_cr("- used:                           %zu", _used);
1583   st->print_cr("- oopmap_offset:                  0x%zx", _oopmap_offset);
1584   st->print_cr("- oopmap_size_in_bits:            %zu", _oopmap_size_in_bits);
1585   st->print_cr("- ptrmap_offset:                  0x%zx", _ptrmap_offset);
1586   st->print_cr("- ptrmap_size_in_bits:            %zu", _ptrmap_size_in_bits);
1587   st->print_cr("- mapped_base:                    " INTPTR_FORMAT, p2i(_mapped_base));
1588 }
1589 
1590 void FileMapInfo::write_region(int region, char* base, size_t size,
1591                                bool read_only, bool allow_exec) {
1592   assert(CDSConfig::is_dumping_archive(), "sanity");
1593 
1594   FileMapRegion* r = region_at(region);
1595   char* requested_base;
1596   size_t mapping_offset = 0;
1597 
1598   if (region == MetaspaceShared::bm) {
1599     requested_base = nullptr; // always null for bm region
1600   } else if (size == 0) {
1601     // This is an unused region (e.g., a heap region when !INCLUDE_CDS_JAVA_HEAP)
1602     requested_base = nullptr;
1603   } else if (HeapShared::is_heap_region(region)) {
1604     assert(CDSConfig::is_dumping_heap(), "sanity");
1605 #if INCLUDE_CDS_JAVA_HEAP
1606     assert(!CDSConfig::is_dumping_dynamic_archive(), "must be");
1607     requested_base = (char*)ArchiveHeapWriter::requested_address();
1608     if (UseCompressedOops) {
1609       mapping_offset = (size_t)((address)requested_base - CompressedOops::base());
1610       assert((mapping_offset >> CompressedOops::shift()) << CompressedOops::shift() == mapping_offset, "must be");
1611     } else {
1612       mapping_offset = 0; // not used with !UseCompressedOops
1613     }
1614 #endif // INCLUDE_CDS_JAVA_HEAP
1615   } else {
1616     char* requested_SharedBaseAddress = (char*)MetaspaceShared::requested_base_address();
1617     requested_base = ArchiveBuilder::current()->to_requested(base);
1618     assert(requested_base >= requested_SharedBaseAddress, "must be");
1619     mapping_offset = requested_base - requested_SharedBaseAddress;
1620   }
1621 
1622   r->set_file_offset(_file_offset);
1623   int crc = ClassLoader::crc32(0, base, (jint)size);
1624   if (size > 0) {
1625     log_info(cds)("Shared file region (%s) %d: %8zu"
1626                    " bytes, addr " INTPTR_FORMAT " file offset 0x%08" PRIxPTR
1627                    " crc 0x%08x",
1628                    region_name(region), region, size, p2i(requested_base), _file_offset, crc);
1629   }
1630 
1631   r->init(region, mapping_offset, size, read_only, allow_exec, crc);
1632 
1633   if (base != nullptr) {
1634     write_bytes_aligned(base, size);
1635   }
1636 }
1637 
1638 static size_t write_bitmap(const CHeapBitMap* map, char* output, size_t offset) {
1639   size_t size_in_bytes = map->size_in_bytes();
1640   map->write_to((BitMap::bm_word_t*)(output + offset), size_in_bytes);
1641   return offset + size_in_bytes;
1642 }
1643 
1644 // The sorting code groups the objects with non-null oop/ptrs together.
1645 // Relevant bitmaps then have lots of leading and trailing zeros, which
1646 // we do not have to store.
1647 size_t FileMapInfo::remove_bitmap_zeros(CHeapBitMap* map) {
1648   BitMap::idx_t first_set = map->find_first_set_bit(0);
1649   BitMap::idx_t last_set  = map->find_last_set_bit(0);
1650   size_t old_size = map->size();
1651 
1652   // Slice and resize bitmap
1653   map->truncate(first_set, last_set + 1);
1654 
1655   assert(map->at(0), "First bit should be set");
1656   assert(map->at(map->size() - 1), "Last bit should be set");
1657   assert(map->size() <= old_size, "sanity");
1658 
1659   return first_set;
1660 }
1661 
1662 char* FileMapInfo::write_bitmap_region(CHeapBitMap* rw_ptrmap, CHeapBitMap* ro_ptrmap, ArchiveHeapInfo* heap_info,
1663                                        size_t &size_in_bytes) {
1664   size_t removed_rw_leading_zeros = remove_bitmap_zeros(rw_ptrmap);
1665   size_t removed_ro_leading_zeros = remove_bitmap_zeros(ro_ptrmap);
1666   header()->set_rw_ptrmap_start_pos(removed_rw_leading_zeros);
1667   header()->set_ro_ptrmap_start_pos(removed_ro_leading_zeros);
1668   size_in_bytes = rw_ptrmap->size_in_bytes() + ro_ptrmap->size_in_bytes();
1669 
1670   if (heap_info->is_used()) {
1671     // Remove leading and trailing zeros
1672     size_t removed_oop_leading_zeros = remove_bitmap_zeros(heap_info->oopmap());
1673     size_t removed_ptr_leading_zeros = remove_bitmap_zeros(heap_info->ptrmap());
1674     header()->set_heap_oopmap_start_pos(removed_oop_leading_zeros);
1675     header()->set_heap_ptrmap_start_pos(removed_ptr_leading_zeros);
1676 
1677     size_in_bytes += heap_info->oopmap()->size_in_bytes();
1678     size_in_bytes += heap_info->ptrmap()->size_in_bytes();
1679   }
1680 
1681   // The bitmap region contains up to 4 parts:
1682   // rw_ptrmap:           metaspace pointers inside the read-write region
1683   // ro_ptrmap:           metaspace pointers inside the read-only region
1684   // heap_info->oopmap(): Java oop pointers in the heap region
1685   // heap_info->ptrmap(): metaspace pointers in the heap region
1686   char* buffer = NEW_C_HEAP_ARRAY(char, size_in_bytes, mtClassShared);
1687   size_t written = 0;
1688 
1689   region_at(MetaspaceShared::rw)->init_ptrmap(0, rw_ptrmap->size());
1690   written = write_bitmap(rw_ptrmap, buffer, written);
1691 
1692   region_at(MetaspaceShared::ro)->init_ptrmap(written, ro_ptrmap->size());
1693   written = write_bitmap(ro_ptrmap, buffer, written);
1694 
1695   if (heap_info->is_used()) {
1696     FileMapRegion* r = region_at(MetaspaceShared::hp);
1697 
1698     r->init_oopmap(written, heap_info->oopmap()->size());
1699     written = write_bitmap(heap_info->oopmap(), buffer, written);
1700 
1701     r->init_ptrmap(written, heap_info->ptrmap()->size());
1702     written = write_bitmap(heap_info->ptrmap(), buffer, written);
1703   }
1704 
1705   write_region(MetaspaceShared::bm, (char*)buffer, size_in_bytes, /*read_only=*/true, /*allow_exec=*/false);
1706   return buffer;
1707 }
1708 
1709 size_t FileMapInfo::write_heap_region(ArchiveHeapInfo* heap_info) {
1710   char* buffer_start = heap_info->buffer_start();
1711   size_t buffer_size = heap_info->buffer_byte_size();
1712   write_region(MetaspaceShared::hp, buffer_start, buffer_size, false, false);
1713   header()->set_heap_root_segments(heap_info->heap_root_segments());
1714   return buffer_size;
1715 }
1716 
1717 // Dump bytes to file -- at the current file position.
1718 
1719 void FileMapInfo::write_bytes(const void* buffer, size_t nbytes) {
1720   assert(_file_open, "must be");
1721   if (!os::write(_fd, buffer, nbytes)) {
1722     // If the shared archive is corrupted, close it and remove it.
1723     close();
1724     remove(_full_path);
1725     MetaspaceShared::writing_error("Unable to write to shared archive file.");
1726   }
1727   _file_offset += nbytes;
1728 }
1729 
1730 bool FileMapInfo::is_file_position_aligned() const {
1731   return _file_offset == align_up(_file_offset,
1732                                   MetaspaceShared::core_region_alignment());
1733 }
1734 
1735 // Align file position to an allocation unit boundary.
1736 
1737 void FileMapInfo::align_file_position() {
1738   assert(_file_open, "must be");
1739   size_t new_file_offset = align_up(_file_offset,
1740                                     MetaspaceShared::core_region_alignment());
1741   if (new_file_offset != _file_offset) {
1742     _file_offset = new_file_offset;
1743     // Seek one byte back from the target and write a byte to insure
1744     // that the written file is the correct length.
1745     _file_offset -= 1;
1746     seek_to_position(_file_offset);
1747     char zero = 0;
1748     write_bytes(&zero, 1);
1749   }
1750 }
1751 
1752 
1753 // Dump bytes to file -- at the current file position.
1754 
1755 void FileMapInfo::write_bytes_aligned(const void* buffer, size_t nbytes) {
1756   align_file_position();
1757   write_bytes(buffer, nbytes);
1758   align_file_position();
1759 }
1760 
1761 // Close the shared archive file.  This does NOT unmap mapped regions.
1762 
1763 void FileMapInfo::close() {
1764   if (_file_open) {
1765     if (::close(_fd) < 0) {
1766       MetaspaceShared::unrecoverable_loading_error("Unable to close the shared archive file.");
1767     }
1768     _file_open = false;
1769     _fd = -1;
1770   }
1771 }
1772 
1773 /*
1774  * Same as os::map_memory() but also pretouches if AlwaysPreTouch is enabled.
1775  */
1776 static char* map_memory(int fd, const char* file_name, size_t file_offset,
1777                         char *addr, size_t bytes, bool read_only,
1778                         bool allow_exec, MemTag mem_tag = mtNone) {
1779   char* mem = os::map_memory(fd, file_name, file_offset, addr, bytes,
1780                              AlwaysPreTouch ? false : read_only,
1781                              allow_exec, mem_tag);
1782   if (mem != nullptr && AlwaysPreTouch) {
1783     os::pretouch_memory(mem, mem + bytes);
1784   }
1785   return mem;
1786 }
1787 
1788 // JVM/TI RedefineClasses() support:
1789 // Remap the shared readonly space to shared readwrite, private.
1790 bool FileMapInfo::remap_shared_readonly_as_readwrite() {
1791   int idx = MetaspaceShared::ro;
1792   FileMapRegion* r = region_at(idx);
1793   if (!r->read_only()) {
1794     // the space is already readwrite so we are done
1795     return true;
1796   }
1797   size_t size = r->used_aligned();
1798   if (!open_for_read()) {
1799     return false;
1800   }
1801   char *addr = r->mapped_base();
1802   // This path should not be reached for Windows; see JDK-8222379.
1803   assert(WINDOWS_ONLY(false) NOT_WINDOWS(true), "Don't call on Windows");
1804   // Replace old mapping with new one that is writable.
1805   char *base = os::map_memory(_fd, _full_path, r->file_offset(),
1806                               addr, size, false /* !read_only */,
1807                               r->allow_exec());
1808   close();
1809   // These have to be errors because the shared region is now unmapped.
1810   if (base == nullptr) {
1811     log_error(cds)("Unable to remap shared readonly space (errno=%d).", errno);
1812     vm_exit(1);
1813   }
1814   if (base != addr) {
1815     log_error(cds)("Unable to remap shared readonly space (errno=%d).", errno);
1816     vm_exit(1);
1817   }
1818   r->set_read_only(false);
1819   return true;
1820 }
1821 
1822 // Memory map a region in the address space.
1823 static const char* shared_region_name[] = { "ReadWrite", "ReadOnly", "Bitmap", "Heap" };
1824 
1825 MapArchiveResult FileMapInfo::map_regions(int regions[], int num_regions, char* mapped_base_address, ReservedSpace rs) {
1826   DEBUG_ONLY(FileMapRegion* last_region = nullptr);
1827   intx addr_delta = mapped_base_address - header()->requested_base_address();
1828 
1829   // Make sure we don't attempt to use header()->mapped_base_address() unless
1830   // it's been successfully mapped.
1831   DEBUG_ONLY(header()->set_mapped_base_address((char*)(uintptr_t)0xdeadbeef);)
1832 
1833   for (int i = 0; i < num_regions; i++) {
1834     int idx = regions[i];
1835     MapArchiveResult result = map_region(idx, addr_delta, mapped_base_address, rs);
1836     if (result != MAP_ARCHIVE_SUCCESS) {
1837       return result;
1838     }
1839     FileMapRegion* r = region_at(idx);
1840     DEBUG_ONLY(if (last_region != nullptr) {
1841         // Ensure that the OS won't be able to allocate new memory spaces between any mapped
1842         // regions, or else it would mess up the simple comparison in MetaspaceObj::is_shared().
1843         assert(r->mapped_base() == last_region->mapped_end(), "must have no gaps");
1844       }
1845       last_region = r;)
1846     log_info(cds)("Mapped %s region #%d at base " INTPTR_FORMAT " top " INTPTR_FORMAT " (%s)", is_static() ? "static " : "dynamic",
1847                   idx, p2i(r->mapped_base()), p2i(r->mapped_end()),
1848                   shared_region_name[idx]);
1849 
1850   }
1851 
1852   header()->set_mapped_base_address(header()->requested_base_address() + addr_delta);
1853   if (addr_delta != 0 && !relocate_pointers_in_core_regions(addr_delta)) {
1854     return MAP_ARCHIVE_OTHER_FAILURE;
1855   }
1856 
1857   return MAP_ARCHIVE_SUCCESS;
1858 }
1859 
1860 bool FileMapInfo::read_region(int i, char* base, size_t size, bool do_commit) {
1861   FileMapRegion* r = region_at(i);
1862   if (do_commit) {
1863     log_info(cds)("Commit %s region #%d at base " INTPTR_FORMAT " top " INTPTR_FORMAT " (%s)%s",
1864                   is_static() ? "static " : "dynamic", i, p2i(base), p2i(base + size),
1865                   shared_region_name[i], r->allow_exec() ? " exec" : "");
1866     if (!os::commit_memory(base, size, r->allow_exec())) {
1867       log_error(cds)("Failed to commit %s region #%d (%s)", is_static() ? "static " : "dynamic",
1868                      i, shared_region_name[i]);
1869       return false;
1870     }
1871   }
1872   if (os::lseek(_fd, (long)r->file_offset(), SEEK_SET) != (int)r->file_offset() ||
1873       read_bytes(base, size) != size) {
1874     return false;
1875   }
1876 
1877   if (VerifySharedSpaces && !r->check_region_crc(base)) {
1878     return false;
1879   }
1880 
1881   r->set_mapped_from_file(false);
1882   r->set_mapped_base(base);
1883 
1884   return true;
1885 }
1886 
1887 MapArchiveResult FileMapInfo::map_region(int i, intx addr_delta, char* mapped_base_address, ReservedSpace rs) {
1888   assert(!HeapShared::is_heap_region(i), "sanity");
1889   FileMapRegion* r = region_at(i);
1890   size_t size = r->used_aligned();
1891   char *requested_addr = mapped_base_address + r->mapping_offset();
1892   assert(!is_mapped(), "must be not mapped yet");
1893   assert(requested_addr != nullptr, "must be specified");
1894 
1895   r->set_mapped_from_file(false);
1896   r->set_in_reserved_space(false);
1897 
1898   if (MetaspaceShared::use_windows_memory_mapping()) {
1899     // Windows cannot remap read-only shared memory to read-write when required for
1900     // RedefineClasses, which is also used by JFR.  Always map windows regions as RW.
1901     r->set_read_only(false);
1902   } else if (JvmtiExport::can_modify_any_class() || JvmtiExport::can_walk_any_space() ||
1903              Arguments::has_jfr_option()) {
1904     // If a tool agent is in use (debugging enabled), or JFR, we must map the address space RW
1905     r->set_read_only(false);
1906   } else if (addr_delta != 0) {
1907     r->set_read_only(false); // Need to patch the pointers
1908   }
1909 
1910   if (MetaspaceShared::use_windows_memory_mapping() && rs.is_reserved()) {
1911     // This is the second time we try to map the archive(s). We have already created a ReservedSpace
1912     // that covers all the FileMapRegions to ensure all regions can be mapped. However, Windows
1913     // can't mmap into a ReservedSpace, so we just ::read() the data. We're going to patch all the
1914     // regions anyway, so there's no benefit for mmap anyway.
1915     if (!read_region(i, requested_addr, size, /* do_commit = */ true)) {
1916       log_info(cds)("Failed to read %s shared space into reserved space at " INTPTR_FORMAT,
1917                     shared_region_name[i], p2i(requested_addr));
1918       return MAP_ARCHIVE_OTHER_FAILURE; // oom or I/O error.
1919     } else {
1920       assert(r->mapped_base() != nullptr, "must be initialized");
1921     }
1922   } else {
1923     // Note that this may either be a "fresh" mapping into unreserved address
1924     // space (Windows, first mapping attempt), or a mapping into pre-reserved
1925     // space (Posix). See also comment in MetaspaceShared::map_archives().
1926     char* base = map_memory(_fd, _full_path, r->file_offset(),
1927                             requested_addr, size, r->read_only(),
1928                             r->allow_exec(), mtClassShared);
1929     if (base != requested_addr) {
1930       log_info(cds)("Unable to map %s shared space at " INTPTR_FORMAT,
1931                     shared_region_name[i], p2i(requested_addr));
1932       _memory_mapping_failed = true;
1933       return MAP_ARCHIVE_MMAP_FAILURE;
1934     }
1935 
1936     if (VerifySharedSpaces && !r->check_region_crc(requested_addr)) {
1937       return MAP_ARCHIVE_OTHER_FAILURE;
1938     }
1939 
1940     r->set_mapped_from_file(true);
1941     r->set_mapped_base(requested_addr);
1942   }
1943 
1944   if (rs.is_reserved()) {
1945     char* mapped_base = r->mapped_base();
1946     assert(rs.base() <= mapped_base && mapped_base + size <= rs.end(),
1947            PTR_FORMAT " <= " PTR_FORMAT " < " PTR_FORMAT " <= " PTR_FORMAT,
1948            p2i(rs.base()), p2i(mapped_base), p2i(mapped_base + size), p2i(rs.end()));
1949     r->set_in_reserved_space(rs.is_reserved());
1950   }
1951   return MAP_ARCHIVE_SUCCESS;
1952 }
1953 
1954 // The return value is the location of the archive relocation bitmap.
1955 char* FileMapInfo::map_bitmap_region() {
1956   FileMapRegion* r = region_at(MetaspaceShared::bm);
1957   if (r->mapped_base() != nullptr) {
1958     return r->mapped_base();
1959   }
1960   bool read_only = true, allow_exec = false;
1961   char* requested_addr = nullptr; // allow OS to pick any location
1962   char* bitmap_base = map_memory(_fd, _full_path, r->file_offset(),
1963                                  requested_addr, r->used_aligned(), read_only, allow_exec, mtClassShared);
1964   if (bitmap_base == nullptr) {
1965     log_info(cds)("failed to map relocation bitmap");
1966     return nullptr;
1967   }
1968 
1969   if (VerifySharedSpaces && !r->check_region_crc(bitmap_base)) {
1970     log_error(cds)("relocation bitmap CRC error");
1971     if (!os::unmap_memory(bitmap_base, r->used_aligned())) {
1972       fatal("os::unmap_memory of relocation bitmap failed");
1973     }
1974     return nullptr;
1975   }
1976 
1977   r->set_mapped_from_file(true);
1978   r->set_mapped_base(bitmap_base);
1979   log_info(cds)("Mapped %s region #%d at base " INTPTR_FORMAT " top " INTPTR_FORMAT " (%s)",
1980                 is_static() ? "static " : "dynamic",
1981                 MetaspaceShared::bm, p2i(r->mapped_base()), p2i(r->mapped_end()),
1982                 shared_region_name[MetaspaceShared::bm]);
1983   return bitmap_base;
1984 }
1985 
1986 class SharedDataRelocationTask : public ArchiveWorkerTask {
1987 private:
1988   BitMapView* const _rw_bm;
1989   BitMapView* const _ro_bm;
1990   SharedDataRelocator* const _rw_reloc;
1991   SharedDataRelocator* const _ro_reloc;
1992 
1993 public:
1994   SharedDataRelocationTask(BitMapView* rw_bm, BitMapView* ro_bm, SharedDataRelocator* rw_reloc, SharedDataRelocator* ro_reloc) :
1995                            ArchiveWorkerTask("Shared Data Relocation"),
1996                            _rw_bm(rw_bm), _ro_bm(ro_bm), _rw_reloc(rw_reloc), _ro_reloc(ro_reloc) {}
1997 
1998   void work(int chunk, int max_chunks) override {
1999     work_on(chunk, max_chunks, _rw_bm, _rw_reloc);
2000     work_on(chunk, max_chunks, _ro_bm, _ro_reloc);
2001   }
2002 
2003   void work_on(int chunk, int max_chunks, BitMapView* bm, SharedDataRelocator* reloc) {
2004     BitMap::idx_t size  = bm->size();
2005     BitMap::idx_t start = MIN2(size, size * chunk / max_chunks);
2006     BitMap::idx_t end   = MIN2(size, size * (chunk + 1) / max_chunks);
2007     assert(end > start, "Sanity: no empty slices");
2008     bm->iterate(reloc, start, end);
2009   }
2010 };
2011 
2012 // This is called when we cannot map the archive at the requested[ base address (usually 0x800000000).
2013 // We relocate all pointers in the 2 core regions (ro, rw).
2014 bool FileMapInfo::relocate_pointers_in_core_regions(intx addr_delta) {
2015   log_debug(cds, reloc)("runtime archive relocation start");
2016   char* bitmap_base = map_bitmap_region();
2017 
2018   if (bitmap_base == nullptr) {
2019     return false; // OOM, or CRC check failure
2020   } else {
2021     BitMapView rw_ptrmap = ptrmap_view(MetaspaceShared::rw);
2022     BitMapView ro_ptrmap = ptrmap_view(MetaspaceShared::ro);
2023 
2024     FileMapRegion* rw_region = first_core_region();
2025     FileMapRegion* ro_region = last_core_region();
2026 
2027     // Patch all pointers inside the RW region
2028     address rw_patch_base = (address)rw_region->mapped_base();
2029     address rw_patch_end  = (address)rw_region->mapped_end();
2030 
2031     // Patch all pointers inside the RO region
2032     address ro_patch_base = (address)ro_region->mapped_base();
2033     address ro_patch_end  = (address)ro_region->mapped_end();
2034 
2035     // the current value of the pointers to be patched must be within this
2036     // range (i.e., must be between the requested base address and the address of the current archive).
2037     // Note: top archive may point to objects in the base archive, but not the other way around.
2038     address valid_old_base = (address)header()->requested_base_address();
2039     address valid_old_end  = valid_old_base + mapping_end_offset();
2040 
2041     // after patching, the pointers must point inside this range
2042     // (the requested location of the archive, as mapped at runtime).
2043     address valid_new_base = (address)header()->mapped_base_address();
2044     address valid_new_end  = (address)mapped_end();
2045 
2046     SharedDataRelocator rw_patcher((address*)rw_patch_base + header()->rw_ptrmap_start_pos(), (address*)rw_patch_end, valid_old_base, valid_old_end,
2047                                 valid_new_base, valid_new_end, addr_delta);
2048     SharedDataRelocator ro_patcher((address*)ro_patch_base + header()->ro_ptrmap_start_pos(), (address*)ro_patch_end, valid_old_base, valid_old_end,
2049                                 valid_new_base, valid_new_end, addr_delta);
2050 
2051     if (AOTCacheParallelRelocation) {
2052       ArchiveWorkers workers;
2053       SharedDataRelocationTask task(&rw_ptrmap, &ro_ptrmap, &rw_patcher, &ro_patcher);
2054       workers.run_task(&task);
2055     } else {
2056       rw_ptrmap.iterate(&rw_patcher);
2057       ro_ptrmap.iterate(&ro_patcher);
2058     }
2059 
2060     // The MetaspaceShared::bm region will be unmapped in MetaspaceShared::initialize_shared_spaces().
2061 
2062     log_debug(cds, reloc)("runtime archive relocation done");
2063     return true;
2064   }
2065 }
2066 
2067 size_t FileMapInfo::read_bytes(void* buffer, size_t count) {
2068   assert(_file_open, "Archive file is not open");
2069   size_t n = ::read(_fd, buffer, (unsigned int)count);
2070   if (n != count) {
2071     // Close the file if there's a problem reading it.
2072     close();
2073     return 0;
2074   }
2075   _file_offset += count;
2076   return count;
2077 }
2078 
2079 // Get the total size in bytes of a read only region
2080 size_t FileMapInfo::readonly_total() {
2081   size_t total = 0;
2082   if (current_info() != nullptr) {
2083     FileMapRegion* r = FileMapInfo::current_info()->region_at(MetaspaceShared::ro);
2084     if (r->read_only()) total += r->used();
2085   }
2086   if (dynamic_info() != nullptr) {
2087     FileMapRegion* r = FileMapInfo::dynamic_info()->region_at(MetaspaceShared::ro);
2088     if (r->read_only()) total += r->used();
2089   }
2090   return total;
2091 }
2092 
2093 #if INCLUDE_CDS_JAVA_HEAP
2094 MemRegion FileMapInfo::_mapped_heap_memregion;
2095 
2096 bool FileMapInfo::has_heap_region() {
2097   return (region_at(MetaspaceShared::hp)->used() > 0);
2098 }
2099 
2100 // Returns the address range of the archived heap region computed using the
2101 // current oop encoding mode. This range may be different than the one seen at
2102 // dump time due to encoding mode differences. The result is used in determining
2103 // if/how these regions should be relocated at run time.
2104 MemRegion FileMapInfo::get_heap_region_requested_range() {
2105   FileMapRegion* r = region_at(MetaspaceShared::hp);
2106   size_t size = r->used();
2107   assert(size > 0, "must have non-empty heap region");
2108 
2109   address start = heap_region_requested_address();
2110   address end = start + size;
2111   log_info(cds)("Requested heap region [" INTPTR_FORMAT " - " INTPTR_FORMAT "] = %8zu bytes",
2112                 p2i(start), p2i(end), size);
2113 
2114   return MemRegion((HeapWord*)start, (HeapWord*)end);
2115 }
2116 
2117 void FileMapInfo::map_or_load_heap_region() {
2118   bool success = false;
2119 
2120   if (can_use_heap_region()) {
2121     if (ArchiveHeapLoader::can_map()) {
2122       success = map_heap_region();
2123     } else if (ArchiveHeapLoader::can_load()) {
2124       success = ArchiveHeapLoader::load_heap_region(this);
2125     } else {
2126       if (!UseCompressedOops && !ArchiveHeapLoader::can_map()) {
2127         log_info(cds)("Cannot use CDS heap data. Selected GC not compatible -XX:-UseCompressedOops");
2128       } else {
2129         log_info(cds)("Cannot use CDS heap data. UseEpsilonGC, UseG1GC, UseSerialGC, UseParallelGC, or UseShenandoahGC are required.");
2130       }
2131     }
2132   }
2133 
2134   if (!success) {
2135     if (CDSConfig::is_using_aot_linked_classes()) {
2136       // It's too late to recover -- we have already committed to use the archived metaspace objects, but
2137       // the archived heap objects cannot be loaded, so we don't have the archived FMG to guarantee that
2138       // all AOT-linked classes are visible.
2139       //
2140       // We get here because the heap is too small. The app will fail anyway. So let's quit.
2141       MetaspaceShared::unrecoverable_loading_error("CDS archive has aot-linked classes but the archived "
2142                                                    "heap objects cannot be loaded. Try increasing your heap size.");
2143     }
2144     CDSConfig::stop_using_full_module_graph("archive heap loading failed");
2145   }
2146 }
2147 
2148 bool FileMapInfo::can_use_heap_region() {
2149   if (!has_heap_region()) {
2150     return false;
2151   }
2152   if (JvmtiExport::should_post_class_file_load_hook() && JvmtiExport::has_early_class_hook_env()) {
2153     ShouldNotReachHere(); // CDS should have been disabled.
2154     // The archived objects are mapped at JVM start-up, but we don't know if
2155     // j.l.String or j.l.Class might be replaced by the ClassFileLoadHook,
2156     // which would make the archived String or mirror objects invalid. Let's be safe and not
2157     // use the archived objects. These 2 classes are loaded during the JVMTI "early" stage.
2158     //
2159     // If JvmtiExport::has_early_class_hook_env() is false, the classes of some objects
2160     // in the archived subgraphs may be replaced by the ClassFileLoadHook. But that's OK
2161     // because we won't install an archived object subgraph if the klass of any of the
2162     // referenced objects are replaced. See HeapShared::initialize_from_archived_subgraph().
2163   }
2164 
2165   // We pre-compute narrow Klass IDs with the runtime mapping start intended to be the base, and a shift of
2166   // ArchiveBuilder::precomputed_narrow_klass_shift. We enforce this encoding at runtime (see
2167   // CompressedKlassPointers::initialize_for_given_encoding()). Therefore, the following assertions must
2168   // hold:
2169   address archive_narrow_klass_base = (address)header()->mapped_base_address();
2170   const int archive_narrow_klass_pointer_bits = header()->narrow_klass_pointer_bits();
2171   const int archive_narrow_klass_shift = header()->narrow_klass_shift();
2172 
2173   log_info(cds)("CDS archive was created with max heap size = %zuM, and the following configuration:",
2174                 max_heap_size()/M);
2175   log_info(cds)("    narrow_klass_base at mapping start address, narrow_klass_pointer_bits = %d, narrow_klass_shift = %d",
2176                 archive_narrow_klass_pointer_bits, archive_narrow_klass_shift);
2177   log_info(cds)("    narrow_oop_mode = %d, narrow_oop_base = " PTR_FORMAT ", narrow_oop_shift = %d",
2178                 narrow_oop_mode(), p2i(narrow_oop_base()), narrow_oop_shift());
2179   log_info(cds)("The current max heap size = %zuM, G1HeapRegion::GrainBytes = %zu",
2180                 MaxHeapSize/M, G1HeapRegion::GrainBytes);
2181   log_info(cds)("    narrow_klass_base = " PTR_FORMAT ", arrow_klass_pointer_bits = %d, narrow_klass_shift = %d",
2182                 p2i(CompressedKlassPointers::base()), CompressedKlassPointers::narrow_klass_pointer_bits(), CompressedKlassPointers::shift());
2183   log_info(cds)("    narrow_oop_mode = %d, narrow_oop_base = " PTR_FORMAT ", narrow_oop_shift = %d",
2184                 CompressedOops::mode(), p2i(CompressedOops::base()), CompressedOops::shift());
2185   log_info(cds)("    heap range = [" PTR_FORMAT " - "  PTR_FORMAT "]",
2186                 UseCompressedOops ? p2i(CompressedOops::begin()) :
2187                                     UseG1GC ? p2i((address)G1CollectedHeap::heap()->reserved().start()) : 0L,
2188                 UseCompressedOops ? p2i(CompressedOops::end()) :
2189                                     UseG1GC ? p2i((address)G1CollectedHeap::heap()->reserved().end()) : 0L);
2190 
2191   int err = 0;
2192   if ( archive_narrow_klass_base != CompressedKlassPointers::base() ||
2193        (err = 1, archive_narrow_klass_pointer_bits != CompressedKlassPointers::narrow_klass_pointer_bits()) ||
2194        (err = 2, archive_narrow_klass_shift != CompressedKlassPointers::shift()) ) {
2195     stringStream ss;
2196     switch (err) {
2197     case 0:
2198       ss.print("Unexpected encoding base encountered (" PTR_FORMAT ", expected " PTR_FORMAT ")",
2199                p2i(CompressedKlassPointers::base()), p2i(archive_narrow_klass_base));
2200       break;
2201     case 1:
2202       ss.print("Unexpected narrow Klass bit length encountered (%d, expected %d)",
2203                CompressedKlassPointers::narrow_klass_pointer_bits(), archive_narrow_klass_pointer_bits);
2204       break;
2205     case 2:
2206       ss.print("Unexpected narrow Klass shift encountered (%d, expected %d)",
2207                CompressedKlassPointers::shift(), archive_narrow_klass_shift);
2208       break;
2209     default:
2210       ShouldNotReachHere();
2211     };
2212     LogTarget(Info, cds) lt;
2213     if (lt.is_enabled()) {
2214       LogStream ls(lt);
2215       ls.print_raw(ss.base());
2216       header()->print(&ls);
2217     }
2218     assert(false, "%s", ss.base());
2219   }
2220 
2221   return true;
2222 }
2223 
2224 // The actual address of this region during dump time.
2225 address FileMapInfo::heap_region_dumptime_address() {
2226   FileMapRegion* r = region_at(MetaspaceShared::hp);
2227   assert(CDSConfig::is_using_archive(), "runtime only");
2228   assert(is_aligned(r->mapping_offset(), sizeof(HeapWord)), "must be");
2229   if (UseCompressedOops) {
2230     return /*dumptime*/ (address)((uintptr_t)narrow_oop_base() + r->mapping_offset());
2231   } else {
2232     return heap_region_requested_address();
2233   }
2234 }
2235 
2236 // The address where this region can be mapped into the runtime heap without
2237 // patching any of the pointers that are embedded in this region.
2238 address FileMapInfo::heap_region_requested_address() {
2239   assert(CDSConfig::is_using_archive(), "runtime only");
2240   FileMapRegion* r = region_at(MetaspaceShared::hp);
2241   assert(is_aligned(r->mapping_offset(), sizeof(HeapWord)), "must be");
2242   assert(ArchiveHeapLoader::can_use(), "GC must support mapping or loading");
2243   if (UseCompressedOops) {
2244     // We can avoid relocation if each region's offset from the runtime CompressedOops::base()
2245     // is the same as its offset from the CompressedOops::base() during dumptime.
2246     // Note that CompressedOops::base() may be different between dumptime and runtime.
2247     //
2248     // Example:
2249     // Dumptime base = 0x1000 and shift is 0. We have a region at address 0x2000. There's a
2250     // narrowOop P stored in this region that points to an object at address 0x2200.
2251     // P's encoded value is 0x1200.
2252     //
2253     // Runtime base = 0x4000 and shift is also 0. If we map this region at 0x5000, then
2254     // the value P can remain 0x1200. The decoded address = (0x4000 + (0x1200 << 0)) = 0x5200,
2255     // which is the runtime location of the referenced object.
2256     return /*runtime*/ (address)((uintptr_t)CompressedOops::base() + r->mapping_offset());
2257   } else {
2258     // This was the hard-coded requested base address used at dump time. With uncompressed oops,
2259     // the heap range is assigned by the OS so we will most likely have to relocate anyway, no matter
2260     // what base address was picked at duump time.
2261     return (address)ArchiveHeapWriter::NOCOOPS_REQUESTED_BASE;
2262   }
2263 }
2264 
2265 bool FileMapInfo::map_heap_region() {
2266   if (map_heap_region_impl()) {
2267 #ifdef ASSERT
2268     // The "old" regions must be parsable -- we cannot have any unused space
2269     // at the start of the lowest G1 region that contains archived objects.
2270     assert(is_aligned(_mapped_heap_memregion.start(), G1HeapRegion::GrainBytes), "must be");
2271 
2272     // Make sure we map at the very top of the heap - see comments in
2273     // init_heap_region_relocation().
2274     MemRegion heap_range = G1CollectedHeap::heap()->reserved();
2275     assert(heap_range.contains(_mapped_heap_memregion), "must be");
2276 
2277     address heap_end = (address)heap_range.end();
2278     address mapped_heap_region_end = (address)_mapped_heap_memregion.end();
2279     assert(heap_end >= mapped_heap_region_end, "must be");
2280     assert(heap_end - mapped_heap_region_end < (intx)(G1HeapRegion::GrainBytes),
2281            "must be at the top of the heap to avoid fragmentation");
2282 #endif
2283 
2284     ArchiveHeapLoader::set_mapped();
2285     return true;
2286   } else {
2287     return false;
2288   }
2289 }
2290 
2291 bool FileMapInfo::map_heap_region_impl() {
2292   assert(UseG1GC, "the following code assumes G1");
2293 
2294   FileMapRegion* r = region_at(MetaspaceShared::hp);
2295   size_t size = r->used();
2296   if (size == 0) {
2297     return false; // no archived java heap data
2298   }
2299 
2300   size_t word_size = size / HeapWordSize;
2301   address requested_start = heap_region_requested_address();
2302 
2303   log_info(cds)("Preferred address to map heap data (to avoid relocation) is " INTPTR_FORMAT, p2i(requested_start));
2304 
2305   // allocate from java heap
2306   HeapWord* start = G1CollectedHeap::heap()->alloc_archive_region(word_size, (HeapWord*)requested_start);
2307   if (start == nullptr) {
2308     log_info(cds)("UseSharedSpaces: Unable to allocate java heap region for archive heap.");
2309     return false;
2310   }
2311 
2312   _mapped_heap_memregion = MemRegion(start, word_size);
2313 
2314   // Map the archived heap data. No need to call MemTracker::record_virtual_memory_tag()
2315   // for mapped region as it is part of the reserved java heap, which is already recorded.
2316   char* addr = (char*)_mapped_heap_memregion.start();
2317   char* base;
2318 
2319   if (MetaspaceShared::use_windows_memory_mapping()) {
2320     if (!read_region(MetaspaceShared::hp, addr,
2321                      align_up(_mapped_heap_memregion.byte_size(), os::vm_page_size()),
2322                      /* do_commit = */ true)) {
2323       dealloc_heap_region();
2324       log_error(cds)("Failed to read archived heap region into " INTPTR_FORMAT, p2i(addr));
2325       return false;
2326     }
2327     // Checks for VerifySharedSpaces is already done inside read_region()
2328     base = addr;
2329   } else {
2330     base = map_memory(_fd, _full_path, r->file_offset(),
2331                       addr, _mapped_heap_memregion.byte_size(), r->read_only(),
2332                       r->allow_exec());
2333     if (base == nullptr || base != addr) {
2334       dealloc_heap_region();
2335       log_info(cds)("UseSharedSpaces: Unable to map at required address in java heap. "
2336                     INTPTR_FORMAT ", size = %zu bytes",
2337                     p2i(addr), _mapped_heap_memregion.byte_size());
2338       return false;
2339     }
2340 
2341     if (VerifySharedSpaces && !r->check_region_crc(base)) {
2342       dealloc_heap_region();
2343       log_info(cds)("UseSharedSpaces: mapped heap region is corrupt");
2344       return false;
2345     }
2346   }
2347 
2348   r->set_mapped_base(base);
2349 
2350   // If the requested range is different from the range allocated by GC, then
2351   // the pointers need to be patched.
2352   address mapped_start = (address) _mapped_heap_memregion.start();
2353   ptrdiff_t delta = mapped_start - requested_start;
2354   if (UseCompressedOops &&
2355       (narrow_oop_mode() != CompressedOops::mode() ||
2356        narrow_oop_shift() != CompressedOops::shift())) {
2357     _heap_pointers_need_patching = true;
2358   }
2359   if (delta != 0) {
2360     _heap_pointers_need_patching = true;
2361   }
2362   ArchiveHeapLoader::init_mapped_heap_info(mapped_start, delta, narrow_oop_shift());
2363 
2364   if (_heap_pointers_need_patching) {
2365     char* bitmap_base = map_bitmap_region();
2366     if (bitmap_base == nullptr) {
2367       log_info(cds)("CDS heap cannot be used because bitmap region cannot be mapped");
2368       dealloc_heap_region();
2369       _heap_pointers_need_patching = false;
2370       return false;
2371     }
2372   }
2373   log_info(cds)("Heap data mapped at " INTPTR_FORMAT ", size = %8zu bytes",
2374                 p2i(mapped_start), _mapped_heap_memregion.byte_size());
2375   log_info(cds)("CDS heap data relocation delta = %zd bytes", delta);
2376   return true;
2377 }
2378 
2379 narrowOop FileMapInfo::encoded_heap_region_dumptime_address() {
2380   assert(CDSConfig::is_using_archive(), "runtime only");
2381   assert(UseCompressedOops, "sanity");
2382   FileMapRegion* r = region_at(MetaspaceShared::hp);
2383   return CompressedOops::narrow_oop_cast(r->mapping_offset() >> narrow_oop_shift());
2384 }
2385 
2386 void FileMapInfo::patch_heap_embedded_pointers() {
2387   if (!ArchiveHeapLoader::is_mapped() || !_heap_pointers_need_patching) {
2388     return;
2389   }
2390 
2391   char* bitmap_base = map_bitmap_region();
2392   assert(bitmap_base != nullptr, "must have already been mapped");
2393 
2394   FileMapRegion* r = region_at(MetaspaceShared::hp);
2395   ArchiveHeapLoader::patch_embedded_pointers(
2396       this, _mapped_heap_memregion,
2397       (address)(region_at(MetaspaceShared::bm)->mapped_base()) + r->oopmap_offset(),
2398       r->oopmap_size_in_bits());
2399 }
2400 
2401 void FileMapInfo::fixup_mapped_heap_region() {
2402   if (ArchiveHeapLoader::is_mapped()) {
2403     assert(!_mapped_heap_memregion.is_empty(), "sanity");
2404 
2405     // Populate the archive regions' G1BlockOffsetTables. That ensures
2406     // fast G1BlockOffsetTable::block_start operations for any given address
2407     // within the archive regions when trying to find start of an object
2408     // (e.g. during card table scanning).
2409     G1CollectedHeap::heap()->populate_archive_regions_bot(_mapped_heap_memregion);
2410   }
2411 }
2412 
2413 // dealloc the archive regions from java heap
2414 void FileMapInfo::dealloc_heap_region() {
2415   G1CollectedHeap::heap()->dealloc_archive_regions(_mapped_heap_memregion);
2416 }
2417 #endif // INCLUDE_CDS_JAVA_HEAP
2418 
2419 void FileMapInfo::unmap_regions(int regions[], int num_regions) {
2420   for (int r = 0; r < num_regions; r++) {
2421     int idx = regions[r];
2422     unmap_region(idx);
2423   }
2424 }
2425 
2426 // Unmap a memory region in the address space.
2427 
2428 void FileMapInfo::unmap_region(int i) {
2429   FileMapRegion* r = region_at(i);
2430   char* mapped_base = r->mapped_base();
2431   size_t size = r->used_aligned();
2432 
2433   if (mapped_base != nullptr) {
2434     if (size > 0 && r->mapped_from_file()) {
2435       log_info(cds)("Unmapping region #%d at base " INTPTR_FORMAT " (%s)", i, p2i(mapped_base),
2436                     shared_region_name[i]);
2437       if (r->in_reserved_space()) {
2438         // This region was mapped inside a ReservedSpace. Its memory will be freed when the ReservedSpace
2439         // is released. Zero it so that we don't accidentally read its content.
2440         log_info(cds)("Region #%d (%s) is in a reserved space, it will be freed when the space is released", i, shared_region_name[i]);
2441       } else {
2442         if (!os::unmap_memory(mapped_base, size)) {
2443           fatal("os::unmap_memory failed");
2444         }
2445       }
2446     }
2447     r->set_mapped_base(nullptr);
2448   }
2449 }
2450 
2451 void FileMapInfo::assert_mark(bool check) {
2452   if (!check) {
2453     MetaspaceShared::unrecoverable_loading_error("Mark mismatch while restoring from shared file.");
2454   }
2455 }
2456 
2457 FileMapInfo* FileMapInfo::_current_info = nullptr;
2458 FileMapInfo* FileMapInfo::_dynamic_archive_info = nullptr;
2459 bool FileMapInfo::_heap_pointers_need_patching = false;
2460 SharedPathTable FileMapInfo::_shared_path_table;
2461 bool FileMapInfo::_validating_shared_path_table = false;
2462 bool FileMapInfo::_memory_mapping_failed = false;
2463 GrowableArray<const char*>* FileMapInfo::_non_existent_class_paths = nullptr;
2464 
2465 // Open the shared archive file, read and validate the header
2466 // information (version, boot classpath, etc.). If initialization
2467 // fails, shared spaces are disabled and the file is closed.
2468 //
2469 // Validation of the archive is done in two steps:
2470 //
2471 // [1] validate_header() - done here.
2472 // [2] validate_shared_path_table - this is done later, because the table is in the RW
2473 //     region of the archive, which is not mapped yet.
2474 bool FileMapInfo::initialize() {
2475   assert(CDSConfig::is_using_archive(), "UseSharedSpaces expected.");
2476   assert(Arguments::has_jimage(), "The shared archive file cannot be used with an exploded module build.");
2477 
2478   if (JvmtiExport::should_post_class_file_load_hook() && JvmtiExport::has_early_class_hook_env()) {
2479     // CDS assumes that no classes resolved in vmClasses::resolve_all()
2480     // are replaced at runtime by JVMTI ClassFileLoadHook. All of those classes are resolved
2481     // during the JVMTI "early" stage, so we can still use CDS if
2482     // JvmtiExport::has_early_class_hook_env() is false.
2483     log_info(cds)("CDS is disabled because early JVMTI ClassFileLoadHook is in use.");
2484     return false;
2485   }
2486 
2487   if (!open_for_read() || !init_from_file(_fd) || !validate_header()) {
2488     if (_is_static) {
2489       log_info(cds)("Initialize static archive failed.");
2490       return false;
2491     } else {
2492       log_info(cds)("Initialize dynamic archive failed.");
2493       if (AutoCreateSharedArchive) {
2494         CDSConfig::enable_dumping_dynamic_archive();
2495         ArchiveClassesAtExit = CDSConfig::dynamic_archive_path();
2496       }
2497       return false;
2498     }
2499   }
2500 
2501   return true;
2502 }
2503 
2504 bool FileMapInfo::validate_aot_class_linking() {
2505   // These checks need to be done after FileMapInfo::initialize(), which gets called before Universe::heap()
2506   // is available.
2507   if (header()->has_aot_linked_classes()) {
2508     CDSConfig::set_has_aot_linked_classes(true);
2509     if (JvmtiExport::should_post_class_file_load_hook()) {
2510       log_error(cds)("CDS archive has aot-linked classes. It cannot be used when JVMTI ClassFileLoadHook is in use.");
2511       return false;
2512     }
2513     if (JvmtiExport::has_early_vmstart_env()) {
2514       log_error(cds)("CDS archive has aot-linked classes. It cannot be used when JVMTI early vm start is in use.");
2515       return false;
2516     }
2517     if (!CDSConfig::is_using_full_module_graph()) {
2518       log_error(cds)("CDS archive has aot-linked classes. It cannot be used when archived full module graph is not used.");
2519       return false;
2520     }
2521 
2522     const char* prop = Arguments::get_property("java.security.manager");
2523     if (prop != nullptr && strcmp(prop, "disallow") != 0) {
2524       log_error(cds)("CDS archive has aot-linked classes. It cannot be used with -Djava.security.manager=%s.", prop);
2525       return false;
2526     }
2527 
2528 #if INCLUDE_JVMTI
2529     if (Arguments::has_jdwp_agent()) {
2530       log_error(cds)("CDS archive has aot-linked classes. It cannot be used with JDWP agent");
2531       return false;
2532     }
2533 #endif
2534   }
2535 
2536   return true;
2537 }
2538 
2539 // The 2 core spaces are RW->RO
2540 FileMapRegion* FileMapInfo::first_core_region() const {
2541   return region_at(MetaspaceShared::rw);
2542 }
2543 
2544 FileMapRegion* FileMapInfo::last_core_region() const {
2545   return region_at(MetaspaceShared::ro);
2546 }
2547 
2548 void FileMapInfo::print(outputStream* st) const {
2549   header()->print(st);
2550   if (!is_static()) {
2551     dynamic_header()->print(st);
2552   }
2553 }
2554 
2555 void FileMapHeader::set_as_offset(char* p, size_t *offset) {
2556   *offset = ArchiveBuilder::current()->any_to_offset((address)p);
2557 }
2558 
2559 int FileMapHeader::compute_crc() {
2560   char* start = (char*)this;
2561   // start computing from the field after _header_size to end of base archive name.
2562   char* buf = (char*)&(_generic_header._header_size) + sizeof(_generic_header._header_size);
2563   size_t sz = header_size() - (buf - start);
2564   int crc = ClassLoader::crc32(0, buf, (jint)sz);
2565   return crc;
2566 }
2567 
2568 // This function should only be called during run time with UseSharedSpaces enabled.
2569 bool FileMapHeader::validate() {
2570   if (_obj_alignment != ObjectAlignmentInBytes) {
2571     log_info(cds)("The shared archive file's ObjectAlignmentInBytes of %d"
2572                   " does not equal the current ObjectAlignmentInBytes of %d.",
2573                   _obj_alignment, ObjectAlignmentInBytes);
2574     return false;
2575   }
2576   if (_compact_strings != CompactStrings) {
2577     log_info(cds)("The shared archive file's CompactStrings setting (%s)"
2578                   " does not equal the current CompactStrings setting (%s).",
2579                   _compact_strings ? "enabled" : "disabled",
2580                   CompactStrings   ? "enabled" : "disabled");
2581     return false;
2582   }
2583 
2584   // This must be done after header validation because it might change the
2585   // header data
2586   const char* prop = Arguments::get_property("java.system.class.loader");
2587   if (prop != nullptr) {
2588     if (has_aot_linked_classes()) {
2589       log_error(cds)("CDS archive has aot-linked classes. It cannot be used when the "
2590                      "java.system.class.loader property is specified.");
2591       return false;
2592     }
2593     log_warning(cds)("Archived non-system classes are disabled because the "
2594             "java.system.class.loader property is specified (value = \"%s\"). "
2595             "To use archived non-system classes, this property must not be set", prop);
2596     _has_platform_or_app_classes = false;
2597   }
2598 
2599 
2600   if (!_verify_local && BytecodeVerificationLocal) {
2601     //  we cannot load boot classes, so there's no point of using the CDS archive
2602     log_info(cds)("The shared archive file's BytecodeVerificationLocal setting (%s)"
2603                                " does not equal the current BytecodeVerificationLocal setting (%s).",
2604                                _verify_local ? "enabled" : "disabled",
2605                                BytecodeVerificationLocal ? "enabled" : "disabled");
2606     return false;
2607   }
2608 
2609   // For backwards compatibility, we don't check the BytecodeVerificationRemote setting
2610   // if the archive only contains system classes.
2611   if (_has_platform_or_app_classes
2612       && !_verify_remote // we didn't verify the archived platform/app classes
2613       && BytecodeVerificationRemote) { // but we want to verify all loaded platform/app classes
2614     log_info(cds)("The shared archive file was created with less restrictive "
2615                                "verification setting than the current setting.");
2616     // Pretend that we didn't have any archived platform/app classes, so they won't be loaded
2617     // by SystemDictionaryShared.
2618     _has_platform_or_app_classes = false;
2619   }
2620 
2621   // Java agents are allowed during run time. Therefore, the following condition is not
2622   // checked: (!_allow_archiving_with_java_agent && AllowArchivingWithJavaAgent)
2623   // Note: _allow_archiving_with_java_agent is set in the shared archive during dump time
2624   // while AllowArchivingWithJavaAgent is set during the current run.
2625   if (_allow_archiving_with_java_agent && !AllowArchivingWithJavaAgent) {
2626     log_warning(cds)("The setting of the AllowArchivingWithJavaAgent is different "
2627                                "from the setting in the shared archive.");
2628     return false;
2629   }
2630 
2631   if (_allow_archiving_with_java_agent) {
2632     log_warning(cds)("This archive was created with AllowArchivingWithJavaAgent. It should be used "
2633             "for testing purposes only and should not be used in a production environment");
2634   }
2635 
2636   log_info(cds)("Archive was created with UseCompressedOops = %d, UseCompressedClassPointers = %d, UseCompactObjectHeaders = %d",
2637                           compressed_oops(), compressed_class_pointers(), compact_headers());
2638   if (compressed_oops() != UseCompressedOops || compressed_class_pointers() != UseCompressedClassPointers) {
2639     log_warning(cds)("Unable to use shared archive.\nThe saved state of UseCompressedOops and UseCompressedClassPointers is "
2640                                "different from runtime, CDS will be disabled.");
2641     return false;
2642   }
2643 
2644   if (compact_headers() != UseCompactObjectHeaders) {
2645     log_warning(cds)("Unable to use shared archive.\nThe shared archive file's UseCompactObjectHeaders setting (%s)"
2646                      " does not equal the current UseCompactObjectHeaders setting (%s).",
2647                      _compact_headers          ? "enabled" : "disabled",
2648                      UseCompactObjectHeaders   ? "enabled" : "disabled");
2649     return false;
2650   }
2651 
2652   if (!_use_optimized_module_handling) {
2653     CDSConfig::stop_using_optimized_module_handling();
2654     log_info(cds)("optimized module handling: disabled because archive was created without optimized module handling");
2655   }
2656 
2657   if (is_static()) {
2658     // Only the static archive can contain the full module graph.
2659     if (!_has_full_module_graph) {
2660       CDSConfig::stop_using_full_module_graph("archive was created without full module graph");
2661     }
2662 
2663     if (_has_archived_invokedynamic) {
2664       CDSConfig::set_has_archived_invokedynamic();
2665     }
2666   }
2667 
2668   return true;
2669 }
2670 
2671 bool FileMapInfo::validate_header() {
2672   if (!header()->validate()) {
2673     return false;
2674   }
2675   if (_is_static) {
2676     return true;
2677   } else {
2678     return DynamicArchive::validate(this);
2679   }
2680 }
2681 
2682 #if INCLUDE_JVMTI
2683 ClassPathEntry** FileMapInfo::_classpath_entries_for_jvmti = nullptr;
2684 
2685 ClassPathEntry* FileMapInfo::get_classpath_entry_for_jvmti(int i, TRAPS) {
2686   if (i == 0) {
2687     // index 0 corresponds to the ClassPathImageEntry which is a globally shared object
2688     // and should never be deleted.
2689     return ClassLoader::get_jrt_entry();
2690   }
2691   ClassPathEntry* ent = _classpath_entries_for_jvmti[i];
2692   if (ent == nullptr) {
2693     SharedClassPathEntry* scpe = shared_path(i);
2694     assert(scpe->is_jar(), "must be"); // other types of scpe will not produce archived classes
2695 
2696     const char* path = scpe->name();
2697     struct stat st;
2698     if (os::stat(path, &st) != 0) {
2699       char *msg = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, strlen(path) + 128);
2700       jio_snprintf(msg, strlen(path) + 127, "error in finding JAR file %s", path);
2701       THROW_MSG_(vmSymbols::java_io_IOException(), msg, nullptr);
2702     } else {
2703       ent = ClassLoader::create_class_path_entry(THREAD, path, &st, false, false, scpe->is_multi_release());
2704       if (ent == nullptr) {
2705         char *msg = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, strlen(path) + 128);
2706         jio_snprintf(msg, strlen(path) + 127, "error in opening JAR file %s", path);
2707         THROW_MSG_(vmSymbols::java_io_IOException(), msg, nullptr);
2708       }
2709     }
2710 
2711     MutexLocker mu(THREAD, CDSClassFileStream_lock);
2712     if (_classpath_entries_for_jvmti[i] == nullptr) {
2713       _classpath_entries_for_jvmti[i] = ent;
2714     } else {
2715       // Another thread has beat me to creating this entry
2716       delete ent;
2717       ent = _classpath_entries_for_jvmti[i];
2718     }
2719   }
2720 
2721   return ent;
2722 }
2723 
2724 ClassFileStream* FileMapInfo::open_stream_for_jvmti(InstanceKlass* ik, Handle class_loader, TRAPS) {
2725   int path_index = ik->shared_classpath_index();
2726   assert(path_index >= 0, "should be called for shared built-in classes only");
2727   assert(path_index < (int)get_number_of_shared_paths(), "sanity");
2728 
2729   ClassPathEntry* cpe = get_classpath_entry_for_jvmti(path_index, CHECK_NULL);
2730   assert(cpe != nullptr, "must be");
2731 
2732   Symbol* name = ik->name();
2733   const char* const class_name = name->as_C_string();
2734   const char* const file_name = ClassLoader::file_name_for_class_name(class_name,
2735                                                                       name->utf8_length());
2736   ClassLoaderData* loader_data = ClassLoaderData::class_loader_data(class_loader());
2737   ClassFileStream* cfs;
2738   if (class_loader() != nullptr && !cpe->is_modules_image() && cpe->is_multi_release_jar()) {
2739     cfs = get_stream_from_class_loader(class_loader, cpe, file_name, CHECK_NULL);
2740   } else {
2741     cfs = cpe->open_stream_for_loader(THREAD, file_name, loader_data);
2742   }
2743   assert(cfs != nullptr, "must be able to read the classfile data of shared classes for built-in loaders.");
2744   log_debug(cds, jvmti)("classfile data for %s [%d: %s] = %d bytes", class_name, path_index,
2745                         cfs->source(), cfs->length());
2746   return cfs;
2747 }
2748 
2749 ClassFileStream* FileMapInfo::get_stream_from_class_loader(Handle class_loader,
2750                                                            ClassPathEntry* cpe,
2751                                                            const char* file_name,
2752                                                            TRAPS) {
2753   JavaValue result(T_OBJECT);
2754   oop class_name = java_lang_String::create_oop_from_str(file_name, THREAD);
2755   Handle h_class_name = Handle(THREAD, class_name);
2756 
2757   // byte[] ClassLoader.getResourceAsByteArray(String name)
2758   JavaCalls::call_virtual(&result,
2759                           class_loader,
2760                           vmClasses::ClassLoader_klass(),
2761                           vmSymbols::getResourceAsByteArray_name(),
2762                           vmSymbols::getResourceAsByteArray_signature(),
2763                           h_class_name,
2764                           CHECK_NULL);
2765   assert(result.get_type() == T_OBJECT, "just checking");
2766   oop obj = result.get_oop();
2767   assert(obj != nullptr, "ClassLoader.getResourceAsByteArray should not return null");
2768 
2769   // copy from byte[] to a buffer
2770   typeArrayOop ba = typeArrayOop(obj);
2771   jint len = ba->length();
2772   u1* buffer = NEW_RESOURCE_ARRAY(u1, len);
2773   ArrayAccess<>::arraycopy_to_native<>(ba, typeArrayOopDesc::element_offset<jbyte>(0), buffer, len);
2774 
2775   return new ClassFileStream(buffer, len, cpe->name());
2776 }
2777 #endif