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