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