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