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