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