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