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