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