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