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/aotClassLocation.hpp"
  26 #include "cds/aotLogging.hpp"
  27 #include "cds/aotMappedHeapLoader.hpp"
  28 #include "cds/aotMappedHeapWriter.hpp"
  29 #include "cds/aotMetaspace.hpp"
  30 #include "cds/archiveBuilder.hpp"
  31 #include "cds/archiveUtils.inline.hpp"
  32 #include "cds/cds_globals.hpp"
  33 #include "cds/cdsConfig.hpp"
  34 #include "cds/dynamicArchive.hpp"
  35 #include "cds/filemap.hpp"
  36 #include "cds/heapShared.inline.hpp"
  37 #include "classfile/altHashing.hpp"
  38 #include "classfile/classFileStream.hpp"
  39 #include "classfile/classLoader.hpp"
  40 #include "classfile/classLoader.inline.hpp"
  41 #include "classfile/classLoaderData.inline.hpp"
  42 #include "classfile/symbolTable.hpp"
  43 #include "classfile/systemDictionaryShared.hpp"
  44 #include "classfile/vmClasses.hpp"
  45 #include "classfile/vmSymbols.hpp"
  46 #include "compiler/compilerDefinitions.inline.hpp"
  47 #include "jvm.h"
  48 #include "logging/log.hpp"
  49 #include "logging/logMessage.hpp"
  50 #include "logging/logStream.hpp"
  51 #include "memory/iterator.inline.hpp"
  52 #include "memory/metadataFactory.hpp"
  53 #include "memory/metaspaceClosure.hpp"
  54 #include "memory/oopFactory.hpp"
  55 #include "memory/universe.hpp"
  56 #include "nmt/memTracker.hpp"
  57 #include "oops/access.hpp"
  58 #include "oops/compressedKlass.hpp"
  59 #include "oops/compressedOops.hpp"
  60 #include "oops/compressedOops.inline.hpp"
  61 #include "oops/objArrayOop.hpp"
  62 #include "oops/oop.inline.hpp"
  63 #include "oops/trainingData.hpp"
  64 #include "oops/typeArrayKlass.hpp"
  65 #include "prims/jvmtiExport.hpp"
  66 #include "runtime/arguments.hpp"
  67 #include "runtime/globals_extension.hpp"
  68 #include "runtime/java.hpp"
  69 #include "runtime/javaCalls.hpp"
  70 #include "runtime/mutexLocker.hpp"
  71 #include "runtime/os.hpp"
  72 #include "runtime/vm_version.hpp"
  73 #include "utilities/align.hpp"
  74 #include "utilities/bitMap.inline.hpp"
  75 #include "utilities/classpathStream.hpp"
  76 #include "utilities/defaultStream.hpp"
  77 #include "utilities/ostream.hpp"
  78 #if INCLUDE_G1GC
  79 #include "gc/g1/g1CollectedHeap.hpp"
  80 #include "gc/g1/g1HeapRegion.hpp"
  81 #endif
  82 
  83 #include <errno.h>
  84 #include <sys/stat.h>
  85 
  86 #ifndef O_BINARY       // if defined (Win32) use binary files.
  87 #define O_BINARY 0     // otherwise do nothing.
  88 #endif
  89 
  90 // Fill in the fileMapInfo structure with data about this VM instance.
  91 
  92 // This method copies the vm version info into header_version.  If the version is too
  93 // long then a truncated version, which has a hash code appended to it, is copied.
  94 //
  95 // Using a template enables this method to verify that header_version is an array of
  96 // length JVM_IDENT_MAX.  This ensures that the code that writes to the CDS file and
  97 // the code that reads the CDS file will both use the same size buffer.  Hence, will
  98 // use identical truncation.  This is necessary for matching of truncated versions.
  99 template <int N> static void get_header_version(char (&header_version) [N]) {
 100   assert(N == JVM_IDENT_MAX, "Bad header_version size");
 101 
 102   const char *vm_version = VM_Version::internal_vm_info_string();
 103   const int version_len = (int)strlen(vm_version);
 104 
 105   memset(header_version, 0, JVM_IDENT_MAX);
 106 
 107   if (version_len < (JVM_IDENT_MAX-1)) {
 108     strcpy(header_version, vm_version);
 109 
 110   } else {
 111     // Get the hash value.  Use a static seed because the hash needs to return the same
 112     // value over multiple jvm invocations.
 113     uint32_t hash = AltHashing::halfsiphash_32(8191, (const uint8_t*)vm_version, version_len);
 114 
 115     // Truncate the ident, saving room for the 8 hex character hash value.
 116     strncpy(header_version, vm_version, JVM_IDENT_MAX-9);
 117 
 118     // Append the hash code as eight hex digits.
 119     os::snprintf_checked(&header_version[JVM_IDENT_MAX-9], 9, "%08x", hash);
 120   }
 121 
 122   assert(header_version[JVM_IDENT_MAX-1] == 0, "must be");
 123 }
 124 
 125 FileMapInfo::FileMapInfo(const char* full_path, bool is_static) :
 126   _is_static(is_static), _file_open(false), _is_mapped(false), _fd(-1), _file_offset(0),
 127   _full_path(full_path), _base_archive_name(nullptr), _header(nullptr) {
 128   if (_is_static) {
 129     assert(_current_info == nullptr, "must be singleton"); // not thread safe
 130     _current_info = this;
 131   } else {
 132     assert(_dynamic_archive_info == nullptr, "must be singleton"); // not thread safe
 133     _dynamic_archive_info = this;
 134   }
 135 }
 136 
 137 FileMapInfo::~FileMapInfo() {
 138   if (_is_static) {
 139     assert(_current_info == this, "must be singleton"); // not thread safe
 140     _current_info = nullptr;
 141   } else {
 142     assert(_dynamic_archive_info == this, "must be singleton"); // not thread safe
 143     _dynamic_archive_info = nullptr;
 144   }
 145 
 146   if (_header != nullptr) {
 147     os::free(_header);
 148   }
 149 
 150   if (_file_open) {
 151     ::close(_fd);
 152   }
 153 }
 154 
 155 void FileMapInfo::free_current_info() {
 156   assert(CDSConfig::is_dumping_final_static_archive(), "only supported in this mode");
 157   assert(_current_info != nullptr, "sanity");
 158   delete _current_info;
 159   assert(_current_info == nullptr, "sanity"); // Side effect expected from the above "delete" operator.
 160 }
 161 
 162 void FileMapInfo::populate_header(size_t core_region_alignment) {
 163   assert(_header == nullptr, "Sanity check");
 164   size_t c_header_size;
 165   size_t header_size;
 166   size_t base_archive_name_size = 0;
 167   size_t base_archive_name_offset = 0;
 168   if (is_static()) {
 169     c_header_size = sizeof(FileMapHeader);
 170     header_size = c_header_size;
 171   } else {
 172     // dynamic header including base archive name for non-default base archive
 173     c_header_size = sizeof(DynamicArchiveHeader);
 174     header_size = c_header_size;
 175 
 176     const char* default_base_archive_name = CDSConfig::default_archive_path();
 177     const char* current_base_archive_name = CDSConfig::input_static_archive_path();
 178     if (!os::same_files(current_base_archive_name, default_base_archive_name)) {
 179       base_archive_name_size = strlen(current_base_archive_name) + 1;
 180       header_size += base_archive_name_size;
 181       base_archive_name_offset = c_header_size;
 182     }
 183   }
 184   _header = (FileMapHeader*)os::malloc(header_size, mtInternal);
 185   memset((void*)_header, 0, header_size);
 186   _header->populate(this,
 187                     core_region_alignment,
 188                     header_size,
 189                     base_archive_name_size,
 190                     base_archive_name_offset);
 191 }
 192 
 193 void FileMapHeader::populate(FileMapInfo *info, size_t core_region_alignment,
 194                              size_t header_size, size_t base_archive_name_size,
 195                              size_t base_archive_name_offset) {
 196   // 1. We require _generic_header._magic to be at the beginning of the file
 197   // 2. FileMapHeader also assumes that _generic_header is at the beginning of the file
 198   assert(offset_of(FileMapHeader, _generic_header) == 0, "must be");
 199   set_header_size((unsigned int)header_size);
 200   set_base_archive_name_offset((unsigned int)base_archive_name_offset);
 201   set_base_archive_name_size((unsigned int)base_archive_name_size);
 202   if (CDSConfig::is_dumping_dynamic_archive()) {
 203     set_magic(CDS_DYNAMIC_ARCHIVE_MAGIC);
 204   } else if (CDSConfig::is_dumping_preimage_static_archive()) {
 205     set_magic(CDS_PREIMAGE_ARCHIVE_MAGIC);
 206   } else {
 207     set_magic(CDS_ARCHIVE_MAGIC);
 208   }
 209   set_version(CURRENT_CDS_ARCHIVE_VERSION);
 210 
 211   if (!info->is_static() && base_archive_name_size != 0) {
 212     // copy base archive name
 213     copy_base_archive_name(CDSConfig::input_static_archive_path());
 214   }
 215   _core_region_alignment = core_region_alignment;
 216   _obj_alignment = ObjectAlignmentInBytes;
 217   _compact_strings = CompactStrings;
 218   _compact_headers = UseCompactObjectHeaders;
 219 #if INCLUDE_CDS_JAVA_HEAP
 220   if (CDSConfig::is_dumping_heap()) {
 221     _object_streaming_mode = HeapShared::is_writing_streaming_mode();
 222     _narrow_oop_mode = AOTMappedHeapWriter::narrow_oop_mode();
 223     _narrow_oop_base = AOTMappedHeapWriter::narrow_oop_base();
 224     _narrow_oop_shift = AOTMappedHeapWriter::narrow_oop_shift();
 225   }
 226 #endif
 227   _compressed_oops = UseCompressedOops;
 228   _compressed_class_ptrs = UseCompressedClassPointers;
 229   if (UseCompressedClassPointers) {
 230 #ifdef _LP64
 231     _narrow_klass_pointer_bits = CompressedKlassPointers::narrow_klass_pointer_bits();
 232     _narrow_klass_shift = ArchiveBuilder::precomputed_narrow_klass_shift();
 233 #endif
 234   } else {
 235     _narrow_klass_pointer_bits = _narrow_klass_shift = -1;
 236   }
 237   // Which JIT compier is used
 238   _compiler_type = (u1)CompilerConfig::compiler_type();
 239   _type_profile_level = TypeProfileLevel;
 240   _type_profile_args_limit = TypeProfileArgsLimit;
 241   _type_profile_parms_limit = TypeProfileParmsLimit;
 242   _type_profile_width = TypeProfileWidth;
 243   _bci_profile_width = BciProfileWidth;
 244   _profile_traps = ProfileTraps;
 245   _type_profile_casts = TypeProfileCasts;
 246   _spec_trap_limit_extra_entries = SpecTrapLimitExtraEntries;
 247   _max_heap_size = MaxHeapSize;
 248   _use_optimized_module_handling = CDSConfig::is_using_optimized_module_handling();
 249   _has_aot_linked_classes = CDSConfig::is_dumping_aot_linked_classes();
 250   _has_full_module_graph = CDSConfig::is_dumping_full_module_graph();
 251   _gc_kind = (int)Universe::heap()->kind();
 252   jio_snprintf(_gc_name, sizeof(_gc_name), Universe::heap()->name());
 253 
 254   // The following fields are for sanity checks for whether this archive
 255   // will function correctly with this JVM and the bootclasspath it's
 256   // invoked with.
 257 
 258   // JVM version string ... changes on each build.
 259   get_header_version(_jvm_ident);
 260 
 261   _verify_local = BytecodeVerificationLocal;
 262   _verify_remote = BytecodeVerificationRemote;
 263   _has_platform_or_app_classes = AOTClassLocationConfig::dumptime()->has_platform_or_app_classes();
 264   _requested_base_address = (char*)SharedBaseAddress;
 265   _mapped_base_address = (char*)SharedBaseAddress;
 266 }
 267 
 268 void FileMapHeader::copy_base_archive_name(const char* archive) {
 269   assert(base_archive_name_size() != 0, "_base_archive_name_size not set");
 270   assert(base_archive_name_offset() != 0, "_base_archive_name_offset not set");
 271   assert(header_size() > sizeof(*this), "_base_archive_name_size not included in header size?");
 272   memcpy((char*)this + base_archive_name_offset(), archive, base_archive_name_size());
 273 }
 274 
 275 void FileMapHeader::print(outputStream* st) {
 276   ResourceMark rm;
 277 
 278   st->print_cr("- magic:                          0x%08x", magic());
 279   st->print_cr("- crc:                            0x%08x", crc());
 280   st->print_cr("- version:                        0x%x", version());
 281   st->print_cr("- header_size:                    " UINT32_FORMAT, header_size());
 282   st->print_cr("- base_archive_name_offset:       " UINT32_FORMAT, base_archive_name_offset());
 283   st->print_cr("- base_archive_name_size:         " UINT32_FORMAT, base_archive_name_size());
 284 
 285   for (int i = 0; i < NUM_CDS_REGIONS; i++) {
 286     FileMapRegion* r = region_at(i);
 287     r->print(st, i);
 288   }
 289   st->print_cr("============ end regions ======== ");
 290 
 291   st->print_cr("- core_region_alignment:                    %zu", _core_region_alignment);
 292   st->print_cr("- obj_alignment:                            %d", _obj_alignment);
 293   st->print_cr("- narrow_oop_base:                          " INTPTR_FORMAT, p2i(_narrow_oop_base));
 294   st->print_cr("- narrow_oop_shift                          %d", _narrow_oop_shift);
 295   st->print_cr("- compact_strings:                          %d", _compact_strings);
 296   st->print_cr("- compact_headers:                          %d", _compact_headers);
 297   st->print_cr("- max_heap_size:                            %zu", _max_heap_size);
 298   st->print_cr("- narrow_oop_mode:                          %d", _narrow_oop_mode);
 299   st->print_cr("- compressed_oops:                          %d", _compressed_oops);
 300   st->print_cr("- compressed_class_ptrs:                    %d", _compressed_class_ptrs);
 301   st->print_cr("- narrow_klass_pointer_bits:                %d", _narrow_klass_pointer_bits);
 302   st->print_cr("- narrow_klass_shift:                       %d", _narrow_klass_shift);
 303   st->print_cr("- cloned_vtables_offset:                    0x%zx", _cloned_vtables_offset);
 304   st->print_cr("- early_serialized_data_offset:             0x%zx", _early_serialized_data_offset);
 305   st->print_cr("- serialized_data_offset:                   0x%zx", _serialized_data_offset);
 306   st->print_cr("- jvm_ident:                                %s", _jvm_ident);
 307   st->print_cr("- class_location_config_offset:             0x%zx", _class_location_config_offset);
 308   st->print_cr("- verify_local:                             %d", _verify_local);
 309   st->print_cr("- verify_remote:                            %d", _verify_remote);
 310   st->print_cr("- has_platform_or_app_classes:              %d", _has_platform_or_app_classes);
 311   st->print_cr("- requested_base_address:                   " INTPTR_FORMAT, p2i(_requested_base_address));
 312   st->print_cr("- mapped_base_address:                      " INTPTR_FORMAT, p2i(_mapped_base_address));
 313 
 314   st->print_cr("- object_streaming_mode:                    %d", _object_streaming_mode);
 315   st->print_cr("- mapped_heap_header");
 316   st->print_cr("  - root_segments");
 317   st->print_cr("    - roots_count:                          %d", _mapped_heap_header.root_segments().roots_count());
 318   st->print_cr("    - base_offset:                          0x%zx", _mapped_heap_header.root_segments().base_offset());
 319   st->print_cr("    - count:                                %zu", _mapped_heap_header.root_segments().count());
 320   st->print_cr("    - max_size_elems:                       %d", _mapped_heap_header.root_segments().max_size_in_elems());
 321   st->print_cr("    - max_size_bytes:                       %zu", _mapped_heap_header.root_segments().max_size_in_bytes());
 322   st->print_cr("  - oopmap_start_pos:                       %zu", _mapped_heap_header.oopmap_start_pos());
 323   st->print_cr("  - oopmap_ptrmap_pos:                      %zu", _mapped_heap_header.ptrmap_start_pos());
 324   st->print_cr("- streamed_heap_header");
 325   st->print_cr("  - forwarding_offset:                      %zu", _streamed_heap_header.forwarding_offset());
 326   st->print_cr("  - roots_offset:                           %zu", _streamed_heap_header.roots_offset());
 327   st->print_cr("  - num_roots:                              %zu", _streamed_heap_header.num_roots());
 328   st->print_cr("  - root_highest_object_index_table_offset: %zu", _streamed_heap_header.root_highest_object_index_table_offset());
 329   st->print_cr("  - num_archived_objects:                   %zu", _streamed_heap_header.num_archived_objects());
 330 
 331   st->print_cr("- _rw_ptrmap_start_pos:                     %zu", _rw_ptrmap_start_pos);
 332   st->print_cr("- _ro_ptrmap_start_pos:                     %zu", _ro_ptrmap_start_pos);
 333   st->print_cr("- use_optimized_module_handling:            %d", _use_optimized_module_handling);
 334   st->print_cr("- has_full_module_graph                     %d", _has_full_module_graph);
 335   st->print_cr("- has_aot_linked_classes                    %d", _has_aot_linked_classes);
 336   st->print_cr("- ptrmap_size_in_bits:                      %zu", _ptrmap_size_in_bits);
 337 }
 338 
 339 bool FileMapInfo::validate_class_location() {
 340   assert(CDSConfig::is_using_archive(), "runtime only");
 341 
 342   AOTClassLocationConfig* config = header()->class_location_config();
 343   bool has_extra_module_paths = false;
 344   if (!config->validate(full_path(), header()->has_aot_linked_classes(), &has_extra_module_paths)) {
 345     if (PrintSharedArchiveAndExit) {
 346       AOTMetaspace::set_archive_loading_failed();
 347       return true;
 348     } else {
 349       return false;
 350     }
 351   }
 352 
 353   if (header()->has_full_module_graph() && has_extra_module_paths) {
 354     CDSConfig::stop_using_optimized_module_handling();
 355     AOTMetaspace::report_loading_error("optimized module handling: disabled because extra module path(s) are specified");
 356   }
 357 
 358   if (CDSConfig::is_dumping_dynamic_archive()) {
 359     // Only support dynamic dumping with the usage of the default CDS archive
 360     // or a simple base archive.
 361     // If the base layer archive contains additional path component besides
 362     // the runtime image and the -cp, dynamic dumping is disabled.
 363     if (config->num_boot_classpaths() > 0) {
 364       CDSConfig::disable_dumping_dynamic_archive();
 365       aot_log_warning(aot)(
 366         "Dynamic archiving is disabled because base layer archive has appended boot classpath");
 367     }
 368     if (config->num_module_paths() > 0) {
 369       if (has_extra_module_paths) {
 370         CDSConfig::disable_dumping_dynamic_archive();
 371         aot_log_warning(aot)(
 372           "Dynamic archiving is disabled because base layer archive has a different module path");
 373       }
 374     }
 375   }
 376 
 377 #if INCLUDE_JVMTI
 378   if (_classpath_entries_for_jvmti != nullptr) {
 379     os::free(_classpath_entries_for_jvmti);
 380   }
 381   size_t sz = sizeof(ClassPathEntry*) * AOTClassLocationConfig::runtime()->length();
 382   _classpath_entries_for_jvmti = (ClassPathEntry**)os::malloc(sz, mtClass);
 383   memset((void*)_classpath_entries_for_jvmti, 0, sz);
 384 #endif
 385 
 386   return true;
 387 }
 388 
 389 // A utility class for reading/validating the GenericCDSFileMapHeader portion of
 390 // a CDS archive's header. The file header of all CDS archives with versions from
 391 // CDS_GENERIC_HEADER_SUPPORTED_MIN_VERSION (12) are guaranteed to always start
 392 // with GenericCDSFileMapHeader. This makes it possible to read important information
 393 // from a CDS archive created by a different version of HotSpot, so that we can
 394 // automatically regenerate the archive as necessary (JDK-8261455).
 395 class FileHeaderHelper {
 396   int _fd;
 397   bool _is_valid;
 398   bool _is_static;
 399   GenericCDSFileMapHeader* _header;
 400   const char* _archive_name;
 401   const char* _base_archive_name;
 402 
 403 public:
 404   FileHeaderHelper(const char* archive_name, bool is_static) {
 405     _fd = -1;
 406     _is_valid = false;
 407     _header = nullptr;
 408     _base_archive_name = nullptr;
 409     _archive_name = archive_name;
 410     _is_static = is_static;
 411   }
 412 
 413   ~FileHeaderHelper() {
 414     if (_header != nullptr) {
 415       FREE_C_HEAP_ARRAY(char, _header);
 416     }
 417     if (_fd != -1) {
 418       ::close(_fd);
 419     }
 420   }
 421 
 422   bool initialize() {
 423     assert(_archive_name != nullptr, "Archive name is null");
 424     _fd = os::open(_archive_name, O_RDONLY | O_BINARY, 0);
 425     if (_fd < 0) {
 426       AOTMetaspace::report_loading_error("Specified %s not found (%s)", CDSConfig::type_of_archive_being_loaded(), _archive_name);
 427       return false;
 428     }
 429     return initialize(_fd);
 430   }
 431 
 432   // for an already opened file, do not set _fd
 433   bool initialize(int fd) {
 434     assert(_archive_name != nullptr, "Archive name is null");
 435     assert(fd != -1, "Archive must be opened already");
 436     // First read the generic header so we know the exact size of the actual header.
 437     const char* file_type = CDSConfig::type_of_archive_being_loaded();
 438     GenericCDSFileMapHeader gen_header;
 439     size_t size = sizeof(GenericCDSFileMapHeader);
 440     os::lseek(fd, 0, SEEK_SET);
 441     size_t n = ::read(fd, (void*)&gen_header, (unsigned int)size);
 442     if (n != size) {
 443       aot_log_warning(aot)("Unable to read generic CDS file map header from %s", file_type);
 444       return false;
 445     }
 446 
 447     if (gen_header._magic != CDS_ARCHIVE_MAGIC &&
 448         gen_header._magic != CDS_DYNAMIC_ARCHIVE_MAGIC &&
 449         gen_header._magic != CDS_PREIMAGE_ARCHIVE_MAGIC) {
 450       aot_log_warning(aot)("The %s has a bad magic number: %#x", file_type, gen_header._magic);
 451       return false;
 452     }
 453 
 454     if (gen_header._version < CDS_GENERIC_HEADER_SUPPORTED_MIN_VERSION) {
 455       aot_log_warning(aot)("Cannot handle %s version 0x%x. Must be at least 0x%x.",
 456                        file_type, gen_header._version, CDS_GENERIC_HEADER_SUPPORTED_MIN_VERSION);
 457       return false;
 458     }
 459 
 460     if (gen_header._version !=  CURRENT_CDS_ARCHIVE_VERSION) {
 461       aot_log_warning(aot)("The %s version 0x%x does not match the required version 0x%x.",
 462                        file_type, gen_header._version, CURRENT_CDS_ARCHIVE_VERSION);
 463     }
 464 
 465     size_t filelen = os::lseek(fd, 0, SEEK_END);
 466     if (gen_header._header_size >= filelen) {
 467       aot_log_warning(aot)("Archive file header larger than archive file");
 468       return false;
 469     }
 470 
 471     // Read the actual header and perform more checks
 472     size = gen_header._header_size;
 473     _header = (GenericCDSFileMapHeader*)NEW_C_HEAP_ARRAY(char, size, mtInternal);
 474     os::lseek(fd, 0, SEEK_SET);
 475     n = ::read(fd, (void*)_header, (unsigned int)size);
 476     if (n != size) {
 477       aot_log_warning(aot)("Unable to read file map header from %s", file_type);
 478       return false;
 479     }
 480 
 481     if (!check_header_crc()) {
 482       return false;
 483     }
 484 
 485     if (!check_and_init_base_archive_name()) {
 486       return false;
 487     }
 488 
 489     // All fields in the GenericCDSFileMapHeader has been validated.
 490     _is_valid = true;
 491     return true;
 492   }
 493 
 494   GenericCDSFileMapHeader* get_generic_file_header() {
 495     assert(_header != nullptr && _is_valid, "must be a valid archive file");
 496     return _header;
 497   }
 498 
 499   const char* base_archive_name() {
 500     assert(_header != nullptr && _is_valid, "must be a valid archive file");
 501     return _base_archive_name;
 502   }
 503 
 504   bool is_static_archive() const {
 505     return _header->_magic == CDS_ARCHIVE_MAGIC;
 506   }
 507 
 508   bool is_dynamic_archive() const {
 509     return _header->_magic == CDS_DYNAMIC_ARCHIVE_MAGIC;
 510   }
 511 
 512   bool is_preimage_static_archive() const {
 513     return _header->_magic == CDS_PREIMAGE_ARCHIVE_MAGIC;
 514   }
 515 
 516  private:
 517   bool check_header_crc() const {
 518     if (VerifySharedSpaces) {
 519       FileMapHeader* header = (FileMapHeader*)_header;
 520       int actual_crc = header->compute_crc();
 521       if (actual_crc != header->crc()) {
 522         aot_log_info(aot)("_crc expected: %d", header->crc());
 523         aot_log_info(aot)("       actual: %d", actual_crc);
 524         aot_log_warning(aot)("Header checksum verification failed.");
 525         return false;
 526       }
 527     }
 528     return true;
 529   }
 530 
 531   bool check_and_init_base_archive_name() {
 532     unsigned int name_offset = _header->_base_archive_name_offset;
 533     unsigned int name_size   = _header->_base_archive_name_size;
 534     unsigned int header_size = _header->_header_size;
 535 
 536     if (name_offset + name_size < name_offset) {
 537       aot_log_warning(aot)("base_archive_name offset/size overflow: " UINT32_FORMAT "/" UINT32_FORMAT,
 538                                  name_offset, name_size);
 539       return false;
 540     }
 541 
 542     if (is_static_archive() || is_preimage_static_archive()) {
 543       if (name_offset != 0) {
 544         aot_log_warning(aot)("static shared archive must have zero _base_archive_name_offset");
 545         return false;
 546       }
 547       if (name_size != 0) {
 548         aot_log_warning(aot)("static shared archive must have zero _base_archive_name_size");
 549         return false;
 550       }
 551     } else {
 552       assert(is_dynamic_archive(), "must be");
 553       if ((name_size == 0 && name_offset != 0) ||
 554           (name_size != 0 && name_offset == 0)) {
 555         // If either is zero, both must be zero. This indicates that we are using the default base archive.
 556         aot_log_warning(aot)("Invalid base_archive_name offset/size: " UINT32_FORMAT "/" UINT32_FORMAT,
 557                                    name_offset, name_size);
 558         return false;
 559       }
 560       if (name_size > 0) {
 561         if (name_offset + name_size > header_size) {
 562           aot_log_warning(aot)("Invalid base_archive_name offset/size (out of range): "
 563                                      UINT32_FORMAT " + " UINT32_FORMAT " > " UINT32_FORMAT ,
 564                                      name_offset, name_size, header_size);
 565           return false;
 566         }
 567         const char* name = ((const char*)_header) + _header->_base_archive_name_offset;
 568         if (name[name_size - 1] != '\0' || strlen(name) != name_size - 1) {
 569           aot_log_warning(aot)("Base archive name is damaged");
 570           return false;
 571         }
 572         if (!os::file_exists(name)) {
 573           aot_log_warning(aot)("Base archive %s does not exist", name);
 574           return false;
 575         }
 576         _base_archive_name = name;
 577       }
 578     }
 579 
 580     return true;
 581   }
 582 };
 583 
 584 // Return value:
 585 // false:
 586 //      <archive_name> is not a valid archive. *base_archive_name is set to null.
 587 // true && (*base_archive_name) == nullptr:
 588 //      <archive_name> is a valid static archive.
 589 // true && (*base_archive_name) != nullptr:
 590 //      <archive_name> is a valid dynamic archive.
 591 bool FileMapInfo::get_base_archive_name_from_header(const char* archive_name,
 592                                                     const char** base_archive_name) {
 593   FileHeaderHelper file_helper(archive_name, false);
 594   *base_archive_name = nullptr;
 595 
 596   if (!file_helper.initialize()) {
 597     return false;
 598   }
 599   GenericCDSFileMapHeader* header = file_helper.get_generic_file_header();
 600   switch (header->_magic) {
 601   case CDS_PREIMAGE_ARCHIVE_MAGIC:
 602     return false; // This is a binary config file, not a proper archive
 603   case CDS_DYNAMIC_ARCHIVE_MAGIC:
 604     break;
 605   default:
 606     assert(header->_magic == CDS_ARCHIVE_MAGIC, "must be");
 607     if (AutoCreateSharedArchive) {
 608      aot_log_warning(aot)("AutoCreateSharedArchive is ignored because %s is a static archive", archive_name);
 609     }
 610     return true;
 611   }
 612 
 613   const char* base = file_helper.base_archive_name();
 614   if (base == nullptr) {
 615     *base_archive_name = CDSConfig::default_archive_path();
 616   } else {
 617     *base_archive_name = os::strdup_check_oom(base);
 618   }
 619 
 620   return true;
 621 }
 622 
 623 bool FileMapInfo::is_preimage_static_archive(const char* file) {
 624   FileHeaderHelper file_helper(file, false);
 625   if (!file_helper.initialize()) {
 626     return false;
 627   }
 628   return file_helper.is_preimage_static_archive();
 629 }
 630 
 631 // Read the FileMapInfo information from the file.
 632 
 633 bool FileMapInfo::init_from_file(int fd) {
 634   FileHeaderHelper file_helper(_full_path, _is_static);
 635   if (!file_helper.initialize(fd)) {
 636     aot_log_warning(aot)("Unable to read the file header.");
 637     return false;
 638   }
 639   GenericCDSFileMapHeader* gen_header = file_helper.get_generic_file_header();
 640 
 641   const char* file_type = CDSConfig::type_of_archive_being_loaded();
 642   if (_is_static) {
 643     if ((gen_header->_magic == CDS_ARCHIVE_MAGIC) ||
 644         (gen_header->_magic == CDS_PREIMAGE_ARCHIVE_MAGIC && CDSConfig::is_dumping_final_static_archive())) {
 645       // Good
 646     } else {
 647       if (CDSConfig::new_aot_flags_used()) {
 648         aot_log_warning(aot)("Not a valid %s (%s)", file_type, _full_path);
 649       } else {
 650         aot_log_warning(aot)("Not a base shared archive: %s", _full_path);
 651       }
 652       return false;
 653     }
 654   } else {
 655     if (gen_header->_magic != CDS_DYNAMIC_ARCHIVE_MAGIC) {
 656       aot_log_warning(aot)("Not a top shared archive: %s", _full_path);
 657       return false;
 658     }
 659   }
 660 
 661   _header = (FileMapHeader*)os::malloc(gen_header->_header_size, mtInternal);
 662   os::lseek(fd, 0, SEEK_SET); // reset to begin of the archive
 663   size_t size = gen_header->_header_size;
 664   size_t n = ::read(fd, (void*)_header, (unsigned int)size);
 665   if (n != size) {
 666     aot_log_warning(aot)("Failed to read file header from the top archive file\n");
 667     return false;
 668   }
 669 
 670   if (header()->version() != CURRENT_CDS_ARCHIVE_VERSION) {
 671     aot_log_info(aot)("_version expected: 0x%x", CURRENT_CDS_ARCHIVE_VERSION);
 672     aot_log_info(aot)("           actual: 0x%x", header()->version());
 673     aot_log_warning(aot)("The %s has the wrong version.", file_type);
 674     return false;
 675   }
 676 
 677   unsigned int base_offset = header()->base_archive_name_offset();
 678   unsigned int name_size = header()->base_archive_name_size();
 679   unsigned int header_size = header()->header_size();
 680   if (base_offset != 0 && name_size != 0) {
 681     if (header_size != base_offset + name_size) {
 682       aot_log_info(aot)("_header_size: " UINT32_FORMAT, header_size);
 683       aot_log_info(aot)("base_archive_name_size: " UINT32_FORMAT, header()->base_archive_name_size());
 684       aot_log_info(aot)("base_archive_name_offset: " UINT32_FORMAT, header()->base_archive_name_offset());
 685       aot_log_warning(aot)("The %s has an incorrect header size.", file_type);
 686       return false;
 687     }
 688   }
 689 
 690   const char* actual_ident = header()->jvm_ident();
 691 
 692   if (actual_ident[JVM_IDENT_MAX-1] != 0) {
 693     aot_log_warning(aot)("JVM version identifier is corrupted.");
 694     return false;
 695   }
 696 
 697   char expected_ident[JVM_IDENT_MAX];
 698   get_header_version(expected_ident);
 699   if (strncmp(actual_ident, expected_ident, JVM_IDENT_MAX-1) != 0) {
 700     aot_log_info(aot)("_jvm_ident expected: %s", expected_ident);
 701     aot_log_info(aot)("             actual: %s", actual_ident);
 702     aot_log_warning(aot)("The %s was created by a different"
 703                   " version or build of HotSpot", file_type);
 704     return false;
 705   }
 706 
 707   _file_offset = header()->header_size(); // accounts for the size of _base_archive_name
 708 
 709   size_t len = os::lseek(fd, 0, SEEK_END);
 710 
 711   for (int i = 0; i < AOTMetaspace::n_regions; i++) {
 712     FileMapRegion* r = region_at(i);
 713     if (r->file_offset() > len || len - r->file_offset() < r->used()) {
 714       aot_log_warning(aot)("The %s has been truncated.", file_type);
 715       return false;
 716     }
 717   }
 718 
 719   return true;
 720 }
 721 
 722 void FileMapInfo::seek_to_position(size_t pos) {
 723   if (os::lseek(_fd, (long)pos, SEEK_SET) < 0) {
 724     aot_log_error(aot)("Unable to seek to position %zu", pos);
 725     AOTMetaspace::unrecoverable_loading_error();
 726   }
 727 }
 728 
 729 // Read the FileMapInfo information from the file.
 730 bool FileMapInfo::open_for_read() {
 731   if (_file_open) {
 732     return true;
 733   }
 734   const char* file_type = CDSConfig::type_of_archive_being_loaded();
 735   const char* info = CDSConfig::is_dumping_final_static_archive() ?
 736     "AOTConfiguration file " : "";
 737   aot_log_info(aot)("trying to map %s%s", info, _full_path);
 738   int fd = os::open(_full_path, O_RDONLY | O_BINARY, 0);
 739   if (fd < 0) {
 740     if (errno == ENOENT) {
 741       aot_log_info(aot)("Specified %s not found (%s)", file_type, _full_path);
 742     } else {
 743       aot_log_warning(aot)("Failed to open %s (%s)", file_type,
 744                     os::strerror(errno));
 745     }
 746     return false;
 747   } else {
 748     aot_log_info(aot)("Opened %s %s.", file_type, _full_path);
 749   }
 750 
 751   _fd = fd;
 752   _file_open = true;
 753   return true;
 754 }
 755 
 756 // Write the FileMapInfo information to the file.
 757 
 758 void FileMapInfo::open_as_output() {
 759   if (CDSConfig::new_aot_flags_used()) {
 760     if (CDSConfig::is_dumping_preimage_static_archive()) {
 761       log_info(aot)("Writing binary AOTConfiguration file: %s",  _full_path);
 762     } else {
 763       log_info(aot)("Writing AOTCache file: %s",  _full_path);
 764     }
 765   } else {
 766     aot_log_info(aot)("Dumping shared data to file: %s", _full_path);
 767   }
 768 
 769 #ifdef _WINDOWS  // On Windows, need WRITE permission to remove the file.
 770   chmod(_full_path, _S_IREAD | _S_IWRITE);
 771 #endif
 772 
 773   // Use remove() to delete the existing file because, on Unix, this will
 774   // allow processes that have it open continued access to the file.
 775   remove(_full_path);
 776   int fd = os::open(_full_path, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0666);
 777   if (fd < 0) {
 778     aot_log_error(aot)("Unable to create %s %s: (%s).", CDSConfig::type_of_archive_being_written(), _full_path,
 779                    os::strerror(errno));
 780     AOTMetaspace::writing_error();
 781     return;
 782   }
 783   _fd = fd;
 784   _file_open = true;
 785 }
 786 
 787 void FileMapInfo::prepare_for_writing() {
 788   // Seek past the header. We will write the header after all regions are written
 789   // and their CRCs computed.
 790   size_t header_bytes = header()->header_size();
 791 
 792   header_bytes = align_up(header_bytes, AOTMetaspace::core_region_alignment());
 793   _file_offset = header_bytes;
 794   seek_to_position(_file_offset);
 795 }
 796 
 797 // Write the header to the file, seek to the next allocation boundary.
 798 
 799 void FileMapInfo::write_header() {
 800   _file_offset = 0;
 801   seek_to_position(_file_offset);
 802   assert(is_file_position_aligned(), "must be");
 803   write_bytes(header(), header()->header_size());
 804 }
 805 
 806 size_t FileMapRegion::used_aligned() const {
 807   return align_up(used(), AOTMetaspace::core_region_alignment());
 808 }
 809 
 810 void FileMapRegion::init(int region_index, size_t mapping_offset, size_t size, bool read_only,
 811                          bool allow_exec, int crc) {
 812   _is_heap_region = HeapShared::is_heap_region(region_index);
 813   _is_bitmap_region = (region_index == AOTMetaspace::bm);
 814   _mapping_offset = mapping_offset;
 815   _used = size;
 816   _read_only = read_only;
 817   _allow_exec = allow_exec;
 818   _crc = crc;
 819   _mapped_from_file = false;
 820   _mapped_base = nullptr;
 821   _in_reserved_space = false;
 822 }
 823 
 824 void FileMapRegion::init_oopmap(size_t offset, size_t size_in_bits) {
 825   _oopmap_offset = offset;
 826   _oopmap_size_in_bits = size_in_bits;
 827 }
 828 
 829 void FileMapRegion::init_ptrmap(size_t offset, size_t size_in_bits) {
 830   _ptrmap_offset = offset;
 831   _ptrmap_size_in_bits = size_in_bits;
 832 }
 833 
 834 bool FileMapRegion::check_region_crc(char* base) const {
 835   // This function should be called after the region has been properly
 836   // loaded into memory via FileMapInfo::map_region() or FileMapInfo::read_region().
 837   // I.e., this->mapped_base() must be valid.
 838   size_t sz = used();
 839   if (sz == 0) {
 840     return true;
 841   }
 842 
 843   assert(base != nullptr, "must be initialized");
 844   int crc = ClassLoader::crc32(0, base, (jint)sz);
 845   if (crc != this->crc()) {
 846     aot_log_warning(aot)("Checksum verification failed.");
 847     return false;
 848   }
 849   return true;
 850 }
 851 
 852 static const char* region_name(int region_index) {
 853   static const char* names[] = {
 854     "rw", "ro", "bm", "hp", "ac"
 855   };
 856   const int num_regions = sizeof(names)/sizeof(names[0]);
 857   assert(0 <= region_index && region_index < num_regions, "sanity");
 858 
 859   return names[region_index];
 860 }
 861 
 862 BitMapView FileMapInfo::bitmap_view(int region_index, bool is_oopmap) {
 863   FileMapRegion* r = region_at(region_index);
 864   char* bitmap_base = is_static() ? FileMapInfo::current_info()->map_bitmap_region() : FileMapInfo::dynamic_info()->map_bitmap_region();
 865   bitmap_base += is_oopmap ? r->oopmap_offset() : r->ptrmap_offset();
 866   size_t size_in_bits = is_oopmap ? r->oopmap_size_in_bits() : r->ptrmap_size_in_bits();
 867 
 868   aot_log_debug(aot, reloc)("mapped %s relocation %smap @ " INTPTR_FORMAT " (%zu bits)",
 869                         region_name(region_index), is_oopmap ? "oop" : "ptr",
 870                         p2i(bitmap_base), size_in_bits);
 871 
 872   return BitMapView((BitMap::bm_word_t*)(bitmap_base), size_in_bits);
 873 }
 874 
 875 BitMapView FileMapInfo::oopmap_view(int region_index) {
 876     return bitmap_view(region_index, /*is_oopmap*/true);
 877   }
 878 
 879 BitMapView FileMapInfo::ptrmap_view(int region_index) {
 880   return bitmap_view(region_index, /*is_oopmap*/false);
 881 }
 882 
 883 void FileMapRegion::print(outputStream* st, int region_index) {
 884   st->print_cr("============ region ============= %d \"%s\"", region_index, region_name(region_index));
 885   st->print_cr("- crc:                            0x%08x", _crc);
 886   st->print_cr("- read_only:                      %d", _read_only);
 887   st->print_cr("- allow_exec:                     %d", _allow_exec);
 888   st->print_cr("- is_heap_region:                 %d", _is_heap_region);
 889   st->print_cr("- is_bitmap_region:               %d", _is_bitmap_region);
 890   st->print_cr("- mapped_from_file:               %d", _mapped_from_file);
 891   st->print_cr("- file_offset:                    0x%zx", _file_offset);
 892   st->print_cr("- mapping_offset:                 0x%zx", _mapping_offset);
 893   st->print_cr("- used:                           %zu", _used);
 894   st->print_cr("- oopmap_offset:                  0x%zx", _oopmap_offset);
 895   st->print_cr("- oopmap_size_in_bits:            %zu", _oopmap_size_in_bits);
 896   st->print_cr("- ptrmap_offset:                  0x%zx", _ptrmap_offset);
 897   st->print_cr("- ptrmap_size_in_bits:            %zu", _ptrmap_size_in_bits);
 898   st->print_cr("- mapped_base:                    " INTPTR_FORMAT, p2i(_mapped_base));
 899 }
 900 
 901 void FileMapInfo::write_region(int region, char* base, size_t size,
 902                                bool read_only, bool allow_exec) {
 903   assert(CDSConfig::is_dumping_archive(), "sanity");
 904 
 905   FileMapRegion* r = region_at(region);
 906   char* requested_base;
 907   size_t mapping_offset = 0;
 908 
 909   if (region == AOTMetaspace::bm) {
 910     requested_base = nullptr; // always null for bm region
 911   } else if (size == 0) {
 912     // This is an unused region (e.g., a heap region when !INCLUDE_CDS_JAVA_HEAP)
 913     requested_base = nullptr;
 914   } else if (HeapShared::is_heap_region(region)) {
 915     assert(CDSConfig::is_dumping_heap(), "sanity");
 916 #if INCLUDE_CDS_JAVA_HEAP
 917     assert(!CDSConfig::is_dumping_dynamic_archive(), "must be");
 918     if (HeapShared::is_writing_mapping_mode()) {
 919       requested_base = (char*)AOTMappedHeapWriter::requested_address();
 920       if (UseCompressedOops) {
 921         mapping_offset = (size_t)((address)requested_base - AOTMappedHeapWriter::narrow_oop_base());
 922         assert((mapping_offset >> CompressedOops::shift()) << CompressedOops::shift() == mapping_offset, "must be");
 923       }
 924     } else {
 925       requested_base = nullptr;
 926     }
 927 #endif // INCLUDE_CDS_JAVA_HEAP
 928   } else {
 929     char* requested_SharedBaseAddress = (char*)AOTMetaspace::requested_base_address();
 930     requested_base = ArchiveBuilder::current()->to_requested(base);
 931     assert(requested_base >= requested_SharedBaseAddress, "must be");
 932     mapping_offset = requested_base - requested_SharedBaseAddress;
 933   }
 934 
 935   r->set_file_offset(_file_offset);
 936   int crc = ClassLoader::crc32(0, base, (jint)size);
 937   if (size > 0) {
 938     aot_log_info(aot)("Shared file region (%s) %d: %8zu"
 939                    " bytes, addr " INTPTR_FORMAT " file offset 0x%08" PRIxPTR
 940                    " crc 0x%08x",
 941                    region_name(region), region, size, p2i(requested_base), _file_offset, crc);
 942   } else {
 943     aot_log_info(aot)("Shared file region (%s) %d: %8zu"
 944                    " bytes", region_name(region), region, size);
 945   }
 946 
 947   r->init(region, mapping_offset, size, read_only, allow_exec, crc);
 948 
 949   if (base != nullptr) {
 950     write_bytes_aligned(base, size);
 951   }
 952 }
 953 
 954 static size_t write_bitmap(const CHeapBitMap* map, char* output, size_t offset) {
 955   size_t size_in_bytes = map->size_in_bytes();
 956   map->write_to((BitMap::bm_word_t*)(output + offset), size_in_bytes);
 957   return offset + size_in_bytes;
 958 }
 959 
 960 // The sorting code groups the objects with non-null oop/ptrs together.
 961 // Relevant bitmaps then have lots of leading and trailing zeros, which
 962 // we do not have to store.
 963 size_t FileMapInfo::remove_bitmap_zeros(CHeapBitMap* map) {
 964   BitMap::idx_t first_set = map->find_first_set_bit(0);
 965   BitMap::idx_t last_set  = map->find_last_set_bit(0);
 966   size_t old_size = map->size();
 967 
 968   // Slice and resize bitmap
 969   map->truncate(first_set, last_set + 1);
 970 
 971   assert(map->at(0), "First bit should be set");
 972   assert(map->at(map->size() - 1), "Last bit should be set");
 973   assert(map->size() <= old_size, "sanity");
 974 
 975   return first_set;
 976 }
 977 
 978 char* FileMapInfo::write_bitmap_region(CHeapBitMap* rw_ptrmap,
 979                                        CHeapBitMap* ro_ptrmap,
 980                                        CHeapBitMap* ac_ptrmap,
 981                                        ArchiveMappedHeapInfo* mapped_heap_info,
 982                                        ArchiveStreamedHeapInfo* streamed_heap_info,
 983                                        size_t &size_in_bytes) {
 984   size_t removed_rw_leading_zeros = remove_bitmap_zeros(rw_ptrmap);
 985   size_t removed_ro_leading_zeros = remove_bitmap_zeros(ro_ptrmap);
 986   header()->set_rw_ptrmap_start_pos(removed_rw_leading_zeros);
 987   header()->set_ro_ptrmap_start_pos(removed_ro_leading_zeros);
 988   size_in_bytes = rw_ptrmap->size_in_bytes() + ro_ptrmap->size_in_bytes() + ac_ptrmap->size_in_bytes();
 989 
 990   if (mapped_heap_info != nullptr && mapped_heap_info->is_used()) {
 991     // Remove leading and trailing zeros
 992     assert(HeapShared::is_writing_mapping_mode(), "unexpected dumping mode");
 993     size_t removed_oop_leading_zeros = remove_bitmap_zeros(mapped_heap_info->oopmap());
 994     size_t removed_ptr_leading_zeros = remove_bitmap_zeros(mapped_heap_info->ptrmap());
 995     mapped_heap_info->set_oopmap_start_pos(removed_oop_leading_zeros);
 996     mapped_heap_info->set_ptrmap_start_pos(removed_ptr_leading_zeros);
 997 
 998     size_in_bytes += mapped_heap_info->oopmap()->size_in_bytes();
 999     size_in_bytes += mapped_heap_info->ptrmap()->size_in_bytes();
1000   } else if (streamed_heap_info != nullptr && streamed_heap_info->is_used()) {
1001     assert(HeapShared::is_writing_streaming_mode(), "unexpected dumping mode");
1002 
1003     size_in_bytes += streamed_heap_info->oopmap()->size_in_bytes();
1004   }
1005 
1006   // The bitmap region contains up to 5 parts:
1007   // rw_ptrmap:                  metaspace pointers inside the read-write region
1008   // ro_ptrmap:                  metaspace pointers inside the read-only region
1009   // ac_ptrmap:                  metaspace pointers inside the AOT code cache region
1010   // *_heap_info->oopmap():      Java oop pointers in the heap region
1011   // mapped_heap_info->ptrmap(): metaspace pointers in the heap region
1012   char* buffer = NEW_C_HEAP_ARRAY(char, size_in_bytes, mtClassShared);
1013   size_t written = 0;
1014 
1015   region_at(AOTMetaspace::rw)->init_ptrmap(0, rw_ptrmap->size());
1016   written = write_bitmap(rw_ptrmap, buffer, written);
1017 
1018   region_at(AOTMetaspace::ro)->init_ptrmap(written, ro_ptrmap->size());
1019   written = write_bitmap(ro_ptrmap, buffer, written);
1020 
1021   if (ac_ptrmap->size() > 0) {
1022     region_at(AOTMetaspace::ac)->init_ptrmap(written, ac_ptrmap->size());
1023     written = write_bitmap(ac_ptrmap, buffer, written);
1024   }
1025 
1026   if (mapped_heap_info != nullptr && mapped_heap_info->is_used()) {
1027     assert(HeapShared::is_writing_mapping_mode(), "unexpected dumping mode");
1028     FileMapRegion* r = region_at(AOTMetaspace::hp);
1029 
1030     r->init_oopmap(written, mapped_heap_info->oopmap()->size());
1031     written = write_bitmap(mapped_heap_info->oopmap(), buffer, written);
1032 
1033     r->init_ptrmap(written, mapped_heap_info->ptrmap()->size());
1034     written = write_bitmap(mapped_heap_info->ptrmap(), buffer, written);
1035   } else if (streamed_heap_info != nullptr && streamed_heap_info->is_used()) {
1036     assert(HeapShared::is_writing_streaming_mode(), "unexpected dumping mode");
1037     FileMapRegion* r = region_at(AOTMetaspace::hp);
1038 
1039     r->init_oopmap(written, streamed_heap_info->oopmap()->size());
1040     written = write_bitmap(streamed_heap_info->oopmap(), buffer, written);
1041   }
1042 
1043   write_region(AOTMetaspace::bm, (char*)buffer, size_in_bytes, /*read_only=*/true, /*allow_exec=*/false);
1044   return buffer;
1045 }
1046 
1047 #if INCLUDE_CDS_JAVA_HEAP
1048 size_t FileMapInfo::write_mapped_heap_region(ArchiveMappedHeapInfo* heap_info) {
1049   char* buffer_start = heap_info->buffer_start();
1050   size_t buffer_size = heap_info->buffer_byte_size();
1051   write_region(AOTMetaspace::hp, buffer_start, buffer_size, false, false);
1052   header()->set_mapped_heap_header(heap_info->create_header());
1053   return buffer_size;
1054 }
1055 
1056 size_t FileMapInfo::write_streamed_heap_region(ArchiveStreamedHeapInfo* heap_info) {
1057   char* buffer_start = heap_info->buffer_start();
1058   size_t buffer_size = heap_info->buffer_byte_size();
1059   write_region(AOTMetaspace::hp, buffer_start, buffer_size, true, false);
1060   header()->set_streamed_heap_header(heap_info->create_header());
1061   return buffer_size;
1062 }
1063 #endif // INCLUDE_CDS_JAVA_HEAP
1064 
1065 // Dump bytes to file -- at the current file position.
1066 
1067 void FileMapInfo::write_bytes(const void* buffer, size_t nbytes) {
1068   assert(_file_open, "must be");
1069   if (!os::write(_fd, buffer, nbytes)) {
1070     // If the shared archive is corrupted, close it and remove it.
1071     close();
1072     remove(_full_path);
1073 
1074     if (CDSConfig::is_dumping_preimage_static_archive()) {
1075       AOTMetaspace::writing_error("Unable to write to AOT configuration file.");
1076     } else if (CDSConfig::new_aot_flags_used()) {
1077       AOTMetaspace::writing_error("Unable to write to AOT cache.");
1078     } else {
1079       AOTMetaspace::writing_error("Unable to write to shared archive.");
1080     }
1081   }
1082   _file_offset += nbytes;
1083 }
1084 
1085 bool FileMapInfo::is_file_position_aligned() const {
1086   return _file_offset == align_up(_file_offset,
1087                                   AOTMetaspace::core_region_alignment());
1088 }
1089 
1090 // Align file position to an allocation unit boundary.
1091 
1092 void FileMapInfo::align_file_position() {
1093   assert(_file_open, "must be");
1094   size_t new_file_offset = align_up(_file_offset,
1095                                     AOTMetaspace::core_region_alignment());
1096   if (new_file_offset != _file_offset) {
1097     _file_offset = new_file_offset;
1098     // Seek one byte back from the target and write a byte to insure
1099     // that the written file is the correct length.
1100     _file_offset -= 1;
1101     seek_to_position(_file_offset);
1102     char zero = 0;
1103     write_bytes(&zero, 1);
1104   }
1105 }
1106 
1107 
1108 // Dump bytes to file -- at the current file position.
1109 
1110 void FileMapInfo::write_bytes_aligned(const void* buffer, size_t nbytes) {
1111   align_file_position();
1112   write_bytes(buffer, nbytes);
1113   align_file_position();
1114 }
1115 
1116 // Close the shared archive file.  This does NOT unmap mapped regions.
1117 
1118 void FileMapInfo::close() {
1119   if (_file_open) {
1120     if (::close(_fd) < 0) {
1121       AOTMetaspace::unrecoverable_loading_error("Unable to close the shared archive file.");
1122     }
1123     _file_open = false;
1124     _fd = -1;
1125   }
1126 }
1127 
1128 /*
1129  * Same as os::map_memory() but also pretouches if AlwaysPreTouch is enabled.
1130  */
1131 static char* map_memory(int fd, const char* file_name, size_t file_offset,
1132                         char* addr, size_t bytes, bool read_only,
1133                         bool allow_exec, MemTag mem_tag) {
1134   char* mem = os::map_memory(fd, file_name, file_offset, addr, bytes,
1135                              mem_tag, AlwaysPreTouch ? false : read_only,
1136                              allow_exec);
1137   if (mem != nullptr && AlwaysPreTouch) {
1138     os::pretouch_memory(mem, mem + bytes);
1139   }
1140   return mem;
1141 }
1142 
1143 char* FileMapInfo::map_heap_region(FileMapRegion* r, char* addr, size_t bytes) {
1144   return ::map_memory(_fd,
1145                     _full_path,
1146                     r->file_offset(),
1147                     addr,
1148                     bytes,
1149                     r->read_only(),
1150                     r->allow_exec(),
1151                     mtJavaHeap);
1152 }
1153 
1154 // JVM/TI RedefineClasses() support:
1155 // Remap the shared readonly space to shared readwrite, private.
1156 bool FileMapInfo::remap_shared_readonly_as_readwrite() {
1157   int idx = AOTMetaspace::ro;
1158   FileMapRegion* r = region_at(idx);
1159   if (!r->read_only()) {
1160     // the space is already readwrite so we are done
1161     return true;
1162   }
1163   size_t size = r->used_aligned();
1164   if (!open_for_read()) {
1165     return false;
1166   }
1167   char *addr = r->mapped_base();
1168   // This path should not be reached for Windows; see JDK-8222379.
1169   assert(WINDOWS_ONLY(false) NOT_WINDOWS(true), "Don't call on Windows");
1170   // Replace old mapping with new one that is writable.
1171   char *base = os::map_memory(_fd, _full_path, r->file_offset(),
1172                               addr, size, mtNone, false /* !read_only */,
1173                               r->allow_exec());
1174   close();
1175   // These have to be errors because the shared region is now unmapped.
1176   if (base == nullptr) {
1177     aot_log_error(aot)("Unable to remap shared readonly space (errno=%d).", errno);
1178     vm_exit(1);
1179   }
1180   if (base != addr) {
1181     aot_log_error(aot)("Unable to remap shared readonly space (errno=%d).", errno);
1182     vm_exit(1);
1183   }
1184   r->set_read_only(false);
1185   return true;
1186 }
1187 
1188 // Memory map a region in the address space.
1189 static const char* shared_region_name[] = { "ReadWrite", "ReadOnly", "Bitmap", "Heap", "Code" };
1190 
1191 MapArchiveResult FileMapInfo::map_regions(int regions[], int num_regions, char* mapped_base_address, ReservedSpace rs) {
1192   DEBUG_ONLY(FileMapRegion* last_region = nullptr);
1193   intx addr_delta = mapped_base_address - header()->requested_base_address();
1194 
1195   // Make sure we don't attempt to use header()->mapped_base_address() unless
1196   // it's been successfully mapped.
1197   DEBUG_ONLY(header()->set_mapped_base_address((char*)(uintptr_t)0xdeadbeef);)
1198 
1199   for (int i = 0; i < num_regions; i++) {
1200     int idx = regions[i];
1201     MapArchiveResult result = map_region(idx, addr_delta, mapped_base_address, rs);
1202     if (result != MAP_ARCHIVE_SUCCESS) {
1203       return result;
1204     }
1205     FileMapRegion* r = region_at(idx);
1206     DEBUG_ONLY(if (last_region != nullptr) {
1207         // Ensure that the OS won't be able to allocate new memory spaces between any mapped
1208         // regions, or else it would mess up the simple comparison in MetaspaceObj::in_aot_cache().
1209         assert(r->mapped_base() == last_region->mapped_end(), "must have no gaps");
1210       }
1211       last_region = r;)
1212     aot_log_info(aot)("Mapped %s region #%d at base " INTPTR_FORMAT " top " INTPTR_FORMAT " (%s)", is_static() ? "static " : "dynamic",
1213                   idx, p2i(r->mapped_base()), p2i(r->mapped_end()),
1214                   shared_region_name[idx]);
1215 
1216   }
1217 
1218   header()->set_mapped_base_address(header()->requested_base_address() + addr_delta);
1219   if (addr_delta != 0 && !relocate_pointers_in_core_regions(addr_delta)) {
1220     return MAP_ARCHIVE_OTHER_FAILURE;
1221   }
1222 
1223   return MAP_ARCHIVE_SUCCESS;
1224 }
1225 
1226 bool FileMapInfo::read_region(int i, char* base, size_t size, bool do_commit) {
1227   FileMapRegion* r = region_at(i);
1228   if (do_commit) {
1229     aot_log_info(aot)("Commit %s region #%d at base " INTPTR_FORMAT " top " INTPTR_FORMAT " (%s)%s",
1230                   is_static() ? "static " : "dynamic", i, p2i(base), p2i(base + size),
1231                   shared_region_name[i], r->allow_exec() ? " exec" : "");
1232     if (!os::commit_memory(base, size, r->allow_exec())) {
1233       aot_log_error(aot)("Failed to commit %s region #%d (%s)", is_static() ? "static " : "dynamic",
1234                      i, shared_region_name[i]);
1235       return false;
1236     }
1237   }
1238   if (os::lseek(_fd, (long)r->file_offset(), SEEK_SET) != (int)r->file_offset() ||
1239       read_bytes(base, size) != size) {
1240     return false;
1241   }
1242 
1243   if (VerifySharedSpaces && !r->check_region_crc(base)) {
1244     return false;
1245   }
1246 
1247   r->set_mapped_from_file(false);
1248   r->set_mapped_base(base);
1249 
1250   return true;
1251 }
1252 
1253 MapArchiveResult FileMapInfo::map_region(int i, intx addr_delta, char* mapped_base_address, ReservedSpace rs) {
1254   assert(!HeapShared::is_heap_region(i), "sanity");
1255   FileMapRegion* r = region_at(i);
1256   size_t size = r->used_aligned();
1257   char *requested_addr = mapped_base_address + r->mapping_offset();
1258   assert(!is_mapped(), "must be not mapped yet");
1259   assert(requested_addr != nullptr, "must be specified");
1260 
1261   r->set_mapped_from_file(false);
1262   r->set_in_reserved_space(false);
1263 
1264   if (AOTMetaspace::use_windows_memory_mapping()) {
1265     // Windows cannot remap read-only shared memory to read-write when required for
1266     // RedefineClasses, which is also used by JFR.  Always map windows regions as RW.
1267     r->set_read_only(false);
1268   } else if (JvmtiExport::can_modify_any_class() || JvmtiExport::can_walk_any_space() ||
1269              Arguments::has_jfr_option()) {
1270     // If a tool agent is in use (debugging enabled), or JFR, we must map the address space RW
1271     r->set_read_only(false);
1272   } else if (addr_delta != 0) {
1273     r->set_read_only(false); // Need to patch the pointers
1274   }
1275 
1276   if (AOTMetaspace::use_windows_memory_mapping() && rs.is_reserved()) {
1277     // This is the second time we try to map the archive(s). We have already created a ReservedSpace
1278     // that covers all the FileMapRegions to ensure all regions can be mapped. However, Windows
1279     // can't mmap into a ReservedSpace, so we just ::read() the data. We're going to patch all the
1280     // regions anyway, so there's no benefit for mmap anyway.
1281     if (!read_region(i, requested_addr, size, /* do_commit = */ true)) {
1282       AOTMetaspace::report_loading_error("Failed to read %s shared space into reserved space at " INTPTR_FORMAT,
1283                                             shared_region_name[i], p2i(requested_addr));
1284       return MAP_ARCHIVE_OTHER_FAILURE; // oom or I/O error.
1285     } else {
1286       assert(r->mapped_base() != nullptr, "must be initialized");
1287     }
1288   } else {
1289     // Note that this may either be a "fresh" mapping into unreserved address
1290     // space (Windows, first mapping attempt), or a mapping into pre-reserved
1291     // space (Posix). See also comment in AOTMetaspace::map_archives().
1292     bool read_only = r->read_only() && !CDSConfig::is_dumping_final_static_archive();
1293 
1294     char* base = map_memory(_fd, _full_path, r->file_offset(),
1295                             requested_addr, size, read_only,
1296                             r->allow_exec(), mtClassShared);
1297     if (base != requested_addr) {
1298       AOTMetaspace::report_loading_error("Unable to map %s shared space at " INTPTR_FORMAT,
1299                                             shared_region_name[i], p2i(requested_addr));
1300       _memory_mapping_failed = true;
1301       return MAP_ARCHIVE_MMAP_FAILURE;
1302     }
1303 
1304     if (VerifySharedSpaces && !r->check_region_crc(requested_addr)) {
1305       return MAP_ARCHIVE_OTHER_FAILURE;
1306     }
1307 
1308     r->set_mapped_from_file(true);
1309     r->set_mapped_base(requested_addr);
1310   }
1311 
1312   if (rs.is_reserved()) {
1313     char* mapped_base = r->mapped_base();
1314     assert(rs.base() <= mapped_base && mapped_base + size <= rs.end(),
1315            PTR_FORMAT " <= " PTR_FORMAT " < " PTR_FORMAT " <= " PTR_FORMAT,
1316            p2i(rs.base()), p2i(mapped_base), p2i(mapped_base + size), p2i(rs.end()));
1317     r->set_in_reserved_space(rs.is_reserved());
1318   }
1319   return MAP_ARCHIVE_SUCCESS;
1320 }
1321 
1322 // The return value is the location of the archive relocation bitmap.
1323 char* FileMapInfo::map_auxiliary_region(int region_index, bool read_only) {
1324   FileMapRegion* r = region_at(region_index);
1325   if (r->mapped_base() != nullptr) {
1326     return r->mapped_base();
1327   }
1328   const char* region_name = shared_region_name[region_index];
1329   bool allow_exec = false;
1330   char* requested_addr = nullptr; // allow OS to pick any location
1331   char* mapped_base = map_memory(_fd, _full_path, r->file_offset(),
1332                                  requested_addr, r->used_aligned(), read_only, allow_exec, mtClassShared);
1333   if (mapped_base == nullptr) {
1334     AOTMetaspace::report_loading_error("failed to map %d region", region_index);
1335     return nullptr;
1336   }
1337 
1338   if (VerifySharedSpaces && !r->check_region_crc(mapped_base)) {
1339     aot_log_error(aot)("region %d CRC error", region_index);
1340     if (!os::unmap_memory(mapped_base, r->used_aligned())) {
1341       fatal("os::unmap_memory of region %d failed", region_index);
1342     }
1343     return nullptr;
1344   }
1345 
1346   r->set_mapped_from_file(true);
1347   r->set_mapped_base(mapped_base);
1348   aot_log_info(aot)("Mapped %s region #%d at base %zu top %zu (%s)",
1349                 is_static() ? "static " : "dynamic",
1350                 region_index, p2i(r->mapped_base()), p2i(r->mapped_end()),
1351                 region_name);
1352   return mapped_base;
1353 }
1354 
1355 char* FileMapInfo::map_bitmap_region() {
1356   return map_auxiliary_region(AOTMetaspace::bm, false);
1357 }
1358 
1359 bool FileMapInfo::map_aot_code_region(ReservedSpace rs) {
1360   FileMapRegion* r = region_at(AOTMetaspace::ac);
1361   assert(r->used() > 0 && r->used_aligned() == rs.size(), "must be");
1362 
1363   char* requested_base = rs.base();
1364   assert(requested_base != nullptr, "should be inside code cache");
1365 
1366   char* mapped_base;
1367   if (AOTMetaspace::use_windows_memory_mapping()) {
1368     if (!read_region(AOTMetaspace::ac, requested_base, r->used_aligned(), /* do_commit = */ true)) {
1369       AOTMetaspace::report_loading_error("Failed to read aot code shared space into reserved space at " INTPTR_FORMAT,
1370                                             p2i(requested_base));
1371       return false;
1372     }
1373     mapped_base = requested_base;
1374   } else {
1375     // We do not execute in-place in the AOT code region.
1376     // AOT code is copied to the CodeCache for execution.
1377     bool read_only = false, allow_exec = false;
1378     mapped_base = map_memory(_fd, _full_path, r->file_offset(),
1379                              requested_base, r->used_aligned(), read_only, allow_exec, mtClassShared);
1380   }
1381   if (mapped_base == nullptr) {
1382     AOTMetaspace::report_loading_error("failed to map aot code region");
1383     return false;
1384   } else {
1385     assert(mapped_base == requested_base, "must be");
1386     r->set_mapped_from_file(true);
1387     r->set_mapped_base(mapped_base);
1388     relocate_pointers_in_aot_code_region();
1389     aot_log_info(aot)("Mapped static  region #%d at base " INTPTR_FORMAT " top " INTPTR_FORMAT " (%s)",
1390                   AOTMetaspace::ac, p2i(r->mapped_base()), p2i(r->mapped_end()),
1391                   shared_region_name[AOTMetaspace::ac]);
1392     return true;
1393   }
1394 }
1395 
1396 class CachedCodeRelocator: public BitMapClosure {
1397   address _code_requested_base;
1398   address* _patch_base;
1399   intx _code_delta;
1400   intx _metadata_delta;
1401 
1402 public:
1403   CachedCodeRelocator(address code_requested_base, address code_mapped_base,
1404                       intx metadata_delta) {
1405     _code_requested_base = code_requested_base;
1406     _patch_base = (address*)code_mapped_base;
1407     _code_delta = code_mapped_base - code_requested_base;
1408     _metadata_delta = metadata_delta;
1409   }
1410 
1411   bool do_bit(size_t offset) {
1412     address* p = _patch_base + offset;
1413     address requested_ptr = *p;
1414     if (requested_ptr < _code_requested_base) {
1415       *p = requested_ptr + _metadata_delta;
1416     } else {
1417       *p = requested_ptr + _code_delta;
1418     }
1419     return true; // keep iterating
1420   }
1421 };
1422 
1423 void FileMapInfo::relocate_pointers_in_aot_code_region() {
1424   FileMapRegion* r = region_at(AOTMetaspace::ac);
1425   char* bitmap_base = map_bitmap_region();
1426 
1427   BitMapView ac_ptrmap = ptrmap_view(AOTMetaspace::ac);
1428   if (ac_ptrmap.size() == 0) {
1429     return;
1430   }
1431 
1432   address core_regions_requested_base = (address)header()->requested_base_address();
1433   address core_regions_mapped_base = (address)header()->mapped_base_address();
1434   address ac_region_requested_base = core_regions_requested_base + r->mapping_offset();
1435   address ac_region_mapped_base = (address)r->mapped_base();
1436 
1437   size_t max_bits_for_core_regions = pointer_delta(mapped_end(), mapped_base(), // FIXME - renamed to core_regions_mapped_base(), etc
1438                                                    sizeof(address));
1439 
1440   CachedCodeRelocator patcher(ac_region_requested_base, ac_region_mapped_base,
1441                               core_regions_mapped_base - core_regions_requested_base);
1442   ac_ptrmap.iterate(&patcher);
1443 }
1444 
1445 class SharedDataRelocationTask : public ArchiveWorkerTask {
1446 private:
1447   BitMapView* const _rw_bm;
1448   BitMapView* const _ro_bm;
1449   SharedDataRelocator* const _rw_reloc;
1450   SharedDataRelocator* const _ro_reloc;
1451 
1452 public:
1453   SharedDataRelocationTask(BitMapView* rw_bm, BitMapView* ro_bm, SharedDataRelocator* rw_reloc, SharedDataRelocator* ro_reloc) :
1454                            ArchiveWorkerTask("Shared Data Relocation"),
1455                            _rw_bm(rw_bm), _ro_bm(ro_bm), _rw_reloc(rw_reloc), _ro_reloc(ro_reloc) {}
1456 
1457   void work(int chunk, int max_chunks) override {
1458     work_on(chunk, max_chunks, _rw_bm, _rw_reloc);
1459     work_on(chunk, max_chunks, _ro_bm, _ro_reloc);
1460   }
1461 
1462   void work_on(int chunk, int max_chunks, BitMapView* bm, SharedDataRelocator* reloc) {
1463     BitMap::idx_t size  = bm->size();
1464     BitMap::idx_t start = MIN2(size, size * chunk / max_chunks);
1465     BitMap::idx_t end   = MIN2(size, size * (chunk + 1) / max_chunks);
1466     assert(end > start, "Sanity: no empty slices");
1467     bm->iterate(reloc, start, end);
1468   }
1469 };
1470 
1471 // This is called when we cannot map the archive at the requested[ base address (usually 0x800000000).
1472 // We relocate all pointers in the 2 core regions (ro, rw).
1473 bool FileMapInfo::relocate_pointers_in_core_regions(intx addr_delta) {
1474   aot_log_debug(aot, reloc)("runtime archive relocation start");
1475   char* bitmap_base = map_bitmap_region();
1476 
1477   if (bitmap_base == nullptr) {
1478     return false; // OOM, or CRC check failure
1479   } else {
1480     BitMapView rw_ptrmap = ptrmap_view(AOTMetaspace::rw);
1481     BitMapView ro_ptrmap = ptrmap_view(AOTMetaspace::ro);
1482 
1483     FileMapRegion* rw_region = first_core_region();
1484     FileMapRegion* ro_region = last_core_region();
1485 
1486     // Patch all pointers inside the RW region
1487     address rw_patch_base = (address)rw_region->mapped_base();
1488     address rw_patch_end  = (address)rw_region->mapped_end();
1489 
1490     // Patch all pointers inside the RO region
1491     address ro_patch_base = (address)ro_region->mapped_base();
1492     address ro_patch_end  = (address)ro_region->mapped_end();
1493 
1494     // the current value of the pointers to be patched must be within this
1495     // range (i.e., must be between the requested base address and the address of the current archive).
1496     // Note: top archive may point to objects in the base archive, but not the other way around.
1497     address valid_old_base = (address)header()->requested_base_address();
1498     address valid_old_end  = valid_old_base + mapping_end_offset();
1499 
1500     // after patching, the pointers must point inside this range
1501     // (the requested location of the archive, as mapped at runtime).
1502     address valid_new_base = (address)header()->mapped_base_address();
1503     address valid_new_end  = (address)mapped_end();
1504 
1505     SharedDataRelocator rw_patcher((address*)rw_patch_base + header()->rw_ptrmap_start_pos(), (address*)rw_patch_end, valid_old_base, valid_old_end,
1506                                 valid_new_base, valid_new_end, addr_delta);
1507     SharedDataRelocator ro_patcher((address*)ro_patch_base + header()->ro_ptrmap_start_pos(), (address*)ro_patch_end, valid_old_base, valid_old_end,
1508                                 valid_new_base, valid_new_end, addr_delta);
1509 
1510     if (AOTCacheParallelRelocation) {
1511       ArchiveWorkers workers;
1512       SharedDataRelocationTask task(&rw_ptrmap, &ro_ptrmap, &rw_patcher, &ro_patcher);
1513       workers.run_task(&task);
1514     } else {
1515       rw_ptrmap.iterate(&rw_patcher);
1516       ro_ptrmap.iterate(&ro_patcher);
1517     }
1518 
1519     // The AOTMetaspace::bm region will be unmapped in AOTMetaspace::initialize_shared_spaces().
1520 
1521     aot_log_debug(aot, reloc)("runtime archive relocation done");
1522     return true;
1523   }
1524 }
1525 
1526 size_t FileMapInfo::read_bytes(void* buffer, size_t count) {
1527   assert(_file_open, "Archive file is not open");
1528   size_t n = ::read(_fd, buffer, (unsigned int)count);
1529   if (n != count) {
1530     // Close the file if there's a problem reading it.
1531     close();
1532     return 0;
1533   }
1534   _file_offset += count;
1535   return count;
1536 }
1537 
1538 // Get the total size in bytes of a read only region
1539 size_t FileMapInfo::readonly_total() {
1540   size_t total = 0;
1541   if (current_info() != nullptr) {
1542     FileMapRegion* r = FileMapInfo::current_info()->region_at(AOTMetaspace::ro);
1543     if (r->read_only()) total += r->used();
1544   }
1545   if (dynamic_info() != nullptr) {
1546     FileMapRegion* r = FileMapInfo::dynamic_info()->region_at(AOTMetaspace::ro);
1547     if (r->read_only()) total += r->used();
1548   }
1549   return total;
1550 }
1551 
1552 #if INCLUDE_CDS_JAVA_HEAP
1553 
1554 bool FileMapInfo::has_heap_region() {
1555   return (region_at(AOTMetaspace::hp)->used() > 0);
1556 }
1557 
1558 static void on_heap_region_loading_error() {
1559   if (CDSConfig::is_using_aot_linked_classes()) {
1560     // It's too late to recover -- we have already committed to use the archived metaspace objects, but
1561     // the archived heap objects cannot be loaded, so we don't have the archived FMG to guarantee that
1562     // all AOT-linked classes are visible.
1563     //
1564     // We get here because the heap is too small. The app will fail anyway. So let's quit.
1565     aot_log_error(aot)("%s has aot-linked classes but the archived "
1566                        "heap objects cannot be loaded. Try increasing your heap size.",
1567                        CDSConfig::type_of_archive_being_loaded());
1568     AOTMetaspace::unrecoverable_loading_error();
1569   }
1570   CDSConfig::stop_using_full_module_graph();
1571 }
1572 
1573 void FileMapInfo::stream_heap_region() {
1574   assert(object_streaming_mode(), "This should only be done for the streaming approach");
1575 
1576   if (map_auxiliary_region(AOTMetaspace::hp, /*readonly=*/true) != nullptr) {
1577     HeapShared::initialize_streaming();
1578   } else {
1579     on_heap_region_loading_error();
1580   }
1581 }
1582 
1583 void FileMapInfo::map_or_load_heap_region() {
1584   assert(!object_streaming_mode(), "This should only be done for the mapping approach");
1585   bool success = false;
1586 
1587   if (AOTMappedHeapLoader::can_map()) {
1588     success = AOTMappedHeapLoader::map_heap_region(this);
1589   } else if (AOTMappedHeapLoader::can_load()) {
1590     success = AOTMappedHeapLoader::load_heap_region(this);
1591   }
1592 
1593   if (!success) {
1594     on_heap_region_loading_error();
1595   }
1596 }
1597 
1598 bool FileMapInfo::can_use_heap_region() {
1599   if (!has_heap_region()) {
1600     return false;
1601   }
1602   if (!object_streaming_mode() && !Universe::heap()->can_load_archived_objects() && !UseG1GC) {
1603     // Incompatible object format
1604     return false;
1605   }
1606   if (JvmtiExport::should_post_class_file_load_hook() && JvmtiExport::has_early_class_hook_env()) {
1607     ShouldNotReachHere(); // CDS should have been disabled.
1608     // The archived objects are mapped at JVM start-up, but we don't know if
1609     // j.l.String or j.l.Class might be replaced by the ClassFileLoadHook,
1610     // which would make the archived String or mirror objects invalid. Let's be safe and not
1611     // use the archived objects. These 2 classes are loaded during the JVMTI "early" stage.
1612     //
1613     // If JvmtiExport::has_early_class_hook_env() is false, the classes of some objects
1614     // in the archived subgraphs may be replaced by the ClassFileLoadHook. But that's OK
1615     // because we won't install an archived object subgraph if the klass of any of the
1616     // referenced objects are replaced. See HeapShared::initialize_from_archived_subgraph().
1617   }
1618 
1619   // We pre-compute narrow Klass IDs with the runtime mapping start intended to be the base, and a shift of
1620   // HeapShared::precomputed_narrow_klass_shift. We enforce this encoding at runtime (see
1621   // CompressedKlassPointers::initialize_for_given_encoding()). Therefore, the following assertions must
1622   // hold:
1623   address archive_narrow_klass_base = (address)header()->mapped_base_address();
1624   const int archive_narrow_klass_pointer_bits = header()->narrow_klass_pointer_bits();
1625   const int archive_narrow_klass_shift = header()->narrow_klass_shift();
1626 
1627   aot_log_info(aot)("CDS archive was created with max heap size = %zuM, and the following configuration:",
1628                 max_heap_size()/M);
1629 
1630   aot_log_info(aot)("    narrow_klass_base at mapping start address, narrow_klass_pointer_bits = %d, narrow_klass_shift = %d",
1631                 archive_narrow_klass_pointer_bits, archive_narrow_klass_shift);
1632   if (UseCompressedOops) {
1633     aot_log_info(aot)("    narrow_oop_mode = %d, narrow_oop_base = " PTR_FORMAT ", narrow_oop_shift = %d",
1634                       narrow_oop_mode(), p2i(narrow_oop_base()), narrow_oop_shift());
1635   }
1636   aot_log_info(aot)("The current max heap size = %zuM, G1HeapRegion::GrainBytes = %zu",
1637                 MaxHeapSize/M, G1HeapRegion::GrainBytes);
1638   aot_log_info(aot)("    narrow_klass_base = " PTR_FORMAT ", arrow_klass_pointer_bits = %d, narrow_klass_shift = %d",
1639                 p2i(CompressedKlassPointers::base()), CompressedKlassPointers::narrow_klass_pointer_bits(), CompressedKlassPointers::shift());
1640   if (UseCompressedOops) {
1641     aot_log_info(aot)("    narrow_oop_mode = %d, narrow_oop_base = " PTR_FORMAT ", narrow_oop_shift = %d",
1642                       CompressedOops::mode(), p2i(CompressedOops::base()), CompressedOops::shift());
1643   }
1644   if (!object_streaming_mode()) {
1645     aot_log_info(aot)("    heap range = [" PTR_FORMAT " - "  PTR_FORMAT "]",
1646                       UseCompressedOops ? p2i(CompressedOops::begin()) :
1647                       UseG1GC ? p2i((address)G1CollectedHeap::heap()->reserved().start()) : 0L,
1648                       UseCompressedOops ? p2i(CompressedOops::end()) :
1649                       UseG1GC ? p2i((address)G1CollectedHeap::heap()->reserved().end()) : 0L);
1650   }
1651 
1652   int err = 0;
1653   if ( archive_narrow_klass_base != CompressedKlassPointers::base() ||
1654        (err = 1, archive_narrow_klass_pointer_bits != CompressedKlassPointers::narrow_klass_pointer_bits()) ||
1655        (err = 2, archive_narrow_klass_shift != CompressedKlassPointers::shift()) ) {
1656     stringStream ss;
1657     switch (err) {
1658     case 0:
1659       ss.print("Unexpected encoding base encountered (" PTR_FORMAT ", expected " PTR_FORMAT ")",
1660                p2i(CompressedKlassPointers::base()), p2i(archive_narrow_klass_base));
1661       break;
1662     case 1:
1663       ss.print("Unexpected narrow Klass bit length encountered (%d, expected %d)",
1664                CompressedKlassPointers::narrow_klass_pointer_bits(), archive_narrow_klass_pointer_bits);
1665       break;
1666     case 2:
1667       ss.print("Unexpected narrow Klass shift encountered (%d, expected %d)",
1668                CompressedKlassPointers::shift(), archive_narrow_klass_shift);
1669       break;
1670     default:
1671       ShouldNotReachHere();
1672     };
1673     if (CDSConfig::new_aot_flags_used()) {
1674       LogTarget(Info, aot) lt;
1675       if (lt.is_enabled()) {
1676         LogStream ls(lt);
1677         ls.print_raw(ss.base());
1678         header()->print(&ls);
1679       }
1680     } else {
1681       LogTarget(Info, cds) lt;
1682       if (lt.is_enabled()) {
1683         LogStream ls(lt);
1684         ls.print_raw(ss.base());
1685         header()->print(&ls);
1686       }
1687     }
1688     assert(false, "%s", ss.base());
1689   }
1690 
1691   return true;
1692 }
1693 
1694 #endif // INCLUDE_CDS_JAVA_HEAP
1695 
1696 // Unmap a memory region in the address space.
1697 
1698 void FileMapInfo::unmap_regions(int regions[], int num_regions) {
1699   for (int r = 0; r < num_regions; r++) {
1700     int idx = regions[r];
1701     unmap_region(idx);
1702   }
1703 }
1704 
1705 void FileMapInfo::unmap_region(int i) {
1706   FileMapRegion* r = region_at(i);
1707   char* mapped_base = r->mapped_base();
1708   size_t size = r->used_aligned();
1709 
1710   if (mapped_base != nullptr) {
1711     if (size > 0 && r->mapped_from_file()) {
1712       aot_log_info(aot)("Unmapping region #%d at base " INTPTR_FORMAT " (%s)", i, p2i(mapped_base),
1713                     shared_region_name[i]);
1714       if (r->in_reserved_space()) {
1715         // This region was mapped inside a ReservedSpace. Its memory will be freed when the ReservedSpace
1716         // is released. Zero it so that we don't accidentally read its content.
1717         aot_log_info(aot)("Region #%d (%s) is in a reserved space, it will be freed when the space is released", i, shared_region_name[i]);
1718       } else {
1719         if (!os::unmap_memory(mapped_base, size)) {
1720           fatal("os::unmap_memory failed");
1721         }
1722       }
1723     }
1724     r->set_mapped_base(nullptr);
1725   }
1726 }
1727 
1728 void FileMapInfo::assert_mark(bool check) {
1729   if (!check) {
1730     AOTMetaspace::unrecoverable_loading_error("Mark mismatch while restoring from shared file.");
1731   }
1732 }
1733 
1734 FileMapInfo* FileMapInfo::_current_info = nullptr;
1735 FileMapInfo* FileMapInfo::_dynamic_archive_info = nullptr;
1736 bool FileMapInfo::_memory_mapping_failed = false;
1737 
1738 // Open the shared archive file, read and validate the header
1739 // information (version, boot classpath, etc.). If initialization
1740 // fails, shared spaces are disabled and the file is closed.
1741 //
1742 // Validation of the archive is done in two steps:
1743 //
1744 // [1] validate_header() - done here.
1745 // [2] validate_shared_path_table - this is done later, because the table is in the RO
1746 //     region of the archive, which is not mapped yet.
1747 bool FileMapInfo::open_as_input() {
1748   assert(CDSConfig::is_using_archive(), "UseSharedSpaces expected.");
1749   assert(Arguments::has_jimage(), "The shared archive file cannot be used with an exploded module build.");
1750 
1751   if (JvmtiExport::should_post_class_file_load_hook() && JvmtiExport::has_early_class_hook_env()) {
1752     // CDS assumes that no classes resolved in vmClasses::resolve_all()
1753     // are replaced at runtime by JVMTI ClassFileLoadHook. All of those classes are resolved
1754     // during the JVMTI "early" stage, so we can still use CDS if
1755     // JvmtiExport::has_early_class_hook_env() is false.
1756     AOTMetaspace::report_loading_error("CDS is disabled because early JVMTI ClassFileLoadHook is in use.");
1757     return false;
1758   }
1759 
1760   if (!open_for_read() || !init_from_file(_fd) || !validate_header()) {
1761     if (_is_static) {
1762       AOTMetaspace::report_loading_error("Loading static archive failed.");
1763       return false;
1764     } else {
1765       AOTMetaspace::report_loading_error("Loading dynamic archive failed.");
1766       if (AutoCreateSharedArchive) {
1767         CDSConfig::enable_dumping_dynamic_archive(_full_path);
1768       }
1769       return false;
1770     }
1771   }
1772 
1773   return true;
1774 }
1775 
1776 bool FileMapInfo::validate_aot_class_linking() {
1777   // These checks need to be done after FileMapInfo::initialize(), which gets called before Universe::heap()
1778   // is available.
1779   if (header()->has_aot_linked_classes()) {
1780     const char* archive_type = CDSConfig::type_of_archive_being_loaded();
1781     CDSConfig::set_has_aot_linked_classes(true);
1782     if (JvmtiExport::should_post_class_file_load_hook()) {
1783       aot_log_error(aot)("%s has aot-linked classes. It cannot be used when JVMTI ClassFileLoadHook is in use.",
1784                      archive_type);
1785       return false;
1786     }
1787     if (JvmtiExport::has_early_vmstart_env()) {
1788       aot_log_error(aot)("%s has aot-linked classes. It cannot be used when JVMTI early vm start is in use.",
1789                      archive_type);
1790       return false;
1791     }
1792     if (!CDSConfig::is_using_full_module_graph()) {
1793       aot_log_error(aot)("%s has aot-linked classes. It cannot be used when archived full module graph is not used.",
1794                      archive_type);
1795       return false;
1796     }
1797 
1798     const char* prop = Arguments::get_property("java.security.manager");
1799     if (prop != nullptr && strcmp(prop, "disallow") != 0) {
1800       aot_log_error(aot)("%s has aot-linked classes. It cannot be used with -Djava.security.manager=%s.",
1801                      archive_type, prop);
1802       return false;
1803     }
1804 
1805     if (header()->gc_kind() != (int)Universe::heap()->kind()) {
1806       log_error(cds)("CDS archive has aot-linked classes. It cannot be used because GC used during dump time (%s) is not the same as runtime (%s)",
1807                      header()->gc_name(), Universe::heap()->name());
1808       return false;
1809     }
1810 
1811 #if INCLUDE_JVMTI
1812     if (Arguments::has_jdwp_agent()) {
1813       aot_log_error(aot)("%s has aot-linked classes. It cannot be used with JDWP agent", archive_type);
1814       return false;
1815     }
1816 #endif
1817   }
1818 
1819   return true;
1820 }
1821 
1822 // The 2 core spaces are RW->RO
1823 FileMapRegion* FileMapInfo::first_core_region() const {
1824   return region_at(AOTMetaspace::rw);
1825 }
1826 
1827 FileMapRegion* FileMapInfo::last_core_region() const {
1828   return region_at(AOTMetaspace::ro);
1829 }
1830 
1831 void FileMapInfo::print(outputStream* st) const {
1832   header()->print(st);
1833   if (!is_static()) {
1834     dynamic_header()->print(st);
1835   }
1836 }
1837 
1838 void FileMapHeader::set_as_offset(char* p, size_t *offset) {
1839   *offset = ArchiveBuilder::current()->any_to_offset((address)p);
1840 }
1841 
1842 int FileMapHeader::compute_crc() {
1843   char* start = (char*)this;
1844   // start computing from the field after _header_size to end of base archive name.
1845   char* buf = (char*)&(_generic_header._header_size) + sizeof(_generic_header._header_size);
1846   size_t sz = header_size() - (buf - start);
1847   int crc = ClassLoader::crc32(0, buf, (jint)sz);
1848   return crc;
1849 }
1850 
1851 // This function should only be called during run time with UseSharedSpaces enabled.
1852 bool FileMapHeader::validate() {
1853   const char* file_type = CDSConfig::type_of_archive_being_loaded();
1854   if (_obj_alignment != ObjectAlignmentInBytes) {
1855     AOTMetaspace::report_loading_error("The %s's ObjectAlignmentInBytes of %d"
1856                                           " does not equal the current ObjectAlignmentInBytes of %d.",
1857                                           file_type, _obj_alignment, ObjectAlignmentInBytes);
1858     return false;
1859   }
1860   if (_compact_strings != CompactStrings) {
1861     AOTMetaspace::report_loading_error("The %s's CompactStrings setting (%s)"
1862                                           " does not equal the current CompactStrings setting (%s).", file_type,
1863                                           _compact_strings ? "enabled" : "disabled",
1864                                           CompactStrings   ? "enabled" : "disabled");
1865     return false;
1866   }
1867   bool jvmci_compiler_is_enabled = CompilerConfig::is_jvmci_compiler_enabled();
1868   CompilerType compiler_type = CompilerConfig::compiler_type();
1869   CompilerType archive_compiler_type = CompilerType(_compiler_type);
1870   // JVMCI compiler does different type profiling settigns and generate
1871   // different code. We can't use archive which was produced
1872   // without it and reverse.
1873   // Only allow mix when JIT compilation is disabled.
1874   // Interpreter is used by default when dumping archive.
1875   bool intepreter_is_used = (archive_compiler_type == CompilerType::compiler_none) ||
1876                             (compiler_type == CompilerType::compiler_none);
1877   if (!intepreter_is_used &&
1878       jvmci_compiler_is_enabled != (archive_compiler_type == CompilerType::compiler_jvmci)) {
1879     AOTMetaspace::report_loading_error("The %s's JIT compiler setting (%s)"
1880                                           " does not equal the current setting (%s).", file_type,
1881                                           compilertype2name(archive_compiler_type), compilertype2name(compiler_type));
1882     return false;
1883   }
1884   if (TrainingData::have_data()) {
1885     if (_type_profile_level != TypeProfileLevel) {
1886       AOTMetaspace::report_loading_error("The %s's TypeProfileLevel setting (%d)"
1887                                             " does not equal the current TypeProfileLevel setting (%d).", file_type,
1888                                             _type_profile_level, TypeProfileLevel);
1889       return false;
1890     }
1891     if (_type_profile_args_limit != TypeProfileArgsLimit) {
1892       AOTMetaspace::report_loading_error("The %s's TypeProfileArgsLimit setting (%d)"
1893                                             " does not equal the current TypeProfileArgsLimit setting (%d).", file_type,
1894                                             _type_profile_args_limit, TypeProfileArgsLimit);
1895       return false;
1896     }
1897     if (_type_profile_parms_limit != TypeProfileParmsLimit) {
1898       AOTMetaspace::report_loading_error("The %s's TypeProfileParamsLimit setting (%d)"
1899                                             " does not equal the current TypeProfileParamsLimit setting (%d).", file_type,
1900                                             _type_profile_args_limit, TypeProfileArgsLimit);
1901       return false;
1902 
1903     }
1904     if (_type_profile_width != TypeProfileWidth) {
1905       AOTMetaspace::report_loading_error("The %s's TypeProfileWidth setting (%d)"
1906                                             " does not equal the current TypeProfileWidth setting (%d).", file_type,
1907                                             (int)_type_profile_width, (int)TypeProfileWidth);
1908       return false;
1909 
1910     }
1911     if (_bci_profile_width != BciProfileWidth) {
1912       AOTMetaspace::report_loading_error("The %s's BciProfileWidth setting (%d)"
1913                                             " does not equal the current BciProfileWidth setting (%d).", file_type,
1914                                             (int)_bci_profile_width, (int)BciProfileWidth);
1915       return false;
1916     }
1917     if (_type_profile_casts != TypeProfileCasts) {
1918       AOTMetaspace::report_loading_error("The %s's TypeProfileCasts setting (%s)"
1919                                             " does not equal the current TypeProfileCasts setting (%s).", file_type,
1920                                             _type_profile_casts ? "enabled" : "disabled",
1921                                             TypeProfileCasts    ? "enabled" : "disabled");
1922 
1923       return false;
1924 
1925     }
1926     if (_profile_traps != ProfileTraps) {
1927       AOTMetaspace::report_loading_error("The %s's ProfileTraps setting (%s)"
1928                                             " does not equal the current ProfileTraps setting (%s).", file_type,
1929                                             _profile_traps ? "enabled" : "disabled",
1930                                             ProfileTraps   ? "enabled" : "disabled");
1931 
1932       return false;
1933     }
1934     if (_spec_trap_limit_extra_entries != SpecTrapLimitExtraEntries) {
1935       AOTMetaspace::report_loading_error("The %s's SpecTrapLimitExtraEntries setting (%d)"
1936                                             " does not equal the current SpecTrapLimitExtraEntries setting (%d).", file_type,
1937                                             _spec_trap_limit_extra_entries, SpecTrapLimitExtraEntries);
1938       return false;
1939 
1940     }
1941   }
1942 
1943   // This must be done after header validation because it might change the
1944   // header data
1945   const char* prop = Arguments::get_property("java.system.class.loader");
1946   if (prop != nullptr) {
1947     if (has_aot_linked_classes()) {
1948       AOTMetaspace::report_loading_error("%s has aot-linked classes. It cannot be used when the "
1949                                             "java.system.class.loader property is specified.",
1950                                             CDSConfig::type_of_archive_being_loaded());
1951       return false;
1952     }
1953     aot_log_warning(aot)("Archived non-system classes are disabled because the "
1954             "java.system.class.loader property is specified (value = \"%s\"). "
1955             "To use archived non-system classes, this property must not be set", prop);
1956     _has_platform_or_app_classes = false;
1957   }
1958 
1959 
1960   if (!_verify_local && BytecodeVerificationLocal) {
1961     //  we cannot load boot classes, so there's no point of using the CDS archive
1962     AOTMetaspace::report_loading_error("The %s's BytecodeVerificationLocal setting (%s)"
1963                                           " does not equal the current BytecodeVerificationLocal setting (%s).", file_type,
1964                                           _verify_local ? "enabled" : "disabled",
1965                                           BytecodeVerificationLocal ? "enabled" : "disabled");
1966     return false;
1967   }
1968 
1969   // For backwards compatibility, we don't check the BytecodeVerificationRemote setting
1970   // if the archive only contains system classes.
1971   if (_has_platform_or_app_classes
1972       && !_verify_remote // we didn't verify the archived platform/app classes
1973       && BytecodeVerificationRemote) { // but we want to verify all loaded platform/app classes
1974     aot_log_info(aot)("The %s was created with less restrictive "
1975                                "verification setting than the current setting.", file_type);
1976     // Pretend that we didn't have any archived platform/app classes, so they won't be loaded
1977     // by SystemDictionaryShared.
1978     _has_platform_or_app_classes = false;
1979   }
1980 
1981   aot_log_info(aot)("The %s was created with UseCompressedOops = %d, UseCompressedClassPointers = %d, UseCompactObjectHeaders = %d",
1982                           file_type, compressed_oops(), compressed_class_pointers(), compact_headers());
1983   if (compressed_oops() != UseCompressedOops || compressed_class_pointers() != UseCompressedClassPointers) {
1984     aot_log_warning(aot)("Unable to use %s.\nThe saved state of UseCompressedOops and UseCompressedClassPointers is "
1985                                "different from runtime, CDS will be disabled.", file_type);
1986     return false;
1987   }
1988 
1989   if (compact_headers() != UseCompactObjectHeaders) {
1990     aot_log_warning(aot)("Unable to use %s.\nThe %s's UseCompactObjectHeaders setting (%s)"
1991                      " does not equal the current UseCompactObjectHeaders setting (%s).", file_type, file_type,
1992                      _compact_headers          ? "enabled" : "disabled",
1993                      UseCompactObjectHeaders   ? "enabled" : "disabled");
1994     return false;
1995   }
1996 
1997   if (!_use_optimized_module_handling && !CDSConfig::is_dumping_final_static_archive()) {
1998     CDSConfig::stop_using_optimized_module_handling();
1999     aot_log_info(aot)("optimized module handling: disabled because archive was created without optimized module handling");
2000   }
2001 
2002   if (is_static()) {
2003     // Only the static archive can contain the full module graph.
2004     if (!_has_full_module_graph) {
2005       CDSConfig::stop_using_full_module_graph("archive was created without full module graph");
2006     }
2007   }
2008 
2009   return true;
2010 }
2011 
2012 bool FileMapInfo::validate_header() {
2013   if (!header()->validate()) {
2014     return false;
2015   }
2016   if (_is_static) {
2017     return true;
2018   } else {
2019     return DynamicArchive::validate(this);
2020   }
2021 }
2022 
2023 #if INCLUDE_JVMTI
2024 ClassPathEntry** FileMapInfo::_classpath_entries_for_jvmti = nullptr;
2025 
2026 ClassPathEntry* FileMapInfo::get_classpath_entry_for_jvmti(int i, TRAPS) {
2027   if (i == 0) {
2028     // index 0 corresponds to the ClassPathImageEntry which is a globally shared object
2029     // and should never be deleted.
2030     return ClassLoader::get_jrt_entry();
2031   }
2032   ClassPathEntry* ent = _classpath_entries_for_jvmti[i];
2033   if (ent == nullptr) {
2034     const AOTClassLocation* cl = AOTClassLocationConfig::runtime()->class_location_at(i);
2035     const char* path = cl->path();
2036     struct stat st;
2037     if (os::stat(path, &st) != 0) {
2038       char *msg = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, strlen(path) + 128);
2039       jio_snprintf(msg, strlen(path) + 127, "error in finding JAR file %s", path);
2040       THROW_MSG_(vmSymbols::java_io_IOException(), msg, nullptr);
2041     } else {
2042       ent = ClassLoader::create_class_path_entry(THREAD, path, &st);
2043       if (ent == nullptr) {
2044         char *msg = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, strlen(path) + 128);
2045         jio_snprintf(msg, strlen(path) + 127, "error in opening JAR file %s", path);
2046         THROW_MSG_(vmSymbols::java_io_IOException(), msg, nullptr);
2047       }
2048     }
2049 
2050     MutexLocker mu(THREAD, CDSClassFileStream_lock);
2051     if (_classpath_entries_for_jvmti[i] == nullptr) {
2052       _classpath_entries_for_jvmti[i] = ent;
2053     } else {
2054       // Another thread has beat me to creating this entry
2055       delete ent;
2056       ent = _classpath_entries_for_jvmti[i];
2057     }
2058   }
2059 
2060   return ent;
2061 }
2062 
2063 ClassFileStream* FileMapInfo::open_stream_for_jvmti(InstanceKlass* ik, Handle class_loader, TRAPS) {
2064   int path_index = ik->shared_classpath_index();
2065   assert(path_index >= 0, "should be called for shared built-in classes only");
2066   assert(path_index < AOTClassLocationConfig::runtime()->length(), "sanity");
2067 
2068   ClassPathEntry* cpe = get_classpath_entry_for_jvmti(path_index, CHECK_NULL);
2069   assert(cpe != nullptr, "must be");
2070 
2071   Symbol* name = ik->name();
2072   const char* const class_name = name->as_C_string();
2073   const char* const file_name = ClassLoader::file_name_for_class_name(class_name,
2074                                                                       name->utf8_length());
2075   ClassLoaderData* loader_data = ClassLoaderData::class_loader_data(class_loader());
2076   const AOTClassLocation* cl = AOTClassLocationConfig::runtime()->class_location_at(path_index);
2077   ClassFileStream* cfs;
2078   if (class_loader() != nullptr && cl->is_multi_release_jar()) {
2079     // This class was loaded from a multi-release JAR file during dump time. The
2080     // process for finding its classfile is complex. Let's defer to the Java code
2081     // in java.lang.ClassLoader.
2082     cfs = get_stream_from_class_loader(class_loader, cpe, file_name, CHECK_NULL);
2083   } else {
2084     cfs = cpe->open_stream_for_loader(THREAD, file_name, loader_data);
2085   }
2086   assert(cfs != nullptr, "must be able to read the classfile data of shared classes for built-in loaders.");
2087   log_debug(aot, jvmti)("classfile data for %s [%d: %s] = %d bytes", class_name, path_index,
2088                         cfs->source(), cfs->length());
2089   return cfs;
2090 }
2091 
2092 ClassFileStream* FileMapInfo::get_stream_from_class_loader(Handle class_loader,
2093                                                            ClassPathEntry* cpe,
2094                                                            const char* file_name,
2095                                                            TRAPS) {
2096   JavaValue result(T_OBJECT);
2097   oop class_name = java_lang_String::create_oop_from_str(file_name, THREAD);
2098   Handle h_class_name = Handle(THREAD, class_name);
2099 
2100   // byte[] ClassLoader.getResourceAsByteArray(String name)
2101   JavaCalls::call_virtual(&result,
2102                           class_loader,
2103                           vmClasses::ClassLoader_klass(),
2104                           vmSymbols::getResourceAsByteArray_name(),
2105                           vmSymbols::getResourceAsByteArray_signature(),
2106                           h_class_name,
2107                           CHECK_NULL);
2108   assert(result.get_type() == T_OBJECT, "just checking");
2109   oop obj = result.get_oop();
2110   assert(obj != nullptr, "ClassLoader.getResourceAsByteArray should not return null");
2111 
2112   // copy from byte[] to a buffer
2113   typeArrayOop ba = typeArrayOop(obj);
2114   jint len = ba->length();
2115   u1* buffer = NEW_RESOURCE_ARRAY(u1, len);
2116   ArrayAccess<>::arraycopy_to_native<>(ba, typeArrayOopDesc::element_offset<jbyte>(0), buffer, len);
2117 
2118   return new ClassFileStream(buffer, len, cpe->name());
2119 }
2120 #endif