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