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