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