1 /*
   2  * Copyright (c) 2003, 2019, 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/dynamicArchive.hpp"
  38 #include "memory/filemap.hpp"
  39 #include "memory/heapShared.inline.hpp"
  40 #include "memory/iterator.inline.hpp"
  41 #include "memory/metadataFactory.hpp"
  42 #include "memory/metaspaceClosure.hpp"
  43 #include "memory/metaspaceShared.hpp"
  44 #include "memory/oopFactory.hpp"
  45 #include "memory/universe.hpp"
  46 #include "oops/compressedOops.hpp"
  47 #include "oops/compressedOops.inline.hpp"
  48 #include "oops/objArrayOop.hpp"
  49 #include "oops/oop.inline.hpp"
  50 #include "prims/jvmtiExport.hpp"
  51 #include "runtime/arguments.hpp"
  52 #include "runtime/java.hpp"
  53 #include "runtime/mutexLocker.hpp"
  54 #include "runtime/os.inline.hpp"
  55 #include "runtime/vm_version.hpp"
  56 #include "services/memTracker.hpp"
  57 #include "utilities/align.hpp"
  58 #include "utilities/defaultStream.hpp"
  59 #if INCLUDE_G1GC
  60 #include "gc/g1/g1CollectedHeap.hpp"
  61 #include "gc/g1/heapRegion.hpp"
  62 #endif
  63 
  64 # include <sys/stat.h>
  65 # include <errno.h>
  66 
  67 #ifndef O_BINARY       // if defined (Win32) use binary files.
  68 #define O_BINARY 0     // otherwise do nothing.
  69 #endif
  70 
  71 extern address JVM_FunctionAtStart();
  72 extern address JVM_FunctionAtEnd();
  73 
  74 // Complain and stop. All error conditions occurring during the writing of
  75 // an archive file should stop the process.  Unrecoverable errors during
  76 // the reading of the archive file should stop the process.
  77 
  78 static void fail(const char *msg, va_list ap) {
  79   // This occurs very early during initialization: tty is not initialized.
  80   jio_fprintf(defaultStream::error_stream(),
  81               "An error has occurred while processing the"
  82               " shared archive file.\n");
  83   jio_vfprintf(defaultStream::error_stream(), msg, ap);
  84   jio_fprintf(defaultStream::error_stream(), "\n");
  85   // Do not change the text of the below message because some tests check for it.
  86   vm_exit_during_initialization("Unable to use shared archive.", NULL);
  87 }
  88 
  89 
  90 void FileMapInfo::fail_stop(const char *msg, ...) {
  91         va_list ap;
  92   va_start(ap, msg);
  93   fail(msg, ap);        // Never returns.
  94   va_end(ap);           // for completeness.
  95 }
  96 
  97 
  98 // Complain and continue.  Recoverable errors during the reading of the
  99 // archive file may continue (with sharing disabled).
 100 //
 101 // If we continue, then disable shared spaces and close the file.
 102 
 103 void FileMapInfo::fail_continue(const char *msg, ...) {
 104   va_list ap;
 105   va_start(ap, msg);
 106   if (_dynamic_archive_info == NULL) {
 107     MetaspaceShared::set_archive_loading_failed();
 108   } else {
 109     // _dynamic_archive_info has been setup after mapping the base archive
 110     DynamicArchive::disable();
 111   }
 112   if (PrintSharedArchiveAndExit && _validating_shared_path_table) {
 113     // If we are doing PrintSharedArchiveAndExit and some of the classpath entries
 114     // do not validate, we can still continue "limping" to validate the remaining
 115     // entries. No need to quit.
 116     tty->print("[");
 117     tty->vprint(msg, ap);
 118     tty->print_cr("]");
 119   } else {
 120     if (RequireSharedSpaces) {
 121       fail(msg, ap);
 122     } else {
 123       if (log_is_enabled(Info, cds)) {
 124         ResourceMark rm;
 125         LogStream ls(Log(cds)::info());
 126         ls.print("UseSharedSpaces: ");
 127         ls.vprint_cr(msg, ap);
 128       }
 129     }
 130     if (_dynamic_archive_info == NULL) {
 131       UseSharedSpaces = false;
 132       assert(current_info() != NULL, "singleton must be registered");
 133       current_info()->close();
 134     } else {
 135       // We are failing when loading the top archive, but the base archive should
 136       // continue to work.
 137       log_warning(cds, dynamic)("Unable to use shared archive. The top archive failed to load: %s", _dynamic_archive_info->_full_path);
 138     }
 139   }
 140   va_end(ap);
 141 }
 142 
 143 // Fill in the fileMapInfo structure with data about this VM instance.
 144 
 145 // This method copies the vm version info into header_version.  If the version is too
 146 // long then a truncated version, which has a hash code appended to it, is copied.
 147 //
 148 // Using a template enables this method to verify that header_version is an array of
 149 // length JVM_IDENT_MAX.  This ensures that the code that writes to the CDS file and
 150 // the code that reads the CDS file will both use the same size buffer.  Hence, will
 151 // use identical truncation.  This is necessary for matching of truncated versions.
 152 template <int N> static void get_header_version(char (&header_version) [N]) {
 153   assert(N == JVM_IDENT_MAX, "Bad header_version size");
 154 
 155   const char *vm_version = VM_Version::internal_vm_info_string();
 156   const int version_len = (int)strlen(vm_version);
 157 
 158   if (version_len < (JVM_IDENT_MAX-1)) {
 159     strcpy(header_version, vm_version);
 160 
 161   } else {
 162     // Get the hash value.  Use a static seed because the hash needs to return the same
 163     // value over multiple jvm invocations.
 164     unsigned int hash = AltHashing::murmur3_32(8191, (const jbyte*)vm_version, version_len);
 165 
 166     // Truncate the ident, saving room for the 8 hex character hash value.
 167     strncpy(header_version, vm_version, JVM_IDENT_MAX-9);
 168 
 169     // Append the hash code as eight hex digits.
 170     sprintf(&header_version[JVM_IDENT_MAX-9], "%08x", hash);
 171     header_version[JVM_IDENT_MAX-1] = 0;  // Null terminate.
 172   }
 173 }
 174 
 175 FileMapInfo::FileMapInfo(bool is_static) {
 176   memset((void*)this, 0, sizeof(FileMapInfo));
 177   _is_static = is_static;
 178   size_t header_size;
 179   if (is_static) {
 180     assert(_current_info == NULL, "must be singleton"); // not thread safe
 181     _current_info = this;
 182     header_size = sizeof(FileMapHeader);
 183   } else {
 184     assert(_dynamic_archive_info == NULL, "must be singleton"); // not thread safe
 185     _dynamic_archive_info = this;
 186     header_size = sizeof(DynamicArchiveHeader);
 187   }
 188   _header = (FileMapHeader*)os::malloc(header_size, mtInternal);
 189   memset((void*)_header, 0, header_size);
 190   _header->_header_size = header_size;
 191   _header->_version = INVALID_CDS_ARCHIVE_VERSION;
 192   _header->_has_platform_or_app_classes = true;
 193   _file_offset = 0;
 194   _file_open = false;
 195 }
 196 
 197 FileMapInfo::~FileMapInfo() {
 198   if (_is_static) {
 199     assert(_current_info == this, "must be singleton"); // not thread safe
 200     _current_info = NULL;
 201   } else {
 202     assert(_dynamic_archive_info == this, "must be singleton"); // not thread safe
 203     _dynamic_archive_info = NULL;
 204   }
 205 }
 206 
 207 void FileMapInfo::populate_header(size_t alignment) {
 208   _header->populate(this, alignment);
 209 }
 210 
 211 void FileMapHeader::populate(FileMapInfo* mapinfo, size_t alignment) {
 212   if (DynamicDumpSharedSpaces) {
 213     _magic = CDS_DYNAMIC_ARCHIVE_MAGIC;
 214   } else {
 215     _magic = CDS_ARCHIVE_MAGIC;
 216   }
 217   _version = CURRENT_CDS_ARCHIVE_VERSION;
 218   _alignment = alignment;
 219   _obj_alignment = ObjectAlignmentInBytes;
 220   _compact_strings = CompactStrings;
 221   _narrow_oop_mode = CompressedOops::mode();
 222   _narrow_oop_base = CompressedOops::base();
 223   _narrow_oop_shift = CompressedOops::shift();
 224   _max_heap_size = MaxHeapSize;
 225   _narrow_klass_base = CompressedKlassPointers::base();
 226   _narrow_klass_shift = CompressedKlassPointers::shift();
 227   _shared_path_table = mapinfo->_shared_path_table;
 228   if (HeapShared::is_heap_object_archiving_allowed()) {
 229     _heap_reserved = Universe::heap()->reserved_region();
 230   }
 231 
 232   // The following fields are for sanity checks for whether this archive
 233   // will function correctly with this JVM and the bootclasspath it's
 234   // invoked with.
 235 
 236   // JVM version string ... changes on each build.
 237   get_header_version(_jvm_ident);
 238 
 239   ClassLoaderExt::finalize_shared_paths_misc_info();
 240   _app_class_paths_start_index = ClassLoaderExt::app_class_paths_start_index();
 241   _app_module_paths_start_index = ClassLoaderExt::app_module_paths_start_index();
 242   _num_module_paths = ClassLoader::num_module_path_entries();
 243   _max_used_path_index = ClassLoaderExt::max_used_path_index();
 244 
 245   _verify_local = BytecodeVerificationLocal;
 246   _verify_remote = BytecodeVerificationRemote;
 247   _has_platform_or_app_classes = ClassLoaderExt::has_platform_or_app_classes();
 248   _shared_base_address = SharedBaseAddress;
 249   _allow_archiving_with_java_agent = AllowArchivingWithJavaAgent;
 250   // the following 2 fields will be set in write_header for dynamic archive header
 251   _base_archive_name_size = 0;
 252   _base_archive_is_default = false;
 253 }
 254 
 255 void SharedClassPathEntry::init(const char* name, bool is_modules_image, TRAPS) {
 256   assert(DumpSharedSpaces || DynamicDumpSharedSpaces, "dump time only");
 257   _timestamp = 0;
 258   _filesize  = 0;
 259 
 260   struct stat st;
 261   if (os::stat(name, &st) == 0) {
 262     if ((st.st_mode & S_IFMT) == S_IFDIR) {
 263       _type = dir_entry;
 264     } else {
 265       // The timestamp of the modules_image is not checked at runtime.
 266       if (is_modules_image) {
 267         _type = modules_image_entry;
 268       } else {
 269         _type = jar_entry;
 270         _timestamp = st.st_mtime;
 271       }
 272       _filesize = st.st_size;
 273     }
 274   } else {
 275     // The file/dir must exist, or it would not have been added
 276     // into ClassLoader::classpath_entry().
 277     //
 278     // If we can't access a jar file in the boot path, then we can't
 279     // make assumptions about where classes get loaded from.
 280     FileMapInfo::fail_stop("Unable to open file %s.", name);
 281   }
 282 
 283   size_t len = strlen(name) + 1;
 284   _name = MetadataFactory::new_array<char>(ClassLoaderData::the_null_class_loader_data(), (int)len, THREAD);
 285   strcpy(_name->data(), name);
 286 }
 287 
 288 bool SharedClassPathEntry::validate(bool is_class_path) {
 289   assert(UseSharedSpaces, "runtime only");
 290 
 291   struct stat st;
 292   const char* name;
 293 
 294   // In order to validate the runtime modules image file size against the archived
 295   // size information, we need to obtain the runtime modules image path. The recorded
 296   // dump time modules image path in the archive may be different from the runtime path
 297   // if the JDK image has beed moved after generating the archive.
 298   if (is_modules_image()) {
 299     name = ClassLoader::get_jrt_entry()->name();
 300   } else {
 301     name = this->name();
 302   }
 303 
 304   bool ok = true;
 305   log_info(class, path)("checking shared classpath entry: %s", name);
 306   if (os::stat(name, &st) != 0 && is_class_path) {
 307     // If the archived module path entry does not exist at runtime, it is not fatal
 308     // (no need to invalid the shared archive) because the shared runtime visibility check
 309     // filters out any archived module classes that do not have a matching runtime
 310     // module path location.
 311     FileMapInfo::fail_continue("Required classpath entry does not exist: %s", name);
 312     ok = false;
 313   } else if (is_dir()) {
 314     if (!os::dir_is_empty(name)) {
 315       FileMapInfo::fail_continue("directory is not empty: %s", name);
 316       ok = false;
 317     }
 318   } else if ((has_timestamp() && _timestamp != st.st_mtime) ||
 319              _filesize != st.st_size) {
 320     ok = false;
 321     if (PrintSharedArchiveAndExit) {
 322       FileMapInfo::fail_continue(_timestamp != st.st_mtime ?
 323                                  "Timestamp mismatch" :
 324                                  "File size mismatch");
 325     } else {
 326       FileMapInfo::fail_continue("A jar file is not the one used while building"
 327                                  " the shared archive file: %s", name);
 328     }
 329   }
 330 
 331   if (PrintSharedArchiveAndExit && !ok) {
 332     // If PrintSharedArchiveAndExit is enabled, don't report failure to the
 333     // caller. Please see above comments for more details.
 334     ok = true;
 335     MetaspaceShared::set_archive_loading_failed();
 336   }
 337   return ok;
 338 }
 339 
 340 void SharedClassPathEntry::metaspace_pointers_do(MetaspaceClosure* it) {
 341   it->push(&_name);
 342   it->push(&_manifest);
 343 }
 344 
 345 void SharedPathTable::metaspace_pointers_do(MetaspaceClosure* it) {
 346   it->push(&_table);
 347   for (int i=0; i<_size; i++) {
 348     path_at(i)->metaspace_pointers_do(it);
 349   }
 350 }
 351 
 352 void SharedPathTable::dumptime_init(ClassLoaderData* loader_data, Thread* THREAD) {
 353   size_t entry_size = sizeof(SharedClassPathEntry);
 354   int num_boot_classpath_entries = ClassLoader::num_boot_classpath_entries();
 355   int num_app_classpath_entries = ClassLoader::num_app_classpath_entries();
 356   int num_module_path_entries = ClassLoader::num_module_path_entries();
 357   int num_entries = num_boot_classpath_entries + num_app_classpath_entries + num_module_path_entries;
 358   size_t bytes = entry_size * num_entries;
 359 
 360   _table = MetadataFactory::new_array<u8>(loader_data, (int)(bytes + 7 / 8), THREAD);
 361   _size = num_entries;
 362 }
 363 
 364 void FileMapInfo::allocate_shared_path_table() {
 365   assert(DumpSharedSpaces || DynamicDumpSharedSpaces, "Sanity");
 366 
 367   Thread* THREAD = Thread::current();
 368   ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data();
 369   ClassPathEntry* jrt = ClassLoader::get_jrt_entry();
 370 
 371   assert(jrt != NULL,
 372          "No modular java runtime image present when allocating the CDS classpath entry table");
 373 
 374   _shared_path_table.dumptime_init(loader_data, THREAD);
 375 
 376   // 1. boot class path
 377   int i = 0;
 378   ClassPathEntry* cpe = jrt;
 379   while (cpe != NULL) {
 380     bool is_jrt = (cpe == jrt);
 381     const char* type = (is_jrt ? "jrt" : (cpe->is_jar_file() ? "jar" : "dir"));
 382     log_info(class, path)("add main shared path (%s) %s", type, cpe->name());
 383     SharedClassPathEntry* ent = shared_path(i);
 384     ent->init(cpe->name(), is_jrt, THREAD);
 385     if (!is_jrt) {    // No need to do the modules image.
 386       EXCEPTION_MARK; // The following call should never throw, but would exit VM on error.
 387       update_shared_classpath(cpe, ent, THREAD);
 388     }
 389     cpe = ClassLoader::get_next_boot_classpath_entry(cpe);
 390     i++;
 391   }
 392   assert(i == ClassLoader::num_boot_classpath_entries(),
 393          "number of boot class path entry mismatch");
 394 
 395   // 2. app class path
 396   ClassPathEntry *acpe = ClassLoader::app_classpath_entries();
 397   while (acpe != NULL) {
 398     log_info(class, path)("add app shared path %s", acpe->name());
 399     SharedClassPathEntry* ent = shared_path(i);
 400     ent->init(acpe->name(), false, THREAD);
 401     EXCEPTION_MARK;
 402     update_shared_classpath(acpe, ent, THREAD);
 403     acpe = acpe->next();
 404     i++;
 405   }
 406 
 407   // 3. module path
 408   ClassPathEntry *mpe = ClassLoader::module_path_entries();
 409   while (mpe != NULL) {
 410     log_info(class, path)("add module path %s",mpe->name());
 411     SharedClassPathEntry* ent = shared_path(i);
 412     ent->init(mpe->name(), false, THREAD);
 413     EXCEPTION_MARK;
 414     update_shared_classpath(mpe, ent, THREAD);
 415     mpe = mpe->next();
 416     i++;
 417   }
 418   assert(i == _shared_path_table.size(), "number of shared path entry mismatch");
 419 }
 420 
 421 void FileMapInfo::check_nonempty_dir_in_shared_path_table() {
 422   assert(DumpSharedSpaces || DynamicDumpSharedSpaces, "dump time only");
 423 
 424   bool has_nonempty_dir = false;
 425 
 426   int last = _shared_path_table.size() - 1;
 427   if (last > ClassLoaderExt::max_used_path_index()) {
 428      // no need to check any path beyond max_used_path_index
 429      last = ClassLoaderExt::max_used_path_index();
 430   }
 431 
 432   for (int i = 0; i <= last; i++) {
 433     SharedClassPathEntry *e = shared_path(i);
 434     if (e->is_dir()) {
 435       const char* path = e->name();
 436       if (!os::dir_is_empty(path)) {
 437         tty->print_cr("Error: non-empty directory '%s'", path);
 438         has_nonempty_dir = true;
 439       }
 440     }
 441   }
 442 
 443   if (has_nonempty_dir) {
 444     ClassLoader::exit_with_path_failure("Cannot have non-empty directory in paths", NULL);
 445   }
 446 }
 447 
 448 class ManifestStream: public ResourceObj {
 449   private:
 450   u1*   _buffer_start; // Buffer bottom
 451   u1*   _buffer_end;   // Buffer top (one past last element)
 452   u1*   _current;      // Current buffer position
 453 
 454  public:
 455   // Constructor
 456   ManifestStream(u1* buffer, int length) : _buffer_start(buffer),
 457                                            _current(buffer) {
 458     _buffer_end = buffer + length;
 459   }
 460 
 461   static bool is_attr(u1* attr, const char* name) {
 462     return strncmp((const char*)attr, name, strlen(name)) == 0;
 463   }
 464 
 465   static char* copy_attr(u1* value, size_t len) {
 466     char* buf = NEW_RESOURCE_ARRAY(char, len + 1);
 467     strncpy(buf, (char*)value, len);
 468     buf[len] = 0;
 469     return buf;
 470   }
 471 
 472   // The return value indicates if the JAR is signed or not
 473   bool check_is_signed() {
 474     u1* attr = _current;
 475     bool isSigned = false;
 476     while (_current < _buffer_end) {
 477       if (*_current == '\n') {
 478         *_current = '\0';
 479         u1* value = (u1*)strchr((char*)attr, ':');
 480         if (value != NULL) {
 481           assert(*(value+1) == ' ', "Unrecognized format" );
 482           if (strstr((char*)attr, "-Digest") != NULL) {
 483             isSigned = true;
 484             break;
 485           }
 486         }
 487         *_current = '\n'; // restore
 488         attr = _current + 1;
 489       }
 490       _current ++;
 491     }
 492     return isSigned;
 493   }
 494 };
 495 
 496 void FileMapInfo::update_shared_classpath(ClassPathEntry *cpe, SharedClassPathEntry* ent, TRAPS) {
 497   ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data();
 498   ResourceMark rm(THREAD);
 499   jint manifest_size;
 500 
 501   if (cpe->is_jar_file()) {
 502     assert(ent->is_jar(), "the shared class path entry is not a JAR file");
 503     char* manifest = ClassLoaderExt::read_manifest(cpe, &manifest_size, CHECK);
 504     if (manifest != NULL) {
 505       ManifestStream* stream = new ManifestStream((u1*)manifest,
 506                                                   manifest_size);
 507       if (stream->check_is_signed()) {
 508         ent->set_is_signed();
 509       } else {
 510         // Copy the manifest into the shared archive
 511         manifest = ClassLoaderExt::read_raw_manifest(cpe, &manifest_size, CHECK);
 512         Array<u1>* buf = MetadataFactory::new_array<u1>(loader_data,
 513                                                         manifest_size,
 514                                                         THREAD);
 515         char* p = (char*)(buf->data());
 516         memcpy(p, manifest, manifest_size);
 517         ent->set_manifest(buf);
 518       }
 519     }
 520   }
 521 }
 522 
 523 
 524 bool FileMapInfo::validate_shared_path_table() {
 525   assert(UseSharedSpaces, "runtime only");
 526 
 527   _validating_shared_path_table = true;
 528 
 529   // Load the shared path table info from the archive header
 530   _shared_path_table = _header->_shared_path_table;
 531   if (DynamicDumpSharedSpaces) {
 532     // Only support dynamic dumping with the usage of the default CDS archive
 533     // or a simple base archive.
 534     // If the base layer archive contains additional path component besides
 535     // the runtime image and the -cp, dynamic dumping is disabled.
 536     //
 537     // When dynamic archiving is enabled, the _shared_path_table is overwritten
 538     // to include the application path and stored in the top layer archive.
 539     assert(shared_path(0)->is_modules_image(), "first shared_path must be the modules image");
 540     if (_header->_app_class_paths_start_index > 1) {
 541       DynamicDumpSharedSpaces = false;
 542       warning(
 543         "Dynamic archiving is disabled because base layer archive has appended boot classpath");
 544     }
 545     if (_header->_num_module_paths > 0) {
 546       DynamicDumpSharedSpaces = false;
 547       warning(
 548         "Dynamic archiving is disabled because base layer archive has module path");
 549     }
 550   }
 551 
 552   int module_paths_start_index = _header->_app_module_paths_start_index;
 553 
 554   // validate the path entries up to the _max_used_path_index
 555   for (int i=0; i < _header->_max_used_path_index + 1; i++) {
 556     if (i < module_paths_start_index) {
 557       if (shared_path(i)->validate()) {
 558         log_info(class, path)("ok");
 559       } else {
 560         if (_dynamic_archive_info != NULL && _dynamic_archive_info->_is_static) {
 561           assert(!UseSharedSpaces, "UseSharedSpaces should be disabled");
 562         }
 563         return false;
 564       }
 565     } else if (i >= module_paths_start_index) {
 566       if (shared_path(i)->validate(false /* not a class path entry */)) {
 567         log_info(class, path)("ok");
 568       } else {
 569         if (_dynamic_archive_info != NULL && _dynamic_archive_info->_is_static) {
 570           assert(!UseSharedSpaces, "UseSharedSpaces should be disabled");
 571         }
 572         return false;
 573       }
 574     }
 575   }
 576 
 577   _validating_shared_path_table = false;
 578 
 579 #if INCLUDE_JVMTI
 580   if (_classpath_entries_for_jvmti != NULL) {
 581     os::free(_classpath_entries_for_jvmti);
 582   }
 583   size_t sz = sizeof(ClassPathEntry*) * get_number_of_shared_paths();
 584   _classpath_entries_for_jvmti = (ClassPathEntry**)os::malloc(sz, mtClass);
 585   memset((void*)_classpath_entries_for_jvmti, 0, sz);
 586 #endif
 587 
 588   return true;
 589 }
 590 
 591 bool FileMapInfo::same_files(const char* file1, const char* file2) {
 592   if (strcmp(file1, file2) == 0) {
 593     return true;
 594   }
 595 
 596   bool is_same = false;
 597   // if the two paths diff only in case
 598   struct stat st1;
 599   struct stat st2;
 600   int ret1;
 601   int ret2;
 602   ret1 = os::stat(file1, &st1);
 603   ret2 = os::stat(file2, &st2);
 604   if (ret1 < 0 || ret2 < 0) {
 605     // one of the files is invalid. So they are not the same.
 606     is_same = false;
 607   } else if (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino) {
 608     // different files
 609     is_same = false;
 610 #ifndef _WINDOWS
 611   } else if (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino) {
 612     // same files
 613     is_same = true;
 614 #else
 615   } else if ((st1.st_size == st2.st_size) && (st1.st_ctime == st2.st_ctime) &&
 616              (st1.st_mtime == st2.st_mtime)) {
 617     // same files
 618     is_same = true;
 619 #endif
 620   }
 621   return is_same;
 622 }
 623 
 624 bool FileMapInfo::check_archive(const char* archive_name, bool is_static) {
 625   int fd = os::open(archive_name, O_RDONLY | O_BINARY, 0);
 626   if (fd < 0) {
 627     // do not vm_exit_during_initialization here because Arguments::init_shared_archive_paths()
 628     // requires a shared archive name. The open_for_read() function will log a message regarding
 629     // failure in opening a shared archive.
 630     return false;
 631   }
 632 
 633   size_t sz = is_static ? sizeof(FileMapHeader) : sizeof(DynamicArchiveHeader);
 634   void* header = os::malloc(sz, mtInternal);
 635   memset(header, 0, sz);
 636   size_t n = os::read(fd, header, (unsigned int)sz);
 637   if (n != sz) {
 638     os::free(header);
 639     os::close(fd);
 640     vm_exit_during_initialization("Unable to read header from shared archive", archive_name);
 641     return false;
 642   }
 643   if (is_static) {
 644     FileMapHeader* static_header = (FileMapHeader*)header;
 645     if (static_header->_magic != CDS_ARCHIVE_MAGIC) {
 646       os::free(header);
 647       os::close(fd);
 648       vm_exit_during_initialization("Not a base shared archive", archive_name);
 649       return false;
 650     }
 651   } else {
 652     DynamicArchiveHeader* dynamic_header = (DynamicArchiveHeader*)header;
 653     if (dynamic_header->_magic != CDS_DYNAMIC_ARCHIVE_MAGIC) {
 654       os::free(header);
 655       os::close(fd);
 656       vm_exit_during_initialization("Not a top shared archive", archive_name);
 657       return false;
 658     }
 659   }
 660   os::free(header);
 661   os::close(fd);
 662   return true;
 663 }
 664 
 665 bool FileMapInfo::get_base_archive_name_from_header(const char* archive_name,
 666                                                     int* size, char** base_archive_name) {
 667   int fd = os::open(archive_name, O_RDONLY | O_BINARY, 0);
 668   if (fd < 0) {
 669     *size = 0;
 670     return false;
 671   }
 672 
 673   // read the header as a dynamic archive header
 674   size_t sz = sizeof(DynamicArchiveHeader);
 675   DynamicArchiveHeader* dynamic_header = (DynamicArchiveHeader*)os::malloc(sz, mtInternal);
 676   size_t n = os::read(fd, dynamic_header, (unsigned int)sz);
 677   if (n != sz) {
 678     fail_continue("Unable to read the file header.");
 679     os::free(dynamic_header);
 680     os::close(fd);
 681     return false;
 682   }
 683   if (dynamic_header->_magic != CDS_DYNAMIC_ARCHIVE_MAGIC) {
 684     // Not a dynamic header, no need to proceed further.
 685     *size = 0;
 686     os::free(dynamic_header);
 687     os::close(fd);
 688     return false;
 689   }
 690   if (dynamic_header->_base_archive_is_default) {
 691     *base_archive_name = Arguments::get_default_shared_archive_path();
 692   } else {
 693     // skip over the _paths_misc_info
 694     sz = dynamic_header->_paths_misc_info_size;
 695     lseek(fd, (long)sz, SEEK_CUR);
 696     // read the base archive name
 697     size_t name_size = dynamic_header->_base_archive_name_size;
 698     if (name_size == 0) {
 699       os::free(dynamic_header);
 700       os::close(fd);
 701       return false;
 702     }
 703     *base_archive_name = NEW_C_HEAP_ARRAY(char, name_size, mtInternal);
 704     n = os::read(fd, *base_archive_name, (unsigned int)name_size);
 705     if (n != name_size) {
 706       fail_continue("Unable to read the base archive name from the header.");
 707       FREE_C_HEAP_ARRAY(char, *base_archive_name);
 708       *base_archive_name = NULL;
 709       os::free(dynamic_header);
 710       os::close(fd);
 711       return false;
 712     }
 713   }
 714 
 715   os::free(dynamic_header);
 716   os::close(fd);
 717   return true;
 718 }
 719 
 720 void FileMapInfo::restore_shared_path_table() {
 721   _shared_path_table = _current_info->_header->_shared_path_table;
 722 }
 723 
 724 // Read the FileMapInfo information from the file.
 725 
 726 bool FileMapInfo::init_from_file(int fd, bool is_static) {
 727   size_t sz = is_static ? sizeof(FileMapHeader) : sizeof(DynamicArchiveHeader);
 728   size_t n = os::read(fd, _header, (unsigned int)sz);
 729   if (n != sz) {
 730     fail_continue("Unable to read the file header.");
 731     return false;
 732   }
 733   if (_header->_version != CURRENT_CDS_ARCHIVE_VERSION) {
 734     fail_continue("The shared archive file has the wrong version.");
 735     return false;
 736   }
 737   _file_offset = n;
 738 
 739   size_t info_size = _header->_paths_misc_info_size;
 740   _paths_misc_info = NEW_C_HEAP_ARRAY(char, info_size, mtClass);
 741   n = os::read(fd, _paths_misc_info, (unsigned int)info_size);
 742   if (n != info_size) {
 743     fail_continue("Unable to read the shared path info header.");
 744     FREE_C_HEAP_ARRAY(char, _paths_misc_info);
 745     _paths_misc_info = NULL;
 746     return false;
 747   }
 748   _file_offset += n + _header->_base_archive_name_size; // accounts for the size of _base_archive_name
 749 
 750   if (is_static) {
 751     if (_header->_magic != CDS_ARCHIVE_MAGIC) {
 752       fail_continue("Incorrect static archive magic number");
 753       return false;
 754     }
 755     // just checking the last region is sufficient since the archive is written
 756     // in sequential order
 757     size_t len = lseek(fd, 0, SEEK_END);
 758     CDSFileMapRegion* si = space_at(MetaspaceShared::last_valid_region);
 759     // The last space might be empty
 760     if (si->_file_offset > len || len - si->_file_offset < si->_used) {
 761       fail_continue("The shared archive file has been truncated.");
 762       return false;
 763     }
 764 
 765     SharedBaseAddress = _header->_shared_base_address;
 766   }
 767 
 768   return true;
 769 }
 770 
 771 
 772 // Read the FileMapInfo information from the file.
 773 bool FileMapInfo::open_for_read(const char* path) {
 774   if (_file_open) {
 775     return true;
 776   }
 777   if (path == NULL) {
 778     _full_path = Arguments::GetSharedArchivePath();
 779   } else {
 780     _full_path = path;
 781   }
 782   int fd = os::open(_full_path, O_RDONLY | O_BINARY, 0);
 783   if (fd < 0) {
 784     if (errno == ENOENT) {
 785       // Not locating the shared archive is ok.
 786       fail_continue("Specified shared archive not found (%s).", _full_path);
 787     } else {
 788       fail_continue("Failed to open shared archive file (%s).",
 789                     os::strerror(errno));
 790     }
 791     return false;
 792   }
 793 
 794   _fd = fd;
 795   _file_open = true;
 796   return true;
 797 }
 798 
 799 // Write the FileMapInfo information to the file.
 800 
 801 void FileMapInfo::open_for_write(const char* path) {
 802   if (path == NULL) {
 803     _full_path = Arguments::GetSharedArchivePath();
 804   } else {
 805     _full_path = path;
 806   }
 807   LogMessage(cds) msg;
 808   if (msg.is_info()) {
 809     msg.info("Dumping shared data to file: ");
 810     msg.info("   %s", _full_path);
 811   }
 812 
 813 #ifdef _WINDOWS  // On Windows, need WRITE permission to remove the file.
 814     chmod(_full_path, _S_IREAD | _S_IWRITE);
 815 #endif
 816 
 817   // Use remove() to delete the existing file because, on Unix, this will
 818   // allow processes that have it open continued access to the file.
 819   remove(_full_path);
 820   int fd = os::open(_full_path, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0444);
 821   if (fd < 0) {
 822     fail_stop("Unable to create shared archive file %s: (%s).", _full_path,
 823               os::strerror(errno));
 824   }
 825   _fd = fd;
 826   _file_offset = 0;
 827   _file_open = true;
 828 }
 829 
 830 
 831 // Write the header to the file, seek to the next allocation boundary.
 832 
 833 void FileMapInfo::write_header() {
 834   int info_size = ClassLoader::get_shared_paths_misc_info_size();
 835 
 836   _header->_paths_misc_info_size = info_size;
 837 
 838   char* base_archive_name = NULL;
 839   if (_header->_magic == CDS_DYNAMIC_ARCHIVE_MAGIC) {
 840     base_archive_name = (char*)Arguments::GetSharedArchivePath();
 841     _header->_base_archive_name_size = (int)strlen(base_archive_name) + 1;
 842     _header->_base_archive_is_default = FLAG_IS_DEFAULT(SharedArchiveFile);
 843   }
 844 
 845   assert(is_file_position_aligned(), "must be");
 846   write_bytes(_header, _header->_header_size);
 847   write_bytes(ClassLoader::get_shared_paths_misc_info(), (size_t)info_size);
 848   if (base_archive_name != NULL) {
 849     write_bytes(base_archive_name, (size_t)_header->_base_archive_name_size);
 850   }
 851   align_file_position();
 852 }
 853 
 854 // Dump region to file.
 855 // This is called twice for each region during archiving, once before
 856 // the archive file is open (_file_open is false) and once after.
 857 void FileMapInfo::write_region(int region, char* base, size_t size,
 858                                bool read_only, bool allow_exec) {
 859   assert(DumpSharedSpaces || DynamicDumpSharedSpaces, "Dump time only");
 860 
 861   CDSFileMapRegion* si = space_at(region);
 862   char* target_base = base;
 863   if (DynamicDumpSharedSpaces) {
 864     target_base = DynamicArchive::buffer_to_target(base);
 865   }
 866 
 867   if (_file_open) {
 868     guarantee(si->_file_offset == _file_offset, "file offset mismatch.");
 869     log_info(cds)("Shared file region %d: " SIZE_FORMAT_HEX_W(08)
 870                   " bytes, addr " INTPTR_FORMAT " file offset " SIZE_FORMAT_HEX_W(08),
 871                   region, size, p2i(target_base), _file_offset);
 872   } else {
 873     si->_file_offset = _file_offset;
 874   }
 875 
 876   if (HeapShared::is_heap_region(region)) {
 877     assert((target_base - (char*)CompressedKlassPointers::base()) % HeapWordSize == 0, "Sanity");
 878     if (target_base != NULL) {
 879       si->_addr._offset = (intx)CompressedOops::encode_not_null((oop)target_base);
 880     } else {
 881       si->_addr._offset = 0;
 882     }
 883   } else {
 884     si->_addr._base = target_base;
 885   }
 886   si->_used = size;
 887   si->_read_only = read_only;
 888   si->_allow_exec = allow_exec;
 889 
 890   // Use the current 'base' when computing the CRC value and writing out data
 891   si->_crc = ClassLoader::crc32(0, base, (jint)size);
 892   if (base != NULL) {
 893     write_bytes_aligned(base, size);
 894   }
 895 }
 896 
 897 // Write out the given archive heap memory regions.  GC code combines multiple
 898 // consecutive archive GC regions into one MemRegion whenever possible and
 899 // produces the 'heap_mem' array.
 900 //
 901 // If the archive heap memory size is smaller than a single dump time GC region
 902 // size, there is only one MemRegion in the array.
 903 //
 904 // If the archive heap memory size is bigger than one dump time GC region size,
 905 // the 'heap_mem' array may contain more than one consolidated MemRegions. When
 906 // the first/bottom archive GC region is a partial GC region (with the empty
 907 // portion at the higher address within the region), one MemRegion is used for
 908 // the bottom partial archive GC region. The rest of the consecutive archive
 909 // GC regions are combined into another MemRegion.
 910 //
 911 // Here's the mapping from (archive heap GC regions) -> (GrowableArray<MemRegion> *regions).
 912 //   + We have 1 or more archive heap regions: ah0, ah1, ah2 ..... ahn
 913 //   + We have 1 or 2 consolidated heap memory regions: r0 and r1
 914 //
 915 // If there's a single archive GC region (ah0), then r0 == ah0, and r1 is empty.
 916 // Otherwise:
 917 //
 918 // "X" represented space that's occupied by heap objects.
 919 // "_" represented unused spaced in the heap region.
 920 //
 921 //
 922 //    |ah0       | ah1 | ah2| ...... | ahn|
 923 //    |XXXXXX|__ |XXXXX|XXXX|XXXXXXXX|XXXX|
 924 //    |<-r0->|   |<- r1 ----------------->|
 925 //            ^^^
 926 //             |
 927 //             +-- gap
 928 size_t FileMapInfo::write_archive_heap_regions(GrowableArray<MemRegion> *heap_mem,
 929                                                GrowableArray<ArchiveHeapOopmapInfo> *oopmaps,
 930                                                int first_region_id, int max_num_regions,
 931                                                bool print_log) {
 932   assert(max_num_regions <= 2, "Only support maximum 2 memory regions");
 933 
 934   int arr_len = heap_mem == NULL ? 0 : heap_mem->length();
 935   if(arr_len > max_num_regions) {
 936     fail_stop("Unable to write archive heap memory regions: "
 937               "number of memory regions exceeds maximum due to fragmentation. "
 938               "Please increase java heap size "
 939               "(current MaxHeapSize is " SIZE_FORMAT ", InitialHeapSize is " SIZE_FORMAT ").",
 940               MaxHeapSize, InitialHeapSize);
 941   }
 942 
 943   size_t total_size = 0;
 944   for (int i = first_region_id, arr_idx = 0;
 945            i < first_region_id + max_num_regions;
 946            i++, arr_idx++) {
 947     char* start = NULL;
 948     size_t size = 0;
 949     if (arr_idx < arr_len) {
 950       start = (char*)heap_mem->at(arr_idx).start();
 951       size = heap_mem->at(arr_idx).byte_size();
 952       total_size += size;
 953     }
 954 
 955     if (print_log) {
 956       log_info(cds)("Archive heap region %d " INTPTR_FORMAT " - " INTPTR_FORMAT " = " SIZE_FORMAT_W(8) " bytes",
 957                     i, p2i(start), p2i(start + size), size);
 958     }
 959     write_region(i, start, size, false, false);
 960     if (size > 0) {
 961       space_at(i)->_oopmap = oopmaps->at(arr_idx)._oopmap;
 962       space_at(i)->_oopmap_size_in_bits = oopmaps->at(arr_idx)._oopmap_size_in_bits;
 963     }
 964   }
 965   return total_size;
 966 }
 967 
 968 // Dump bytes to file -- at the current file position.
 969 
 970 void FileMapInfo::write_bytes(const void* buffer, size_t nbytes) {
 971   if (_file_open) {
 972     size_t n = os::write(_fd, buffer, (unsigned int)nbytes);
 973     if (n != nbytes) {
 974       // If the shared archive is corrupted, close it and remove it.
 975       close();
 976       remove(_full_path);
 977       fail_stop("Unable to write to shared archive file.");
 978     }
 979   }
 980   _file_offset += nbytes;
 981 }
 982 
 983 bool FileMapInfo::is_file_position_aligned() const {
 984   return _file_offset == align_up(_file_offset,
 985                                   os::vm_allocation_granularity());
 986 }
 987 
 988 // Align file position to an allocation unit boundary.
 989 
 990 void FileMapInfo::align_file_position() {
 991   size_t new_file_offset = align_up(_file_offset,
 992                                          os::vm_allocation_granularity());
 993   if (new_file_offset != _file_offset) {
 994     _file_offset = new_file_offset;
 995     if (_file_open) {
 996       // Seek one byte back from the target and write a byte to insure
 997       // that the written file is the correct length.
 998       _file_offset -= 1;
 999       if (lseek(_fd, (long)_file_offset, SEEK_SET) < 0) {
1000         fail_stop("Unable to seek.");
1001       }
1002       char zero = 0;
1003       write_bytes(&zero, 1);
1004     }
1005   }
1006 }
1007 
1008 
1009 // Dump bytes to file -- at the current file position.
1010 
1011 void FileMapInfo::write_bytes_aligned(const void* buffer, size_t nbytes) {
1012   align_file_position();
1013   write_bytes(buffer, nbytes);
1014   align_file_position();
1015 }
1016 
1017 
1018 // Close the shared archive file.  This does NOT unmap mapped regions.
1019 
1020 void FileMapInfo::close() {
1021   if (_file_open) {
1022     if (::close(_fd) < 0) {
1023       fail_stop("Unable to close the shared archive file.");
1024     }
1025     _file_open = false;
1026     _fd = -1;
1027   }
1028 }
1029 
1030 
1031 // JVM/TI RedefineClasses() support:
1032 // Remap the shared readonly space to shared readwrite, private.
1033 bool FileMapInfo::remap_shared_readonly_as_readwrite() {
1034   int idx = MetaspaceShared::ro;
1035   CDSFileMapRegion* si = space_at(idx);
1036   if (!si->_read_only) {
1037     // the space is already readwrite so we are done
1038     return true;
1039   }
1040   size_t used = si->_used;
1041   size_t size = align_up(used, os::vm_allocation_granularity());
1042   if (!open_for_read()) {
1043     return false;
1044   }
1045   char *addr = region_addr(idx);
1046   char *base = os::remap_memory(_fd, _full_path, si->_file_offset,
1047                                 addr, size, false /* !read_only */,
1048                                 si->_allow_exec);
1049   close();
1050   // These have to be errors because the shared region is now unmapped.
1051   if (base == NULL) {
1052     log_error(cds)("Unable to remap shared readonly space (errno=%d).", errno);
1053     vm_exit(1);
1054   }
1055   if (base != addr) {
1056     log_error(cds)("Unable to remap shared readonly space (errno=%d).", errno);
1057     vm_exit(1);
1058   }
1059   si->_read_only = false;
1060   return true;
1061 }
1062 
1063 // Map the whole region at once, assumed to be allocated contiguously.
1064 ReservedSpace FileMapInfo::reserve_shared_memory() {
1065   char* requested_addr = region_addr(0);
1066   size_t size = FileMapInfo::core_spaces_size();
1067 
1068   // Reserve the space first, then map otherwise map will go right over some
1069   // other reserved memory (like the code cache).
1070   ReservedSpace rs(size, os::vm_allocation_granularity(), false, requested_addr);
1071   if (!rs.is_reserved()) {
1072     fail_continue("Unable to reserve shared space at required address "
1073                   INTPTR_FORMAT, p2i(requested_addr));
1074     return rs;
1075   }
1076   // the reserved virtual memory is for mapping class data sharing archive
1077   MemTracker::record_virtual_memory_type((address)rs.base(), mtClassShared);
1078 
1079   return rs;
1080 }
1081 
1082 // Memory map a region in the address space.
1083 static const char* shared_region_name[] = { "MiscData", "ReadWrite", "ReadOnly", "MiscCode", "OptionalData",
1084                                             "String1", "String2", "OpenArchive1", "OpenArchive2" };
1085 
1086 char* FileMapInfo::map_regions(int regions[], char* saved_base[], size_t len) {
1087   char* prev_top = NULL;
1088   char* curr_base;
1089   char* curr_top;
1090   int i = 0;
1091   for (i = 0; i < (int)len; i++) {
1092     curr_base = map_region(regions[i], &curr_top);
1093     if (curr_base == NULL) {
1094       return NULL;
1095     }
1096     if (i > 0) {
1097       // We require that mc->rw->ro->md->od to be laid out consecutively, with no
1098       // gaps between them. That way, we can ensure that the OS won't be able to
1099       // allocate any new memory spaces inside _shared_metaspace_{base,top}, which
1100       // would mess up the simple comparision in MetaspaceShared::is_in_shared_metaspace().
1101       assert(curr_base == prev_top, "must be");
1102     }
1103     log_info(cds)("Mapped region #%d at base %p top %p", regions[i], curr_base, curr_top);
1104     saved_base[i] = curr_base;
1105     prev_top = curr_top;
1106   }
1107   return curr_top;
1108 }
1109 
1110 char* FileMapInfo::map_region(int i, char** top_ret) {
1111   assert(!HeapShared::is_heap_region(i), "sanity");
1112   CDSFileMapRegion* si = space_at(i);
1113   size_t used = si->_used;
1114   size_t alignment = os::vm_allocation_granularity();
1115   size_t size = align_up(used, alignment);
1116   char *requested_addr = region_addr(i);
1117 
1118 #ifdef _WINDOWS
1119   // Windows cannot remap read-only shared memory to read-write when required for
1120   // RedefineClasses, which is also used by JFR.  Always map windows regions as RW.
1121   si->_read_only = false;
1122 #else
1123   // If a tool agent is in use (debugging enabled), or JFR, we must map the address space RW
1124   if (JvmtiExport::can_modify_any_class() || JvmtiExport::can_walk_any_space() ||
1125       Arguments::has_jfr_option()) {
1126     si->_read_only = false;
1127   }
1128 #endif // _WINDOWS
1129 
1130   // map the contents of the CDS archive in this memory
1131   char *base = os::map_memory(_fd, _full_path, si->_file_offset,
1132                               requested_addr, size, si->_read_only,
1133                               si->_allow_exec);
1134   if (base == NULL || base != requested_addr) {
1135     fail_continue("Unable to map %s shared space at required address.", shared_region_name[i]);
1136     _memory_mapping_failed = true;
1137     return NULL;
1138   }
1139 #ifdef _WINDOWS
1140   // This call is Windows-only because the memory_type gets recorded for the other platforms
1141   // in method FileMapInfo::reserve_shared_memory(), which is not called on Windows.
1142   MemTracker::record_virtual_memory_type((address)base, mtClassShared);
1143 #endif
1144 
1145   if (VerifySharedSpaces && !verify_region_checksum(i)) {
1146     return NULL;
1147   }
1148 
1149   *top_ret = base + size;
1150   return base;
1151 }
1152 
1153 size_t FileMapInfo::read_bytes(void* buffer, size_t count) {
1154   assert(_file_open, "Archive file is not open");
1155   size_t n = os::read(_fd, buffer, (unsigned int)count);
1156   if (n != count) {
1157     // Close the file if there's a problem reading it.
1158     close();
1159     return 0;
1160   }
1161   _file_offset += count;
1162   return count;
1163 }
1164 
1165 address FileMapInfo::decode_start_address(CDSFileMapRegion* spc, bool with_current_oop_encoding_mode) {
1166   if (with_current_oop_encoding_mode) {
1167     return (address)CompressedOops::decode_not_null(offset_of_space(spc));
1168   } else {
1169     return (address)HeapShared::decode_from_archive(offset_of_space(spc));
1170   }
1171 }
1172 
1173 static MemRegion *closed_archive_heap_ranges = NULL;
1174 static MemRegion *open_archive_heap_ranges = NULL;
1175 static int num_closed_archive_heap_ranges = 0;
1176 static int num_open_archive_heap_ranges = 0;
1177 
1178 #if INCLUDE_CDS_JAVA_HEAP
1179 bool FileMapInfo::has_heap_regions() {
1180   return (_header->_space[MetaspaceShared::first_closed_archive_heap_region]._used > 0);
1181 }
1182 
1183 // Returns the address range of the archived heap regions computed using the
1184 // current oop encoding mode. This range may be different than the one seen at
1185 // dump time due to encoding mode differences. The result is used in determining
1186 // if/how these regions should be relocated at run time.
1187 MemRegion FileMapInfo::get_heap_regions_range_with_current_oop_encoding_mode() {
1188   address start = (address) max_uintx;
1189   address end   = NULL;
1190 
1191   for (int i = MetaspaceShared::first_closed_archive_heap_region;
1192            i <= MetaspaceShared::last_valid_region;
1193            i++) {
1194     CDSFileMapRegion* si = space_at(i);
1195     size_t size = si->_used;
1196     if (size > 0) {
1197       address s = start_address_as_decoded_with_current_oop_encoding_mode(si);
1198       address e = s + size;
1199       if (start > s) {
1200         start = s;
1201       }
1202       if (end < e) {
1203         end = e;
1204       }
1205     }
1206   }
1207   assert(end != NULL, "must have at least one used heap region");
1208   return MemRegion((HeapWord*)start, (HeapWord*)end);
1209 }
1210 
1211 //
1212 // Map the closed and open archive heap objects to the runtime java heap.
1213 //
1214 // The shared objects are mapped at (or close to ) the java heap top in
1215 // closed archive regions. The mapped objects contain no out-going
1216 // references to any other java heap regions. GC does not write into the
1217 // mapped closed archive heap region.
1218 //
1219 // The open archive heap objects are mapped below the shared objects in
1220 // the runtime java heap. The mapped open archive heap data only contains
1221 // references to the shared objects and open archive objects initially.
1222 // During runtime execution, out-going references to any other java heap
1223 // regions may be added. GC may mark and update references in the mapped
1224 // open archive objects.
1225 void FileMapInfo::map_heap_regions_impl() {
1226   if (!HeapShared::is_heap_object_archiving_allowed()) {
1227     log_info(cds)("CDS heap data is being ignored. UseG1GC, "
1228                   "UseCompressedOops and UseCompressedClassPointers are required.");
1229     return;
1230   }
1231 
1232   if (JvmtiExport::should_post_class_file_load_hook() && JvmtiExport::has_early_class_hook_env()) {
1233     ShouldNotReachHere(); // CDS should have been disabled.
1234     // The archived objects are mapped at JVM start-up, but we don't know if
1235     // j.l.String or j.l.Class might be replaced by the ClassFileLoadHook,
1236     // which would make the archived String or mirror objects invalid. Let's be safe and not
1237     // use the archived objects. These 2 classes are loaded during the JVMTI "early" stage.
1238     //
1239     // If JvmtiExport::has_early_class_hook_env() is false, the classes of some objects
1240     // in the archived subgraphs may be replaced by the ClassFileLoadHook. But that's OK
1241     // because we won't install an archived object subgraph if the klass of any of the
1242     // referenced objects are replaced. See HeapShared::initialize_from_archived_subgraph().
1243   }
1244 
1245   MemRegion heap_reserved = Universe::heap()->reserved_region();
1246 
1247   log_info(cds)("CDS archive was created with max heap size = " SIZE_FORMAT "M, and the following configuration:",
1248                 max_heap_size()/M);
1249   log_info(cds)("    narrow_klass_base = " PTR_FORMAT ", narrow_klass_shift = %d",
1250                 p2i(narrow_klass_base()), narrow_klass_shift());
1251   log_info(cds)("    narrow_oop_mode = %d, narrow_oop_base = " PTR_FORMAT ", narrow_oop_shift = %d",
1252                 narrow_oop_mode(), p2i(narrow_oop_base()), narrow_oop_shift());
1253 
1254   log_info(cds)("The current max heap size = " SIZE_FORMAT "M, HeapRegion::GrainBytes = " SIZE_FORMAT,
1255                 heap_reserved.byte_size()/M, HeapRegion::GrainBytes);
1256   log_info(cds)("    narrow_klass_base = " PTR_FORMAT ", narrow_klass_shift = %d",
1257                 p2i(CompressedKlassPointers::base()), CompressedKlassPointers::shift());
1258   log_info(cds)("    narrow_oop_mode = %d, narrow_oop_base = " PTR_FORMAT ", narrow_oop_shift = %d",
1259                 CompressedOops::mode(), p2i(CompressedOops::base()), CompressedOops::shift());
1260 
1261   if (narrow_klass_base() != CompressedKlassPointers::base() ||
1262       narrow_klass_shift() != CompressedKlassPointers::shift()) {
1263     log_info(cds)("CDS heap data cannot be used because the archive was created with an incompatible narrow klass encoding mode.");
1264     return;
1265   }
1266 
1267   if (narrow_oop_mode() != CompressedOops::mode() ||
1268       narrow_oop_base() != CompressedOops::base() ||
1269       narrow_oop_shift() != CompressedOops::shift()) {
1270     log_info(cds)("CDS heap data need to be relocated because the archive was created with an incompatible oop encoding mode.");
1271     _heap_pointers_need_patching = true;
1272   } else {
1273     MemRegion range = get_heap_regions_range_with_current_oop_encoding_mode();
1274     if (!heap_reserved.contains(range)) {
1275       log_info(cds)("CDS heap data need to be relocated because");
1276       log_info(cds)("the desired range " PTR_FORMAT " - "  PTR_FORMAT, p2i(range.start()), p2i(range.end()));
1277       log_info(cds)("is outside of the heap " PTR_FORMAT " - "  PTR_FORMAT, p2i(heap_reserved.start()), p2i(heap_reserved.end()));
1278       _heap_pointers_need_patching = true;
1279     }
1280   }
1281 
1282   ptrdiff_t delta = 0;
1283   if (_heap_pointers_need_patching) {
1284     //   dumptime heap end  ------------v
1285     //   [      |archived heap regions| ]         runtime heap end ------v
1286     //                                       [   |archived heap regions| ]
1287     //                                  |<-----delta-------------------->|
1288     //
1289     // At dump time, the archived heap regions were near the top of the heap.
1290     // At run time, they may not be inside the heap, so we move them so
1291     // that they are now near the top of the runtime time. This can be done by
1292     // the simple math of adding the delta as shown above.
1293     address dumptime_heap_end = (address)_header->_heap_reserved.end();
1294     address runtime_heap_end = (address)heap_reserved.end();
1295     delta = runtime_heap_end - dumptime_heap_end;
1296   }
1297 
1298   log_info(cds)("CDS heap data relocation delta = " INTX_FORMAT " bytes", delta);
1299   HeapShared::init_narrow_oop_decoding(narrow_oop_base() + delta, narrow_oop_shift());
1300 
1301   CDSFileMapRegion* si = space_at(MetaspaceShared::first_closed_archive_heap_region);
1302   address relocated_closed_heap_region_bottom = start_address_as_decoded_from_archive(si);
1303   if (!is_aligned(relocated_closed_heap_region_bottom, HeapRegion::GrainBytes)) {
1304     // Align the bottom of the closed archive heap regions at G1 region boundary.
1305     // This will avoid the situation where the highest open region and the lowest
1306     // closed region sharing the same G1 region. Otherwise we will fail to map the
1307     // open regions.
1308     size_t align = size_t(relocated_closed_heap_region_bottom) % HeapRegion::GrainBytes;
1309     delta -= align;
1310     log_info(cds)("CDS heap data need to be relocated lower by a further " SIZE_FORMAT
1311                   " bytes to " INTX_FORMAT " to be aligned with HeapRegion::GrainBytes",
1312                   align, delta);
1313     HeapShared::init_narrow_oop_decoding(narrow_oop_base() + delta, narrow_oop_shift());
1314     _heap_pointers_need_patching = true;
1315     relocated_closed_heap_region_bottom = start_address_as_decoded_from_archive(si);
1316   }
1317   assert(is_aligned(relocated_closed_heap_region_bottom, HeapRegion::GrainBytes),
1318          "must be");
1319 
1320   // Map the closed_archive_heap regions, GC does not write into the regions.
1321   if (map_heap_data(&closed_archive_heap_ranges,
1322                     MetaspaceShared::first_closed_archive_heap_region,
1323                     MetaspaceShared::max_closed_archive_heap_region,
1324                     &num_closed_archive_heap_ranges)) {
1325     HeapShared::set_closed_archive_heap_region_mapped();
1326 
1327     // Now, map open_archive heap regions, GC can write into the regions.
1328     if (map_heap_data(&open_archive_heap_ranges,
1329                       MetaspaceShared::first_open_archive_heap_region,
1330                       MetaspaceShared::max_open_archive_heap_region,
1331                       &num_open_archive_heap_ranges,
1332                       true /* open */)) {
1333       HeapShared::set_open_archive_heap_region_mapped();
1334     }
1335   }
1336 }
1337 
1338 void FileMapInfo::map_heap_regions() {
1339   if (has_heap_regions()) {
1340     map_heap_regions_impl();
1341   }
1342 
1343   if (!HeapShared::closed_archive_heap_region_mapped()) {
1344     assert(closed_archive_heap_ranges == NULL &&
1345            num_closed_archive_heap_ranges == 0, "sanity");
1346   }
1347 
1348   if (!HeapShared::open_archive_heap_region_mapped()) {
1349     assert(open_archive_heap_ranges == NULL && num_open_archive_heap_ranges == 0, "sanity");
1350   }
1351 }
1352 
1353 bool FileMapInfo::map_heap_data(MemRegion **heap_mem, int first,
1354                                 int max, int* num, bool is_open_archive) {
1355   MemRegion * regions = new MemRegion[max];
1356   CDSFileMapRegion* si;
1357   int region_num = 0;
1358 
1359   for (int i = first;
1360            i < first + max; i++) {
1361     si = space_at(i);
1362     size_t size = si->_used;
1363     if (size > 0) {
1364       HeapWord* start = (HeapWord*)start_address_as_decoded_from_archive(si);
1365       regions[region_num] = MemRegion(start, size / HeapWordSize);
1366       region_num ++;
1367       log_info(cds)("Trying to map heap data: region[%d] at " INTPTR_FORMAT ", size = " SIZE_FORMAT_W(8) " bytes",
1368                     i, p2i(start), size);
1369     }
1370   }
1371 
1372   if (region_num == 0) {
1373     return false; // no archived java heap data
1374   }
1375 
1376   // Check that ranges are within the java heap
1377   if (!G1CollectedHeap::heap()->check_archive_addresses(regions, region_num)) {
1378     log_info(cds)("UseSharedSpaces: Unable to allocate region, range is not within java heap.");
1379     return false;
1380   }
1381 
1382   // allocate from java heap
1383   if (!G1CollectedHeap::heap()->alloc_archive_regions(
1384              regions, region_num, is_open_archive)) {
1385     log_info(cds)("UseSharedSpaces: Unable to allocate region, java heap range is already in use.");
1386     return false;
1387   }
1388 
1389   // Map the archived heap data. No need to call MemTracker::record_virtual_memory_type()
1390   // for mapped regions as they are part of the reserved java heap, which is
1391   // already recorded.
1392   for (int i = 0; i < region_num; i++) {
1393     si = space_at(first + i);
1394     char* addr = (char*)regions[i].start();
1395     char* base = os::map_memory(_fd, _full_path, si->_file_offset,
1396                                 addr, regions[i].byte_size(), si->_read_only,
1397                                 si->_allow_exec);
1398     if (base == NULL || base != addr) {
1399       // dealloc the regions from java heap
1400       dealloc_archive_heap_regions(regions, region_num, is_open_archive);
1401       log_info(cds)("UseSharedSpaces: Unable to map at required address in java heap. "
1402                     INTPTR_FORMAT ", size = " SIZE_FORMAT " bytes",
1403                     p2i(addr), regions[i].byte_size());
1404       return false;
1405     }
1406 
1407     if (VerifySharedSpaces && !region_crc_check(addr, regions[i].byte_size(), si->_crc)) {
1408       // dealloc the regions from java heap
1409       dealloc_archive_heap_regions(regions, region_num, is_open_archive);
1410       log_info(cds)("UseSharedSpaces: mapped heap regions are corrupt");
1411       return false;
1412     }
1413   }
1414 
1415   // the shared heap data is mapped successfully
1416   *heap_mem = regions;
1417   *num = region_num;
1418   return true;
1419 }
1420 
1421 void FileMapInfo::patch_archived_heap_embedded_pointers() {
1422   if (!_heap_pointers_need_patching) {
1423     return;
1424   }
1425 
1426   patch_archived_heap_embedded_pointers(closed_archive_heap_ranges,
1427                                         num_closed_archive_heap_ranges,
1428                                         MetaspaceShared::first_closed_archive_heap_region);
1429 
1430   patch_archived_heap_embedded_pointers(open_archive_heap_ranges,
1431                                         num_open_archive_heap_ranges,
1432                                         MetaspaceShared::first_open_archive_heap_region);
1433 }
1434 
1435 void FileMapInfo::patch_archived_heap_embedded_pointers(MemRegion* ranges, int num_ranges,
1436                                                         int first_region_idx) {
1437   for (int i=0; i<num_ranges; i++) {
1438     CDSFileMapRegion* si = space_at(i + first_region_idx);
1439     HeapShared::patch_archived_heap_embedded_pointers(ranges[i], (address)si->_oopmap,
1440                                                       si->_oopmap_size_in_bits);
1441   }
1442 }
1443 
1444 // This internally allocates objects using SystemDictionary::Object_klass(), so it
1445 // must be called after the well-known classes are resolved.
1446 void FileMapInfo::fixup_mapped_heap_regions() {
1447   // If any closed regions were found, call the fill routine to make them parseable.
1448   // Note that closed_archive_heap_ranges may be non-NULL even if no ranges were found.
1449   if (num_closed_archive_heap_ranges != 0) {
1450     assert(closed_archive_heap_ranges != NULL,
1451            "Null closed_archive_heap_ranges array with non-zero count");
1452     G1CollectedHeap::heap()->fill_archive_regions(closed_archive_heap_ranges,
1453                                                   num_closed_archive_heap_ranges);
1454   }
1455 
1456   // do the same for mapped open archive heap regions
1457   if (num_open_archive_heap_ranges != 0) {
1458     assert(open_archive_heap_ranges != NULL, "NULL open_archive_heap_ranges array with non-zero count");
1459     G1CollectedHeap::heap()->fill_archive_regions(open_archive_heap_ranges,
1460                                                   num_open_archive_heap_ranges);
1461   }
1462 }
1463 
1464 // dealloc the archive regions from java heap
1465 void FileMapInfo::dealloc_archive_heap_regions(MemRegion* regions, int num, bool is_open) {
1466   if (num > 0) {
1467     assert(regions != NULL, "Null archive ranges array with non-zero count");
1468     G1CollectedHeap::heap()->dealloc_archive_regions(regions, num, is_open);
1469   }
1470 }
1471 #endif // INCLUDE_CDS_JAVA_HEAP
1472 
1473 bool FileMapInfo::region_crc_check(char* buf, size_t size, int expected_crc) {
1474   int crc = ClassLoader::crc32(0, buf, (jint)size);
1475   if (crc != expected_crc) {
1476     fail_continue("Checksum verification failed.");
1477     return false;
1478   }
1479   return true;
1480 }
1481 
1482 bool FileMapInfo::verify_region_checksum(int i) {
1483   assert(VerifySharedSpaces, "sanity");
1484 
1485   size_t sz = space_at(i)->_used;
1486 
1487   if (sz == 0) {
1488     return true; // no data
1489   }
1490 
1491   return region_crc_check(region_addr(i), sz, space_at(i)->_crc);
1492 }
1493 
1494 void FileMapInfo::unmap_regions(int regions[], char* saved_base[], size_t len) {
1495   for (int i = 0; i < (int)len; i++) {
1496     if (saved_base[i] != NULL) {
1497       unmap_region(regions[i]);
1498     }
1499   }
1500 }
1501 
1502 // Unmap a memory region in the address space.
1503 
1504 void FileMapInfo::unmap_region(int i) {
1505   assert(!HeapShared::is_heap_region(i), "sanity");
1506   CDSFileMapRegion* si = space_at(i);
1507   size_t used = si->_used;
1508   size_t size = align_up(used, os::vm_allocation_granularity());
1509 
1510   if (used == 0) {
1511     return;
1512   }
1513 
1514   char* addr = region_addr(i);
1515   if (!os::unmap_memory(addr, size)) {
1516     fail_stop("Unable to unmap shared space.");
1517   }
1518 }
1519 
1520 void FileMapInfo::assert_mark(bool check) {
1521   if (!check) {
1522     fail_stop("Mark mismatch while restoring from shared file.");
1523   }
1524 }
1525 
1526 void FileMapInfo::metaspace_pointers_do(MetaspaceClosure* it) {
1527   _shared_path_table.metaspace_pointers_do(it);
1528 }
1529 
1530 FileMapInfo* FileMapInfo::_current_info = NULL;
1531 FileMapInfo* FileMapInfo::_dynamic_archive_info = NULL;
1532 bool FileMapInfo::_heap_pointers_need_patching = false;
1533 SharedPathTable FileMapInfo::_shared_path_table;
1534 bool FileMapInfo::_validating_shared_path_table = false;
1535 bool FileMapInfo::_memory_mapping_failed = false;
1536 
1537 // Open the shared archive file, read and validate the header
1538 // information (version, boot classpath, etc.).  If initialization
1539 // fails, shared spaces are disabled and the file is closed. [See
1540 // fail_continue.]
1541 //
1542 // Validation of the archive is done in two steps:
1543 //
1544 // [1] validate_header() - done here. This checks the header, including _paths_misc_info.
1545 // [2] validate_shared_path_table - this is done later, because the table is in the RW
1546 //     region of the archive, which is not mapped yet.
1547 bool FileMapInfo::initialize(bool is_static) {
1548   assert(UseSharedSpaces, "UseSharedSpaces expected.");
1549 
1550   if (JvmtiExport::should_post_class_file_load_hook() && JvmtiExport::has_early_class_hook_env()) {
1551     // CDS assumes that no classes resolved in SystemDictionary::resolve_well_known_classes
1552     // are replaced at runtime by JVMTI ClassFileLoadHook. All of those classes are resolved
1553     // during the JVMTI "early" stage, so we can still use CDS if
1554     // JvmtiExport::has_early_class_hook_env() is false.
1555     FileMapInfo::fail_continue("CDS is disabled because early JVMTI ClassFileLoadHook is in use.");
1556     return false;
1557   }
1558 
1559   if (!open_for_read()) {
1560     return false;
1561   }
1562 
1563   init_from_file(_fd, is_static);
1564   if (!validate_header(is_static)) {
1565     return false;
1566   }
1567   return true;
1568 }
1569 
1570 char* FileMapInfo::region_addr(int idx) {
1571   CDSFileMapRegion* si = space_at(idx);
1572   if (HeapShared::is_heap_region(idx)) {
1573     assert(DumpSharedSpaces, "The following doesn't work at runtime");
1574     return si->_used > 0 ?
1575           (char*)start_address_as_decoded_with_current_oop_encoding_mode(si) : NULL;
1576   } else {
1577     return si->_addr._base;
1578   }
1579 }
1580 
1581 int FileMapHeader::compute_crc() {
1582   char* start = (char*)this;
1583   // start computing from the field after _crc
1584   char* buf = (char*)&_crc + sizeof(_crc);
1585   size_t sz = _header_size - (buf - start);
1586   int crc = ClassLoader::crc32(0, buf, (jint)sz);
1587   return crc;
1588 }
1589 
1590 // This function should only be called during run time with UseSharedSpaces enabled.
1591 bool FileMapHeader::validate() {
1592   if (VerifySharedSpaces && compute_crc() != _crc) {
1593     FileMapInfo::fail_continue("Header checksum verification failed.");
1594     return false;
1595   }
1596 
1597   if (!Arguments::has_jimage()) {
1598     FileMapInfo::fail_continue("The shared archive file cannot be used with an exploded module build.");
1599     return false;
1600   }
1601 
1602   if (_version != CURRENT_CDS_ARCHIVE_VERSION) {
1603     FileMapInfo::fail_continue("The shared archive file is the wrong version.");
1604     return false;
1605   }
1606   if (_magic != CDS_ARCHIVE_MAGIC && _magic != CDS_DYNAMIC_ARCHIVE_MAGIC) {
1607     FileMapInfo::fail_continue("The shared archive file has a bad magic number.");
1608     return false;
1609   }
1610   char header_version[JVM_IDENT_MAX];
1611   get_header_version(header_version);
1612   if (strncmp(_jvm_ident, header_version, JVM_IDENT_MAX-1) != 0) {
1613     log_info(class, path)("expected: %s", header_version);
1614     log_info(class, path)("actual:   %s", _jvm_ident);
1615     FileMapInfo::fail_continue("The shared archive file was created by a different"
1616                   " version or build of HotSpot");
1617     return false;
1618   }
1619   if (_obj_alignment != ObjectAlignmentInBytes) {
1620     FileMapInfo::fail_continue("The shared archive file's ObjectAlignmentInBytes of %d"
1621                   " does not equal the current ObjectAlignmentInBytes of " INTX_FORMAT ".",
1622                   _obj_alignment, ObjectAlignmentInBytes);
1623     return false;
1624   }
1625   if (_compact_strings != CompactStrings) {
1626     FileMapInfo::fail_continue("The shared archive file's CompactStrings setting (%s)"
1627                   " does not equal the current CompactStrings setting (%s).",
1628                   _compact_strings ? "enabled" : "disabled",
1629                   CompactStrings   ? "enabled" : "disabled");
1630     return false;
1631   }
1632 
1633   // This must be done after header validation because it might change the
1634   // header data
1635   const char* prop = Arguments::get_property("java.system.class.loader");
1636   if (prop != NULL) {
1637     warning("Archived non-system classes are disabled because the "
1638             "java.system.class.loader property is specified (value = \"%s\"). "
1639             "To use archived non-system classes, this property must not be set", prop);
1640     _has_platform_or_app_classes = false;
1641   }
1642 
1643   // For backwards compatibility, we don't check the verification setting
1644   // if the archive only contains system classes.
1645   if (_has_platform_or_app_classes &&
1646       ((!_verify_local && BytecodeVerificationLocal) ||
1647        (!_verify_remote && BytecodeVerificationRemote))) {
1648     FileMapInfo::fail_continue("The shared archive file was created with less restrictive "
1649                   "verification setting than the current setting.");
1650     return false;
1651   }
1652 
1653   // Java agents are allowed during run time. Therefore, the following condition is not
1654   // checked: (!_allow_archiving_with_java_agent && AllowArchivingWithJavaAgent)
1655   // Note: _allow_archiving_with_java_agent is set in the shared archive during dump time
1656   // while AllowArchivingWithJavaAgent is set during the current run.
1657   if (_allow_archiving_with_java_agent && !AllowArchivingWithJavaAgent) {
1658     FileMapInfo::fail_continue("The setting of the AllowArchivingWithJavaAgent is different "
1659                                "from the setting in the shared archive.");
1660     return false;
1661   }
1662 
1663   if (_allow_archiving_with_java_agent) {
1664     warning("This archive was created with AllowArchivingWithJavaAgent. It should be used "
1665             "for testing purposes only and should not be used in a production environment");
1666   }
1667 
1668   return true;
1669 }
1670 
1671 bool FileMapInfo::validate_header(bool is_static) {
1672   bool status = _header->validate();
1673 
1674   if (status) {
1675     if (!ClassLoader::check_shared_paths_misc_info(_paths_misc_info, _header->_paths_misc_info_size, is_static)) {
1676       if (!PrintSharedArchiveAndExit) {
1677         fail_continue("shared class paths mismatch (hint: enable -Xlog:class+path=info to diagnose the failure)");
1678         status = false;
1679       }
1680     }
1681   }
1682 
1683   if (_paths_misc_info != NULL) {
1684     FREE_C_HEAP_ARRAY(char, _paths_misc_info);
1685     _paths_misc_info = NULL;
1686   }
1687   return status;
1688 }
1689 
1690 // Check if a given address is within one of the shared regions
1691 bool FileMapInfo::is_in_shared_region(const void* p, int idx) {
1692   assert(idx == MetaspaceShared::ro ||
1693          idx == MetaspaceShared::rw ||
1694          idx == MetaspaceShared::mc ||
1695          idx == MetaspaceShared::md, "invalid region index");
1696   char* base = region_addr(idx);
1697   if (p >= base && p < base + space_at(idx)->_used) {
1698     return true;
1699   }
1700   return false;
1701 }
1702 
1703 // Unmap mapped regions of shared space.
1704 void FileMapInfo::stop_sharing_and_unmap(const char* msg) {
1705   MetaspaceShared::set_shared_metaspace_range(NULL, NULL);
1706 
1707   FileMapInfo *map_info = FileMapInfo::current_info();
1708   if (map_info) {
1709     map_info->fail_continue("%s", msg);
1710     for (int i = 0; i < MetaspaceShared::num_non_heap_spaces; i++) {
1711       if (!HeapShared::is_heap_region(i)) {
1712         char *addr = map_info->region_addr(i);
1713         if (addr != NULL) {
1714           map_info->unmap_region(i);
1715           map_info->space_at(i)->_addr._base = NULL;
1716         }
1717       }
1718     }
1719     // Dealloc the archive heap regions only without unmapping. The regions are part
1720     // of the java heap. Unmapping of the heap regions are managed by GC.
1721     map_info->dealloc_archive_heap_regions(open_archive_heap_ranges,
1722                                            num_open_archive_heap_ranges,
1723                                            true);
1724     map_info->dealloc_archive_heap_regions(closed_archive_heap_ranges,
1725                                            num_closed_archive_heap_ranges,
1726                                            false);
1727   } else if (DumpSharedSpaces) {
1728     fail_stop("%s", msg);
1729   }
1730 }
1731 
1732 #if INCLUDE_JVMTI
1733 ClassPathEntry** FileMapInfo::_classpath_entries_for_jvmti = NULL;
1734 
1735 ClassPathEntry* FileMapInfo::get_classpath_entry_for_jvmti(int i, TRAPS) {
1736   ClassPathEntry* ent = _classpath_entries_for_jvmti[i];
1737   if (ent == NULL) {
1738     if (i == 0) {
1739       ent = ClassLoader:: get_jrt_entry();
1740       assert(ent != NULL, "must be");
1741     } else {
1742       SharedClassPathEntry* scpe = shared_path(i);
1743       assert(scpe->is_jar(), "must be"); // other types of scpe will not produce archived classes
1744 
1745       const char* path = scpe->name();
1746       struct stat st;
1747       if (os::stat(path, &st) != 0) {
1748         char *msg = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, strlen(path) + 128); ;
1749         jio_snprintf(msg, strlen(path) + 127, "error in opening JAR file %s", path);
1750         THROW_MSG_(vmSymbols::java_io_IOException(), msg, NULL);
1751       } else {
1752         ent = ClassLoader::create_class_path_entry(path, &st, /*throw_exception=*/true, false, CHECK_NULL);
1753       }
1754     }
1755 
1756     MutexLocker mu(CDSClassFileStream_lock, THREAD);
1757     if (_classpath_entries_for_jvmti[i] == NULL) {
1758       _classpath_entries_for_jvmti[i] = ent;
1759     } else {
1760       // Another thread has beat me to creating this entry
1761       delete ent;
1762       ent = _classpath_entries_for_jvmti[i];
1763     }
1764   }
1765 
1766   return ent;
1767 }
1768 
1769 ClassFileStream* FileMapInfo::open_stream_for_jvmti(InstanceKlass* ik, Handle class_loader, TRAPS) {
1770   int path_index = ik->shared_classpath_index();
1771   assert(path_index >= 0, "should be called for shared built-in classes only");
1772   assert(path_index < (int)get_number_of_shared_paths(), "sanity");
1773 
1774   ClassPathEntry* cpe = get_classpath_entry_for_jvmti(path_index, CHECK_NULL);
1775   assert(cpe != NULL, "must be");
1776 
1777   Symbol* name = ik->name();
1778   const char* const class_name = name->as_C_string();
1779   const char* const file_name = ClassLoader::file_name_for_class_name(class_name,
1780                                                                       name->utf8_length());
1781   ClassLoaderData* loader_data = ClassLoaderData::class_loader_data(class_loader());
1782   ClassFileStream* cfs = cpe->open_stream_for_loader(file_name, loader_data, THREAD);
1783   assert(cfs != NULL, "must be able to read the classfile data of shared classes for built-in loaders.");
1784   log_debug(cds, jvmti)("classfile data for %s [%d: %s] = %d bytes", class_name, path_index,
1785                         cfs->source(), cfs->length());
1786   return cfs;
1787 }
1788 
1789 #endif