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