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