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