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