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