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