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