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