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