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