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