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