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