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