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