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