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