1 /*
   2  * Copyright (c) 2012, 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_io.h"
  27 #include "cds/archiveBuilder.hpp"
  28 #include "cds/archiveHeapLoader.hpp"
  29 #include "cds/cds_globals.hpp"
  30 #include "cds/cdsProtectionDomain.hpp"
  31 #include "cds/classListWriter.hpp"
  32 #include "cds/classListParser.hpp"
  33 #include "cds/cppVtables.hpp"
  34 #include "cds/dumpAllocStats.hpp"
  35 #include "cds/filemap.hpp"
  36 #include "cds/heapShared.hpp"
  37 #include "cds/lambdaFormInvokers.hpp"
  38 #include "cds/metaspaceShared.hpp"
  39 #include "classfile/classLoaderDataGraph.hpp"
  40 #include "classfile/classLoaderDataShared.hpp"
  41 #include "classfile/classLoaderExt.hpp"
  42 #include "classfile/javaClasses.inline.hpp"
  43 #include "classfile/loaderConstraints.hpp"
  44 #include "classfile/placeholders.hpp"
  45 #include "classfile/symbolTable.hpp"
  46 #include "classfile/stringTable.hpp"
  47 #include "classfile/systemDictionary.hpp"
  48 #include "classfile/systemDictionaryShared.hpp"
  49 #include "classfile/vmClasses.hpp"
  50 #include "classfile/vmSymbols.hpp"
  51 #include "code/codeCache.hpp"
  52 #include "gc/shared/gcVMOperations.hpp"
  53 #include "interpreter/bytecodeStream.hpp"
  54 #include "interpreter/bytecodes.hpp"
  55 #include "logging/log.hpp"
  56 #include "logging/logMessage.hpp"
  57 #include "logging/logStream.hpp"
  58 #include "memory/metaspace.hpp"
  59 #include "memory/metaspaceClosure.hpp"
  60 #include "memory/resourceArea.hpp"
  61 #include "memory/universe.hpp"
  62 #include "oops/compressedOops.inline.hpp"
  63 #include "oops/flatArrayKlass.hpp"
  64 #include "oops/inlineKlass.hpp"
  65 #include "oops/instanceMirrorKlass.hpp"
  66 #include "oops/klass.inline.hpp"
  67 #include "oops/objArrayOop.hpp"
  68 #include "oops/oop.inline.hpp"
  69 #include "oops/oopHandle.hpp"
  70 #include "prims/jvmtiExport.hpp"
  71 #include "runtime/arguments.hpp"
  72 #include "runtime/globals_extension.hpp"
  73 #include "runtime/handles.inline.hpp"
  74 #include "runtime/os.inline.hpp"
  75 #include "runtime/safepointVerifiers.hpp"
  76 #include "runtime/sharedRuntime.hpp"
  77 #include "runtime/vmThread.hpp"
  78 #include "runtime/vmOperations.hpp"
  79 #include "services/memTracker.hpp"
  80 #include "utilities/align.hpp"
  81 #include "utilities/bitMap.inline.hpp"
  82 #include "utilities/ostream.hpp"
  83 #include "utilities/defaultStream.hpp"
  84 #include "utilities/resourceHash.hpp"
  85 #if INCLUDE_G1GC
  86 #include "gc/g1/g1CollectedHeap.inline.hpp"
  87 #endif
  88 
  89 ReservedSpace MetaspaceShared::_symbol_rs;
  90 VirtualSpace MetaspaceShared::_symbol_vs;
  91 bool MetaspaceShared::_has_error_classes;
  92 bool MetaspaceShared::_archive_loading_failed = false;
  93 bool MetaspaceShared::_remapped_readwrite = false;
  94 void* MetaspaceShared::_shared_metaspace_static_top = NULL;
  95 intx MetaspaceShared::_relocation_delta;
  96 char* MetaspaceShared::_requested_base_address;
  97 bool MetaspaceShared::_use_optimized_module_handling = true;
  98 bool MetaspaceShared::_use_full_module_graph = true;
  99 
 100 // The CDS archive is divided into the following regions:
 101 //     rw  - read-write metadata
 102 //     ro  - read-only metadata and read-only tables
 103 //
 104 //     ca0 - closed archive heap space #0
 105 //     ca1 - closed archive heap space #1 (may be empty)
 106 //     oa0 - open archive heap space #0
 107 //     oa1 - open archive heap space #1 (may be empty)
 108 //
 109 //     bm  - bitmap for relocating the above 7 regions.
 110 //
 111 // The rw and ro regions are linearly allocated, in the order of rw->ro.
 112 // These regions are aligned with MetaspaceShared::core_region_alignment().
 113 //
 114 // These 2 regions are populated in the following steps:
 115 // [0] All classes are loaded in MetaspaceShared::preload_classes(). All metadata are
 116 //     temporarily allocated outside of the shared regions.
 117 // [1] We enter a safepoint and allocate a buffer for the rw/ro regions.
 118 // [2] C++ vtables are copied into the rw region.
 119 // [3] ArchiveBuilder copies RW metadata into the rw region.
 120 // [4] ArchiveBuilder copies RO metadata into the ro region.
 121 // [5] SymbolTable, StringTable, SystemDictionary, and a few other read-only data
 122 //     are copied into the ro region as read-only tables.
 123 //
 124 // The ca0/ca1 and oa0/oa1 regions are populated inside HeapShared::archive_objects.
 125 // Their layout is independent of the rw/ro regions.
 126 
 127 static DumpRegion _symbol_region("symbols");
 128 
 129 char* MetaspaceShared::symbol_space_alloc(size_t num_bytes) {
 130   return _symbol_region.allocate(num_bytes);
 131 }
 132 
 133 // os::vm_allocation_granularity() is usually 4K for most OSes. However, some platforms
 134 // such as linux-aarch64 and macos-x64 ...
 135 // it can be either 4K or 64K and on macos-aarch64 it is 16K. To generate archives that are
 136 // compatible for both settings, an alternative cds core region alignment can be enabled
 137 // at building time:
 138 //   --enable-compactible-cds-alignment
 139 // Upon successful configuration, the compactible alignment then can be defined in:
 140 //   os_linux_aarch64.cpp
 141 //   os_bsd_x86.cpp
 142 size_t MetaspaceShared::core_region_alignment() {
 143   return os::cds_core_region_alignment();
 144 }
 145 
 146 static bool shared_base_valid(char* shared_base) {
 147 #ifdef _LP64
 148   return CompressedKlassPointers::is_valid_base((address)shared_base);
 149 #else
 150   return true;
 151 #endif
 152 }
 153 
 154 class DumpClassListCLDClosure : public CLDClosure {
 155   static const int INITIAL_TABLE_SIZE = 1987;
 156   static const int MAX_TABLE_SIZE = 61333;
 157 
 158   fileStream *_stream;
 159   ResizeableResourceHashtable<InstanceKlass*, bool,
 160                               ResourceObj::C_HEAP, mtClassShared> _dumped_classes;
 161 
 162   void dump(InstanceKlass* ik) {
 163     bool created;
 164     _dumped_classes.put_if_absent(ik, &created);
 165     if (!created) {
 166       return;
 167     }
 168     if (_dumped_classes.maybe_grow()) {
 169       log_info(cds, hashtables)("Expanded _dumped_classes table to %d", _dumped_classes.table_size());
 170     }
 171     if (ik->java_super()) {
 172       dump(ik->java_super());
 173     }
 174     Array<InstanceKlass*>* interfaces = ik->local_interfaces();
 175     int len = interfaces->length();
 176     for (int i = 0; i < len; i++) {
 177       dump(interfaces->at(i));
 178     }
 179     ClassListWriter::write_to_stream(ik, _stream);
 180   }
 181 
 182 public:
 183   DumpClassListCLDClosure(fileStream* f)
 184   : CLDClosure(), _dumped_classes(INITIAL_TABLE_SIZE, MAX_TABLE_SIZE) {
 185     _stream = f;
 186   }
 187 
 188   void do_cld(ClassLoaderData* cld) {
 189     for (Klass* klass = cld->klasses(); klass != NULL; klass = klass->next_link()) {
 190       if (klass->is_instance_klass()) {
 191         dump(InstanceKlass::cast(klass));
 192       }
 193     }
 194   }
 195 };
 196 
 197 void MetaspaceShared::dump_loaded_classes(const char* file_name, TRAPS) {
 198   fileStream stream(file_name, "w");
 199   if (stream.is_open()) {
 200     MutexLocker lock(ClassLoaderDataGraph_lock);
 201     MutexLocker lock2(ClassListFile_lock, Mutex::_no_safepoint_check_flag);
 202     DumpClassListCLDClosure collect_classes(&stream);
 203     ClassLoaderDataGraph::loaded_cld_do(&collect_classes);
 204   } else {
 205     THROW_MSG(vmSymbols::java_io_IOException(), "Failed to open file");
 206   }
 207 }
 208 
 209 static bool shared_base_too_high(char* specified_base, char* aligned_base, size_t cds_max) {
 210   if (specified_base != NULL && aligned_base < specified_base) {
 211     // SharedBaseAddress is very high (e.g., 0xffffffffffffff00) so
 212     // align_up(SharedBaseAddress, MetaspaceShared::core_region_alignment()) has wrapped around.
 213     return true;
 214   }
 215   if (max_uintx - uintx(aligned_base) < uintx(cds_max)) {
 216     // The end of the archive will wrap around
 217     return true;
 218   }
 219 
 220   return false;
 221 }
 222 
 223 static char* compute_shared_base(size_t cds_max) {
 224   char* specified_base = (char*)SharedBaseAddress;
 225   char* aligned_base = align_up(specified_base, MetaspaceShared::core_region_alignment());
 226 
 227   const char* err = NULL;
 228   if (shared_base_too_high(specified_base, aligned_base, cds_max)) {
 229     err = "too high";
 230   } else if (!shared_base_valid(aligned_base)) {
 231     err = "invalid for this platform";
 232   } else {
 233     return aligned_base;
 234   }
 235 
 236   log_warning(cds)("SharedBaseAddress (" INTPTR_FORMAT ") is %s. Reverted to " INTPTR_FORMAT,
 237                    p2i((void*)SharedBaseAddress), err,
 238                    p2i((void*)Arguments::default_SharedBaseAddress()));
 239 
 240   specified_base = (char*)Arguments::default_SharedBaseAddress();
 241   aligned_base = align_up(specified_base, MetaspaceShared::core_region_alignment());
 242 
 243   // Make sure the default value of SharedBaseAddress specified in globals.hpp is sane.
 244   assert(!shared_base_too_high(specified_base, aligned_base, cds_max), "Sanity");
 245   assert(shared_base_valid(aligned_base), "Sanity");
 246   return aligned_base;
 247 }
 248 
 249 void MetaspaceShared::initialize_for_static_dump() {
 250   assert(DumpSharedSpaces, "should be called for dump time only");
 251   log_info(cds)("Core region alignment: " SIZE_FORMAT, core_region_alignment());
 252   // The max allowed size for CDS archive. We use this to limit SharedBaseAddress
 253   // to avoid address space wrap around.
 254   size_t cds_max;
 255   const size_t reserve_alignment = core_region_alignment();
 256 
 257 #ifdef _LP64
 258   const uint64_t UnscaledClassSpaceMax = (uint64_t(max_juint) + 1);
 259   cds_max = align_down(UnscaledClassSpaceMax, reserve_alignment);
 260 #else
 261   // We don't support archives larger than 256MB on 32-bit due to limited
 262   //  virtual address space.
 263   cds_max = align_down(256*M, reserve_alignment);
 264 #endif
 265 
 266   _requested_base_address = compute_shared_base(cds_max);
 267   SharedBaseAddress = (size_t)_requested_base_address;
 268 
 269   size_t symbol_rs_size = LP64_ONLY(3 * G) NOT_LP64(128 * M);
 270   _symbol_rs = ReservedSpace(symbol_rs_size);
 271   if (!_symbol_rs.is_reserved()) {
 272     vm_exit_during_initialization("Unable to reserve memory for symbols",
 273                                   err_msg(SIZE_FORMAT " bytes.", symbol_rs_size));
 274   }
 275   _symbol_region.init(&_symbol_rs, &_symbol_vs);
 276 }
 277 
 278 // Called by universe_post_init()
 279 void MetaspaceShared::post_initialize(TRAPS) {
 280   if (UseSharedSpaces) {
 281     int size = FileMapInfo::get_number_of_shared_paths();
 282     if (size > 0) {
 283       CDSProtectionDomain::allocate_shared_data_arrays(size, CHECK);
 284       if (!DynamicDumpSharedSpaces) {
 285         FileMapInfo* info;
 286         if (FileMapInfo::dynamic_info() == NULL) {
 287           info = FileMapInfo::current_info();
 288         } else {
 289           info = FileMapInfo::dynamic_info();
 290         }
 291         ClassLoaderExt::init_paths_start_index(info->app_class_paths_start_index());
 292         ClassLoaderExt::init_app_module_paths_start_index(info->app_module_paths_start_index());
 293       }
 294     }
 295   }
 296 }
 297 
 298 static GrowableArrayCHeap<OopHandle, mtClassShared>* _extra_interned_strings = NULL;
 299 static GrowableArrayCHeap<Symbol*, mtClassShared>* _extra_symbols = NULL;
 300 
 301 void MetaspaceShared::read_extra_data(JavaThread* current, const char* filename) {
 302   _extra_interned_strings = new GrowableArrayCHeap<OopHandle, mtClassShared>(10000);
 303   _extra_symbols = new GrowableArrayCHeap<Symbol*, mtClassShared>(1000);
 304 
 305   HashtableTextDump reader(filename);
 306   reader.check_version("VERSION: 1.0");
 307 
 308   while (reader.remain() > 0) {
 309     int utf8_length;
 310     int prefix_type = reader.scan_prefix(&utf8_length);
 311     ResourceMark rm(current);
 312     if (utf8_length == 0x7fffffff) {
 313       // buf_len will overflown 32-bit value.
 314       vm_exit_during_initialization(err_msg("string length too large: %d", utf8_length));
 315     }
 316     int buf_len = utf8_length+1;
 317     char* utf8_buffer = NEW_RESOURCE_ARRAY(char, buf_len);
 318     reader.get_utf8(utf8_buffer, utf8_length);
 319     utf8_buffer[utf8_length] = '\0';
 320 
 321     if (prefix_type == HashtableTextDump::SymbolPrefix) {
 322       _extra_symbols->append(SymbolTable::new_permanent_symbol(utf8_buffer));
 323     } else{
 324       assert(prefix_type == HashtableTextDump::StringPrefix, "Sanity");
 325       ExceptionMark em(current);
 326       JavaThread* THREAD = current; // For exception macros.
 327       oop str = StringTable::intern(utf8_buffer, THREAD);
 328 
 329       if (HAS_PENDING_EXCEPTION) {
 330         log_warning(cds, heap)("[line %d] extra interned string allocation failed; size too large: %d",
 331                                reader.last_line_no(), utf8_length);
 332         CLEAR_PENDING_EXCEPTION;
 333       } else {
 334 #if INCLUDE_G1GC
 335         if (UseG1GC) {
 336           typeArrayOop body = java_lang_String::value(str);
 337           const HeapRegion* hr = G1CollectedHeap::heap()->heap_region_containing(body);
 338           if (hr->is_humongous()) {
 339             // Don't keep it alive, so it will be GC'ed before we dump the strings, in order
 340             // to maximize free heap space and minimize fragmentation.
 341             log_warning(cds, heap)("[line %d] extra interned string ignored; size too large: %d",
 342                                 reader.last_line_no(), utf8_length);
 343             continue;
 344           }
 345         }
 346 #endif
 347         // Make sure this string is included in the dumped interned string table.
 348         assert(str != NULL, "must succeed");
 349         _extra_interned_strings->append(OopHandle(Universe::vm_global(), str));
 350       }
 351     }
 352   }
 353 }
 354 
 355 // Read/write a data stream for restoring/preserving metadata pointers and
 356 // miscellaneous data from/to the shared archive file.
 357 
 358 void MetaspaceShared::serialize(SerializeClosure* soc) {
 359   int tag = 0;
 360   soc->do_tag(--tag);
 361 
 362   // Verify the sizes of various metadata in the system.
 363   soc->do_tag(sizeof(Method));
 364   soc->do_tag(sizeof(ConstMethod));
 365   soc->do_tag(arrayOopDesc::base_offset_in_bytes(T_BYTE));
 366   soc->do_tag(sizeof(ConstantPool));
 367   soc->do_tag(sizeof(ConstantPoolCache));
 368   soc->do_tag(objArrayOopDesc::base_offset_in_bytes());
 369   soc->do_tag(typeArrayOopDesc::base_offset_in_bytes(T_BYTE));
 370   soc->do_tag(sizeof(Symbol));
 371 
 372   // Need to do this first, as subsequent steps may call virtual functions
 373   // in archived Metadata objects.
 374   CppVtables::serialize(soc);
 375   soc->do_tag(--tag);
 376 
 377   // Dump/restore miscellaneous metadata.
 378   JavaClasses::serialize_offsets(soc);
 379   Universe::serialize(soc);
 380   soc->do_tag(--tag);
 381 
 382   // Dump/restore references to commonly used names and signatures.
 383   vmSymbols::serialize(soc);
 384   soc->do_tag(--tag);
 385 
 386   // Dump/restore the symbol/string/subgraph_info tables
 387   SymbolTable::serialize_shared_table_header(soc);
 388   StringTable::serialize_shared_table_header(soc);
 389   HeapShared::serialize(soc);
 390   SystemDictionaryShared::serialize_dictionary_headers(soc);
 391 
 392   InstanceMirrorKlass::serialize_offsets(soc);
 393 
 394   // Dump/restore well known classes (pointers)
 395   SystemDictionaryShared::serialize_vm_classes(soc);
 396   soc->do_tag(--tag);
 397 
 398   CDS_JAVA_HEAP_ONLY(ClassLoaderDataShared::serialize(soc);)
 399 
 400   LambdaFormInvokers::serialize(soc);
 401   soc->do_tag(666);
 402 }
 403 
 404 static void rewrite_nofast_bytecode(const methodHandle& method) {
 405   BytecodeStream bcs(method);
 406   while (!bcs.is_last_bytecode()) {
 407     Bytecodes::Code opcode = bcs.next();
 408     switch (opcode) {
 409     case Bytecodes::_getfield:      *bcs.bcp() = Bytecodes::_nofast_getfield;      break;
 410     case Bytecodes::_putfield:      *bcs.bcp() = Bytecodes::_nofast_putfield;      break;
 411     case Bytecodes::_aload_0:       *bcs.bcp() = Bytecodes::_nofast_aload_0;       break;
 412     case Bytecodes::_iload: {
 413       if (!bcs.is_wide()) {
 414         *bcs.bcp() = Bytecodes::_nofast_iload;
 415       }
 416       break;
 417     }
 418     default: break;
 419     }
 420   }
 421 }
 422 
 423 // [1] Rewrite all bytecodes as needed, so that the ConstMethod* will not be modified
 424 //     at run time by RewriteBytecodes/RewriteFrequentPairs
 425 // [2] Assign a fingerprint, so one doesn't need to be assigned at run-time.
 426 void MetaspaceShared::rewrite_nofast_bytecodes_and_calculate_fingerprints(Thread* thread, InstanceKlass* ik) {
 427   for (int i = 0; i < ik->methods()->length(); i++) {
 428     methodHandle m(thread, ik->methods()->at(i));
 429     if (ik->can_be_verified_at_dumptime() && ik->is_linked()) {
 430       rewrite_nofast_bytecode(m);
 431     }
 432     Fingerprinter fp(m);
 433     // The side effect of this call sets method's fingerprint field.
 434     fp.fingerprint();
 435   }
 436 }
 437 
 438 class VM_PopulateDumpSharedSpace : public VM_GC_Operation {
 439 private:
 440   GrowableArray<MemRegion> *_closed_heap_regions;
 441   GrowableArray<MemRegion> *_open_heap_regions;
 442 
 443   GrowableArray<ArchiveHeapOopmapInfo> *_closed_heap_oopmaps;
 444   GrowableArray<ArchiveHeapOopmapInfo> *_open_heap_oopmaps;
 445 
 446   void dump_java_heap_objects(GrowableArray<Klass*>* klasses) NOT_CDS_JAVA_HEAP_RETURN;
 447   void dump_heap_oopmaps() NOT_CDS_JAVA_HEAP_RETURN;
 448   void dump_heap_oopmaps(GrowableArray<MemRegion>* regions,
 449                                  GrowableArray<ArchiveHeapOopmapInfo>* oopmaps);
 450   void dump_shared_symbol_table(GrowableArray<Symbol*>* symbols) {
 451     log_info(cds)("Dumping symbol table ...");
 452     SymbolTable::write_to_archive(symbols);
 453   }
 454   char* dump_read_only_tables();
 455 
 456 public:
 457 
 458   VM_PopulateDumpSharedSpace() :
 459     VM_GC_Operation(0 /* total collections, ignored */, GCCause::_archive_time_gc),
 460     _closed_heap_regions(NULL),
 461     _open_heap_regions(NULL),
 462     _closed_heap_oopmaps(NULL),
 463     _open_heap_oopmaps(NULL) {}
 464 
 465   bool skip_operation() const { return false; }
 466 
 467   VMOp_Type type() const { return VMOp_PopulateDumpSharedSpace; }
 468   void doit();   // outline because gdb sucks
 469   bool allow_nested_vm_operations() const { return true; }
 470 }; // class VM_PopulateDumpSharedSpace
 471 
 472 class StaticArchiveBuilder : public ArchiveBuilder {
 473 public:
 474   StaticArchiveBuilder() : ArchiveBuilder() {}
 475 
 476   virtual void iterate_roots(MetaspaceClosure* it, bool is_relocating_pointers) {
 477     FileMapInfo::metaspace_pointers_do(it, false);
 478     SystemDictionaryShared::dumptime_classes_do(it);
 479     Universe::metaspace_pointers_do(it);
 480     vmSymbols::metaspace_pointers_do(it);
 481 
 482     // The above code should find all the symbols that are referenced by the
 483     // archived classes. We just need to add the extra symbols which
 484     // may not be used by any of the archived classes -- these are usually
 485     // symbols that we anticipate to be used at run time, so we can store
 486     // them in the RO region, to be shared across multiple processes.
 487     if (_extra_symbols != NULL) {
 488       for (int i = 0; i < _extra_symbols->length(); i++) {
 489         it->push(_extra_symbols->adr_at(i));
 490       }
 491     }
 492   }
 493 };
 494 
 495 char* VM_PopulateDumpSharedSpace::dump_read_only_tables() {
 496   ArchiveBuilder::OtherROAllocMark mark;
 497 
 498   SystemDictionaryShared::write_to_archive();
 499 
 500   // Write lambform lines into archive
 501   LambdaFormInvokers::dump_static_archive_invokers();
 502   // Write the other data to the output array.
 503   DumpRegion* ro_region = ArchiveBuilder::current()->ro_region();
 504   char* start = ro_region->top();
 505   WriteClosure wc(ro_region);
 506   MetaspaceShared::serialize(&wc);
 507 
 508   // Write the bitmaps for patching the archive heap regions
 509   dump_heap_oopmaps();
 510 
 511   return start;
 512 }
 513 
 514 void VM_PopulateDumpSharedSpace::doit() {
 515   HeapShared::run_full_gc_in_vm_thread();
 516 
 517   DEBUG_ONLY(SystemDictionaryShared::NoClassLoadingMark nclm);
 518 
 519   FileMapInfo::check_nonempty_dir_in_shared_path_table();
 520 
 521   NOT_PRODUCT(SystemDictionary::verify();)
 522 
 523   // Block concurrent class unloading from changing the _dumptime_table
 524   MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
 525   SystemDictionaryShared::check_excluded_classes();
 526 
 527   StaticArchiveBuilder builder;
 528   builder.gather_source_objs();
 529   builder.reserve_buffer();
 530 
 531   char* cloned_vtables = CppVtables::dumptime_init(&builder);
 532 
 533   builder.dump_rw_metadata();
 534   builder.dump_ro_metadata();
 535   builder.relocate_metaspaceobj_embedded_pointers();
 536 
 537   // Dump supported java heap objects
 538   dump_java_heap_objects(builder.klasses());
 539 
 540   builder.relocate_roots();
 541   dump_shared_symbol_table(builder.symbols());
 542 
 543   builder.relocate_vm_classes();
 544 
 545   log_info(cds)("Make classes shareable");
 546   builder.make_klasses_shareable();
 547 
 548   char* serialized_data = dump_read_only_tables();
 549 
 550   SystemDictionaryShared::adjust_lambda_proxy_class_dictionary();
 551 
 552   // The vtable clones contain addresses of the current process.
 553   // We don't want to write these addresses into the archive.
 554   CppVtables::zero_archived_vtables();
 555 
 556   // relocate the data so that it can be mapped to MetaspaceShared::requested_base_address()
 557   // without runtime relocation.
 558   builder.relocate_to_requested();
 559 
 560   // Write the archive file
 561   const char* static_archive = Arguments::GetSharedArchivePath();
 562   assert(static_archive != nullptr, "SharedArchiveFile not set?");
 563   FileMapInfo* mapinfo = new FileMapInfo(static_archive, true);
 564   mapinfo->populate_header(MetaspaceShared::core_region_alignment());
 565   mapinfo->set_serialized_data(serialized_data);
 566   mapinfo->set_cloned_vtables(cloned_vtables);
 567   mapinfo->open_for_write();
 568   builder.write_archive(mapinfo,
 569                         _closed_heap_regions,
 570                         _open_heap_regions,
 571                         _closed_heap_oopmaps,
 572                         _open_heap_oopmaps);
 573 
 574   if (PrintSystemDictionaryAtExit) {
 575     SystemDictionary::print();
 576   }
 577 
 578   if (AllowArchivingWithJavaAgent) {
 579     warning("This archive was created with AllowArchivingWithJavaAgent. It should be used "
 580             "for testing purposes only and should not be used in a production environment");
 581   }
 582 
 583   // There may be pending VM operations. We have changed some global states
 584   // (such as vmClasses::_klasses) that may cause these VM operations
 585   // to fail. For safety, forget these operations and exit the VM directly.
 586   os::_exit(0);
 587 }
 588 
 589 class CollectCLDClosure : public CLDClosure {
 590   GrowableArray<ClassLoaderData*> _loaded_cld;
 591   GrowableArray<OopHandle> _loaded_cld_handles; // keep the CLDs alive
 592   Thread* _current_thread;
 593 public:
 594   CollectCLDClosure(Thread* thread) : _current_thread(thread) {}
 595   ~CollectCLDClosure() {
 596     for (int i = 0; i < _loaded_cld_handles.length(); i++) {
 597       _loaded_cld_handles.at(i).release(Universe::vm_global());
 598     }
 599   }
 600   void do_cld(ClassLoaderData* cld) {
 601     assert(cld->is_alive(), "must be");
 602     _loaded_cld.append(cld);
 603     _loaded_cld_handles.append(OopHandle(Universe::vm_global(), cld->holder()));
 604   }
 605 
 606   int nof_cld() const                { return _loaded_cld.length(); }
 607   ClassLoaderData* cld_at(int index) { return _loaded_cld.at(index); }
 608 };
 609 
 610 // Check if we can eagerly link this class at dump time, so we can avoid the
 611 // runtime linking overhead (especially verification)
 612 bool MetaspaceShared::may_be_eagerly_linked(InstanceKlass* ik) {
 613   if (!ik->can_be_verified_at_dumptime()) {
 614     // For old classes, try to leave them in the unlinked state, so
 615     // we can still store them in the archive. They must be
 616     // linked/verified at runtime.
 617     return false;
 618   }
 619   if (DynamicDumpSharedSpaces && ik->is_shared_unregistered_class()) {
 620     // Linking of unregistered classes at this stage may cause more
 621     // classes to be resolved, resulting in calls to ClassLoader.loadClass()
 622     // that may not be expected by custom class loaders.
 623     //
 624     // It's OK to do this for the built-in loaders as we know they can
 625     // tolerate this. (Note that unregistered classes are loaded by the NULL
 626     // loader during DumpSharedSpaces).
 627     return false;
 628   }
 629   return true;
 630 }
 631 
 632 bool MetaspaceShared::link_class_for_cds(InstanceKlass* ik, TRAPS) {
 633   // Link the class to cause the bytecodes to be rewritten and the
 634   // cpcache to be created. Class verification is done according
 635   // to -Xverify setting.
 636   bool res = MetaspaceShared::try_link_class(THREAD, ik);
 637 
 638   if (DumpSharedSpaces) {
 639     // The following function is used to resolve all Strings in the statically
 640     // dumped classes to archive all the Strings. The archive heap is not supported
 641     // for the dynamic archive.
 642     ik->constants()->resolve_class_constants(CHECK_(false)); // may throw OOM when interning strings.
 643   }
 644   return res;
 645 }
 646 
 647 void MetaspaceShared::link_shared_classes(bool jcmd_request, TRAPS) {
 648   if (!jcmd_request) {
 649     LambdaFormInvokers::regenerate_holder_classes(CHECK);
 650   }
 651 
 652   // Collect all loaded ClassLoaderData.
 653   CollectCLDClosure collect_cld(THREAD);
 654   {
 655     // ClassLoaderDataGraph::loaded_cld_do requires ClassLoaderDataGraph_lock.
 656     // We cannot link the classes while holding this lock (or else we may run into deadlock).
 657     // Therefore, we need to first collect all the CLDs, and then link their classes after
 658     // releasing the lock.
 659     MutexLocker lock(ClassLoaderDataGraph_lock);
 660     ClassLoaderDataGraph::loaded_cld_do(&collect_cld);
 661   }
 662 
 663   while (true) {
 664     bool has_linked = false;
 665     for (int i = 0; i < collect_cld.nof_cld(); i++) {
 666       ClassLoaderData* cld = collect_cld.cld_at(i);
 667       for (Klass* klass = cld->klasses(); klass != NULL; klass = klass->next_link()) {
 668         if (klass->is_instance_klass()) {
 669           InstanceKlass* ik = InstanceKlass::cast(klass);
 670           if (may_be_eagerly_linked(ik)) {
 671             has_linked |= link_class_for_cds(ik, CHECK);
 672           }
 673         }
 674       }
 675     }
 676 
 677     if (!has_linked) {
 678       break;
 679     }
 680     // Class linking includes verification which may load more classes.
 681     // Keep scanning until we have linked no more classes.
 682   }
 683 }
 684 
 685 void MetaspaceShared::prepare_for_dumping() {
 686   Arguments::assert_is_dumping_archive();
 687   Arguments::check_unsupported_dumping_properties();
 688 
 689   ClassLoader::initialize_shared_path(JavaThread::current());
 690 }
 691 
 692 // Preload classes from a list, populate the shared spaces and dump to a
 693 // file.
 694 void MetaspaceShared::preload_and_dump() {
 695   EXCEPTION_MARK;
 696   ResourceMark rm(THREAD);
 697   preload_and_dump_impl(THREAD);
 698   if (HAS_PENDING_EXCEPTION) {
 699     if (PENDING_EXCEPTION->is_a(vmClasses::OutOfMemoryError_klass())) {
 700       vm_direct_exit(-1,  err_msg("Out of memory. Please run with a larger Java heap, current MaxHeapSize = "
 701                                   SIZE_FORMAT "M", MaxHeapSize/M));
 702     } else {
 703       log_error(cds)("%s: %s", PENDING_EXCEPTION->klass()->external_name(),
 704                      java_lang_String::as_utf8_string(java_lang_Throwable::message(PENDING_EXCEPTION)));
 705       vm_direct_exit(-1, "VM exits due to exception, use -Xlog:cds,exceptions=trace for detail");
 706     }
 707   } else {
 708     // On success, the VM_PopulateDumpSharedSpace op should have
 709     // exited the VM.
 710     ShouldNotReachHere();
 711   }
 712 }
 713 
 714 #if INCLUDE_CDS_JAVA_HEAP && defined(_LP64)
 715 void MetaspaceShared::adjust_heap_sizes_for_dumping() {
 716   if (!DumpSharedSpaces || UseCompressedOops) {
 717     return;
 718   }
 719   // CDS heap dumping requires all string oops to have an offset
 720   // from the heap bottom that can be encoded in 32-bit.
 721   julong max_heap_size = (julong)(4 * G);
 722 
 723   if (MinHeapSize > max_heap_size) {
 724     log_debug(cds)("Setting MinHeapSize to 4G for CDS dumping, original size = " SIZE_FORMAT "M", MinHeapSize/M);
 725     FLAG_SET_ERGO(MinHeapSize, max_heap_size);
 726   }
 727   if (InitialHeapSize > max_heap_size) {
 728     log_debug(cds)("Setting InitialHeapSize to 4G for CDS dumping, original size = " SIZE_FORMAT "M", InitialHeapSize/M);
 729     FLAG_SET_ERGO(InitialHeapSize, max_heap_size);
 730   }
 731   if (MaxHeapSize > max_heap_size) {
 732     log_debug(cds)("Setting MaxHeapSize to 4G for CDS dumping, original size = " SIZE_FORMAT "M", MaxHeapSize/M);
 733     FLAG_SET_ERGO(MaxHeapSize, max_heap_size);
 734   }
 735 }
 736 #endif // INCLUDE_CDS_JAVA_HEAP && _LP64
 737 
 738 void MetaspaceShared::preload_classes(TRAPS) {
 739   char default_classlist[JVM_MAXPATHLEN];
 740   const char* classlist_path;
 741 
 742   if (SharedClassListFile == NULL) {
 743     // Construct the path to the class list (in jre/lib)
 744     // Walk up two directories from the location of the VM and
 745     // optionally tack on "lib" (depending on platform)
 746     os::jvm_path(default_classlist, sizeof(default_classlist));
 747     for (int i = 0; i < 3; i++) {
 748       char *end = strrchr(default_classlist, *os::file_separator());
 749       if (end != NULL) *end = '\0';
 750     }
 751     int classlist_path_len = (int)strlen(default_classlist);
 752     if (classlist_path_len >= 3) {
 753       if (strcmp(default_classlist + classlist_path_len - 3, "lib") != 0) {
 754         if (classlist_path_len < JVM_MAXPATHLEN - 4) {
 755           jio_snprintf(default_classlist + classlist_path_len,
 756                        sizeof(default_classlist) - classlist_path_len,
 757                        "%slib", os::file_separator());
 758           classlist_path_len += 4;
 759         }
 760       }
 761     }
 762     if (classlist_path_len < JVM_MAXPATHLEN - 10) {
 763       jio_snprintf(default_classlist + classlist_path_len,
 764                    sizeof(default_classlist) - classlist_path_len,
 765                    "%sclasslist", os::file_separator());
 766     }
 767     classlist_path = default_classlist;
 768   } else {
 769     classlist_path = SharedClassListFile;
 770   }
 771 
 772   log_info(cds)("Loading classes to share ...");
 773   _has_error_classes = false;
 774   int class_count = parse_classlist(classlist_path, CHECK);
 775   if (ExtraSharedClassListFile) {
 776     class_count += parse_classlist(ExtraSharedClassListFile, CHECK);
 777   }
 778 
 779   // Exercise the manifest processing code to ensure classes used by CDS at runtime
 780   // are always archived
 781   const char* dummy = "Manifest-Version: 1.0\n";
 782   CDSProtectionDomain::create_jar_manifest(dummy, strlen(dummy), CHECK);
 783 
 784   log_info(cds)("Loading classes to share: done.");
 785   log_info(cds)("Shared spaces: preloaded %d classes", class_count);
 786 }
 787 
 788 void MetaspaceShared::preload_and_dump_impl(TRAPS) {
 789   preload_classes(CHECK);
 790 
 791   if (SharedArchiveConfigFile) {
 792     log_info(cds)("Reading extra data from %s ...", SharedArchiveConfigFile);
 793     read_extra_data(THREAD, SharedArchiveConfigFile);
 794     log_info(cds)("Reading extra data: done.");
 795   }
 796 
 797   HeapShared::init_for_dumping(CHECK);
 798 
 799   // Rewrite and link classes
 800   log_info(cds)("Rewriting and linking classes ...");
 801 
 802   // Link any classes which got missed. This would happen if we have loaded classes that
 803   // were not explicitly specified in the classlist. E.g., if an interface implemented by class K
 804   // fails verification, all other interfaces that were not specified in the classlist but
 805   // are implemented by K are not verified.
 806   link_shared_classes(false/*not from jcmd*/, CHECK);
 807   log_info(cds)("Rewriting and linking classes: done");
 808 
 809 #if INCLUDE_CDS_JAVA_HEAP
 810     if (use_full_module_graph()) {
 811       HeapShared::reset_archived_object_states(CHECK);
 812     }
 813 #endif
 814 
 815   VM_PopulateDumpSharedSpace op;
 816   VMThread::execute(&op);
 817 }
 818 
 819 
 820 int MetaspaceShared::parse_classlist(const char* classlist_path, TRAPS) {
 821   ClassListParser parser(classlist_path);
 822   return parser.parse(THREAD); // returns the number of classes loaded.
 823 }
 824 
 825 // Returns true if the class's status has changed.
 826 bool MetaspaceShared::try_link_class(JavaThread* current, InstanceKlass* ik) {
 827   ExceptionMark em(current);
 828   JavaThread* THREAD = current; // For exception macros.
 829   Arguments::assert_is_dumping_archive();
 830   if (ik->is_loaded() && !ik->is_linked() && ik->can_be_verified_at_dumptime() &&
 831       !SystemDictionaryShared::has_class_failed_verification(ik)) {
 832     bool saved = BytecodeVerificationLocal;
 833     if (ik->is_shared_unregistered_class() && ik->class_loader() == NULL) {
 834       // The verification decision is based on BytecodeVerificationRemote
 835       // for non-system classes. Since we are using the NULL classloader
 836       // to load non-system classes for customized class loaders during dumping,
 837       // we need to temporarily change BytecodeVerificationLocal to be the same as
 838       // BytecodeVerificationRemote. Note this can cause the parent system
 839       // classes also being verified. The extra overhead is acceptable during
 840       // dumping.
 841       BytecodeVerificationLocal = BytecodeVerificationRemote;
 842     }
 843     ik->link_class(THREAD);
 844     if (HAS_PENDING_EXCEPTION) {
 845       ResourceMark rm(THREAD);
 846       log_warning(cds)("Preload Warning: Verification failed for %s",
 847                     ik->external_name());
 848       CLEAR_PENDING_EXCEPTION;
 849       SystemDictionaryShared::set_class_has_failed_verification(ik);
 850       _has_error_classes = true;
 851     }
 852     BytecodeVerificationLocal = saved;
 853     return true;
 854   } else {
 855     return false;
 856   }
 857 }
 858 
 859 #if INCLUDE_CDS_JAVA_HEAP
 860 void VM_PopulateDumpSharedSpace::dump_java_heap_objects(GrowableArray<Klass*>* klasses) {
 861   if(!HeapShared::can_write()) {
 862     log_info(cds)(
 863       "Archived java heap is not supported as UseG1GC "
 864       "and UseCompressedClassPointers are required."
 865       "Current settings: UseG1GC=%s, UseCompressedClassPointers=%s.",
 866       BOOL_TO_STR(UseG1GC), BOOL_TO_STR(UseCompressedClassPointers));
 867     return;
 868   }
 869   // Find all the interned strings that should be dumped.
 870   int i;
 871   for (i = 0; i < klasses->length(); i++) {
 872     Klass* k = klasses->at(i);
 873     if (k->is_instance_klass()) {
 874       InstanceKlass* ik = InstanceKlass::cast(k);
 875       if (ik->is_linked()) {
 876         ik->constants()->add_dumped_interned_strings();
 877       }
 878     }
 879   }
 880   if (_extra_interned_strings != NULL) {
 881     for (i = 0; i < _extra_interned_strings->length(); i ++) {
 882       OopHandle string = _extra_interned_strings->at(i);
 883       HeapShared::add_to_dumped_interned_strings(string.resolve());
 884     }
 885   }
 886 
 887   // The closed and open archive heap space has maximum two regions.
 888   // See FileMapInfo::write_heap_regions() for details.
 889   _closed_heap_regions = new GrowableArray<MemRegion>(2);
 890   _open_heap_regions = new GrowableArray<MemRegion>(2);
 891   HeapShared::archive_objects(_closed_heap_regions, _open_heap_regions);
 892   ArchiveBuilder::OtherROAllocMark mark;
 893   HeapShared::write_subgraph_info_table();
 894 }
 895 
 896 void VM_PopulateDumpSharedSpace::dump_heap_oopmaps() {
 897   if (HeapShared::can_write()) {
 898     _closed_heap_oopmaps = new GrowableArray<ArchiveHeapOopmapInfo>(2);
 899     dump_heap_oopmaps(_closed_heap_regions, _closed_heap_oopmaps);
 900 
 901     _open_heap_oopmaps = new GrowableArray<ArchiveHeapOopmapInfo>(2);
 902     dump_heap_oopmaps(_open_heap_regions, _open_heap_oopmaps);
 903   }
 904 }
 905 
 906 void VM_PopulateDumpSharedSpace::dump_heap_oopmaps(GrowableArray<MemRegion>* regions,
 907                                                    GrowableArray<ArchiveHeapOopmapInfo>* oopmaps) {
 908   for (int i=0; i<regions->length(); i++) {
 909     ResourceBitMap oopmap = HeapShared::calculate_oopmap(regions->at(i));
 910     size_t size_in_bits = oopmap.size();
 911     size_t size_in_bytes = oopmap.size_in_bytes();
 912     uintptr_t* buffer = (uintptr_t*)NEW_C_HEAP_ARRAY(char, size_in_bytes, mtInternal);
 913     oopmap.write_to(buffer, size_in_bytes);
 914     log_info(cds, heap)("Oopmap = " INTPTR_FORMAT " (" SIZE_FORMAT_W(6) " bytes) for heap region "
 915                         INTPTR_FORMAT " (" SIZE_FORMAT_W(8) " bytes)",
 916                         p2i(buffer), size_in_bytes,
 917                         p2i(regions->at(i).start()), regions->at(i).byte_size());
 918 
 919     ArchiveHeapOopmapInfo info;
 920     info._oopmap = (address)buffer;
 921     info._oopmap_size_in_bits = size_in_bits;
 922     info._oopmap_size_in_bytes = size_in_bytes;
 923     oopmaps->append(info);
 924   }
 925 }
 926 #endif // INCLUDE_CDS_JAVA_HEAP
 927 
 928 void MetaspaceShared::set_shared_metaspace_range(void* base, void *static_top, void* top) {
 929   assert(base <= static_top && static_top <= top, "must be");
 930   _shared_metaspace_static_top = static_top;
 931   MetaspaceObj::set_shared_metaspace_range(base, top);
 932 }
 933 
 934 // Return true if given address is in the misc data region
 935 bool MetaspaceShared::is_in_shared_region(const void* p, int idx) {
 936   return UseSharedSpaces && FileMapInfo::current_info()->is_in_shared_region(p, idx);
 937 }
 938 
 939 bool MetaspaceShared::is_shared_dynamic(void* p) {
 940   if ((p < MetaspaceObj::shared_metaspace_top()) &&
 941       (p >= _shared_metaspace_static_top)) {
 942     return true;
 943   } else {
 944     return false;
 945   }
 946 }
 947 
 948 void MetaspaceShared::initialize_runtime_shared_and_meta_spaces() {
 949   assert(UseSharedSpaces, "Must be called when UseSharedSpaces is enabled");
 950   MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE;
 951 
 952   FileMapInfo* static_mapinfo = open_static_archive();
 953   FileMapInfo* dynamic_mapinfo = NULL;
 954 
 955   if (static_mapinfo != NULL) {
 956     log_info(cds)("Core region alignment: " SIZE_FORMAT, static_mapinfo->core_region_alignment());
 957     dynamic_mapinfo = open_dynamic_archive();
 958 
 959     // First try to map at the requested address
 960     result = map_archives(static_mapinfo, dynamic_mapinfo, true);
 961     if (result == MAP_ARCHIVE_MMAP_FAILURE) {
 962       // Mapping has failed (probably due to ASLR). Let's map at an address chosen
 963       // by the OS.
 964       log_info(cds)("Try to map archive(s) at an alternative address");
 965       result = map_archives(static_mapinfo, dynamic_mapinfo, false);
 966     }
 967   }
 968 
 969   if (result == MAP_ARCHIVE_SUCCESS) {
 970     bool dynamic_mapped = (dynamic_mapinfo != NULL && dynamic_mapinfo->is_mapped());
 971     char* cds_base = static_mapinfo->mapped_base();
 972     char* cds_end =  dynamic_mapped ? dynamic_mapinfo->mapped_end() : static_mapinfo->mapped_end();
 973     set_shared_metaspace_range(cds_base, static_mapinfo->mapped_end(), cds_end);
 974     _relocation_delta = static_mapinfo->relocation_delta();
 975     _requested_base_address = static_mapinfo->requested_base_address();
 976     if (dynamic_mapped) {
 977       FileMapInfo::set_shared_path_table(dynamic_mapinfo);
 978       // turn AutoCreateSharedArchive off if successfully mapped
 979       AutoCreateSharedArchive = false;
 980     } else {
 981       FileMapInfo::set_shared_path_table(static_mapinfo);
 982     }
 983   } else {
 984     set_shared_metaspace_range(NULL, NULL, NULL);
 985     if (DynamicDumpSharedSpaces) {
 986       warning("-XX:ArchiveClassesAtExit is unsupported when base CDS archive is not loaded. Run with -Xlog:cds for more info.");
 987     }
 988     UseSharedSpaces = false;
 989     // The base archive cannot be mapped. We cannot dump the dynamic shared archive.
 990     AutoCreateSharedArchive = false;
 991     DynamicDumpSharedSpaces = false;
 992     FileMapInfo::fail_continue("Unable to map shared spaces");
 993     if (PrintSharedArchiveAndExit) {
 994       vm_exit_during_initialization("Unable to use shared archive.");
 995     }
 996   }
 997 
 998   if (static_mapinfo != NULL && !static_mapinfo->is_mapped()) {
 999     delete static_mapinfo;
1000   }
1001   if (dynamic_mapinfo != NULL && !dynamic_mapinfo->is_mapped()) {
1002     delete dynamic_mapinfo;
1003   }
1004 }
1005 
1006 FileMapInfo* MetaspaceShared::open_static_archive() {
1007   const char* static_archive = Arguments::GetSharedArchivePath();
1008   assert(static_archive != nullptr, "SharedArchivePath is NULL");
1009   FileMapInfo* mapinfo = new FileMapInfo(static_archive, true);
1010   if (!mapinfo->initialize()) {
1011     delete(mapinfo);
1012     return NULL;
1013   }
1014   return mapinfo;
1015 }
1016 
1017 FileMapInfo* MetaspaceShared::open_dynamic_archive() {
1018   if (DynamicDumpSharedSpaces) {
1019     return NULL;
1020   }
1021   const char* dynamic_archive = Arguments::GetSharedDynamicArchivePath();
1022   if (dynamic_archive == nullptr) {
1023     return NULL;
1024   }
1025 
1026   FileMapInfo* mapinfo = new FileMapInfo(dynamic_archive, false);
1027   if (!mapinfo->initialize()) {
1028     delete(mapinfo);
1029     return NULL;
1030   }
1031   return mapinfo;
1032 }
1033 
1034 // use_requested_addr:
1035 //  true  = map at FileMapHeader::_requested_base_address
1036 //  false = map at an alternative address picked by OS.
1037 MapArchiveResult MetaspaceShared::map_archives(FileMapInfo* static_mapinfo, FileMapInfo* dynamic_mapinfo,
1038                                                bool use_requested_addr) {
1039   if (use_requested_addr && static_mapinfo->requested_base_address() == NULL) {
1040     log_info(cds)("Archive(s) were created with -XX:SharedBaseAddress=0. Always map at os-selected address.");
1041     return MAP_ARCHIVE_MMAP_FAILURE;
1042   }
1043 
1044   PRODUCT_ONLY(if (ArchiveRelocationMode == 1 && use_requested_addr) {
1045       // For product build only -- this is for benchmarking the cost of doing relocation.
1046       // For debug builds, the check is done below, after reserving the space, for better test coverage
1047       // (see comment below).
1048       log_info(cds)("ArchiveRelocationMode == 1: always map archive(s) at an alternative address");
1049       return MAP_ARCHIVE_MMAP_FAILURE;
1050     });
1051 
1052   if (ArchiveRelocationMode == 2 && !use_requested_addr) {
1053     log_info(cds)("ArchiveRelocationMode == 2: never map archive(s) at an alternative address");
1054     return MAP_ARCHIVE_MMAP_FAILURE;
1055   };
1056 
1057   if (dynamic_mapinfo != NULL) {
1058     // Ensure that the OS won't be able to allocate new memory spaces between the two
1059     // archives, or else it would mess up the simple comparison in MetaspaceObj::is_shared().
1060     assert(static_mapinfo->mapping_end_offset() == dynamic_mapinfo->mapping_base_offset(), "no gap");
1061   }
1062 
1063   ReservedSpace total_space_rs, archive_space_rs, class_space_rs;
1064   MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE;
1065   char* mapped_base_address = reserve_address_space_for_archives(static_mapinfo,
1066                                                                  dynamic_mapinfo,
1067                                                                  use_requested_addr,
1068                                                                  total_space_rs,
1069                                                                  archive_space_rs,
1070                                                                  class_space_rs);
1071   if (mapped_base_address == NULL) {
1072     result = MAP_ARCHIVE_MMAP_FAILURE;
1073     log_debug(cds)("Failed to reserve spaces (use_requested_addr=%u)", (unsigned)use_requested_addr);
1074   } else {
1075 
1076 #ifdef ASSERT
1077     // Some sanity checks after reserving address spaces for archives
1078     //  and class space.
1079     assert(archive_space_rs.is_reserved(), "Sanity");
1080     if (Metaspace::using_class_space()) {
1081       // Class space must closely follow the archive space. Both spaces
1082       //  must be aligned correctly.
1083       assert(class_space_rs.is_reserved(),
1084              "A class space should have been reserved");
1085       assert(class_space_rs.base() >= archive_space_rs.end(),
1086              "class space should follow the cds archive space");
1087       assert(is_aligned(archive_space_rs.base(),
1088                         core_region_alignment()),
1089              "Archive space misaligned");
1090       assert(is_aligned(class_space_rs.base(),
1091                         Metaspace::reserve_alignment()),
1092              "class space misaligned");
1093     }
1094 #endif // ASSERT
1095 
1096     log_info(cds)("Reserved archive_space_rs [" INTPTR_FORMAT " - " INTPTR_FORMAT "] (" SIZE_FORMAT ") bytes",
1097                    p2i(archive_space_rs.base()), p2i(archive_space_rs.end()), archive_space_rs.size());
1098     log_info(cds)("Reserved class_space_rs   [" INTPTR_FORMAT " - " INTPTR_FORMAT "] (" SIZE_FORMAT ") bytes",
1099                    p2i(class_space_rs.base()), p2i(class_space_rs.end()), class_space_rs.size());
1100 
1101     if (MetaspaceShared::use_windows_memory_mapping()) {
1102       // We have now reserved address space for the archives, and will map in
1103       //  the archive files into this space.
1104       //
1105       // Special handling for Windows: on Windows we cannot map a file view
1106       //  into an existing memory mapping. So, we unmap the address range we
1107       //  just reserved again, which will make it available for mapping the
1108       //  archives.
1109       // Reserving this range has not been for naught however since it makes
1110       //  us reasonably sure the address range is available.
1111       //
1112       // But still it may fail, since between unmapping the range and mapping
1113       //  in the archive someone else may grab the address space. Therefore
1114       //  there is a fallback in FileMap::map_region() where we just read in
1115       //  the archive files sequentially instead of mapping it in. We couple
1116       //  this with use_requested_addr, since we're going to patch all the
1117       //  pointers anyway so there's no benefit to mmap.
1118       if (use_requested_addr) {
1119         assert(!total_space_rs.is_reserved(), "Should not be reserved for Windows");
1120         log_info(cds)("Windows mmap workaround: releasing archive space.");
1121         archive_space_rs.release();
1122       }
1123     }
1124     MapArchiveResult static_result = map_archive(static_mapinfo, mapped_base_address, archive_space_rs);
1125     MapArchiveResult dynamic_result = (static_result == MAP_ARCHIVE_SUCCESS) ?
1126                                      map_archive(dynamic_mapinfo, mapped_base_address, archive_space_rs) : MAP_ARCHIVE_OTHER_FAILURE;
1127 
1128     DEBUG_ONLY(if (ArchiveRelocationMode == 1 && use_requested_addr) {
1129       // This is for simulating mmap failures at the requested address. In
1130       //  debug builds, we do it here (after all archives have possibly been
1131       //  mapped), so we can thoroughly test the code for failure handling
1132       //  (releasing all allocated resource, etc).
1133       log_info(cds)("ArchiveRelocationMode == 1: always map archive(s) at an alternative address");
1134       if (static_result == MAP_ARCHIVE_SUCCESS) {
1135         static_result = MAP_ARCHIVE_MMAP_FAILURE;
1136       }
1137       if (dynamic_result == MAP_ARCHIVE_SUCCESS) {
1138         dynamic_result = MAP_ARCHIVE_MMAP_FAILURE;
1139       }
1140     });
1141 
1142     if (static_result == MAP_ARCHIVE_SUCCESS) {
1143       if (dynamic_result == MAP_ARCHIVE_SUCCESS) {
1144         result = MAP_ARCHIVE_SUCCESS;
1145       } else if (dynamic_result == MAP_ARCHIVE_OTHER_FAILURE) {
1146         assert(dynamic_mapinfo != NULL && !dynamic_mapinfo->is_mapped(), "must have failed");
1147         // No need to retry mapping the dynamic archive again, as it will never succeed
1148         // (bad file, etc) -- just keep the base archive.
1149         log_warning(cds, dynamic)("Unable to use shared archive. The top archive failed to load: %s",
1150                                   dynamic_mapinfo->full_path());
1151         result = MAP_ARCHIVE_SUCCESS;
1152         // TODO, we can give the unused space for the dynamic archive to class_space_rs, but there's no
1153         // easy API to do that right now.
1154       } else {
1155         result = MAP_ARCHIVE_MMAP_FAILURE;
1156       }
1157     } else if (static_result == MAP_ARCHIVE_OTHER_FAILURE) {
1158       result = MAP_ARCHIVE_OTHER_FAILURE;
1159     } else {
1160       result = MAP_ARCHIVE_MMAP_FAILURE;
1161     }
1162   }
1163 
1164   if (result == MAP_ARCHIVE_SUCCESS) {
1165     SharedBaseAddress = (size_t)mapped_base_address;
1166     LP64_ONLY({
1167         if (Metaspace::using_class_space()) {
1168           // Set up ccs in metaspace.
1169           Metaspace::initialize_class_space(class_space_rs);
1170 
1171           // Set up compressed Klass pointer encoding: the encoding range must
1172           //  cover both archive and class space.
1173           address cds_base = (address)static_mapinfo->mapped_base();
1174           address ccs_end = (address)class_space_rs.end();
1175           assert(ccs_end > cds_base, "Sanity check");
1176           CompressedKlassPointers::initialize(cds_base, ccs_end - cds_base);
1177 
1178           // map_heap_regions() compares the current narrow oop and klass encodings
1179           // with the archived ones, so it must be done after all encodings are determined.
1180           static_mapinfo->map_or_load_heap_regions();
1181         }
1182       });
1183     log_info(cds)("optimized module handling: %s", MetaspaceShared::use_optimized_module_handling() ? "enabled" : "disabled");
1184     log_info(cds)("full module graph: %s", MetaspaceShared::use_full_module_graph() ? "enabled" : "disabled");
1185   } else {
1186     unmap_archive(static_mapinfo);
1187     unmap_archive(dynamic_mapinfo);
1188     release_reserved_spaces(total_space_rs, archive_space_rs, class_space_rs);
1189   }
1190 
1191   return result;
1192 }
1193 
1194 
1195 // This will reserve two address spaces suitable to house Klass structures, one
1196 //  for the cds archives (static archive and optionally dynamic archive) and
1197 //  optionally one move for ccs.
1198 //
1199 // Since both spaces must fall within the compressed class pointer encoding
1200 //  range, they are allocated close to each other.
1201 //
1202 // Space for archives will be reserved first, followed by a potential gap,
1203 //  followed by the space for ccs:
1204 //
1205 // +-- Base address             A        B                     End
1206 // |                            |        |                      |
1207 // v                            v        v                      v
1208 // +-------------+--------------+        +----------------------+
1209 // | static arc  | [dyn. arch]  | [gap]  | compr. class space   |
1210 // +-------------+--------------+        +----------------------+
1211 //
1212 // (The gap may result from different alignment requirements between metaspace
1213 //  and CDS)
1214 //
1215 // If UseCompressedClassPointers is disabled, only one address space will be
1216 //  reserved:
1217 //
1218 // +-- Base address             End
1219 // |                            |
1220 // v                            v
1221 // +-------------+--------------+
1222 // | static arc  | [dyn. arch]  |
1223 // +-------------+--------------+
1224 //
1225 // Base address: If use_archive_base_addr address is true, the Base address is
1226 //  determined by the address stored in the static archive. If
1227 //  use_archive_base_addr address is false, this base address is determined
1228 //  by the platform.
1229 //
1230 // If UseCompressedClassPointers=1, the range encompassing both spaces will be
1231 //  suitable to en/decode narrow Klass pointers: the base will be valid for
1232 //  encoding, the range [Base, End) not surpass KlassEncodingMetaspaceMax.
1233 //
1234 // Return:
1235 //
1236 // - On success:
1237 //    - total_space_rs will be reserved as whole for archive_space_rs and
1238 //      class_space_rs if UseCompressedClassPointers is true.
1239 //      On Windows, try reserve archive_space_rs and class_space_rs
1240 //      separately first if use_archive_base_addr is true.
1241 //    - archive_space_rs will be reserved and large enough to host static and
1242 //      if needed dynamic archive: [Base, A).
1243 //      archive_space_rs.base and size will be aligned to CDS reserve
1244 //      granularity.
1245 //    - class_space_rs: If UseCompressedClassPointers=1, class_space_rs will
1246 //      be reserved. Its start address will be aligned to metaspace reserve
1247 //      alignment, which may differ from CDS alignment. It will follow the cds
1248 //      archive space, close enough such that narrow class pointer encoding
1249 //      covers both spaces.
1250 //      If UseCompressedClassPointers=0, class_space_rs remains unreserved.
1251 // - On error: NULL is returned and the spaces remain unreserved.
1252 char* MetaspaceShared::reserve_address_space_for_archives(FileMapInfo* static_mapinfo,
1253                                                           FileMapInfo* dynamic_mapinfo,
1254                                                           bool use_archive_base_addr,
1255                                                           ReservedSpace& total_space_rs,
1256                                                           ReservedSpace& archive_space_rs,
1257                                                           ReservedSpace& class_space_rs) {
1258 
1259   address const base_address = (address) (use_archive_base_addr ? static_mapinfo->requested_base_address() : NULL);
1260   const size_t archive_space_alignment = core_region_alignment();
1261 
1262   // Size and requested location of the archive_space_rs (for both static and dynamic archives)
1263   assert(static_mapinfo->mapping_base_offset() == 0, "Must be");
1264   size_t archive_end_offset  = (dynamic_mapinfo == NULL) ? static_mapinfo->mapping_end_offset() : dynamic_mapinfo->mapping_end_offset();
1265   size_t archive_space_size = align_up(archive_end_offset, archive_space_alignment);
1266 
1267   // If a base address is given, it must have valid alignment and be suitable as encoding base.
1268   if (base_address != NULL) {
1269     assert(is_aligned(base_address, archive_space_alignment),
1270            "Archive base address invalid: " PTR_FORMAT ".", p2i(base_address));
1271     if (Metaspace::using_class_space()) {
1272       assert(CompressedKlassPointers::is_valid_base(base_address),
1273              "Archive base address invalid: " PTR_FORMAT ".", p2i(base_address));
1274     }
1275   }
1276 
1277   if (!Metaspace::using_class_space()) {
1278     // Get the simple case out of the way first:
1279     // no compressed class space, simple allocation.
1280     archive_space_rs = ReservedSpace(archive_space_size, archive_space_alignment,
1281                                      os::vm_page_size(), (char*)base_address);
1282     if (archive_space_rs.is_reserved()) {
1283       assert(base_address == NULL ||
1284              (address)archive_space_rs.base() == base_address, "Sanity");
1285       // Register archive space with NMT.
1286       MemTracker::record_virtual_memory_type(archive_space_rs.base(), mtClassShared);
1287       return archive_space_rs.base();
1288     }
1289     return NULL;
1290   }
1291 
1292 #ifdef _LP64
1293 
1294   // Complex case: two spaces adjacent to each other, both to be addressable
1295   //  with narrow class pointers.
1296   // We reserve the whole range spanning both spaces, then split that range up.
1297 
1298   const size_t class_space_alignment = Metaspace::reserve_alignment();
1299 
1300   // To simplify matters, lets assume that metaspace alignment will always be
1301   //  equal or a multiple of archive alignment.
1302   assert(is_power_of_2(class_space_alignment) &&
1303                        is_power_of_2(archive_space_alignment) &&
1304                        class_space_alignment >= archive_space_alignment,
1305                        "Sanity");
1306 
1307   const size_t class_space_size = CompressedClassSpaceSize;
1308   assert(CompressedClassSpaceSize > 0 &&
1309          is_aligned(CompressedClassSpaceSize, class_space_alignment),
1310          "CompressedClassSpaceSize malformed: "
1311          SIZE_FORMAT, CompressedClassSpaceSize);
1312 
1313   const size_t ccs_begin_offset = align_up(base_address + archive_space_size,
1314                                            class_space_alignment) - base_address;
1315   const size_t gap_size = ccs_begin_offset - archive_space_size;
1316 
1317   const size_t total_range_size =
1318       align_up(archive_space_size + gap_size + class_space_size, core_region_alignment());
1319 
1320   assert(total_range_size > ccs_begin_offset, "must be");
1321   if (use_windows_memory_mapping() && use_archive_base_addr) {
1322     if (base_address != nullptr) {
1323       // On Windows, we cannot safely split a reserved memory space into two (see JDK-8255917).
1324       // Hence, we optimistically reserve archive space and class space side-by-side. We only
1325       // do this for use_archive_base_addr=true since for use_archive_base_addr=false case
1326       // caller will not split the combined space for mapping, instead read the archive data
1327       // via sequential file IO.
1328       address ccs_base = base_address + archive_space_size + gap_size;
1329       archive_space_rs = ReservedSpace(archive_space_size, archive_space_alignment,
1330                                        os::vm_page_size(), (char*)base_address);
1331       class_space_rs   = ReservedSpace(class_space_size, class_space_alignment,
1332                                        os::vm_page_size(), (char*)ccs_base);
1333     }
1334     if (!archive_space_rs.is_reserved() || !class_space_rs.is_reserved()) {
1335       release_reserved_spaces(total_space_rs, archive_space_rs, class_space_rs);
1336       return NULL;
1337     }
1338   } else {
1339     if (use_archive_base_addr && base_address != nullptr) {
1340       total_space_rs = ReservedSpace(total_range_size, archive_space_alignment,
1341                                      os::vm_page_size(), (char*) base_address);
1342     } else {
1343       // Reserve at any address, but leave it up to the platform to choose a good one.
1344       total_space_rs = Metaspace::reserve_address_space_for_compressed_classes(total_range_size);
1345     }
1346 
1347     if (!total_space_rs.is_reserved()) {
1348       return NULL;
1349     }
1350 
1351     // Paranoid checks:
1352     assert(base_address == NULL || (address)total_space_rs.base() == base_address,
1353            "Sanity (" PTR_FORMAT " vs " PTR_FORMAT ")", p2i(base_address), p2i(total_space_rs.base()));
1354     assert(is_aligned(total_space_rs.base(), archive_space_alignment), "Sanity");
1355     assert(total_space_rs.size() == total_range_size, "Sanity");
1356     assert(CompressedKlassPointers::is_valid_base((address)total_space_rs.base()), "Sanity");
1357 
1358     // Now split up the space into ccs and cds archive. For simplicity, just leave
1359     //  the gap reserved at the end of the archive space. Do not do real splitting.
1360     archive_space_rs = total_space_rs.first_part(ccs_begin_offset,
1361                                                  (size_t)archive_space_alignment);
1362     class_space_rs = total_space_rs.last_part(ccs_begin_offset);
1363     MemTracker::record_virtual_memory_split_reserved(total_space_rs.base(), total_space_rs.size(),
1364                                                      ccs_begin_offset);
1365   }
1366   assert(is_aligned(archive_space_rs.base(), archive_space_alignment), "Sanity");
1367   assert(is_aligned(archive_space_rs.size(), archive_space_alignment), "Sanity");
1368   assert(is_aligned(class_space_rs.base(), class_space_alignment), "Sanity");
1369   assert(is_aligned(class_space_rs.size(), class_space_alignment), "Sanity");
1370 
1371   // NMT: fix up the space tags
1372   MemTracker::record_virtual_memory_type(archive_space_rs.base(), mtClassShared);
1373   MemTracker::record_virtual_memory_type(class_space_rs.base(), mtClass);
1374 
1375   return archive_space_rs.base();
1376 
1377 #else
1378   ShouldNotReachHere();
1379   return NULL;
1380 #endif
1381 
1382 }
1383 
1384 void MetaspaceShared::release_reserved_spaces(ReservedSpace& total_space_rs,
1385                                               ReservedSpace& archive_space_rs,
1386                                               ReservedSpace& class_space_rs) {
1387   if (total_space_rs.is_reserved()) {
1388     log_debug(cds)("Released shared space (archive + class) " INTPTR_FORMAT, p2i(total_space_rs.base()));
1389     total_space_rs.release();
1390   } else {
1391     if (archive_space_rs.is_reserved()) {
1392       log_debug(cds)("Released shared space (archive) " INTPTR_FORMAT, p2i(archive_space_rs.base()));
1393       archive_space_rs.release();
1394     }
1395     if (class_space_rs.is_reserved()) {
1396       log_debug(cds)("Released shared space (classes) " INTPTR_FORMAT, p2i(class_space_rs.base()));
1397       class_space_rs.release();
1398     }
1399   }
1400 }
1401 
1402 static int archive_regions[]     = { MetaspaceShared::rw, MetaspaceShared::ro };
1403 static int archive_regions_count = 2;
1404 
1405 MapArchiveResult MetaspaceShared::map_archive(FileMapInfo* mapinfo, char* mapped_base_address, ReservedSpace rs) {
1406   assert(UseSharedSpaces, "must be runtime");
1407   if (mapinfo == NULL) {
1408     return MAP_ARCHIVE_SUCCESS; // The dynamic archive has not been specified. No error has happened -- trivially succeeded.
1409   }
1410 
1411   mapinfo->set_is_mapped(false);
1412   if (mapinfo->core_region_alignment() != (size_t)core_region_alignment()) {
1413     log_info(cds)("Unable to map CDS archive -- core_region_alignment() expected: " SIZE_FORMAT
1414                   " actual: " SIZE_FORMAT, mapinfo->core_region_alignment(), core_region_alignment());
1415     return MAP_ARCHIVE_OTHER_FAILURE;
1416   }
1417 
1418   MapArchiveResult result =
1419     mapinfo->map_regions(archive_regions, archive_regions_count, mapped_base_address, rs);
1420 
1421   if (result != MAP_ARCHIVE_SUCCESS) {
1422     unmap_archive(mapinfo);
1423     return result;
1424   }
1425 
1426   if (!mapinfo->validate_shared_path_table()) {
1427     unmap_archive(mapinfo);
1428     return MAP_ARCHIVE_OTHER_FAILURE;
1429   }
1430 
1431   mapinfo->set_is_mapped(true);
1432   return MAP_ARCHIVE_SUCCESS;
1433 }
1434 
1435 void MetaspaceShared::unmap_archive(FileMapInfo* mapinfo) {
1436   assert(UseSharedSpaces, "must be runtime");
1437   if (mapinfo != NULL) {
1438     mapinfo->unmap_regions(archive_regions, archive_regions_count);
1439     mapinfo->unmap_region(MetaspaceShared::bm);
1440     mapinfo->set_is_mapped(false);
1441   }
1442 }
1443 
1444 // For -XX:PrintSharedArchiveAndExit
1445 class CountSharedSymbols : public SymbolClosure {
1446  private:
1447    int _count;
1448  public:
1449    CountSharedSymbols() : _count(0) {}
1450   void do_symbol(Symbol** sym) {
1451     _count++;
1452   }
1453   int total() { return _count; }
1454 
1455 };
1456 
1457 // Read the miscellaneous data from the shared file, and
1458 // serialize it out to its various destinations.
1459 
1460 void MetaspaceShared::initialize_shared_spaces() {
1461   FileMapInfo *static_mapinfo = FileMapInfo::current_info();
1462 
1463   // Verify various attributes of the archive, plus initialize the
1464   // shared string/symbol tables.
1465   char* buffer = static_mapinfo->serialized_data();
1466   intptr_t* array = (intptr_t*)buffer;
1467   ReadClosure rc(&array);
1468   serialize(&rc);
1469 
1470   // Initialize the run-time symbol table.
1471   SymbolTable::create_table();
1472 
1473   // Finish up archived heap initialization. These must be
1474   // done after ReadClosure.
1475   static_mapinfo->patch_heap_embedded_pointers();
1476   ArchiveHeapLoader::finish_initialization();
1477 
1478   // Close the mapinfo file
1479   static_mapinfo->close();
1480 
1481   static_mapinfo->unmap_region(MetaspaceShared::bm);
1482 
1483   FileMapInfo *dynamic_mapinfo = FileMapInfo::dynamic_info();
1484   if (dynamic_mapinfo != NULL) {
1485     intptr_t* buffer = (intptr_t*)dynamic_mapinfo->serialized_data();
1486     ReadClosure rc(&buffer);
1487     SymbolTable::serialize_shared_table_header(&rc, false);
1488     SystemDictionaryShared::serialize_dictionary_headers(&rc, false);
1489     dynamic_mapinfo->close();
1490     dynamic_mapinfo->unmap_region(MetaspaceShared::bm);
1491   }
1492 
1493   // Set up LambdaFormInvokers::_lambdaform_lines for dynamic dump
1494   if (DynamicDumpSharedSpaces) {
1495     // Read stored LF format lines stored in static archive
1496     LambdaFormInvokers::read_static_archive_invokers();
1497   }
1498 
1499   if (PrintSharedArchiveAndExit) {
1500     // Print archive names
1501     if (dynamic_mapinfo != nullptr) {
1502       tty->print_cr("\n\nBase archive name: %s", Arguments::GetSharedArchivePath());
1503       tty->print_cr("Base archive version %d", static_mapinfo->version());
1504     } else {
1505       tty->print_cr("Static archive name: %s", static_mapinfo->full_path());
1506       tty->print_cr("Static archive version %d", static_mapinfo->version());
1507     }
1508 
1509     SystemDictionaryShared::print_shared_archive(tty);
1510     if (dynamic_mapinfo != nullptr) {
1511       tty->print_cr("\n\nDynamic archive name: %s", dynamic_mapinfo->full_path());
1512       tty->print_cr("Dynamic archive version %d", dynamic_mapinfo->version());
1513       SystemDictionaryShared::print_shared_archive(tty, false/*dynamic*/);
1514     }
1515 
1516     // collect shared symbols and strings
1517     CountSharedSymbols cl;
1518     SymbolTable::shared_symbols_do(&cl);
1519     tty->print_cr("Number of shared symbols: %d", cl.total());
1520     tty->print_cr("Number of shared strings: %zu", StringTable::shared_entry_count());
1521     tty->print_cr("VM version: %s\r\n", static_mapinfo->vm_version());
1522     if (FileMapInfo::current_info() == NULL || _archive_loading_failed) {
1523       tty->print_cr("archive is invalid");
1524       vm_exit(1);
1525     } else {
1526       tty->print_cr("archive is valid");
1527       vm_exit(0);
1528     }
1529   }
1530 }
1531 
1532 // JVM/TI RedefineClasses() support:
1533 bool MetaspaceShared::remap_shared_readonly_as_readwrite() {
1534   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1535 
1536   if (UseSharedSpaces) {
1537     // remap the shared readonly space to shared readwrite, private
1538     FileMapInfo* mapinfo = FileMapInfo::current_info();
1539     if (!mapinfo->remap_shared_readonly_as_readwrite()) {
1540       return false;
1541     }
1542     if (FileMapInfo::dynamic_info() != NULL) {
1543       mapinfo = FileMapInfo::dynamic_info();
1544       if (!mapinfo->remap_shared_readonly_as_readwrite()) {
1545         return false;
1546       }
1547     }
1548     _remapped_readwrite = true;
1549   }
1550   return true;
1551 }
1552 
1553 bool MetaspaceShared::use_full_module_graph() {
1554 #if INCLUDE_CDS_JAVA_HEAP
1555   if (ClassLoaderDataShared::is_full_module_graph_loaded()) {
1556     return true;
1557   }
1558 #endif
1559   bool result = _use_optimized_module_handling && _use_full_module_graph;
1560   if (DumpSharedSpaces) {
1561     result &= HeapShared::can_write();
1562   } else if (UseSharedSpaces) {
1563     result &= ArchiveHeapLoader::can_use();
1564   } else {
1565     result = false;
1566   }
1567 
1568   if (result && UseSharedSpaces) {
1569     // Classes used by the archived full module graph are loaded in JVMTI early phase.
1570     assert(!(JvmtiExport::should_post_class_file_load_hook() && JvmtiExport::has_early_class_hook_env()),
1571            "CDS should be disabled if early class hooks are enabled");
1572   }
1573   return result;
1574 }
1575 
1576 void MetaspaceShared::print_on(outputStream* st) {
1577   if (UseSharedSpaces) {
1578     st->print("CDS archive(s) mapped at: ");
1579     address base = (address)MetaspaceObj::shared_metaspace_base();
1580     address static_top = (address)_shared_metaspace_static_top;
1581     address top = (address)MetaspaceObj::shared_metaspace_top();
1582     st->print("[" PTR_FORMAT "-" PTR_FORMAT "-" PTR_FORMAT "), ", p2i(base), p2i(static_top), p2i(top));
1583     st->print("size " SIZE_FORMAT ", ", top - base);
1584     st->print("SharedBaseAddress: " PTR_FORMAT ", ArchiveRelocationMode: %d.", SharedBaseAddress, ArchiveRelocationMode);
1585   } else {
1586     st->print("CDS archive(s) not mapped");
1587   }
1588   st->cr();
1589 }