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