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