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