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