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