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