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