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 "precompiled.hpp"
  26 #include "cds/archiveBuilder.hpp"
  27 #include "cds/archiveHeapLoader.inline.hpp"
  28 #include "cds/archiveHeapWriter.hpp"
  29 #include "cds/archiveUtils.inline.hpp"
  30 #include "cds/cds_globals.hpp"
  31 #include "cds/cdsConfig.hpp"
  32 #include "cds/dynamicArchive.hpp"
  33 #include "cds/filemap.hpp"
  34 #include "cds/heapShared.hpp"
  35 #include "cds/metaspaceShared.hpp"
  36 #include "classfile/altHashing.hpp"
  37 #include "classfile/classFileStream.hpp"
  38 #include "classfile/classLoader.hpp"
  39 #include "classfile/classLoader.inline.hpp"
  40 #include "classfile/classLoaderData.inline.hpp"
  41 #include "classfile/classLoaderExt.hpp"
  42 #include "classfile/symbolTable.hpp"
  43 #include "classfile/systemDictionaryShared.hpp"
  44 #include "classfile/vmClasses.hpp"
  45 #include "classfile/vmSymbols.hpp"
  46 #include "jvm.h"
  47 #include "logging/log.hpp"
  48 #include "logging/logMessage.hpp"
  49 #include "logging/logStream.hpp"
  50 #include "memory/iterator.inline.hpp"
  51 #include "memory/metadataFactory.hpp"
  52 #include "memory/metaspaceClosure.hpp"
  53 #include "memory/oopFactory.hpp"
  54 #include "memory/universe.hpp"
  55 #include "nmt/memTracker.hpp"
  56 #include "oops/access.hpp"
  57 #include "oops/compressedOops.hpp"
  58 #include "oops/compressedOops.inline.hpp"
  59 #include "oops/compressedKlass.hpp"
  60 #include "oops/objArrayOop.hpp"
  61 #include "oops/oop.inline.hpp"
  62 #include "oops/typeArrayKlass.hpp"
  63 #include "prims/jvmtiExport.hpp"
  64 #include "runtime/arguments.hpp"
  65 #include "runtime/globals_extension.hpp"
  66 #include "runtime/java.hpp"
  67 #include "runtime/javaCalls.hpp"
  68 #include "runtime/mutexLocker.hpp"
  69 #include "runtime/os.hpp"
  70 #include "runtime/vm_version.hpp"
  71 #include "utilities/align.hpp"
  72 #include "utilities/bitMap.inline.hpp"
  73 #include "utilities/classpathStream.hpp"
  74 #include "utilities/defaultStream.hpp"
  75 #include "utilities/ostream.hpp"
  76 #if INCLUDE_G1GC
  77 #include "gc/g1/g1CollectedHeap.hpp"
  78 #include "gc/g1/g1HeapRegion.hpp"
  79 #endif
  80 
  81 # include <sys/stat.h>
  82 # include <errno.h>
  83 
  84 #ifndef O_BINARY       // if defined (Win32) use binary files.
  85 #define O_BINARY 0     // otherwise do nothing.
  86 #endif
  87 
  88 // Fill in the fileMapInfo structure with data about this VM instance.
  89 
  90 // This method copies the vm version info into header_version.  If the version is too
  91 // long then a truncated version, which has a hash code appended to it, is copied.
  92 //
  93 // Using a template enables this method to verify that header_version is an array of
  94 // length JVM_IDENT_MAX.  This ensures that the code that writes to the CDS file and
  95 // the code that reads the CDS file will both use the same size buffer.  Hence, will
  96 // use identical truncation.  This is necessary for matching of truncated versions.
  97 template <int N> static void get_header_version(char (&header_version) [N]) {
  98   assert(N == JVM_IDENT_MAX, "Bad header_version size");
  99 
 100   const char *vm_version = VM_Version::internal_vm_info_string();
 101   const int version_len = (int)strlen(vm_version);
 102 
 103   memset(header_version, 0, JVM_IDENT_MAX);
 104 
 105   if (version_len < (JVM_IDENT_MAX-1)) {
 106     strcpy(header_version, vm_version);
 107 
 108   } else {
 109     // Get the hash value.  Use a static seed because the hash needs to return the same
 110     // value over multiple jvm invocations.
 111     uint32_t hash = AltHashing::halfsiphash_32(8191, (const uint8_t*)vm_version, version_len);
 112 
 113     // Truncate the ident, saving room for the 8 hex character hash value.
 114     strncpy(header_version, vm_version, JVM_IDENT_MAX-9);
 115 
 116     // Append the hash code as eight hex digits.
 117     os::snprintf_checked(&header_version[JVM_IDENT_MAX-9], 9, "%08x", hash);
 118     header_version[JVM_IDENT_MAX-1] = 0;  // Null terminate.
 119   }
 120 
 121   assert(header_version[JVM_IDENT_MAX-1] == 0, "must be");
 122 }
 123 
 124 FileMapInfo::FileMapInfo(const char* full_path, bool is_static) :
 125   _is_static(is_static), _file_open(false), _is_mapped(false), _fd(-1), _file_offset(0),
 126   _full_path(full_path), _base_archive_name(nullptr), _header(nullptr) {
 127   if (_is_static) {
 128     assert(_current_info == nullptr, "must be singleton"); // not thread safe
 129     _current_info = this;
 130   } else {
 131     assert(_dynamic_archive_info == nullptr, "must be singleton"); // not thread safe
 132     _dynamic_archive_info = this;
 133   }
 134 }
 135 
 136 FileMapInfo::~FileMapInfo() {
 137   if (_is_static) {
 138     assert(_current_info == this, "must be singleton"); // not thread safe
 139     _current_info = nullptr;
 140   } else {
 141     assert(_dynamic_archive_info == this, "must be singleton"); // not thread safe
 142     _dynamic_archive_info = nullptr;
 143   }
 144 
 145   if (_header != nullptr) {
 146     os::free(_header);
 147   }
 148 
 149   if (_file_open) {
 150     ::close(_fd);
 151   }
 152 }
 153 
 154 void FileMapInfo::populate_header(size_t core_region_alignment) {
 155   assert(_header == nullptr, "Sanity check");
 156   size_t c_header_size;
 157   size_t header_size;
 158   size_t base_archive_name_size = 0;
 159   size_t base_archive_name_offset = 0;
 160   size_t longest_common_prefix_size = 0;
 161   if (is_static()) {
 162     c_header_size = sizeof(FileMapHeader);
 163     header_size = c_header_size;
 164   } else {
 165     // dynamic header including base archive name for non-default base archive
 166     c_header_size = sizeof(DynamicArchiveHeader);
 167     header_size = c_header_size;
 168 
 169     const char* default_base_archive_name = CDSConfig::default_archive_path();
 170     const char* current_base_archive_name = CDSConfig::static_archive_path();
 171     if (!os::same_files(current_base_archive_name, default_base_archive_name)) {
 172       base_archive_name_size = strlen(current_base_archive_name) + 1;
 173       header_size += base_archive_name_size;
 174       base_archive_name_offset = c_header_size;
 175     }
 176   }
 177   ResourceMark rm;
 178   GrowableArray<const char*>* app_cp_array = create_dumptime_app_classpath_array();
 179   int len = app_cp_array->length();
 180   longest_common_prefix_size = longest_common_app_classpath_prefix_len(len, app_cp_array);
 181   _header = (FileMapHeader*)os::malloc(header_size, mtInternal);
 182   memset((void*)_header, 0, header_size);
 183   _header->populate(this,
 184                     core_region_alignment,
 185                     header_size,
 186                     base_archive_name_size,
 187                     base_archive_name_offset,
 188                     longest_common_prefix_size);
 189 }
 190 
 191 void FileMapHeader::populate(FileMapInfo *info, size_t core_region_alignment,
 192                              size_t header_size, size_t base_archive_name_size,
 193                              size_t base_archive_name_offset, size_t common_app_classpath_prefix_size) {
 194   // 1. We require _generic_header._magic to be at the beginning of the file
 195   // 2. FileMapHeader also assumes that _generic_header is at the beginning of the file
 196   assert(offset_of(FileMapHeader, _generic_header) == 0, "must be");
 197   set_header_size((unsigned int)header_size);
 198   set_base_archive_name_offset((unsigned int)base_archive_name_offset);
 199   set_base_archive_name_size((unsigned int)base_archive_name_size);
 200   set_common_app_classpath_prefix_size((unsigned int)common_app_classpath_prefix_size);
 201   set_magic(CDSConfig::is_dumping_dynamic_archive() ? CDS_DYNAMIC_ARCHIVE_MAGIC : CDS_ARCHIVE_MAGIC);
 202   set_version(CURRENT_CDS_ARCHIVE_VERSION);
 203 
 204   if (!info->is_static() && base_archive_name_size != 0) {
 205     // copy base archive name
 206     copy_base_archive_name(CDSConfig::static_archive_path());
 207   }
 208   _core_region_alignment = core_region_alignment;
 209   _obj_alignment = ObjectAlignmentInBytes;
 210   _compact_strings = CompactStrings;
 211   _compact_headers = UseCompactObjectHeaders;
 212   if (CDSConfig::is_dumping_heap()) {
 213     _narrow_oop_mode = CompressedOops::mode();
 214     _narrow_oop_base = CompressedOops::base();
 215     _narrow_oop_shift = CompressedOops::shift();
 216   }
 217   _compressed_oops = UseCompressedOops;
 218   _compressed_class_ptrs = UseCompressedClassPointers;
 219   if (UseCompressedClassPointers) {
 220 #ifdef _LP64
 221     _narrow_klass_pointer_bits = CompressedKlassPointers::narrow_klass_pointer_bits();
 222     _narrow_klass_shift = ArchiveBuilder::precomputed_narrow_klass_shift();
 223 #endif
 224   } else {
 225     _narrow_klass_pointer_bits = _narrow_klass_shift = -1;
 226   }
 227   _max_heap_size = MaxHeapSize;
 228   _use_optimized_module_handling = CDSConfig::is_using_optimized_module_handling();
 229   _has_aot_linked_classes = CDSConfig::is_dumping_aot_linked_classes();
 230   _has_full_module_graph = CDSConfig::is_dumping_full_module_graph();
 231   _has_archived_invokedynamic = CDSConfig::is_dumping_invokedynamic();
 232 
 233   // The following fields are for sanity checks for whether this archive
 234   // will function correctly with this JVM and the bootclasspath it's
 235   // invoked with.
 236 
 237   // JVM version string ... changes on each build.
 238   get_header_version(_jvm_ident);
 239 
 240   _app_class_paths_start_index = ClassLoaderExt::app_class_paths_start_index();
 241   _app_module_paths_start_index = ClassLoaderExt::app_module_paths_start_index();
 242   _max_used_path_index = ClassLoaderExt::max_used_path_index();
 243   _num_module_paths = ClassLoader::num_module_path_entries();
 244 
 245   _verify_local = BytecodeVerificationLocal;
 246   _verify_remote = BytecodeVerificationRemote;
 247   _has_platform_or_app_classes = ClassLoaderExt::has_platform_or_app_classes();
 248   _has_non_jar_in_classpath = ClassLoaderExt::has_non_jar_in_classpath();
 249   _requested_base_address = (char*)SharedBaseAddress;
 250   _mapped_base_address = (char*)SharedBaseAddress;
 251   _allow_archiving_with_java_agent = AllowArchivingWithJavaAgent;
 252 
 253   if (!CDSConfig::is_dumping_dynamic_archive()) {
 254     set_shared_path_table(info->_shared_path_table);
 255   }
 256 }
 257 
 258 void FileMapHeader::copy_base_archive_name(const char* archive) {
 259   assert(base_archive_name_size() != 0, "_base_archive_name_size not set");
 260   assert(base_archive_name_offset() != 0, "_base_archive_name_offset not set");
 261   assert(header_size() > sizeof(*this), "_base_archive_name_size not included in header size?");
 262   memcpy((char*)this + base_archive_name_offset(), archive, base_archive_name_size());
 263 }
 264 
 265 void FileMapHeader::print(outputStream* st) {
 266   ResourceMark rm;
 267 
 268   st->print_cr("- magic:                          0x%08x", magic());
 269   st->print_cr("- crc:                            0x%08x", crc());
 270   st->print_cr("- version:                        0x%x", version());
 271   st->print_cr("- header_size:                    " UINT32_FORMAT, header_size());
 272   st->print_cr("- common_app_classpath_size:      " UINT32_FORMAT, common_app_classpath_prefix_size());
 273   st->print_cr("- base_archive_name_offset:       " UINT32_FORMAT, base_archive_name_offset());
 274   st->print_cr("- base_archive_name_size:         " UINT32_FORMAT, base_archive_name_size());
 275 
 276   for (int i = 0; i < NUM_CDS_REGIONS; i++) {
 277     FileMapRegion* r = region_at(i);
 278     r->print(st, i);
 279   }
 280   st->print_cr("============ end regions ======== ");
 281 
 282   st->print_cr("- core_region_alignment:          " SIZE_FORMAT, _core_region_alignment);
 283   st->print_cr("- obj_alignment:                  %d", _obj_alignment);
 284   st->print_cr("- narrow_oop_base:                " INTPTR_FORMAT, p2i(_narrow_oop_base));
 285   st->print_cr("- narrow_oop_shift                %d", _narrow_oop_shift);
 286   st->print_cr("- compact_strings:                %d", _compact_strings);
 287   st->print_cr("- compact_headers:                %d", _compact_headers);
 288   st->print_cr("- max_heap_size:                  %zu", _max_heap_size);
 289   st->print_cr("- narrow_oop_mode:                %d", _narrow_oop_mode);
 290   st->print_cr("- compressed_oops:                %d", _compressed_oops);
 291   st->print_cr("- compressed_class_ptrs:          %d", _compressed_class_ptrs);
 292   st->print_cr("- narrow_klass_pointer_bits:      %d", _narrow_klass_pointer_bits);
 293   st->print_cr("- narrow_klass_shift:             %d", _narrow_klass_shift);
 294   st->print_cr("- cloned_vtables_offset:          " SIZE_FORMAT_X, _cloned_vtables_offset);
 295   st->print_cr("- early_serialized_data_offset:   " SIZE_FORMAT_X, _early_serialized_data_offset);
 296   st->print_cr("- serialized_data_offset:         " SIZE_FORMAT_X, _serialized_data_offset);
 297   st->print_cr("- jvm_ident:                      %s", _jvm_ident);
 298   st->print_cr("- shared_path_table_offset:       " SIZE_FORMAT_X, _shared_path_table_offset);
 299   st->print_cr("- app_class_paths_start_index:    %d", _app_class_paths_start_index);
 300   st->print_cr("- app_module_paths_start_index:   %d", _app_module_paths_start_index);
 301   st->print_cr("- num_module_paths:               %d", _num_module_paths);
 302   st->print_cr("- max_used_path_index:            %d", _max_used_path_index);
 303   st->print_cr("- verify_local:                   %d", _verify_local);
 304   st->print_cr("- verify_remote:                  %d", _verify_remote);
 305   st->print_cr("- has_platform_or_app_classes:    %d", _has_platform_or_app_classes);
 306   st->print_cr("- has_non_jar_in_classpath:       %d", _has_non_jar_in_classpath);
 307   st->print_cr("- requested_base_address:         " INTPTR_FORMAT, p2i(_requested_base_address));
 308   st->print_cr("- mapped_base_address:            " INTPTR_FORMAT, p2i(_mapped_base_address));
 309   st->print_cr("- heap_root_segments.roots_count: %d" , _heap_root_segments.roots_count());
 310   st->print_cr("- heap_root_segments.base_offset: " SIZE_FORMAT_X, _heap_root_segments.base_offset());
 311   st->print_cr("- heap_root_segments.count:       " SIZE_FORMAT, _heap_root_segments.count());
 312   st->print_cr("- heap_root_segments.max_size_elems: %d", _heap_root_segments.max_size_in_elems());
 313   st->print_cr("- heap_root_segments.max_size_bytes: %d", _heap_root_segments.max_size_in_bytes());
 314   st->print_cr("- _heap_oopmap_start_pos:         " SIZE_FORMAT, _heap_oopmap_start_pos);
 315   st->print_cr("- _heap_ptrmap_start_pos:         " SIZE_FORMAT, _heap_ptrmap_start_pos);
 316   st->print_cr("- _rw_ptrmap_start_pos:           " SIZE_FORMAT, _rw_ptrmap_start_pos);
 317   st->print_cr("- _ro_ptrmap_start_pos:           " SIZE_FORMAT, _ro_ptrmap_start_pos);
 318   st->print_cr("- allow_archiving_with_java_agent:%d", _allow_archiving_with_java_agent);
 319   st->print_cr("- use_optimized_module_handling:  %d", _use_optimized_module_handling);
 320   st->print_cr("- has_full_module_graph           %d", _has_full_module_graph);
 321   st->print_cr("- has_aot_linked_classes          %d", _has_aot_linked_classes);
 322   st->print_cr("- has_archived_invokedynamic      %d", _has_archived_invokedynamic);
 323 }
 324 
 325 void SharedClassPathEntry::init_as_non_existent(const char* path, TRAPS) {
 326   _type = non_existent_entry;
 327   set_name(path, CHECK);
 328 }
 329 
 330 void SharedClassPathEntry::init(bool is_modules_image,
 331                                 bool is_module_path,
 332                                 ClassPathEntry* cpe, TRAPS) {
 333   assert(CDSConfig::is_dumping_archive(), "sanity");
 334   _timestamp = 0;
 335   _filesize  = 0;
 336   _from_class_path_attr = false;
 337 
 338   struct stat st;
 339   if (os::stat(cpe->name(), &st) == 0) {
 340     if ((st.st_mode & S_IFMT) == S_IFDIR) {
 341       _type = dir_entry;
 342     } else {
 343       // The timestamp of the modules_image is not checked at runtime.
 344       if (is_modules_image) {
 345         _type = modules_image_entry;
 346       } else {
 347         _type = jar_entry;
 348         _timestamp = st.st_mtime;
 349         _from_class_path_attr = cpe->from_class_path_attr();
 350         _is_multi_release = cpe->is_multi_release_jar();
 351       }
 352       _filesize = st.st_size;
 353       _is_module_path = is_module_path;
 354     }
 355   } else {
 356     // The file/dir must exist, or it would not have been added
 357     // into ClassLoader::classpath_entry().
 358     //
 359     // If we can't access a jar file in the boot path, then we can't
 360     // make assumptions about where classes get loaded from.
 361     log_error(cds)("Unable to open file %s.", cpe->name());
 362     MetaspaceShared::unrecoverable_loading_error();
 363   }
 364 
 365   // No need to save the name of the module file, as it will be computed at run time
 366   // to allow relocation of the JDK directory.
 367   const char* name = is_modules_image  ? "" : cpe->name();
 368   set_name(name, CHECK);
 369 }
 370 
 371 void SharedClassPathEntry::set_name(const char* name, TRAPS) {
 372   size_t len = strlen(name) + 1;
 373   _name = MetadataFactory::new_array<char>(ClassLoaderData::the_null_class_loader_data(), (int)len, CHECK);
 374   strcpy(_name->data(), name);
 375 }
 376 
 377 void SharedClassPathEntry::copy_from(SharedClassPathEntry* ent, ClassLoaderData* loader_data, TRAPS) {
 378   assert(ent != nullptr, "sanity");
 379   _type = ent->_type;
 380   _is_module_path = ent->_is_module_path;
 381   _timestamp = ent->_timestamp;
 382   _filesize = ent->_filesize;
 383   _from_class_path_attr = ent->_from_class_path_attr;
 384   set_name(ent->name(), CHECK);
 385 
 386   if (ent->is_jar() && ent->manifest() != nullptr) {
 387     Array<u1>* buf = MetadataFactory::new_array<u1>(loader_data,
 388                                                     ent->manifest_size(),
 389                                                     CHECK);
 390     char* p = (char*)(buf->data());
 391     memcpy(p, ent->manifest(), ent->manifest_size());
 392     set_manifest(buf);
 393   }
 394 }
 395 
 396 const char* SharedClassPathEntry::name() const {
 397   if (CDSConfig::is_using_archive() && is_modules_image()) {
 398     // In order to validate the runtime modules image file size against the archived
 399     // size information, we need to obtain the runtime modules image path. The recorded
 400     // dump time modules image path in the archive may be different from the runtime path
 401     // if the JDK image has beed moved after generating the archive.
 402     return ClassLoader::get_jrt_entry()->name();
 403   } else {
 404     return _name->data();
 405   }
 406 }
 407 
 408 bool SharedClassPathEntry::validate(bool is_class_path) const {
 409   assert(CDSConfig::is_using_archive(), "runtime only");
 410 
 411   struct stat st;
 412   const char* name = this->name();
 413 
 414   bool ok = true;
 415   log_info(class, path)("checking shared classpath entry: %s", name);
 416   if (os::stat(name, &st) != 0 && is_class_path) {
 417     // If the archived module path entry does not exist at runtime, it is not fatal
 418     // (no need to invalid the shared archive) because the shared runtime visibility check
 419     // filters out any archived module classes that do not have a matching runtime
 420     // module path location.
 421     log_warning(cds)("Required classpath entry does not exist: %s", name);
 422     ok = false;
 423   } else if (is_dir()) {
 424     if (!os::dir_is_empty(name)) {
 425       log_warning(cds)("directory is not empty: %s", name);
 426       ok = false;
 427     }
 428   } else {
 429     bool size_differs = _filesize != st.st_size;
 430     bool time_differs = has_timestamp() && _timestamp != st.st_mtime;
 431     if (time_differs || size_differs) {
 432       ok = false;
 433       if (PrintSharedArchiveAndExit) {
 434         log_warning(cds)(time_differs ? "Timestamp mismatch" : "File size mismatch");
 435       } else {
 436         const char* bad_file_msg = "This file is not the one used while building the shared archive file:";
 437         log_warning(cds)("%s %s", bad_file_msg, name);
 438         if (!log_is_enabled(Info, cds)) {
 439           log_warning(cds)("%s %s", bad_file_msg, name);
 440         }
 441         if (time_differs) {
 442           log_warning(cds)("%s timestamp has changed.", name);
 443         }
 444         if (size_differs) {
 445           log_warning(cds)("%s size has changed.", name);
 446         }
 447       }
 448     }
 449   }
 450 
 451   if (PrintSharedArchiveAndExit && !ok) {
 452     // If PrintSharedArchiveAndExit is enabled, don't report failure to the
 453     // caller. Please see above comments for more details.
 454     ok = true;
 455     MetaspaceShared::set_archive_loading_failed();
 456   }
 457   return ok;
 458 }
 459 
 460 bool SharedClassPathEntry::check_non_existent() const {
 461   assert(_type == non_existent_entry, "must be");
 462   log_info(class, path)("should be non-existent: %s", name());
 463   struct stat st;
 464   if (os::stat(name(), &st) != 0) {
 465     log_info(class, path)("ok");
 466     return true; // file doesn't exist
 467   } else {
 468     return false;
 469   }
 470 }
 471 
 472 void SharedClassPathEntry::metaspace_pointers_do(MetaspaceClosure* it) {
 473   it->push(&_name);
 474   it->push(&_manifest);
 475 }
 476 
 477 void SharedPathTable::metaspace_pointers_do(MetaspaceClosure* it) {
 478   it->push(&_entries);
 479 }
 480 
 481 void SharedPathTable::dumptime_init(ClassLoaderData* loader_data, TRAPS) {
 482   const int num_entries =
 483     ClassLoader::num_boot_classpath_entries() +
 484     ClassLoader::num_app_classpath_entries() +
 485     ClassLoader::num_module_path_entries() +
 486     FileMapInfo::num_non_existent_class_paths();
 487   _entries = MetadataFactory::new_array<SharedClassPathEntry*>(loader_data, num_entries, CHECK);
 488   for (int i = 0; i < num_entries; i++) {
 489     SharedClassPathEntry* ent =
 490       new (loader_data, SharedClassPathEntry::size(), MetaspaceObj::SharedClassPathEntryType, THREAD) SharedClassPathEntry;
 491     _entries->at_put(i, ent);
 492   }
 493 }
 494 
 495 void FileMapInfo::allocate_shared_path_table(TRAPS) {
 496   assert(CDSConfig::is_dumping_archive(), "sanity");
 497 
 498   ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data();
 499   ClassPathEntry* jrt = ClassLoader::get_jrt_entry();
 500 
 501   assert(jrt != nullptr,
 502          "No modular java runtime image present when allocating the CDS classpath entry table");
 503 
 504   _shared_path_table.dumptime_init(loader_data, CHECK);
 505 
 506   // 1. boot class path
 507   int i = 0;
 508   i = add_shared_classpaths(i, "boot",   jrt, CHECK);
 509   i = add_shared_classpaths(i, "app",    ClassLoader::app_classpath_entries(), CHECK);
 510   i = add_shared_classpaths(i, "module", ClassLoader::module_path_entries(), CHECK);
 511 
 512   for (int x = 0; x < num_non_existent_class_paths(); x++, i++) {
 513     const char* path = _non_existent_class_paths->at(x);
 514     shared_path(i)->init_as_non_existent(path, CHECK);
 515   }
 516 
 517   assert(i == _shared_path_table.size(), "number of shared path entry mismatch");
 518 }
 519 
 520 int FileMapInfo::add_shared_classpaths(int i, const char* which, ClassPathEntry *cpe, TRAPS) {
 521   while (cpe != nullptr) {
 522     bool is_jrt = (cpe == ClassLoader::get_jrt_entry());
 523     bool is_module_path = i >= ClassLoaderExt::app_module_paths_start_index();
 524     const char* type = (is_jrt ? "jrt" : (cpe->is_jar_file() ? "jar" : "dir"));
 525     log_info(class, path)("add %s shared path (%s) %s", which, type, cpe->name());
 526     SharedClassPathEntry* ent = shared_path(i);
 527     ent->init(is_jrt, is_module_path, cpe, CHECK_0);
 528     if (cpe->is_jar_file()) {
 529       update_jar_manifest(cpe, ent, CHECK_0);
 530     }
 531     if (is_jrt) {
 532       cpe = ClassLoader::get_next_boot_classpath_entry(cpe);
 533     } else {
 534       cpe = cpe->next();
 535     }
 536     i++;
 537   }
 538 
 539   return i;
 540 }
 541 
 542 void FileMapInfo::check_nonempty_dir_in_shared_path_table() {
 543   assert(CDSConfig::is_dumping_archive(), "sanity");
 544 
 545   bool has_nonempty_dir = false;
 546 
 547   int last = _shared_path_table.size() - 1;
 548   if (last > ClassLoaderExt::max_used_path_index()) {
 549      // no need to check any path beyond max_used_path_index
 550      last = ClassLoaderExt::max_used_path_index();
 551   }
 552 
 553   for (int i = 0; i <= last; i++) {
 554     SharedClassPathEntry *e = shared_path(i);
 555     if (e->is_dir()) {
 556       const char* path = e->name();
 557       if (!os::dir_is_empty(path)) {
 558         log_error(cds)("Error: non-empty directory '%s'", path);
 559         has_nonempty_dir = true;
 560       }
 561     }
 562   }
 563 
 564   if (has_nonempty_dir) {
 565     ClassLoader::exit_with_path_failure("Cannot have non-empty directory in paths", nullptr);
 566   }
 567 }
 568 
 569 void FileMapInfo::record_non_existent_class_path_entry(const char* path) {
 570   assert(CDSConfig::is_dumping_archive(), "sanity");
 571   log_info(class, path)("non-existent Class-Path entry %s", path);
 572   if (_non_existent_class_paths == nullptr) {
 573     _non_existent_class_paths = new (mtClass) GrowableArray<const char*>(10, mtClass);
 574   }
 575   _non_existent_class_paths->append(os::strdup(path));
 576 }
 577 
 578 int FileMapInfo::num_non_existent_class_paths() {
 579   assert(CDSConfig::is_dumping_archive(), "sanity");
 580   if (_non_existent_class_paths != nullptr) {
 581     return _non_existent_class_paths->length();
 582   } else {
 583     return 0;
 584   }
 585 }
 586 
 587 int FileMapInfo::get_module_shared_path_index(Symbol* location) {
 588   if (location->starts_with("jrt:", 4) && get_number_of_shared_paths() > 0) {
 589     assert(shared_path(0)->is_modules_image(), "first shared_path must be the modules image");
 590     return 0;
 591   }
 592 
 593   if (ClassLoaderExt::app_module_paths_start_index() >= get_number_of_shared_paths()) {
 594     // The archive(s) were created without --module-path option
 595     return -1;
 596   }
 597 
 598   if (!location->starts_with("file:", 5)) {
 599     return -1;
 600   }
 601 
 602   // skip_uri_protocol was also called during dump time -- see ClassLoaderExt::process_module_table()
 603   ResourceMark rm;
 604   const char* file = ClassLoader::uri_to_path(location->as_C_string());
 605   for (int i = ClassLoaderExt::app_module_paths_start_index(); i < get_number_of_shared_paths(); i++) {
 606     SharedClassPathEntry* ent = shared_path(i);
 607     if (!ent->is_non_existent()) {
 608       assert(ent->in_named_module(), "must be");
 609       bool cond = strcmp(file, ent->name()) == 0;
 610       log_debug(class, path)("get_module_shared_path_index (%d) %s : %s = %s", i,
 611                              location->as_C_string(), ent->name(), cond ? "same" : "different");
 612       if (cond) {
 613         return i;
 614       }
 615     }
 616   }
 617 
 618   return -1;
 619 }
 620 
 621 class ManifestStream: public ResourceObj {
 622   private:
 623   u1*   _buffer_start; // Buffer bottom
 624   u1*   _buffer_end;   // Buffer top (one past last element)
 625   u1*   _current;      // Current buffer position
 626 
 627  public:
 628   // Constructor
 629   ManifestStream(u1* buffer, int length) : _buffer_start(buffer),
 630                                            _current(buffer) {
 631     _buffer_end = buffer + length;
 632   }
 633 
 634   static bool is_attr(u1* attr, const char* name) {
 635     return strncmp((const char*)attr, name, strlen(name)) == 0;
 636   }
 637 
 638   static char* copy_attr(u1* value, size_t len) {
 639     char* buf = NEW_RESOURCE_ARRAY(char, len + 1);
 640     strncpy(buf, (char*)value, len);
 641     buf[len] = 0;
 642     return buf;
 643   }
 644 };
 645 
 646 void FileMapInfo::update_jar_manifest(ClassPathEntry *cpe, SharedClassPathEntry* ent, TRAPS) {
 647   ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data();
 648   ResourceMark rm(THREAD);
 649   jint manifest_size;
 650 
 651   assert(cpe->is_jar_file() && ent->is_jar(), "the shared class path entry is not a JAR file");
 652   char* manifest = ClassLoaderExt::read_manifest(THREAD, cpe, &manifest_size);
 653   if (manifest != nullptr) {
 654     ManifestStream* stream = new ManifestStream((u1*)manifest,
 655                                                 manifest_size);
 656     // Copy the manifest into the shared archive
 657     manifest = ClassLoaderExt::read_raw_manifest(THREAD, cpe, &manifest_size);
 658     Array<u1>* buf = MetadataFactory::new_array<u1>(loader_data,
 659                                                     manifest_size,
 660                                                     CHECK);
 661     char* p = (char*)(buf->data());
 662     memcpy(p, manifest, manifest_size);
 663     ent->set_manifest(buf);
 664   }
 665 }
 666 
 667 char* FileMapInfo::skip_first_path_entry(const char* path) {
 668   size_t path_sep_len = strlen(os::path_separator());
 669   char* p = strstr((char*)path, os::path_separator());
 670   if (p != nullptr) {
 671     debug_only( {
 672       size_t image_name_len = strlen(MODULES_IMAGE_NAME);
 673       assert(strncmp(p - image_name_len, MODULES_IMAGE_NAME, image_name_len) == 0,
 674              "first entry must be the modules image");
 675     } );
 676     p += path_sep_len;
 677   } else {
 678     debug_only( {
 679       assert(ClassLoader::string_ends_with(path, MODULES_IMAGE_NAME),
 680              "first entry must be the modules image");
 681     } );
 682   }
 683   return p;
 684 }
 685 
 686 int FileMapInfo::num_paths(const char* path) {
 687   if (path == nullptr) {
 688     return 0;
 689   }
 690   int npaths = 1;
 691   char* p = (char*)path;
 692   while (p != nullptr) {
 693     char* prev = p;
 694     p = strstr((char*)p, os::path_separator());
 695     if (p != nullptr) {
 696       p++;
 697       // don't count empty path
 698       if ((p - prev) > 1) {
 699        npaths++;
 700       }
 701     }
 702   }
 703   return npaths;
 704 }
 705 
 706 // Returns true if a path within the paths exists and has non-zero size.
 707 bool FileMapInfo::check_paths_existence(const char* paths) {
 708   ClasspathStream cp_stream(paths);
 709   bool exist = false;
 710   struct stat st;
 711   while (cp_stream.has_next()) {
 712     const char* path = cp_stream.get_next();
 713     if (os::stat(path, &st) == 0 && st.st_size > 0) {
 714       exist = true;
 715       break;
 716     }
 717   }
 718   return exist;
 719 }
 720 
 721 GrowableArray<const char*>* FileMapInfo::create_dumptime_app_classpath_array() {
 722   assert(CDSConfig::is_dumping_archive(), "sanity");
 723   GrowableArray<const char*>* path_array = new GrowableArray<const char*>(10);
 724   ClassPathEntry* cpe = ClassLoader::app_classpath_entries();
 725   while (cpe != nullptr) {
 726     path_array->append(cpe->name());
 727     cpe = cpe->next();
 728   }
 729   return path_array;
 730 }
 731 
 732 GrowableArray<const char*>* FileMapInfo::create_path_array(const char* paths) {
 733   GrowableArray<const char*>* path_array = new GrowableArray<const char*>(10);
 734   JavaThread* current = JavaThread::current();
 735   ClasspathStream cp_stream(paths);
 736   bool non_jar_in_cp = header()->has_non_jar_in_classpath();
 737   while (cp_stream.has_next()) {
 738     const char* path = cp_stream.get_next();
 739     if (!non_jar_in_cp) {
 740       struct stat st;
 741       if (os::stat(path, &st) == 0) {
 742         path_array->append(path);
 743       }
 744     } else {
 745       const char* canonical_path = ClassLoader::get_canonical_path(path, current);
 746       if (canonical_path != nullptr) {
 747         char* error_msg = nullptr;
 748         jzfile* zip = ClassLoader::open_zip_file(canonical_path, &error_msg, current);
 749         if (zip != nullptr && error_msg == nullptr) {
 750           path_array->append(path);
 751         }
 752       }
 753     }
 754   }
 755   return path_array;
 756 }
 757 
 758 bool FileMapInfo::classpath_failure(const char* msg, const char* name) {
 759   ClassLoader::trace_class_path(msg, name);
 760   if (PrintSharedArchiveAndExit) {
 761     MetaspaceShared::set_archive_loading_failed();
 762   }
 763   return false;
 764 }
 765 
 766 unsigned int FileMapInfo::longest_common_app_classpath_prefix_len(int num_paths,
 767                                                                   GrowableArray<const char*>* rp_array) {
 768   if (num_paths == 0) {
 769     return 0;
 770   }
 771   unsigned int pos;
 772   for (pos = 0; ; pos++) {
 773     for (int i = 0; i < num_paths; i++) {
 774       if (rp_array->at(i)[pos] != '\0' && rp_array->at(i)[pos] == rp_array->at(0)[pos]) {
 775         continue;
 776       }
 777       // search backward for the pos before the file separator char
 778       while (pos > 0) {
 779         if (rp_array->at(0)[--pos] == *os::file_separator()) {
 780           return pos + 1;
 781         }
 782       }
 783       return 0;
 784     }
 785   }
 786   return 0;
 787 }
 788 
 789 bool FileMapInfo::check_paths(int shared_path_start_idx, int num_paths, GrowableArray<const char*>* rp_array,
 790                               unsigned int dumptime_prefix_len, unsigned int runtime_prefix_len) {
 791   int i = 0;
 792   int j = shared_path_start_idx;
 793   while (i < num_paths) {
 794     while (shared_path(j)->from_class_path_attr()) {
 795       // shared_path(j) was expanded from the JAR file attribute "Class-Path:"
 796       // during dump time. It's not included in the -classpath VM argument.
 797       j++;
 798     }
 799     assert(strlen(shared_path(j)->name()) > (size_t)dumptime_prefix_len, "sanity");
 800     const char* dumptime_path = shared_path(j)->name() + dumptime_prefix_len;
 801     assert(strlen(rp_array->at(i)) > (size_t)runtime_prefix_len, "sanity");
 802     const char* runtime_path = rp_array->at(i)  + runtime_prefix_len;
 803     if (!os::same_files(dumptime_path, runtime_path)) {
 804       return false;
 805     }
 806     i++;
 807     j++;
 808   }
 809   return true;
 810 }
 811 
 812 bool FileMapInfo::validate_boot_class_paths() {
 813   //
 814   // - Archive contains boot classes only - relaxed boot path check:
 815   //   Extra path elements appended to the boot path at runtime are allowed.
 816   //
 817   // - Archive contains application or platform classes - strict boot path check:
 818   //   Validate the entire runtime boot path, which must be compatible
 819   //   with the dump time boot path. Appending boot path at runtime is not
 820   //   allowed.
 821   //
 822 
 823   // The first entry in boot path is the modules_image (guaranteed by
 824   // ClassLoader::setup_boot_search_path()). Skip the first entry. The
 825   // path of the runtime modules_image may be different from the dump
 826   // time path (e.g. the JDK image is copied to a different location
 827   // after generating the shared archive), which is acceptable. For most
 828   // common cases, the dump time boot path might contain modules_image only.
 829   char* runtime_boot_path = Arguments::get_boot_class_path();
 830   char* rp = skip_first_path_entry(runtime_boot_path);
 831   assert(shared_path(0)->is_modules_image(), "first shared_path must be the modules image");
 832   int dp_len = header()->app_class_paths_start_index() - 1; // ignore the first path to the module image
 833   bool match = true;
 834 
 835   bool relaxed_check = !header()->has_platform_or_app_classes();
 836   if (dp_len == 0 && rp == nullptr) {
 837     return true;   // ok, both runtime and dump time boot paths have modules_images only
 838   } else if (dp_len == 0 && rp != nullptr) {
 839     if (relaxed_check) {
 840       return true;   // ok, relaxed check, runtime has extra boot append path entries
 841     } else {
 842       ResourceMark rm;
 843       if (check_paths_existence(rp)) {
 844         // If a path exists in the runtime boot paths, it is considered a mismatch
 845         // since there's no boot path specified during dump time.
 846         match = false;
 847       }
 848     }
 849   } else if (dp_len > 0 && rp != nullptr) {
 850     int num;
 851     ResourceMark rm;
 852     GrowableArray<const char*>* rp_array = create_path_array(rp);
 853     int rp_len = rp_array->length();
 854     if (rp_len >= dp_len) {
 855       if (relaxed_check) {
 856         // only check the leading entries in the runtime boot path, up to
 857         // the length of the dump time boot path
 858         num = dp_len;
 859       } else {
 860         // check the full runtime boot path, must match with dump time
 861         num = rp_len;
 862       }
 863       match = check_paths(1, num, rp_array, 0, 0);
 864     } else {
 865       // create_path_array() ignores non-existing paths. Although the dump time and runtime boot classpath lengths
 866       // are the same initially, after the call to create_path_array(), the runtime boot classpath length could become
 867       // shorter. We consider boot classpath mismatch in this case.
 868       match = false;
 869     }
 870   }
 871 
 872   if (!match) {
 873     // The paths are different
 874     return classpath_failure("[BOOT classpath mismatch, actual =", runtime_boot_path);
 875   }
 876   return true;
 877 }
 878 
 879 bool FileMapInfo::validate_app_class_paths(int shared_app_paths_len) {
 880   const char *appcp = Arguments::get_appclasspath();
 881   assert(appcp != nullptr, "null app classpath");
 882   int rp_len = num_paths(appcp);
 883   bool match = false;
 884   if (rp_len < shared_app_paths_len) {
 885     return classpath_failure("Run time APP classpath is shorter than the one at dump time: ", appcp);
 886   }
 887   if (shared_app_paths_len != 0 && rp_len != 0) {
 888     // Prefix is OK: E.g., dump with -cp foo.jar, but run with -cp foo.jar:bar.jar.
 889     ResourceMark rm;
 890     GrowableArray<const char*>* rp_array = create_path_array(appcp);
 891     if (rp_array->length() == 0) {
 892       // None of the jar file specified in the runtime -cp exists.
 893       return classpath_failure("None of the jar file specified in the runtime -cp exists: -Djava.class.path=", appcp);
 894     }
 895     if (rp_array->length() < shared_app_paths_len) {
 896       // create_path_array() ignores non-existing paths. Although the dump time and runtime app classpath lengths
 897       // are the same initially, after the call to create_path_array(), the runtime app classpath length could become
 898       // shorter. We consider app classpath mismatch in this case.
 899       return classpath_failure("[APP classpath mismatch, actual: -Djava.class.path=", appcp);
 900     }
 901 
 902     // Handling of non-existent entries in the classpath: we eliminate all the non-existent
 903     // entries from both the dump time classpath (ClassLoader::update_class_path_entry_list)
 904     // and the runtime classpath (FileMapInfo::create_path_array), and check the remaining
 905     // entries. E.g.:
 906     //
 907     // dump : -cp a.jar:NE1:NE2:b.jar  -> a.jar:b.jar -> recorded in archive.
 908     // run 1: -cp NE3:a.jar:NE4:b.jar  -> a.jar:b.jar -> matched
 909     // run 2: -cp x.jar:NE4:b.jar      -> x.jar:b.jar -> mismatched
 910 
 911     int j = header()->app_class_paths_start_index();
 912     match = check_paths(j, shared_app_paths_len, rp_array, 0, 0);
 913     if (!match) {
 914       // To facilitate app deployment, we allow the JAR files to be moved *together* to
 915       // a different location, as long as they are still stored under the same directory
 916       // structure. E.g., the following is OK.
 917       //     java -Xshare:dump -cp /a/Foo.jar:/a/b/Bar.jar  ...
 918       //     java -Xshare:auto -cp /x/y/Foo.jar:/x/y/b/Bar.jar  ...
 919       unsigned int dumptime_prefix_len = header()->common_app_classpath_prefix_size();
 920       unsigned int runtime_prefix_len = longest_common_app_classpath_prefix_len(shared_app_paths_len, rp_array);
 921       if (dumptime_prefix_len != 0 || runtime_prefix_len != 0) {
 922         log_info(class, path)("LCP length for app classpath (dumptime: %u, runtime: %u)",
 923                               dumptime_prefix_len, runtime_prefix_len);
 924         match = check_paths(j, shared_app_paths_len, rp_array,
 925                                dumptime_prefix_len, runtime_prefix_len);
 926       }
 927       if (!match) {
 928         return classpath_failure("[APP classpath mismatch, actual: -Djava.class.path=", appcp);
 929       }
 930     }
 931   }
 932   return true;
 933 }
 934 
 935 void FileMapInfo::log_paths(const char* msg, int start_idx, int end_idx) {
 936   LogTarget(Info, class, path) lt;
 937   if (lt.is_enabled()) {
 938     LogStream ls(lt);
 939     ls.print("%s", msg);
 940     const char* prefix = "";
 941     for (int i = start_idx; i < end_idx; i++) {
 942       ls.print("%s%s", prefix, shared_path(i)->name());
 943       prefix = os::path_separator();
 944     }
 945     ls.cr();
 946   }
 947 }
 948 
 949 void FileMapInfo::extract_module_paths(const char* runtime_path, GrowableArray<const char*>* module_paths) {
 950   GrowableArray<const char*>* path_array = create_path_array(runtime_path);
 951   int num_paths = path_array->length();
 952   for (int i = 0; i < num_paths; i++) {
 953     const char* name = path_array->at(i);
 954     ClassLoaderExt::extract_jar_files_from_path(name, module_paths);
 955   }
 956   // module paths are stored in sorted order in the CDS archive.
 957   module_paths->sort(ClassLoaderExt::compare_module_names);
 958 }
 959 
 960 bool FileMapInfo::check_module_paths() {
 961   const char* runtime_path = Arguments::get_property("jdk.module.path");
 962   int archived_num_module_paths = header()->num_module_paths();
 963   if (runtime_path == nullptr && archived_num_module_paths == 0) {
 964     return true;
 965   }
 966   if ((runtime_path == nullptr && archived_num_module_paths > 0) ||
 967       (runtime_path != nullptr && archived_num_module_paths == 0)) {
 968     return false;
 969   }
 970   ResourceMark rm;
 971   GrowableArray<const char*>* module_paths = new GrowableArray<const char*>(3);
 972   extract_module_paths(runtime_path, module_paths);
 973   int num_paths = module_paths->length();
 974   if (num_paths != archived_num_module_paths) {
 975     return false;
 976   }
 977   return check_paths(header()->app_module_paths_start_index(), num_paths, module_paths, 0, 0);
 978 }
 979 
 980 bool FileMapInfo::validate_shared_path_table() {
 981   assert(CDSConfig::is_using_archive(), "runtime only");
 982 
 983   _validating_shared_path_table = true;
 984 
 985   // Load the shared path table info from the archive header
 986   _shared_path_table = header()->shared_path_table();
 987 
 988   bool matched_module_paths = true;
 989   if (CDSConfig::is_dumping_dynamic_archive() || header()->has_full_module_graph()) {
 990     matched_module_paths = check_module_paths();
 991   }
 992   if (header()->has_full_module_graph() && !matched_module_paths) {
 993     CDSConfig::stop_using_optimized_module_handling();
 994     log_info(cds)("optimized module handling: disabled because of mismatched module paths");
 995   }
 996 
 997   if (CDSConfig::is_dumping_dynamic_archive()) {
 998     // Only support dynamic dumping with the usage of the default CDS archive
 999     // or a simple base archive.
1000     // If the base layer archive contains additional path component besides
1001     // the runtime image and the -cp, dynamic dumping is disabled.
1002     //
1003     // When dynamic archiving is enabled, the _shared_path_table is overwritten
1004     // to include the application path and stored in the top layer archive.
1005     assert(shared_path(0)->is_modules_image(), "first shared_path must be the modules image");
1006     if (header()->app_class_paths_start_index() > 1) {
1007       CDSConfig::disable_dumping_dynamic_archive();
1008       log_warning(cds)(
1009         "Dynamic archiving is disabled because base layer archive has appended boot classpath");
1010     }
1011     if (header()->num_module_paths() > 0) {
1012       if (!matched_module_paths) {
1013         CDSConfig::disable_dumping_dynamic_archive();
1014         log_warning(cds)(
1015           "Dynamic archiving is disabled because base layer archive has a different module path");
1016       }
1017     }
1018   }
1019 
1020   log_paths("Expecting BOOT path=", 0, header()->app_class_paths_start_index());
1021   log_paths("Expecting -Djava.class.path=", header()->app_class_paths_start_index(), header()->app_module_paths_start_index());
1022 
1023   int module_paths_start_index = header()->app_module_paths_start_index();
1024   int shared_app_paths_len = 0;
1025 
1026   // validate the path entries up to the _max_used_path_index
1027   for (int i=0; i < header()->max_used_path_index() + 1; i++) {
1028     if (i < module_paths_start_index) {
1029       if (shared_path(i)->validate()) {
1030         // Only count the app class paths not from the "Class-path" attribute of a jar manifest.
1031         if (!shared_path(i)->from_class_path_attr() && i >= header()->app_class_paths_start_index()) {
1032           shared_app_paths_len++;
1033         }
1034         log_info(class, path)("ok");
1035       } else {
1036         if (_dynamic_archive_info != nullptr && _dynamic_archive_info->_is_static) {
1037           assert(!CDSConfig::is_using_archive(), "UseSharedSpaces should be disabled");
1038         }
1039         return false;
1040       }
1041     } else if (i >= module_paths_start_index) {
1042       if (shared_path(i)->validate(false /* not a class path entry */)) {
1043         log_info(class, path)("ok");
1044       } else {
1045         if (_dynamic_archive_info != nullptr && _dynamic_archive_info->_is_static) {
1046           assert(!CDSConfig::is_using_archive(), "UseSharedSpaces should be disabled");
1047         }
1048         return false;
1049       }
1050     }
1051   }
1052 
1053   if (header()->max_used_path_index() == 0) {
1054     // default archive only contains the module image in the bootclasspath
1055     assert(shared_path(0)->is_modules_image(), "first shared_path must be the modules image");
1056   } else {
1057     if (!validate_boot_class_paths() || !validate_app_class_paths(shared_app_paths_len)) {
1058       const char* mismatch_msg = "shared class paths mismatch";
1059       const char* hint_msg = log_is_enabled(Info, class, path) ?
1060           "" : " (hint: enable -Xlog:class+path=info to diagnose the failure)";
1061       if (RequireSharedSpaces) {
1062         log_error(cds)("%s%s", mismatch_msg, hint_msg);
1063         MetaspaceShared::unrecoverable_loading_error();
1064       } else {
1065         log_warning(cds)("%s%s", mismatch_msg, hint_msg);
1066       }
1067       return false;
1068     }
1069   }
1070 
1071   if (!validate_non_existent_class_paths()) {
1072     return false;
1073   }
1074 
1075   _validating_shared_path_table = false;
1076 
1077 #if INCLUDE_JVMTI
1078   if (_classpath_entries_for_jvmti != nullptr) {
1079     os::free(_classpath_entries_for_jvmti);
1080   }
1081   size_t sz = sizeof(ClassPathEntry*) * get_number_of_shared_paths();
1082   _classpath_entries_for_jvmti = (ClassPathEntry**)os::malloc(sz, mtClass);
1083   memset((void*)_classpath_entries_for_jvmti, 0, sz);
1084 #endif
1085 
1086   return true;
1087 }
1088 
1089 bool FileMapInfo::validate_non_existent_class_paths() {
1090   // All of the recorded non-existent paths came from the Class-Path: attribute from the JAR
1091   // files on the app classpath. If any of these are found to exist during runtime,
1092   // it will change how classes are loading for the app loader. For safety, disable
1093   // loading of archived platform/app classes (currently there's no way to disable just the
1094   // app classes).
1095 
1096   assert(CDSConfig::is_using_archive(), "runtime only");
1097   for (int i = header()->app_module_paths_start_index() + header()->num_module_paths();
1098        i < get_number_of_shared_paths();
1099        i++) {
1100     SharedClassPathEntry* ent = shared_path(i);
1101     if (!ent->check_non_existent()) {
1102       if (header()->has_aot_linked_classes()) {
1103         log_error(cds)("CDS archive has aot-linked classes. It cannot be used because the "
1104                        "file %s exists", ent->name());
1105         return false;
1106       } else {
1107         log_warning(cds)("Archived non-system classes are disabled because the "
1108                          "file %s exists", ent->name());
1109         header()->set_has_platform_or_app_classes(false);
1110       }
1111     }
1112   }
1113 
1114   return true;
1115 }
1116 
1117 // A utility class for reading/validating the GenericCDSFileMapHeader portion of
1118 // a CDS archive's header. The file header of all CDS archives with versions from
1119 // CDS_GENERIC_HEADER_SUPPORTED_MIN_VERSION (12) are guaranteed to always start
1120 // with GenericCDSFileMapHeader. This makes it possible to read important information
1121 // from a CDS archive created by a different version of HotSpot, so that we can
1122 // automatically regenerate the archive as necessary (JDK-8261455).
1123 class FileHeaderHelper {
1124   int _fd;
1125   bool _is_valid;
1126   bool _is_static;
1127   GenericCDSFileMapHeader* _header;
1128   const char* _archive_name;
1129   const char* _base_archive_name;
1130 
1131 public:
1132   FileHeaderHelper(const char* archive_name, bool is_static) {
1133     _fd = -1;
1134     _is_valid = false;
1135     _header = nullptr;
1136     _base_archive_name = nullptr;
1137     _archive_name = archive_name;
1138     _is_static = is_static;
1139   }
1140 
1141   ~FileHeaderHelper() {
1142     if (_header != nullptr) {
1143       FREE_C_HEAP_ARRAY(char, _header);
1144     }
1145     if (_fd != -1) {
1146       ::close(_fd);
1147     }
1148   }
1149 
1150   bool initialize() {
1151     assert(_archive_name != nullptr, "Archive name is null");
1152     _fd = os::open(_archive_name, O_RDONLY | O_BINARY, 0);
1153     if (_fd < 0) {
1154       log_info(cds)("Specified shared archive not found (%s)", _archive_name);
1155       return false;
1156     }
1157     return initialize(_fd);
1158   }
1159 
1160   // for an already opened file, do not set _fd
1161   bool initialize(int fd) {
1162     assert(_archive_name != nullptr, "Archive name is null");
1163     assert(fd != -1, "Archive must be opened already");
1164     // First read the generic header so we know the exact size of the actual header.
1165     GenericCDSFileMapHeader gen_header;
1166     size_t size = sizeof(GenericCDSFileMapHeader);
1167     os::lseek(fd, 0, SEEK_SET);
1168     size_t n = ::read(fd, (void*)&gen_header, (unsigned int)size);
1169     if (n != size) {
1170       log_warning(cds)("Unable to read generic CDS file map header from shared archive");
1171       return false;
1172     }
1173 
1174     if (gen_header._magic != CDS_ARCHIVE_MAGIC &&
1175         gen_header._magic != CDS_DYNAMIC_ARCHIVE_MAGIC) {
1176       log_warning(cds)("The shared archive file has a bad magic number: %#x", gen_header._magic);
1177       return false;
1178     }
1179 
1180     if (gen_header._version < CDS_GENERIC_HEADER_SUPPORTED_MIN_VERSION) {
1181       log_warning(cds)("Cannot handle shared archive file version 0x%x. Must be at least 0x%x.",
1182                                  gen_header._version, CDS_GENERIC_HEADER_SUPPORTED_MIN_VERSION);
1183       return false;
1184     }
1185 
1186     if (gen_header._version !=  CURRENT_CDS_ARCHIVE_VERSION) {
1187       log_warning(cds)("The shared archive file version 0x%x does not match the required version 0x%x.",
1188                                  gen_header._version, CURRENT_CDS_ARCHIVE_VERSION);
1189     }
1190 
1191     size_t filelen = os::lseek(fd, 0, SEEK_END);
1192     if (gen_header._header_size >= filelen) {
1193       log_warning(cds)("Archive file header larger than archive file");
1194       return false;
1195     }
1196 
1197     // Read the actual header and perform more checks
1198     size = gen_header._header_size;
1199     _header = (GenericCDSFileMapHeader*)NEW_C_HEAP_ARRAY(char, size, mtInternal);
1200     os::lseek(fd, 0, SEEK_SET);
1201     n = ::read(fd, (void*)_header, (unsigned int)size);
1202     if (n != size) {
1203       log_warning(cds)("Unable to read actual CDS file map header from shared archive");
1204       return false;
1205     }
1206 
1207     if (!check_header_crc()) {
1208       return false;
1209     }
1210 
1211     if (!check_and_init_base_archive_name()) {
1212       return false;
1213     }
1214 
1215     // All fields in the GenericCDSFileMapHeader has been validated.
1216     _is_valid = true;
1217     return true;
1218   }
1219 
1220   GenericCDSFileMapHeader* get_generic_file_header() {
1221     assert(_header != nullptr && _is_valid, "must be a valid archive file");
1222     return _header;
1223   }
1224 
1225   const char* base_archive_name() {
1226     assert(_header != nullptr && _is_valid, "must be a valid archive file");
1227     return _base_archive_name;
1228   }
1229 
1230  private:
1231   bool check_header_crc() const {
1232     if (VerifySharedSpaces) {
1233       FileMapHeader* header = (FileMapHeader*)_header;
1234       int actual_crc = header->compute_crc();
1235       if (actual_crc != header->crc()) {
1236         log_info(cds)("_crc expected: %d", header->crc());
1237         log_info(cds)("       actual: %d", actual_crc);
1238         log_warning(cds)("Header checksum verification failed.");
1239         return false;
1240       }
1241     }
1242     return true;
1243   }
1244 
1245   bool check_and_init_base_archive_name() {
1246     unsigned int name_offset = _header->_base_archive_name_offset;
1247     unsigned int name_size   = _header->_base_archive_name_size;
1248     unsigned int header_size = _header->_header_size;
1249 
1250     if (name_offset + name_size < name_offset) {
1251       log_warning(cds)("base_archive_name offset/size overflow: " UINT32_FORMAT "/" UINT32_FORMAT,
1252                                  name_offset, name_size);
1253       return false;
1254     }
1255     if (_header->_magic == CDS_ARCHIVE_MAGIC) {
1256       if (name_offset != 0) {
1257         log_warning(cds)("static shared archive must have zero _base_archive_name_offset");
1258         return false;
1259       }
1260       if (name_size != 0) {
1261         log_warning(cds)("static shared archive must have zero _base_archive_name_size");
1262         return false;
1263       }
1264     } else {
1265       assert(_header->_magic == CDS_DYNAMIC_ARCHIVE_MAGIC, "must be");
1266       if ((name_size == 0 && name_offset != 0) ||
1267           (name_size != 0 && name_offset == 0)) {
1268         // If either is zero, both must be zero. This indicates that we are using the default base archive.
1269         log_warning(cds)("Invalid base_archive_name offset/size: " UINT32_FORMAT "/" UINT32_FORMAT,
1270                                    name_offset, name_size);
1271         return false;
1272       }
1273       if (name_size > 0) {
1274         if (name_offset + name_size > header_size) {
1275           log_warning(cds)("Invalid base_archive_name offset/size (out of range): "
1276                                      UINT32_FORMAT " + " UINT32_FORMAT " > " UINT32_FORMAT ,
1277                                      name_offset, name_size, header_size);
1278           return false;
1279         }
1280         const char* name = ((const char*)_header) + _header->_base_archive_name_offset;
1281         if (name[name_size - 1] != '\0' || strlen(name) != name_size - 1) {
1282           log_warning(cds)("Base archive name is damaged");
1283           return false;
1284         }
1285         if (!os::file_exists(name)) {
1286           log_warning(cds)("Base archive %s does not exist", name);
1287           return false;
1288         }
1289         _base_archive_name = name;
1290       }
1291     }
1292 
1293     return true;
1294   }
1295 };
1296 
1297 // Return value:
1298 // false:
1299 //      <archive_name> is not a valid archive. *base_archive_name is set to null.
1300 // true && (*base_archive_name) == nullptr:
1301 //      <archive_name> is a valid static archive.
1302 // true && (*base_archive_name) != nullptr:
1303 //      <archive_name> is a valid dynamic archive.
1304 bool FileMapInfo::get_base_archive_name_from_header(const char* archive_name,
1305                                                     char** base_archive_name) {
1306   FileHeaderHelper file_helper(archive_name, false);
1307   *base_archive_name = nullptr;
1308 
1309   if (!file_helper.initialize()) {
1310     return false;
1311   }
1312   GenericCDSFileMapHeader* header = file_helper.get_generic_file_header();
1313   if (header->_magic != CDS_DYNAMIC_ARCHIVE_MAGIC) {
1314     assert(header->_magic == CDS_ARCHIVE_MAGIC, "must be");
1315     if (AutoCreateSharedArchive) {
1316      log_warning(cds)("AutoCreateSharedArchive is ignored because %s is a static archive", archive_name);
1317     }
1318     return true;
1319   }
1320 
1321   const char* base = file_helper.base_archive_name();
1322   if (base == nullptr) {
1323     *base_archive_name = CDSConfig::default_archive_path();
1324   } else {
1325     *base_archive_name = os::strdup_check_oom(base);
1326   }
1327 
1328   return true;
1329 }
1330 
1331 // Read the FileMapInfo information from the file.
1332 
1333 bool FileMapInfo::init_from_file(int fd) {
1334   FileHeaderHelper file_helper(_full_path, _is_static);
1335   if (!file_helper.initialize(fd)) {
1336     log_warning(cds)("Unable to read the file header.");
1337     return false;
1338   }
1339   GenericCDSFileMapHeader* gen_header = file_helper.get_generic_file_header();
1340 
1341   if (_is_static) {
1342     if (gen_header->_magic != CDS_ARCHIVE_MAGIC) {
1343       log_warning(cds)("Not a base shared archive: %s", _full_path);
1344       return false;
1345     }
1346   } else {
1347     if (gen_header->_magic != CDS_DYNAMIC_ARCHIVE_MAGIC) {
1348       log_warning(cds)("Not a top shared archive: %s", _full_path);
1349       return false;
1350     }
1351   }
1352 
1353   _header = (FileMapHeader*)os::malloc(gen_header->_header_size, mtInternal);
1354   os::lseek(fd, 0, SEEK_SET); // reset to begin of the archive
1355   size_t size = gen_header->_header_size;
1356   size_t n = ::read(fd, (void*)_header, (unsigned int)size);
1357   if (n != size) {
1358     log_warning(cds)("Failed to read file header from the top archive file\n");
1359     return false;
1360   }
1361 
1362   if (header()->version() != CURRENT_CDS_ARCHIVE_VERSION) {
1363     log_info(cds)("_version expected: 0x%x", CURRENT_CDS_ARCHIVE_VERSION);
1364     log_info(cds)("           actual: 0x%x", header()->version());
1365     log_warning(cds)("The shared archive file has the wrong version.");
1366     return false;
1367   }
1368 
1369   int common_path_size = header()->common_app_classpath_prefix_size();
1370   if (common_path_size < 0) {
1371       log_warning(cds)("common app classpath prefix len < 0");
1372       return false;
1373   }
1374 
1375   unsigned int base_offset = header()->base_archive_name_offset();
1376   unsigned int name_size = header()->base_archive_name_size();
1377   unsigned int header_size = header()->header_size();
1378   if (base_offset != 0 && name_size != 0) {
1379     if (header_size != base_offset + name_size) {
1380       log_info(cds)("_header_size: " UINT32_FORMAT, header_size);
1381       log_info(cds)("common_app_classpath_size: " UINT32_FORMAT, header()->common_app_classpath_prefix_size());
1382       log_info(cds)("base_archive_name_size: " UINT32_FORMAT, header()->base_archive_name_size());
1383       log_info(cds)("base_archive_name_offset: " UINT32_FORMAT, header()->base_archive_name_offset());
1384       log_warning(cds)("The shared archive file has an incorrect header size.");
1385       return false;
1386     }
1387   }
1388 
1389   const char* actual_ident = header()->jvm_ident();
1390 
1391   if (actual_ident[JVM_IDENT_MAX-1] != 0) {
1392     log_warning(cds)("JVM version identifier is corrupted.");
1393     return false;
1394   }
1395 
1396   char expected_ident[JVM_IDENT_MAX];
1397   get_header_version(expected_ident);
1398   if (strncmp(actual_ident, expected_ident, JVM_IDENT_MAX-1) != 0) {
1399     log_info(cds)("_jvm_ident expected: %s", expected_ident);
1400     log_info(cds)("             actual: %s", actual_ident);
1401     log_warning(cds)("The shared archive file was created by a different"
1402                   " version or build of HotSpot");
1403     return false;
1404   }
1405 
1406   _file_offset = header()->header_size(); // accounts for the size of _base_archive_name
1407 
1408   size_t len = os::lseek(fd, 0, SEEK_END);
1409 
1410   for (int i = 0; i < MetaspaceShared::n_regions; i++) {
1411     FileMapRegion* r = region_at(i);
1412     if (r->file_offset() > len || len - r->file_offset() < r->used()) {
1413       log_warning(cds)("The shared archive file has been truncated.");
1414       return false;
1415     }
1416   }
1417 
1418   return true;
1419 }
1420 
1421 void FileMapInfo::seek_to_position(size_t pos) {
1422   if (os::lseek(_fd, (long)pos, SEEK_SET) < 0) {
1423     log_error(cds)("Unable to seek to position " SIZE_FORMAT, pos);
1424     MetaspaceShared::unrecoverable_loading_error();
1425   }
1426 }
1427 
1428 // Read the FileMapInfo information from the file.
1429 bool FileMapInfo::open_for_read() {
1430   if (_file_open) {
1431     return true;
1432   }
1433   log_info(cds)("trying to map %s", _full_path);
1434   int fd = os::open(_full_path, O_RDONLY | O_BINARY, 0);
1435   if (fd < 0) {
1436     if (errno == ENOENT) {
1437       log_info(cds)("Specified shared archive not found (%s)", _full_path);
1438     } else {
1439       log_warning(cds)("Failed to open shared archive file (%s)",
1440                     os::strerror(errno));
1441     }
1442     return false;
1443   } else {
1444     log_info(cds)("Opened archive %s.", _full_path);
1445   }
1446 
1447   _fd = fd;
1448   _file_open = true;
1449   return true;
1450 }
1451 
1452 // Write the FileMapInfo information to the file.
1453 
1454 void FileMapInfo::open_for_write() {
1455   LogMessage(cds) msg;
1456   if (msg.is_info()) {
1457     msg.info("Dumping shared data to file: ");
1458     msg.info("   %s", _full_path);
1459   }
1460 
1461 #ifdef _WINDOWS  // On Windows, need WRITE permission to remove the file.
1462     chmod(_full_path, _S_IREAD | _S_IWRITE);
1463 #endif
1464 
1465   // Use remove() to delete the existing file because, on Unix, this will
1466   // allow processes that have it open continued access to the file.
1467   remove(_full_path);
1468   int fd = os::open(_full_path, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0444);
1469   if (fd < 0) {
1470     log_error(cds)("Unable to create shared archive file %s: (%s).", _full_path,
1471                    os::strerror(errno));
1472     MetaspaceShared::writing_error();
1473     return;
1474   }
1475   _fd = fd;
1476   _file_open = true;
1477 
1478   // Seek past the header. We will write the header after all regions are written
1479   // and their CRCs computed.
1480   size_t header_bytes = header()->header_size();
1481 
1482   header_bytes = align_up(header_bytes, MetaspaceShared::core_region_alignment());
1483   _file_offset = header_bytes;
1484   seek_to_position(_file_offset);
1485 }
1486 
1487 // Write the header to the file, seek to the next allocation boundary.
1488 
1489 void FileMapInfo::write_header() {
1490   _file_offset = 0;
1491   seek_to_position(_file_offset);
1492   assert(is_file_position_aligned(), "must be");
1493   write_bytes(header(), header()->header_size());
1494 }
1495 
1496 size_t FileMapRegion::used_aligned() const {
1497   return align_up(used(), MetaspaceShared::core_region_alignment());
1498 }
1499 
1500 void FileMapRegion::init(int region_index, size_t mapping_offset, size_t size, bool read_only,
1501                          bool allow_exec, int crc) {
1502   _is_heap_region = HeapShared::is_heap_region(region_index);
1503   _is_bitmap_region = (region_index == MetaspaceShared::bm);
1504   _mapping_offset = mapping_offset;
1505   _used = size;
1506   _read_only = read_only;
1507   _allow_exec = allow_exec;
1508   _crc = crc;
1509   _mapped_from_file = false;
1510   _mapped_base = nullptr;
1511   _in_reserved_space = false;
1512 }
1513 
1514 void FileMapRegion::init_oopmap(size_t offset, size_t size_in_bits) {
1515   _oopmap_offset = offset;
1516   _oopmap_size_in_bits = size_in_bits;
1517 }
1518 
1519 void FileMapRegion::init_ptrmap(size_t offset, size_t size_in_bits) {
1520   _ptrmap_offset = offset;
1521   _ptrmap_size_in_bits = size_in_bits;
1522 }
1523 
1524 bool FileMapRegion::check_region_crc(char* base) const {
1525   // This function should be called after the region has been properly
1526   // loaded into memory via FileMapInfo::map_region() or FileMapInfo::read_region().
1527   // I.e., this->mapped_base() must be valid.
1528   size_t sz = used();
1529   if (sz == 0) {
1530     return true;
1531   }
1532 
1533   assert(base != nullptr, "must be initialized");
1534   int crc = ClassLoader::crc32(0, base, (jint)sz);
1535   if (crc != this->crc()) {
1536     log_warning(cds)("Checksum verification failed.");
1537     return false;
1538   }
1539   return true;
1540 }
1541 
1542 static const char* region_name(int region_index) {
1543   static const char* names[] = {
1544     "rw", "ro", "bm", "hp"
1545   };
1546   const int num_regions = sizeof(names)/sizeof(names[0]);
1547   assert(0 <= region_index && region_index < num_regions, "sanity");
1548 
1549   return names[region_index];
1550 }
1551 
1552 BitMapView FileMapInfo::bitmap_view(int region_index, bool is_oopmap) {
1553   FileMapRegion* r = region_at(region_index);
1554   char* bitmap_base = is_static() ? FileMapInfo::current_info()->map_bitmap_region() : FileMapInfo::dynamic_info()->map_bitmap_region();
1555   bitmap_base += is_oopmap ? r->oopmap_offset() : r->ptrmap_offset();
1556   size_t size_in_bits = is_oopmap ? r->oopmap_size_in_bits() : r->ptrmap_size_in_bits();
1557 
1558   log_debug(cds, reloc)("mapped %s relocation %smap @ " INTPTR_FORMAT " (" SIZE_FORMAT " bits)",
1559                         region_name(region_index), is_oopmap ? "oop" : "ptr",
1560                         p2i(bitmap_base), size_in_bits);
1561 
1562   return BitMapView((BitMap::bm_word_t*)(bitmap_base), size_in_bits);
1563 }
1564 
1565 BitMapView FileMapInfo::oopmap_view(int region_index) {
1566     return bitmap_view(region_index, /*is_oopmap*/true);
1567   }
1568 
1569 BitMapView FileMapInfo::ptrmap_view(int region_index) {
1570   return bitmap_view(region_index, /*is_oopmap*/false);
1571 }
1572 
1573 void FileMapRegion::print(outputStream* st, int region_index) {
1574   st->print_cr("============ region ============= %d \"%s\"", region_index, region_name(region_index));
1575   st->print_cr("- crc:                            0x%08x", _crc);
1576   st->print_cr("- read_only:                      %d", _read_only);
1577   st->print_cr("- allow_exec:                     %d", _allow_exec);
1578   st->print_cr("- is_heap_region:                 %d", _is_heap_region);
1579   st->print_cr("- is_bitmap_region:               %d", _is_bitmap_region);
1580   st->print_cr("- mapped_from_file:               %d", _mapped_from_file);
1581   st->print_cr("- file_offset:                    " SIZE_FORMAT_X, _file_offset);
1582   st->print_cr("- mapping_offset:                 " SIZE_FORMAT_X, _mapping_offset);
1583   st->print_cr("- used:                           " SIZE_FORMAT, _used);
1584   st->print_cr("- oopmap_offset:                  " SIZE_FORMAT_X, _oopmap_offset);
1585   st->print_cr("- oopmap_size_in_bits:            " SIZE_FORMAT, _oopmap_size_in_bits);
1586   st->print_cr("- ptrmap_offset:                  " SIZE_FORMAT_X, _ptrmap_offset);
1587   st->print_cr("- ptrmap_size_in_bits:            " SIZE_FORMAT, _ptrmap_size_in_bits);
1588   st->print_cr("- mapped_base:                    " INTPTR_FORMAT, p2i(_mapped_base));
1589 }
1590 
1591 void FileMapInfo::write_region(int region, char* base, size_t size,
1592                                bool read_only, bool allow_exec) {
1593   assert(CDSConfig::is_dumping_archive(), "sanity");
1594 
1595   FileMapRegion* r = region_at(region);
1596   char* requested_base;
1597   size_t mapping_offset = 0;
1598 
1599   if (region == MetaspaceShared::bm) {
1600     requested_base = nullptr; // always null for bm region
1601   } else if (size == 0) {
1602     // This is an unused region (e.g., a heap region when !INCLUDE_CDS_JAVA_HEAP)
1603     requested_base = nullptr;
1604   } else if (HeapShared::is_heap_region(region)) {
1605     assert(HeapShared::can_write(), "sanity");
1606 #if INCLUDE_CDS_JAVA_HEAP
1607     assert(!CDSConfig::is_dumping_dynamic_archive(), "must be");
1608     requested_base = (char*)ArchiveHeapWriter::requested_address();
1609     if (UseCompressedOops) {
1610       mapping_offset = (size_t)((address)requested_base - CompressedOops::base());
1611       assert((mapping_offset >> CompressedOops::shift()) << CompressedOops::shift() == mapping_offset, "must be");
1612     } else {
1613       mapping_offset = 0; // not used with !UseCompressedOops
1614     }
1615 #endif // INCLUDE_CDS_JAVA_HEAP
1616   } else {
1617     char* requested_SharedBaseAddress = (char*)MetaspaceShared::requested_base_address();
1618     requested_base = ArchiveBuilder::current()->to_requested(base);
1619     assert(requested_base >= requested_SharedBaseAddress, "must be");
1620     mapping_offset = requested_base - requested_SharedBaseAddress;
1621   }
1622 
1623   r->set_file_offset(_file_offset);
1624   int crc = ClassLoader::crc32(0, base, (jint)size);
1625   if (size > 0) {
1626     log_info(cds)("Shared file region (%s) %d: " SIZE_FORMAT_W(8)
1627                    " bytes, addr " INTPTR_FORMAT " file offset 0x%08" PRIxPTR
1628                    " crc 0x%08x",
1629                    region_name(region), region, size, p2i(requested_base), _file_offset, crc);
1630   }
1631 
1632   r->init(region, mapping_offset, size, read_only, allow_exec, crc);
1633 
1634   if (base != nullptr) {
1635     write_bytes_aligned(base, size);
1636   }
1637 }
1638 
1639 static size_t write_bitmap(const CHeapBitMap* map, char* output, size_t offset) {
1640   size_t size_in_bytes = map->size_in_bytes();
1641   map->write_to((BitMap::bm_word_t*)(output + offset), size_in_bytes);
1642   return offset + size_in_bytes;
1643 }
1644 
1645 // The sorting code groups the objects with non-null oop/ptrs together.
1646 // Relevant bitmaps then have lots of leading and trailing zeros, which
1647 // we do not have to store.
1648 size_t FileMapInfo::remove_bitmap_zeros(CHeapBitMap* map) {
1649   BitMap::idx_t first_set = map->find_first_set_bit(0);
1650   BitMap::idx_t last_set  = map->find_last_set_bit(0);
1651   size_t old_size = map->size();
1652 
1653   // Slice and resize bitmap
1654   map->truncate(first_set, last_set + 1);
1655 
1656   assert(map->at(0), "First bit should be set");
1657   assert(map->at(map->size() - 1), "Last bit should be set");
1658   assert(map->size() <= old_size, "sanity");
1659 
1660   return first_set;
1661 }
1662 
1663 char* FileMapInfo::write_bitmap_region(CHeapBitMap* rw_ptrmap, CHeapBitMap* ro_ptrmap, ArchiveHeapInfo* heap_info,
1664                                        size_t &size_in_bytes) {
1665   size_t removed_rw_leading_zeros = remove_bitmap_zeros(rw_ptrmap);
1666   size_t removed_ro_leading_zeros = remove_bitmap_zeros(ro_ptrmap);
1667   header()->set_rw_ptrmap_start_pos(removed_rw_leading_zeros);
1668   header()->set_ro_ptrmap_start_pos(removed_ro_leading_zeros);
1669   size_in_bytes = rw_ptrmap->size_in_bytes() + ro_ptrmap->size_in_bytes();
1670 
1671   if (heap_info->is_used()) {
1672     // Remove leading and trailing zeros
1673     size_t removed_oop_leading_zeros = remove_bitmap_zeros(heap_info->oopmap());
1674     size_t removed_ptr_leading_zeros = remove_bitmap_zeros(heap_info->ptrmap());
1675     header()->set_heap_oopmap_start_pos(removed_oop_leading_zeros);
1676     header()->set_heap_ptrmap_start_pos(removed_ptr_leading_zeros);
1677 
1678     size_in_bytes += heap_info->oopmap()->size_in_bytes();
1679     size_in_bytes += heap_info->ptrmap()->size_in_bytes();
1680   }
1681 
1682   // The bitmap region contains up to 4 parts:
1683   // rw_ptrmap:           metaspace pointers inside the read-write region
1684   // ro_ptrmap:           metaspace pointers inside the read-only region
1685   // heap_info->oopmap(): Java oop pointers in the heap region
1686   // heap_info->ptrmap(): metaspace pointers in the heap region
1687   char* buffer = NEW_C_HEAP_ARRAY(char, size_in_bytes, mtClassShared);
1688   size_t written = 0;
1689 
1690   region_at(MetaspaceShared::rw)->init_ptrmap(0, rw_ptrmap->size());
1691   written = write_bitmap(rw_ptrmap, buffer, written);
1692 
1693   region_at(MetaspaceShared::ro)->init_ptrmap(written, ro_ptrmap->size());
1694   written = write_bitmap(ro_ptrmap, buffer, written);
1695 
1696   if (heap_info->is_used()) {
1697     FileMapRegion* r = region_at(MetaspaceShared::hp);
1698 
1699     r->init_oopmap(written, heap_info->oopmap()->size());
1700     written = write_bitmap(heap_info->oopmap(), buffer, written);
1701 
1702     r->init_ptrmap(written, heap_info->ptrmap()->size());
1703     written = write_bitmap(heap_info->ptrmap(), buffer, written);
1704   }
1705 
1706   write_region(MetaspaceShared::bm, (char*)buffer, size_in_bytes, /*read_only=*/true, /*allow_exec=*/false);
1707   return buffer;
1708 }
1709 
1710 size_t FileMapInfo::write_heap_region(ArchiveHeapInfo* heap_info) {
1711   char* buffer_start = heap_info->buffer_start();
1712   size_t buffer_size = heap_info->buffer_byte_size();
1713   write_region(MetaspaceShared::hp, buffer_start, buffer_size, false, false);
1714   header()->set_heap_root_segments(heap_info->heap_root_segments());
1715   return buffer_size;
1716 }
1717 
1718 // Dump bytes to file -- at the current file position.
1719 
1720 void FileMapInfo::write_bytes(const void* buffer, size_t nbytes) {
1721   assert(_file_open, "must be");
1722   if (!os::write(_fd, buffer, nbytes)) {
1723     // If the shared archive is corrupted, close it and remove it.
1724     close();
1725     remove(_full_path);
1726     MetaspaceShared::writing_error("Unable to write to shared archive file.");
1727   }
1728   _file_offset += nbytes;
1729 }
1730 
1731 bool FileMapInfo::is_file_position_aligned() const {
1732   return _file_offset == align_up(_file_offset,
1733                                   MetaspaceShared::core_region_alignment());
1734 }
1735 
1736 // Align file position to an allocation unit boundary.
1737 
1738 void FileMapInfo::align_file_position() {
1739   assert(_file_open, "must be");
1740   size_t new_file_offset = align_up(_file_offset,
1741                                     MetaspaceShared::core_region_alignment());
1742   if (new_file_offset != _file_offset) {
1743     _file_offset = new_file_offset;
1744     // Seek one byte back from the target and write a byte to insure
1745     // that the written file is the correct length.
1746     _file_offset -= 1;
1747     seek_to_position(_file_offset);
1748     char zero = 0;
1749     write_bytes(&zero, 1);
1750   }
1751 }
1752 
1753 
1754 // Dump bytes to file -- at the current file position.
1755 
1756 void FileMapInfo::write_bytes_aligned(const void* buffer, size_t nbytes) {
1757   align_file_position();
1758   write_bytes(buffer, nbytes);
1759   align_file_position();
1760 }
1761 
1762 // Close the shared archive file.  This does NOT unmap mapped regions.
1763 
1764 void FileMapInfo::close() {
1765   if (_file_open) {
1766     if (::close(_fd) < 0) {
1767       MetaspaceShared::unrecoverable_loading_error("Unable to close the shared archive file.");
1768     }
1769     _file_open = false;
1770     _fd = -1;
1771   }
1772 }
1773 
1774 /*
1775  * Same as os::map_memory() but also pretouches if AlwaysPreTouch is enabled.
1776  */
1777 static char* map_memory(int fd, const char* file_name, size_t file_offset,
1778                         char *addr, size_t bytes, bool read_only,
1779                         bool allow_exec, MemTag mem_tag = mtNone) {
1780   char* mem = os::map_memory(fd, file_name, file_offset, addr, bytes,
1781                              AlwaysPreTouch ? false : read_only,
1782                              allow_exec, mem_tag);
1783   if (mem != nullptr && AlwaysPreTouch) {
1784     os::pretouch_memory(mem, mem + bytes);
1785   }
1786   return mem;
1787 }
1788 
1789 // JVM/TI RedefineClasses() support:
1790 // Remap the shared readonly space to shared readwrite, private.
1791 bool FileMapInfo::remap_shared_readonly_as_readwrite() {
1792   int idx = MetaspaceShared::ro;
1793   FileMapRegion* r = region_at(idx);
1794   if (!r->read_only()) {
1795     // the space is already readwrite so we are done
1796     return true;
1797   }
1798   size_t size = r->used_aligned();
1799   if (!open_for_read()) {
1800     return false;
1801   }
1802   char *addr = r->mapped_base();
1803   // This path should not be reached for Windows; see JDK-8222379.
1804   assert(WINDOWS_ONLY(false) NOT_WINDOWS(true), "Don't call on Windows");
1805   // Replace old mapping with new one that is writable.
1806   char *base = os::map_memory(_fd, _full_path, r->file_offset(),
1807                               addr, size, false /* !read_only */,
1808                               r->allow_exec());
1809   close();
1810   // These have to be errors because the shared region is now unmapped.
1811   if (base == nullptr) {
1812     log_error(cds)("Unable to remap shared readonly space (errno=%d).", errno);
1813     vm_exit(1);
1814   }
1815   if (base != addr) {
1816     log_error(cds)("Unable to remap shared readonly space (errno=%d).", errno);
1817     vm_exit(1);
1818   }
1819   r->set_read_only(false);
1820   return true;
1821 }
1822 
1823 // Memory map a region in the address space.
1824 static const char* shared_region_name[] = { "ReadWrite", "ReadOnly", "Bitmap", "Heap" };
1825 
1826 MapArchiveResult FileMapInfo::map_regions(int regions[], int num_regions, char* mapped_base_address, ReservedSpace rs) {
1827   DEBUG_ONLY(FileMapRegion* last_region = nullptr);
1828   intx addr_delta = mapped_base_address - header()->requested_base_address();
1829 
1830   // Make sure we don't attempt to use header()->mapped_base_address() unless
1831   // it's been successfully mapped.
1832   DEBUG_ONLY(header()->set_mapped_base_address((char*)(uintptr_t)0xdeadbeef);)
1833 
1834   for (int i = 0; i < num_regions; i++) {
1835     int idx = regions[i];
1836     MapArchiveResult result = map_region(idx, addr_delta, mapped_base_address, rs);
1837     if (result != MAP_ARCHIVE_SUCCESS) {
1838       return result;
1839     }
1840     FileMapRegion* r = region_at(idx);
1841     DEBUG_ONLY(if (last_region != nullptr) {
1842         // Ensure that the OS won't be able to allocate new memory spaces between any mapped
1843         // regions, or else it would mess up the simple comparison in MetaspaceObj::is_shared().
1844         assert(r->mapped_base() == last_region->mapped_end(), "must have no gaps");
1845       }
1846       last_region = r;)
1847     log_info(cds)("Mapped %s region #%d at base " INTPTR_FORMAT " top " INTPTR_FORMAT " (%s)", is_static() ? "static " : "dynamic",
1848                   idx, p2i(r->mapped_base()), p2i(r->mapped_end()),
1849                   shared_region_name[idx]);
1850 
1851   }
1852 
1853   header()->set_mapped_base_address(header()->requested_base_address() + addr_delta);
1854   if (addr_delta != 0 && !relocate_pointers_in_core_regions(addr_delta)) {
1855     return MAP_ARCHIVE_OTHER_FAILURE;
1856   }
1857 
1858   return MAP_ARCHIVE_SUCCESS;
1859 }
1860 
1861 bool FileMapInfo::read_region(int i, char* base, size_t size, bool do_commit) {
1862   FileMapRegion* r = region_at(i);
1863   if (do_commit) {
1864     log_info(cds)("Commit %s region #%d at base " INTPTR_FORMAT " top " INTPTR_FORMAT " (%s)%s",
1865                   is_static() ? "static " : "dynamic", i, p2i(base), p2i(base + size),
1866                   shared_region_name[i], r->allow_exec() ? " exec" : "");
1867     if (!os::commit_memory(base, size, r->allow_exec())) {
1868       log_error(cds)("Failed to commit %s region #%d (%s)", is_static() ? "static " : "dynamic",
1869                      i, shared_region_name[i]);
1870       return false;
1871     }
1872   }
1873   if (os::lseek(_fd, (long)r->file_offset(), SEEK_SET) != (int)r->file_offset() ||
1874       read_bytes(base, size) != size) {
1875     return false;
1876   }
1877 
1878   if (VerifySharedSpaces && !r->check_region_crc(base)) {
1879     return false;
1880   }
1881 
1882   r->set_mapped_from_file(false);
1883   r->set_mapped_base(base);
1884 
1885   return true;
1886 }
1887 
1888 MapArchiveResult FileMapInfo::map_region(int i, intx addr_delta, char* mapped_base_address, ReservedSpace rs) {
1889   assert(!HeapShared::is_heap_region(i), "sanity");
1890   FileMapRegion* r = region_at(i);
1891   size_t size = r->used_aligned();
1892   char *requested_addr = mapped_base_address + r->mapping_offset();
1893   assert(!is_mapped(), "must be not mapped yet");
1894   assert(requested_addr != nullptr, "must be specified");
1895 
1896   r->set_mapped_from_file(false);
1897   r->set_in_reserved_space(false);
1898 
1899   if (MetaspaceShared::use_windows_memory_mapping()) {
1900     // Windows cannot remap read-only shared memory to read-write when required for
1901     // RedefineClasses, which is also used by JFR.  Always map windows regions as RW.
1902     r->set_read_only(false);
1903   } else if (JvmtiExport::can_modify_any_class() || JvmtiExport::can_walk_any_space() ||
1904              Arguments::has_jfr_option()) {
1905     // If a tool agent is in use (debugging enabled), or JFR, we must map the address space RW
1906     r->set_read_only(false);
1907   } else if (addr_delta != 0) {
1908     r->set_read_only(false); // Need to patch the pointers
1909   }
1910 
1911   if (MetaspaceShared::use_windows_memory_mapping() && rs.is_reserved()) {
1912     // This is the second time we try to map the archive(s). We have already created a ReservedSpace
1913     // that covers all the FileMapRegions to ensure all regions can be mapped. However, Windows
1914     // can't mmap into a ReservedSpace, so we just ::read() the data. We're going to patch all the
1915     // regions anyway, so there's no benefit for mmap anyway.
1916     if (!read_region(i, requested_addr, size, /* do_commit = */ true)) {
1917       log_info(cds)("Failed to read %s shared space into reserved space at " INTPTR_FORMAT,
1918                     shared_region_name[i], p2i(requested_addr));
1919       return MAP_ARCHIVE_OTHER_FAILURE; // oom or I/O error.
1920     } else {
1921       assert(r->mapped_base() != nullptr, "must be initialized");
1922     }
1923   } else {
1924     // Note that this may either be a "fresh" mapping into unreserved address
1925     // space (Windows, first mapping attempt), or a mapping into pre-reserved
1926     // space (Posix). See also comment in MetaspaceShared::map_archives().
1927     char* base = map_memory(_fd, _full_path, r->file_offset(),
1928                             requested_addr, size, r->read_only(),
1929                             r->allow_exec(), mtClassShared);
1930     if (base != requested_addr) {
1931       log_info(cds)("Unable to map %s shared space at " INTPTR_FORMAT,
1932                     shared_region_name[i], p2i(requested_addr));
1933       _memory_mapping_failed = true;
1934       return MAP_ARCHIVE_MMAP_FAILURE;
1935     }
1936 
1937     if (VerifySharedSpaces && !r->check_region_crc(requested_addr)) {
1938       return MAP_ARCHIVE_OTHER_FAILURE;
1939     }
1940 
1941     r->set_mapped_from_file(true);
1942     r->set_mapped_base(requested_addr);
1943   }
1944 
1945   if (rs.is_reserved()) {
1946     char* mapped_base = r->mapped_base();
1947     assert(rs.base() <= mapped_base && mapped_base + size <= rs.end(),
1948            PTR_FORMAT " <= " PTR_FORMAT " < " PTR_FORMAT " <= " PTR_FORMAT,
1949            p2i(rs.base()), p2i(mapped_base), p2i(mapped_base + size), p2i(rs.end()));
1950     r->set_in_reserved_space(rs.is_reserved());
1951   }
1952   return MAP_ARCHIVE_SUCCESS;
1953 }
1954 
1955 // The return value is the location of the archive relocation bitmap.
1956 char* FileMapInfo::map_bitmap_region() {
1957   FileMapRegion* r = region_at(MetaspaceShared::bm);
1958   if (r->mapped_base() != nullptr) {
1959     return r->mapped_base();
1960   }
1961   bool read_only = true, allow_exec = false;
1962   char* requested_addr = nullptr; // allow OS to pick any location
1963   char* bitmap_base = map_memory(_fd, _full_path, r->file_offset(),
1964                                  requested_addr, r->used_aligned(), read_only, allow_exec, mtClassShared);
1965   if (bitmap_base == nullptr) {
1966     log_info(cds)("failed to map relocation bitmap");
1967     return nullptr;
1968   }
1969 
1970   if (VerifySharedSpaces && !r->check_region_crc(bitmap_base)) {
1971     log_error(cds)("relocation bitmap CRC error");
1972     if (!os::unmap_memory(bitmap_base, r->used_aligned())) {
1973       fatal("os::unmap_memory of relocation bitmap failed");
1974     }
1975     return nullptr;
1976   }
1977 
1978   r->set_mapped_from_file(true);
1979   r->set_mapped_base(bitmap_base);
1980   log_info(cds)("Mapped %s region #%d at base " INTPTR_FORMAT " top " INTPTR_FORMAT " (%s)",
1981                 is_static() ? "static " : "dynamic",
1982                 MetaspaceShared::bm, p2i(r->mapped_base()), p2i(r->mapped_end()),
1983                 shared_region_name[MetaspaceShared::bm]);
1984   return bitmap_base;
1985 }
1986 
1987 class SharedDataRelocationTask : public ArchiveWorkerTask {
1988 private:
1989   BitMapView* const _rw_bm;
1990   BitMapView* const _ro_bm;
1991   SharedDataRelocator* const _rw_reloc;
1992   SharedDataRelocator* const _ro_reloc;
1993 
1994 public:
1995   SharedDataRelocationTask(BitMapView* rw_bm, BitMapView* ro_bm, SharedDataRelocator* rw_reloc, SharedDataRelocator* ro_reloc) :
1996                            ArchiveWorkerTask("Shared Data Relocation"),
1997                            _rw_bm(rw_bm), _ro_bm(ro_bm), _rw_reloc(rw_reloc), _ro_reloc(ro_reloc) {}
1998 
1999   void work(int chunk, int max_chunks) override {
2000     work_on(chunk, max_chunks, _rw_bm, _rw_reloc);
2001     work_on(chunk, max_chunks, _ro_bm, _ro_reloc);
2002   }
2003 
2004   void work_on(int chunk, int max_chunks, BitMapView* bm, SharedDataRelocator* reloc) {
2005     BitMap::idx_t size  = bm->size();
2006     BitMap::idx_t start = MIN2(size, size * chunk / max_chunks);
2007     BitMap::idx_t end   = MIN2(size, size * (chunk + 1) / max_chunks);
2008     assert(end > start, "Sanity: no empty slices");
2009     bm->iterate(reloc, start, end);
2010   }
2011 };
2012 
2013 // This is called when we cannot map the archive at the requested[ base address (usually 0x800000000).
2014 // We relocate all pointers in the 2 core regions (ro, rw).
2015 bool FileMapInfo::relocate_pointers_in_core_regions(intx addr_delta) {
2016   log_debug(cds, reloc)("runtime archive relocation start");
2017   char* bitmap_base = map_bitmap_region();
2018 
2019   if (bitmap_base == nullptr) {
2020     return false; // OOM, or CRC check failure
2021   } else {
2022     BitMapView rw_ptrmap = ptrmap_view(MetaspaceShared::rw);
2023     BitMapView ro_ptrmap = ptrmap_view(MetaspaceShared::ro);
2024 
2025     FileMapRegion* rw_region = first_core_region();
2026     FileMapRegion* ro_region = last_core_region();
2027 
2028     // Patch all pointers inside the RW region
2029     address rw_patch_base = (address)rw_region->mapped_base();
2030     address rw_patch_end  = (address)rw_region->mapped_end();
2031 
2032     // Patch all pointers inside the RO region
2033     address ro_patch_base = (address)ro_region->mapped_base();
2034     address ro_patch_end  = (address)ro_region->mapped_end();
2035 
2036     // the current value of the pointers to be patched must be within this
2037     // range (i.e., must be between the requested base address and the address of the current archive).
2038     // Note: top archive may point to objects in the base archive, but not the other way around.
2039     address valid_old_base = (address)header()->requested_base_address();
2040     address valid_old_end  = valid_old_base + mapping_end_offset();
2041 
2042     // after patching, the pointers must point inside this range
2043     // (the requested location of the archive, as mapped at runtime).
2044     address valid_new_base = (address)header()->mapped_base_address();
2045     address valid_new_end  = (address)mapped_end();
2046 
2047     SharedDataRelocator rw_patcher((address*)rw_patch_base + header()->rw_ptrmap_start_pos(), (address*)rw_patch_end, valid_old_base, valid_old_end,
2048                                 valid_new_base, valid_new_end, addr_delta);
2049     SharedDataRelocator ro_patcher((address*)ro_patch_base + header()->ro_ptrmap_start_pos(), (address*)ro_patch_end, valid_old_base, valid_old_end,
2050                                 valid_new_base, valid_new_end, addr_delta);
2051 
2052     if (AOTCacheParallelRelocation) {
2053       ArchiveWorkers workers;
2054       SharedDataRelocationTask task(&rw_ptrmap, &ro_ptrmap, &rw_patcher, &ro_patcher);
2055       workers.run_task(&task);
2056     } else {
2057       rw_ptrmap.iterate(&rw_patcher);
2058       ro_ptrmap.iterate(&ro_patcher);
2059     }
2060 
2061     // The MetaspaceShared::bm region will be unmapped in MetaspaceShared::initialize_shared_spaces().
2062 
2063     log_debug(cds, reloc)("runtime archive relocation done");
2064     return true;
2065   }
2066 }
2067 
2068 size_t FileMapInfo::read_bytes(void* buffer, size_t count) {
2069   assert(_file_open, "Archive file is not open");
2070   size_t n = ::read(_fd, buffer, (unsigned int)count);
2071   if (n != count) {
2072     // Close the file if there's a problem reading it.
2073     close();
2074     return 0;
2075   }
2076   _file_offset += count;
2077   return count;
2078 }
2079 
2080 // Get the total size in bytes of a read only region
2081 size_t FileMapInfo::readonly_total() {
2082   size_t total = 0;
2083   if (current_info() != nullptr) {
2084     FileMapRegion* r = FileMapInfo::current_info()->region_at(MetaspaceShared::ro);
2085     if (r->read_only()) total += r->used();
2086   }
2087   if (dynamic_info() != nullptr) {
2088     FileMapRegion* r = FileMapInfo::dynamic_info()->region_at(MetaspaceShared::ro);
2089     if (r->read_only()) total += r->used();
2090   }
2091   return total;
2092 }
2093 
2094 #if INCLUDE_CDS_JAVA_HEAP
2095 MemRegion FileMapInfo::_mapped_heap_memregion;
2096 
2097 bool FileMapInfo::has_heap_region() {
2098   return (region_at(MetaspaceShared::hp)->used() > 0);
2099 }
2100 
2101 // Returns the address range of the archived heap region computed using the
2102 // current oop encoding mode. This range may be different than the one seen at
2103 // dump time due to encoding mode differences. The result is used in determining
2104 // if/how these regions should be relocated at run time.
2105 MemRegion FileMapInfo::get_heap_region_requested_range() {
2106   FileMapRegion* r = region_at(MetaspaceShared::hp);
2107   size_t size = r->used();
2108   assert(size > 0, "must have non-empty heap region");
2109 
2110   address start = heap_region_requested_address();
2111   address end = start + size;
2112   log_info(cds)("Requested heap region [" INTPTR_FORMAT " - " INTPTR_FORMAT "] = "  SIZE_FORMAT_W(8) " bytes",
2113                 p2i(start), p2i(end), size);
2114 
2115   return MemRegion((HeapWord*)start, (HeapWord*)end);
2116 }
2117 
2118 void FileMapInfo::map_or_load_heap_region() {
2119   bool success = false;
2120 
2121   if (can_use_heap_region()) {
2122     if (ArchiveHeapLoader::can_map()) {
2123       success = map_heap_region();
2124     } else if (ArchiveHeapLoader::can_load()) {
2125       success = ArchiveHeapLoader::load_heap_region(this);
2126     } else {
2127       if (!UseCompressedOops && !ArchiveHeapLoader::can_map()) {
2128         log_info(cds)("Cannot use CDS heap data. Selected GC not compatible -XX:-UseCompressedOops");
2129       } else {
2130         log_info(cds)("Cannot use CDS heap data. UseEpsilonGC, UseG1GC, UseSerialGC, UseParallelGC, or UseShenandoahGC are required.");
2131       }
2132     }
2133   }
2134 
2135   if (!success) {
2136     if (CDSConfig::is_using_aot_linked_classes()) {
2137       // It's too late to recover -- we have already committed to use the archived metaspace objects, but
2138       // the archived heap objects cannot be loaded, so we don't have the archived FMG to guarantee that
2139       // all AOT-linked classes are visible.
2140       //
2141       // We get here because the heap is too small. The app will fail anyway. So let's quit.
2142       MetaspaceShared::unrecoverable_loading_error("CDS archive has aot-linked classes but the archived "
2143                                                    "heap objects cannot be loaded. Try increasing your heap size.");
2144     }
2145     CDSConfig::stop_using_full_module_graph("archive heap loading failed");
2146   }
2147 }
2148 
2149 bool FileMapInfo::can_use_heap_region() {
2150   if (!has_heap_region()) {
2151     return false;
2152   }
2153   if (JvmtiExport::should_post_class_file_load_hook() && JvmtiExport::has_early_class_hook_env()) {
2154     ShouldNotReachHere(); // CDS should have been disabled.
2155     // The archived objects are mapped at JVM start-up, but we don't know if
2156     // j.l.String or j.l.Class might be replaced by the ClassFileLoadHook,
2157     // which would make the archived String or mirror objects invalid. Let's be safe and not
2158     // use the archived objects. These 2 classes are loaded during the JVMTI "early" stage.
2159     //
2160     // If JvmtiExport::has_early_class_hook_env() is false, the classes of some objects
2161     // in the archived subgraphs may be replaced by the ClassFileLoadHook. But that's OK
2162     // because we won't install an archived object subgraph if the klass of any of the
2163     // referenced objects are replaced. See HeapShared::initialize_from_archived_subgraph().
2164   }
2165 
2166   // We pre-compute narrow Klass IDs with the runtime mapping start intended to be the base, and a shift of
2167   // ArchiveBuilder::precomputed_narrow_klass_shift. We enforce this encoding at runtime (see
2168   // CompressedKlassPointers::initialize_for_given_encoding()). Therefore, the following assertions must
2169   // hold:
2170   address archive_narrow_klass_base = (address)header()->mapped_base_address();
2171   const int archive_narrow_klass_pointer_bits = header()->narrow_klass_pointer_bits();
2172   const int archive_narrow_klass_shift = header()->narrow_klass_shift();
2173 
2174   log_info(cds)("CDS archive was created with max heap size = " SIZE_FORMAT "M, and the following configuration:",
2175                 max_heap_size()/M);
2176   log_info(cds)("    narrow_klass_base at mapping start address, narrow_klass_pointer_bits = %d, narrow_klass_shift = %d",
2177                 archive_narrow_klass_pointer_bits, archive_narrow_klass_shift);
2178   log_info(cds)("    narrow_oop_mode = %d, narrow_oop_base = " PTR_FORMAT ", narrow_oop_shift = %d",
2179                 narrow_oop_mode(), p2i(narrow_oop_base()), narrow_oop_shift());
2180   log_info(cds)("The current max heap size = " SIZE_FORMAT "M, G1HeapRegion::GrainBytes = " SIZE_FORMAT,
2181                 MaxHeapSize/M, G1HeapRegion::GrainBytes);
2182   log_info(cds)("    narrow_klass_base = " PTR_FORMAT ", arrow_klass_pointer_bits = %d, narrow_klass_shift = %d",
2183                 p2i(CompressedKlassPointers::base()), CompressedKlassPointers::narrow_klass_pointer_bits(), CompressedKlassPointers::shift());
2184   log_info(cds)("    narrow_oop_mode = %d, narrow_oop_base = " PTR_FORMAT ", narrow_oop_shift = %d",
2185                 CompressedOops::mode(), p2i(CompressedOops::base()), CompressedOops::shift());
2186   log_info(cds)("    heap range = [" PTR_FORMAT " - "  PTR_FORMAT "]",
2187                 UseCompressedOops ? p2i(CompressedOops::begin()) :
2188                                     UseG1GC ? p2i((address)G1CollectedHeap::heap()->reserved().start()) : 0L,
2189                 UseCompressedOops ? p2i(CompressedOops::end()) :
2190                                     UseG1GC ? p2i((address)G1CollectedHeap::heap()->reserved().end()) : 0L);
2191 
2192   int err = 0;
2193   if ( archive_narrow_klass_base != CompressedKlassPointers::base() ||
2194        (err = 1, archive_narrow_klass_pointer_bits != CompressedKlassPointers::narrow_klass_pointer_bits()) ||
2195        (err = 2, archive_narrow_klass_shift != CompressedKlassPointers::shift()) ) {
2196     stringStream ss;
2197     switch (err) {
2198     case 0:
2199       ss.print("Unexpected encoding base encountered (" PTR_FORMAT ", expected " PTR_FORMAT ")",
2200                p2i(CompressedKlassPointers::base()), p2i(archive_narrow_klass_base));
2201       break;
2202     case 1:
2203       ss.print("Unexpected narrow Klass bit length encountered (%d, expected %d)",
2204                CompressedKlassPointers::narrow_klass_pointer_bits(), archive_narrow_klass_pointer_bits);
2205       break;
2206     case 2:
2207       ss.print("Unexpected narrow Klass shift encountered (%d, expected %d)",
2208                CompressedKlassPointers::shift(), archive_narrow_klass_shift);
2209       break;
2210     default:
2211       ShouldNotReachHere();
2212     };
2213     LogTarget(Info, cds) lt;
2214     if (lt.is_enabled()) {
2215       LogStream ls(lt);
2216       ls.print_raw(ss.base());
2217       header()->print(&ls);
2218     }
2219     assert(false, "%s", ss.base());
2220   }
2221 
2222   return true;
2223 }
2224 
2225 // The actual address of this region during dump time.
2226 address FileMapInfo::heap_region_dumptime_address() {
2227   FileMapRegion* r = region_at(MetaspaceShared::hp);
2228   assert(CDSConfig::is_using_archive(), "runtime only");
2229   assert(is_aligned(r->mapping_offset(), sizeof(HeapWord)), "must be");
2230   if (UseCompressedOops) {
2231     return /*dumptime*/ (address)((uintptr_t)narrow_oop_base() + r->mapping_offset());
2232   } else {
2233     return heap_region_requested_address();
2234   }
2235 }
2236 
2237 // The address where this region can be mapped into the runtime heap without
2238 // patching any of the pointers that are embedded in this region.
2239 address FileMapInfo::heap_region_requested_address() {
2240   assert(CDSConfig::is_using_archive(), "runtime only");
2241   FileMapRegion* r = region_at(MetaspaceShared::hp);
2242   assert(is_aligned(r->mapping_offset(), sizeof(HeapWord)), "must be");
2243   assert(ArchiveHeapLoader::can_use(), "GC must support mapping or loading");
2244   if (UseCompressedOops) {
2245     // We can avoid relocation if each region's offset from the runtime CompressedOops::base()
2246     // is the same as its offset from the CompressedOops::base() during dumptime.
2247     // Note that CompressedOops::base() may be different between dumptime and runtime.
2248     //
2249     // Example:
2250     // Dumptime base = 0x1000 and shift is 0. We have a region at address 0x2000. There's a
2251     // narrowOop P stored in this region that points to an object at address 0x2200.
2252     // P's encoded value is 0x1200.
2253     //
2254     // Runtime base = 0x4000 and shift is also 0. If we map this region at 0x5000, then
2255     // the value P can remain 0x1200. The decoded address = (0x4000 + (0x1200 << 0)) = 0x5200,
2256     // which is the runtime location of the referenced object.
2257     return /*runtime*/ (address)((uintptr_t)CompressedOops::base() + r->mapping_offset());
2258   } else {
2259     // This was the hard-coded requested base address used at dump time. With uncompressed oops,
2260     // the heap range is assigned by the OS so we will most likely have to relocate anyway, no matter
2261     // what base address was picked at duump time.
2262     return (address)ArchiveHeapWriter::NOCOOPS_REQUESTED_BASE;
2263   }
2264 }
2265 
2266 bool FileMapInfo::map_heap_region() {
2267   if (map_heap_region_impl()) {
2268 #ifdef ASSERT
2269     // The "old" regions must be parsable -- we cannot have any unused space
2270     // at the start of the lowest G1 region that contains archived objects.
2271     assert(is_aligned(_mapped_heap_memregion.start(), G1HeapRegion::GrainBytes), "must be");
2272 
2273     // Make sure we map at the very top of the heap - see comments in
2274     // init_heap_region_relocation().
2275     MemRegion heap_range = G1CollectedHeap::heap()->reserved();
2276     assert(heap_range.contains(_mapped_heap_memregion), "must be");
2277 
2278     address heap_end = (address)heap_range.end();
2279     address mapped_heap_region_end = (address)_mapped_heap_memregion.end();
2280     assert(heap_end >= mapped_heap_region_end, "must be");
2281     assert(heap_end - mapped_heap_region_end < (intx)(G1HeapRegion::GrainBytes),
2282            "must be at the top of the heap to avoid fragmentation");
2283 #endif
2284 
2285     ArchiveHeapLoader::set_mapped();
2286     return true;
2287   } else {
2288     return false;
2289   }
2290 }
2291 
2292 bool FileMapInfo::map_heap_region_impl() {
2293   assert(UseG1GC, "the following code assumes G1");
2294 
2295   FileMapRegion* r = region_at(MetaspaceShared::hp);
2296   size_t size = r->used();
2297   if (size == 0) {
2298     return false; // no archived java heap data
2299   }
2300 
2301   size_t word_size = size / HeapWordSize;
2302   address requested_start = heap_region_requested_address();
2303 
2304   log_info(cds)("Preferred address to map heap data (to avoid relocation) is " INTPTR_FORMAT, p2i(requested_start));
2305 
2306   // allocate from java heap
2307   HeapWord* start = G1CollectedHeap::heap()->alloc_archive_region(word_size, (HeapWord*)requested_start);
2308   if (start == nullptr) {
2309     log_info(cds)("UseSharedSpaces: Unable to allocate java heap region for archive heap.");
2310     return false;
2311   }
2312 
2313   _mapped_heap_memregion = MemRegion(start, word_size);
2314 
2315   // Map the archived heap data. No need to call MemTracker::record_virtual_memory_tag()
2316   // for mapped region as it is part of the reserved java heap, which is already recorded.
2317   char* addr = (char*)_mapped_heap_memregion.start();
2318   char* base;
2319 
2320   if (MetaspaceShared::use_windows_memory_mapping()) {
2321     if (!read_region(MetaspaceShared::hp, addr,
2322                      align_up(_mapped_heap_memregion.byte_size(), os::vm_page_size()),
2323                      /* do_commit = */ true)) {
2324       dealloc_heap_region();
2325       log_error(cds)("Failed to read archived heap region into " INTPTR_FORMAT, p2i(addr));
2326       return false;
2327     }
2328     // Checks for VerifySharedSpaces is already done inside read_region()
2329     base = addr;
2330   } else {
2331     base = map_memory(_fd, _full_path, r->file_offset(),
2332                       addr, _mapped_heap_memregion.byte_size(), r->read_only(),
2333                       r->allow_exec());
2334     if (base == nullptr || base != addr) {
2335       dealloc_heap_region();
2336       log_info(cds)("UseSharedSpaces: Unable to map at required address in java heap. "
2337                     INTPTR_FORMAT ", size = " SIZE_FORMAT " bytes",
2338                     p2i(addr), _mapped_heap_memregion.byte_size());
2339       return false;
2340     }
2341 
2342     if (VerifySharedSpaces && !r->check_region_crc(base)) {
2343       dealloc_heap_region();
2344       log_info(cds)("UseSharedSpaces: mapped heap region is corrupt");
2345       return false;
2346     }
2347   }
2348 
2349   r->set_mapped_base(base);
2350 
2351   // If the requested range is different from the range allocated by GC, then
2352   // the pointers need to be patched.
2353   address mapped_start = (address) _mapped_heap_memregion.start();
2354   ptrdiff_t delta = mapped_start - requested_start;
2355   if (UseCompressedOops &&
2356       (narrow_oop_mode() != CompressedOops::mode() ||
2357        narrow_oop_shift() != CompressedOops::shift())) {
2358     _heap_pointers_need_patching = true;
2359   }
2360   if (delta != 0) {
2361     _heap_pointers_need_patching = true;
2362   }
2363   ArchiveHeapLoader::init_mapped_heap_info(mapped_start, delta, narrow_oop_shift());
2364 
2365   if (_heap_pointers_need_patching) {
2366     char* bitmap_base = map_bitmap_region();
2367     if (bitmap_base == nullptr) {
2368       log_info(cds)("CDS heap cannot be used because bitmap region cannot be mapped");
2369       dealloc_heap_region();
2370       _heap_pointers_need_patching = false;
2371       return false;
2372     }
2373   }
2374   log_info(cds)("Heap data mapped at " INTPTR_FORMAT ", size = " SIZE_FORMAT_W(8) " bytes",
2375                 p2i(mapped_start), _mapped_heap_memregion.byte_size());
2376   log_info(cds)("CDS heap data relocation delta = %zd bytes", delta);
2377   return true;
2378 }
2379 
2380 narrowOop FileMapInfo::encoded_heap_region_dumptime_address() {
2381   assert(CDSConfig::is_using_archive(), "runtime only");
2382   assert(UseCompressedOops, "sanity");
2383   FileMapRegion* r = region_at(MetaspaceShared::hp);
2384   return CompressedOops::narrow_oop_cast(r->mapping_offset() >> narrow_oop_shift());
2385 }
2386 
2387 void FileMapInfo::patch_heap_embedded_pointers() {
2388   if (!ArchiveHeapLoader::is_mapped() || !_heap_pointers_need_patching) {
2389     return;
2390   }
2391 
2392   char* bitmap_base = map_bitmap_region();
2393   assert(bitmap_base != nullptr, "must have already been mapped");
2394 
2395   FileMapRegion* r = region_at(MetaspaceShared::hp);
2396   ArchiveHeapLoader::patch_embedded_pointers(
2397       this, _mapped_heap_memregion,
2398       (address)(region_at(MetaspaceShared::bm)->mapped_base()) + r->oopmap_offset(),
2399       r->oopmap_size_in_bits());
2400 }
2401 
2402 void FileMapInfo::fixup_mapped_heap_region() {
2403   if (ArchiveHeapLoader::is_mapped()) {
2404     assert(!_mapped_heap_memregion.is_empty(), "sanity");
2405 
2406     // Populate the archive regions' G1BlockOffsetTables. That ensures
2407     // fast G1BlockOffsetTable::block_start operations for any given address
2408     // within the archive regions when trying to find start of an object
2409     // (e.g. during card table scanning).
2410     G1CollectedHeap::heap()->populate_archive_regions_bot(_mapped_heap_memregion);
2411   }
2412 }
2413 
2414 // dealloc the archive regions from java heap
2415 void FileMapInfo::dealloc_heap_region() {
2416   G1CollectedHeap::heap()->dealloc_archive_regions(_mapped_heap_memregion);
2417 }
2418 #endif // INCLUDE_CDS_JAVA_HEAP
2419 
2420 void FileMapInfo::unmap_regions(int regions[], int num_regions) {
2421   for (int r = 0; r < num_regions; r++) {
2422     int idx = regions[r];
2423     unmap_region(idx);
2424   }
2425 }
2426 
2427 // Unmap a memory region in the address space.
2428 
2429 void FileMapInfo::unmap_region(int i) {
2430   FileMapRegion* r = region_at(i);
2431   char* mapped_base = r->mapped_base();
2432   size_t size = r->used_aligned();
2433 
2434   if (mapped_base != nullptr) {
2435     if (size > 0 && r->mapped_from_file()) {
2436       log_info(cds)("Unmapping region #%d at base " INTPTR_FORMAT " (%s)", i, p2i(mapped_base),
2437                     shared_region_name[i]);
2438       if (r->in_reserved_space()) {
2439         // This region was mapped inside a ReservedSpace. Its memory will be freed when the ReservedSpace
2440         // is released. Zero it so that we don't accidentally read its content.
2441         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]);
2442       } else {
2443         if (!os::unmap_memory(mapped_base, size)) {
2444           fatal("os::unmap_memory failed");
2445         }
2446       }
2447     }
2448     r->set_mapped_base(nullptr);
2449   }
2450 }
2451 
2452 void FileMapInfo::assert_mark(bool check) {
2453   if (!check) {
2454     MetaspaceShared::unrecoverable_loading_error("Mark mismatch while restoring from shared file.");
2455   }
2456 }
2457 
2458 FileMapInfo* FileMapInfo::_current_info = nullptr;
2459 FileMapInfo* FileMapInfo::_dynamic_archive_info = nullptr;
2460 bool FileMapInfo::_heap_pointers_need_patching = false;
2461 SharedPathTable FileMapInfo::_shared_path_table;
2462 bool FileMapInfo::_validating_shared_path_table = false;
2463 bool FileMapInfo::_memory_mapping_failed = false;
2464 GrowableArray<const char*>* FileMapInfo::_non_existent_class_paths = nullptr;
2465 
2466 // Open the shared archive file, read and validate the header
2467 // information (version, boot classpath, etc.). If initialization
2468 // fails, shared spaces are disabled and the file is closed.
2469 //
2470 // Validation of the archive is done in two steps:
2471 //
2472 // [1] validate_header() - done here.
2473 // [2] validate_shared_path_table - this is done later, because the table is in the RW
2474 //     region of the archive, which is not mapped yet.
2475 bool FileMapInfo::initialize() {
2476   assert(CDSConfig::is_using_archive(), "UseSharedSpaces expected.");
2477   assert(Arguments::has_jimage(), "The shared archive file cannot be used with an exploded module build.");
2478 
2479   if (JvmtiExport::should_post_class_file_load_hook() && JvmtiExport::has_early_class_hook_env()) {
2480     // CDS assumes that no classes resolved in vmClasses::resolve_all()
2481     // are replaced at runtime by JVMTI ClassFileLoadHook. All of those classes are resolved
2482     // during the JVMTI "early" stage, so we can still use CDS if
2483     // JvmtiExport::has_early_class_hook_env() is false.
2484     log_info(cds)("CDS is disabled because early JVMTI ClassFileLoadHook is in use.");
2485     return false;
2486   }
2487 
2488   if (!open_for_read() || !init_from_file(_fd) || !validate_header()) {
2489     if (_is_static) {
2490       log_info(cds)("Initialize static archive failed.");
2491       return false;
2492     } else {
2493       log_info(cds)("Initialize dynamic archive failed.");
2494       if (AutoCreateSharedArchive) {
2495         CDSConfig::enable_dumping_dynamic_archive();
2496         ArchiveClassesAtExit = CDSConfig::dynamic_archive_path();
2497       }
2498       return false;
2499     }
2500   }
2501 
2502   return true;
2503 }
2504 
2505 bool FileMapInfo::validate_aot_class_linking() {
2506   // These checks need to be done after FileMapInfo::initialize(), which gets called before Universe::heap()
2507   // is available.
2508   if (header()->has_aot_linked_classes()) {
2509     CDSConfig::set_has_aot_linked_classes(true);
2510     if (JvmtiExport::should_post_class_file_load_hook()) {
2511       log_error(cds)("CDS archive has aot-linked classes. It cannot be used when JVMTI ClassFileLoadHook is in use.");
2512       return false;
2513     }
2514     if (JvmtiExport::has_early_vmstart_env()) {
2515       log_error(cds)("CDS archive has aot-linked classes. It cannot be used when JVMTI early vm start is in use.");
2516       return false;
2517     }
2518     if (!CDSConfig::is_using_full_module_graph()) {
2519       log_error(cds)("CDS archive has aot-linked classes. It cannot be used when archived full module graph is not used.");
2520       return false;
2521     }
2522 
2523     const char* prop = Arguments::get_property("java.security.manager");
2524     if (prop != nullptr && strcmp(prop, "disallow") != 0) {
2525       log_error(cds)("CDS archive has aot-linked classes. It cannot be used with -Djava.security.manager=%s.", prop);
2526       return false;
2527     }
2528   }
2529 
2530   return true;
2531 }
2532 
2533 // The 2 core spaces are RW->RO
2534 FileMapRegion* FileMapInfo::first_core_region() const {
2535   return region_at(MetaspaceShared::rw);
2536 }
2537 
2538 FileMapRegion* FileMapInfo::last_core_region() const {
2539   return region_at(MetaspaceShared::ro);
2540 }
2541 
2542 void FileMapInfo::print(outputStream* st) const {
2543   header()->print(st);
2544   if (!is_static()) {
2545     dynamic_header()->print(st);
2546   }
2547 }
2548 
2549 void FileMapHeader::set_as_offset(char* p, size_t *offset) {
2550   *offset = ArchiveBuilder::current()->any_to_offset((address)p);
2551 }
2552 
2553 int FileMapHeader::compute_crc() {
2554   char* start = (char*)this;
2555   // start computing from the field after _header_size to end of base archive name.
2556   char* buf = (char*)&(_generic_header._header_size) + sizeof(_generic_header._header_size);
2557   size_t sz = header_size() - (buf - start);
2558   int crc = ClassLoader::crc32(0, buf, (jint)sz);
2559   return crc;
2560 }
2561 
2562 // This function should only be called during run time with UseSharedSpaces enabled.
2563 bool FileMapHeader::validate() {
2564   if (_obj_alignment != ObjectAlignmentInBytes) {
2565     log_info(cds)("The shared archive file's ObjectAlignmentInBytes of %d"
2566                   " does not equal the current ObjectAlignmentInBytes of %d.",
2567                   _obj_alignment, ObjectAlignmentInBytes);
2568     return false;
2569   }
2570   if (_compact_strings != CompactStrings) {
2571     log_info(cds)("The shared archive file's CompactStrings setting (%s)"
2572                   " does not equal the current CompactStrings setting (%s).",
2573                   _compact_strings ? "enabled" : "disabled",
2574                   CompactStrings   ? "enabled" : "disabled");
2575     return false;
2576   }
2577 
2578   // This must be done after header validation because it might change the
2579   // header data
2580   const char* prop = Arguments::get_property("java.system.class.loader");
2581   if (prop != nullptr) {
2582     if (has_aot_linked_classes()) {
2583       log_error(cds)("CDS archive has aot-linked classes. It cannot be used when the "
2584                      "java.system.class.loader property is specified.");
2585       return false;
2586     }
2587     log_warning(cds)("Archived non-system classes are disabled because the "
2588             "java.system.class.loader property is specified (value = \"%s\"). "
2589             "To use archived non-system classes, this property must not be set", prop);
2590     _has_platform_or_app_classes = false;
2591   }
2592 
2593 
2594   if (!_verify_local && BytecodeVerificationLocal) {
2595     //  we cannot load boot classes, so there's no point of using the CDS archive
2596     log_info(cds)("The shared archive file's BytecodeVerificationLocal setting (%s)"
2597                                " does not equal the current BytecodeVerificationLocal setting (%s).",
2598                                _verify_local ? "enabled" : "disabled",
2599                                BytecodeVerificationLocal ? "enabled" : "disabled");
2600     return false;
2601   }
2602 
2603   // For backwards compatibility, we don't check the BytecodeVerificationRemote setting
2604   // if the archive only contains system classes.
2605   if (_has_platform_or_app_classes
2606       && !_verify_remote // we didn't verify the archived platform/app classes
2607       && BytecodeVerificationRemote) { // but we want to verify all loaded platform/app classes
2608     log_info(cds)("The shared archive file was created with less restrictive "
2609                                "verification setting than the current setting.");
2610     // Pretend that we didn't have any archived platform/app classes, so they won't be loaded
2611     // by SystemDictionaryShared.
2612     _has_platform_or_app_classes = false;
2613   }
2614 
2615   // Java agents are allowed during run time. Therefore, the following condition is not
2616   // checked: (!_allow_archiving_with_java_agent && AllowArchivingWithJavaAgent)
2617   // Note: _allow_archiving_with_java_agent is set in the shared archive during dump time
2618   // while AllowArchivingWithJavaAgent is set during the current run.
2619   if (_allow_archiving_with_java_agent && !AllowArchivingWithJavaAgent) {
2620     log_warning(cds)("The setting of the AllowArchivingWithJavaAgent is different "
2621                                "from the setting in the shared archive.");
2622     return false;
2623   }
2624 
2625   if (_allow_archiving_with_java_agent) {
2626     log_warning(cds)("This archive was created with AllowArchivingWithJavaAgent. It should be used "
2627             "for testing purposes only and should not be used in a production environment");
2628   }
2629 
2630   log_info(cds)("Archive was created with UseCompressedOops = %d, UseCompressedClassPointers = %d, UseCompactObjectHeaders = %d",
2631                           compressed_oops(), compressed_class_pointers(), compact_headers());
2632   if (compressed_oops() != UseCompressedOops || compressed_class_pointers() != UseCompressedClassPointers) {
2633     log_warning(cds)("Unable to use shared archive.\nThe saved state of UseCompressedOops and UseCompressedClassPointers is "
2634                                "different from runtime, CDS will be disabled.");
2635     return false;
2636   }
2637 
2638   if (compact_headers() != UseCompactObjectHeaders) {
2639     log_warning(cds)("Unable to use shared archive.\nThe shared archive file's UseCompactObjectHeaders setting (%s)"
2640                      " does not equal the current UseCompactObjectHeaders setting (%s).",
2641                      _compact_headers          ? "enabled" : "disabled",
2642                      UseCompactObjectHeaders   ? "enabled" : "disabled");
2643     return false;
2644   }
2645 
2646   if (!_use_optimized_module_handling) {
2647     CDSConfig::stop_using_optimized_module_handling();
2648     log_info(cds)("optimized module handling: disabled because archive was created without optimized module handling");
2649   }
2650 
2651   if (is_static()) {
2652     // Only the static archive can contain the full module graph.
2653     if (!_has_full_module_graph) {
2654       CDSConfig::stop_using_full_module_graph("archive was created without full module graph");
2655     }
2656 
2657     if (_has_archived_invokedynamic) {
2658       CDSConfig::set_has_archived_invokedynamic();
2659     }
2660   }
2661 
2662   return true;
2663 }
2664 
2665 bool FileMapInfo::validate_header() {
2666   if (!header()->validate()) {
2667     return false;
2668   }
2669   if (_is_static) {
2670     return true;
2671   } else {
2672     return DynamicArchive::validate(this);
2673   }
2674 }
2675 
2676 #if INCLUDE_JVMTI
2677 ClassPathEntry** FileMapInfo::_classpath_entries_for_jvmti = nullptr;
2678 
2679 ClassPathEntry* FileMapInfo::get_classpath_entry_for_jvmti(int i, TRAPS) {
2680   if (i == 0) {
2681     // index 0 corresponds to the ClassPathImageEntry which is a globally shared object
2682     // and should never be deleted.
2683     return ClassLoader::get_jrt_entry();
2684   }
2685   ClassPathEntry* ent = _classpath_entries_for_jvmti[i];
2686   if (ent == nullptr) {
2687     SharedClassPathEntry* scpe = shared_path(i);
2688     assert(scpe->is_jar(), "must be"); // other types of scpe will not produce archived classes
2689 
2690     const char* path = scpe->name();
2691     struct stat st;
2692     if (os::stat(path, &st) != 0) {
2693       char *msg = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, strlen(path) + 128);
2694       jio_snprintf(msg, strlen(path) + 127, "error in finding JAR file %s", path);
2695       THROW_MSG_(vmSymbols::java_io_IOException(), msg, nullptr);
2696     } else {
2697       ent = ClassLoader::create_class_path_entry(THREAD, path, &st, false, false, scpe->is_multi_release());
2698       if (ent == nullptr) {
2699         char *msg = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, strlen(path) + 128);
2700         jio_snprintf(msg, strlen(path) + 127, "error in opening JAR file %s", path);
2701         THROW_MSG_(vmSymbols::java_io_IOException(), msg, nullptr);
2702       }
2703     }
2704 
2705     MutexLocker mu(THREAD, CDSClassFileStream_lock);
2706     if (_classpath_entries_for_jvmti[i] == nullptr) {
2707       _classpath_entries_for_jvmti[i] = ent;
2708     } else {
2709       // Another thread has beat me to creating this entry
2710       delete ent;
2711       ent = _classpath_entries_for_jvmti[i];
2712     }
2713   }
2714 
2715   return ent;
2716 }
2717 
2718 ClassFileStream* FileMapInfo::open_stream_for_jvmti(InstanceKlass* ik, Handle class_loader, TRAPS) {
2719   int path_index = ik->shared_classpath_index();
2720   assert(path_index >= 0, "should be called for shared built-in classes only");
2721   assert(path_index < (int)get_number_of_shared_paths(), "sanity");
2722 
2723   ClassPathEntry* cpe = get_classpath_entry_for_jvmti(path_index, CHECK_NULL);
2724   assert(cpe != nullptr, "must be");
2725 
2726   Symbol* name = ik->name();
2727   const char* const class_name = name->as_C_string();
2728   const char* const file_name = ClassLoader::file_name_for_class_name(class_name,
2729                                                                       name->utf8_length());
2730   ClassLoaderData* loader_data = ClassLoaderData::class_loader_data(class_loader());
2731   ClassFileStream* cfs;
2732   if (class_loader() != nullptr && !cpe->is_modules_image() && cpe->is_multi_release_jar()) {
2733     cfs = get_stream_from_class_loader(class_loader, cpe, file_name, CHECK_NULL);
2734   } else {
2735     cfs = cpe->open_stream_for_loader(THREAD, file_name, loader_data);
2736   }
2737   assert(cfs != nullptr, "must be able to read the classfile data of shared classes for built-in loaders.");
2738   log_debug(cds, jvmti)("classfile data for %s [%d: %s] = %d bytes", class_name, path_index,
2739                         cfs->source(), cfs->length());
2740   return cfs;
2741 }
2742 
2743 ClassFileStream* FileMapInfo::get_stream_from_class_loader(Handle class_loader,
2744                                                            ClassPathEntry* cpe,
2745                                                            const char* file_name,
2746                                                            TRAPS) {
2747   JavaValue result(T_OBJECT);
2748   oop class_name = java_lang_String::create_oop_from_str(file_name, THREAD);
2749   Handle h_class_name = Handle(THREAD, class_name);
2750 
2751   // byte[] ClassLoader.getResourceAsByteArray(String name)
2752   JavaCalls::call_virtual(&result,
2753                           class_loader,
2754                           vmClasses::ClassLoader_klass(),
2755                           vmSymbols::getResourceAsByteArray_name(),
2756                           vmSymbols::getResourceAsByteArray_signature(),
2757                           h_class_name,
2758                           CHECK_NULL);
2759   assert(result.get_type() == T_OBJECT, "just checking");
2760   oop obj = result.get_oop();
2761   assert(obj != nullptr, "ClassLoader.getResourceAsByteArray should not return null");
2762 
2763   // copy from byte[] to a buffer
2764   typeArrayOop ba = typeArrayOop(obj);
2765   jint len = ba->length();
2766   u1* buffer = NEW_RESOURCE_ARRAY(u1, len);
2767   ArrayAccess<>::arraycopy_to_native<>(ba, typeArrayOopDesc::element_offset<jbyte>(0), buffer, len);
2768 
2769   return new ClassFileStream(buffer, len, cpe->name());
2770 }
2771 #endif