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