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