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