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