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