1 /*
   2  * Copyright (c) 2012, 2024, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "cds/archiveBuilder.hpp"
  27 #include "cds/archiveHeapLoader.hpp"
  28 #include "cds/archiveHeapWriter.hpp"
  29 #include "cds/cds_globals.hpp"
  30 #include "cds/cdsConfig.hpp"
  31 #include "cds/cdsProtectionDomain.hpp"
  32 #include "cds/cds_globals.hpp"
  33 #include "cds/classListParser.hpp"
  34 #include "cds/classListWriter.hpp"
  35 #include "cds/classPrelinker.hpp"
  36 #include "cds/cppVtables.hpp"
  37 #include "cds/dumpAllocStats.hpp"
  38 #include "cds/dynamicArchive.hpp"
  39 #include "cds/filemap.hpp"
  40 #include "cds/heapShared.hpp"
  41 #include "cds/lambdaFormInvokers.hpp"
  42 #include "cds/metaspaceShared.hpp"
  43 #include "classfile/classLoaderDataGraph.hpp"
  44 #include "classfile/classLoaderDataShared.hpp"
  45 #include "classfile/classLoaderExt.hpp"
  46 #include "classfile/javaClasses.inline.hpp"
  47 #include "classfile/loaderConstraints.hpp"
  48 #include "classfile/modules.hpp"
  49 #include "classfile/placeholders.hpp"
  50 #include "classfile/stringTable.hpp"
  51 #include "classfile/symbolTable.hpp"
  52 #include "classfile/systemDictionary.hpp"
  53 #include "classfile/systemDictionaryShared.hpp"
  54 #include "classfile/vmClasses.hpp"
  55 #include "classfile/vmSymbols.hpp"
  56 #include "code/codeCache.hpp"
  57 #include "gc/shared/gcVMOperations.hpp"
  58 #include "interpreter/bytecodeStream.hpp"
  59 #include "interpreter/bytecodes.hpp"
  60 #include "jvm_io.h"
  61 #include "logging/log.hpp"
  62 #include "logging/logMessage.hpp"
  63 #include "logging/logStream.hpp"
  64 #include "memory/metaspace.hpp"
  65 #include "memory/metaspaceClosure.hpp"
  66 #include "memory/resourceArea.hpp"
  67 #include "memory/universe.hpp"
  68 #include "nmt/memTracker.hpp"
  69 #include "oops/compressedKlass.hpp"
  70 #include "oops/instanceMirrorKlass.hpp"
  71 #include "oops/klass.inline.hpp"
  72 #include "oops/objArrayOop.hpp"
  73 #include "oops/oop.inline.hpp"
  74 #include "oops/oopHandle.hpp"
  75 #include "prims/jvmtiExport.hpp"
  76 #include "runtime/arguments.hpp"
  77 #include "runtime/globals.hpp"
  78 #include "runtime/globals_extension.hpp"
  79 #include "runtime/handles.inline.hpp"
  80 #include "runtime/os.inline.hpp"
  81 #include "runtime/safepointVerifiers.hpp"
  82 #include "runtime/sharedRuntime.hpp"
  83 #include "runtime/vmOperations.hpp"
  84 #include "runtime/vmThread.hpp"
  85 #include "sanitizers/leak.hpp"
  86 #include "utilities/align.hpp"
  87 #include "utilities/bitMap.inline.hpp"
  88 #include "utilities/defaultStream.hpp"

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

1179             );
1180 #endif // INCLUDE_CDS_JAVA_HEAP





1181           // map_or_load_heap_region() compares the current narrow oop and klass encodings
1182           // with the archived ones, so it must be done after all encodings are determined.
1183           static_mapinfo->map_or_load_heap_region();
1184         }
1185 #endif // _LP64
1186     log_info(cds)("initial optimized module handling: %s", CDSConfig::is_using_optimized_module_handling() ? "enabled" : "disabled");
1187     log_info(cds)("initial full module graph: %s", CDSConfig::is_using_full_module_graph() ? "enabled" : "disabled");
1188   } else {
1189     unmap_archive(static_mapinfo);
1190     unmap_archive(dynamic_mapinfo);
1191     release_reserved_spaces(total_space_rs, archive_space_rs, class_space_rs);
1192   }
1193 
1194   return result;
1195 }
1196 
1197 
1198 // This will reserve two address spaces suitable to house Klass structures, one
1199 //  for the cds archives (static archive and optionally dynamic archive) and
1200 //  optionally one move for ccs.
1201 //
1202 // Since both spaces must fall within the compressed class pointer encoding
1203 //  range, they are allocated close to each other.
1204 //
1205 // Space for archives will be reserved first, followed by a potential gap,
1206 //  followed by the space for ccs:
1207 //
1208 // +-- Base address             A        B                     End
1209 // |                            |        |                      |
1210 // v                            v        v                      v
1211 // +-------------+--------------+        +----------------------+
1212 // | static arc  | [dyn. arch]  | [gap]  | compr. class space   |
1213 // +-------------+--------------+        +----------------------+
1214 //
1215 // (The gap may result from different alignment requirements between metaspace
1216 //  and CDS)
1217 //
1218 // If UseCompressedClassPointers is disabled, only one address space will be
1219 //  reserved:
1220 //
1221 // +-- Base address             End
1222 // |                            |
1223 // v                            v
1224 // +-------------+--------------+
1225 // | static arc  | [dyn. arch]  |
1226 // +-------------+--------------+
1227 //
1228 // Base address: If use_archive_base_addr address is true, the Base address is
1229 //  determined by the address stored in the static archive. If
1230 //  use_archive_base_addr address is false, this base address is determined
1231 //  by the platform.
1232 //
1233 // If UseCompressedClassPointers=1, the range encompassing both spaces will be
1234 //  suitable to en/decode narrow Klass pointers: the base will be valid for
1235 //  encoding, the range [Base, End) not surpass KlassEncodingMetaspaceMax.
1236 //
1237 // Return:
1238 //
1239 // - On success:
1240 //    - total_space_rs will be reserved as whole for archive_space_rs and
1241 //      class_space_rs if UseCompressedClassPointers is true.
1242 //      On Windows, try reserve archive_space_rs and class_space_rs
1243 //      separately first if use_archive_base_addr is true.
1244 //    - archive_space_rs will be reserved and large enough to host static and
1245 //      if needed dynamic archive: [Base, A).
1246 //      archive_space_rs.base and size will be aligned to CDS reserve
1247 //      granularity.
1248 //    - class_space_rs: If UseCompressedClassPointers=1, class_space_rs will
1249 //      be reserved. Its start address will be aligned to metaspace reserve
1250 //      alignment, which may differ from CDS alignment. It will follow the cds
1251 //      archive space, close enough such that narrow class pointer encoding
1252 //      covers both spaces.
1253 //      If UseCompressedClassPointers=0, class_space_rs remains unreserved.
1254 // - On error: null is returned and the spaces remain unreserved.
1255 char* MetaspaceShared::reserve_address_space_for_archives(FileMapInfo* static_mapinfo,
1256                                                           FileMapInfo* dynamic_mapinfo,
1257                                                           bool use_archive_base_addr,
1258                                                           ReservedSpace& total_space_rs,
1259                                                           ReservedSpace& archive_space_rs,
1260                                                           ReservedSpace& class_space_rs) {
1261 
1262   address const base_address = (address) (use_archive_base_addr ? static_mapinfo->requested_base_address() : nullptr);
1263   const size_t archive_space_alignment = core_region_alignment();
1264 
1265   // Size and requested location of the archive_space_rs (for both static and dynamic archives)
1266   assert(static_mapinfo->mapping_base_offset() == 0, "Must be");
1267   size_t archive_end_offset  = (dynamic_mapinfo == nullptr) ? static_mapinfo->mapping_end_offset() : dynamic_mapinfo->mapping_end_offset();
1268   size_t archive_space_size = align_up(archive_end_offset, archive_space_alignment);
1269 
1270   if (!Metaspace::using_class_space()) {
1271     // Get the simple case out of the way first:
1272     // no compressed class space, simple allocation.
1273 
1274     // When running without class space, requested archive base should be aligned to cds core alignment.
1275     assert(is_aligned(base_address, archive_space_alignment),
1276              "Archive base address unaligned: " PTR_FORMAT ", needs alignment: %zu.",
1277              p2i(base_address), archive_space_alignment);
1278 
1279     archive_space_rs = ReservedSpace(archive_space_size, archive_space_alignment,
1280                                      os::vm_page_size(), (char*)base_address);
1281     if (archive_space_rs.is_reserved()) {
1282       assert(base_address == nullptr ||
1283              (address)archive_space_rs.base() == base_address, "Sanity");
1284       // Register archive space with NMT.
1285       MemTracker::record_virtual_memory_type(archive_space_rs.base(), mtClassShared);
1286       return archive_space_rs.base();
1287     }
1288     return nullptr;
1289   }
1290 
1291 #ifdef _LP64
1292 
1293   // Complex case: two spaces adjacent to each other, both to be addressable
1294   //  with narrow class pointers.
1295   // We reserve the whole range spanning both spaces, then split that range up.
1296 
1297   const size_t class_space_alignment = Metaspace::reserve_alignment();
1298 
1299   // When running with class space, requested archive base must satisfy both cds core alignment
1300   // and class space alignment.
1301   const size_t base_address_alignment = MAX2(class_space_alignment, archive_space_alignment);
1302   assert(is_aligned(base_address, base_address_alignment),
1303            "Archive base address unaligned: " PTR_FORMAT ", needs alignment: %zu.",
1304            p2i(base_address), base_address_alignment);
1305 
1306   size_t class_space_size = CompressedClassSpaceSize;
1307   assert(CompressedClassSpaceSize > 0 &&
1308          is_aligned(CompressedClassSpaceSize, class_space_alignment),
1309          "CompressedClassSpaceSize malformed: "
1310          SIZE_FORMAT, CompressedClassSpaceSize);
1311 
1312   const size_t ccs_begin_offset = align_up(archive_space_size, class_space_alignment);
1313   const size_t gap_size = ccs_begin_offset - archive_space_size;
1314 
1315   // Reduce class space size if it would not fit into the Klass encoding range
1316   constexpr size_t max_encoding_range_size = 4 * G;
1317   guarantee(archive_space_size < max_encoding_range_size - class_space_alignment, "Archive too large");
1318   if ((archive_space_size + gap_size + class_space_size) > max_encoding_range_size) {
1319     class_space_size = align_down(max_encoding_range_size - archive_space_size - gap_size, class_space_alignment);
1320     log_info(metaspace)("CDS initialization: reducing class space size from " SIZE_FORMAT " to " SIZE_FORMAT,
1321         CompressedClassSpaceSize, class_space_size);
1322     FLAG_SET_ERGO(CompressedClassSpaceSize, class_space_size);
1323   }
1324 
1325   const size_t total_range_size =
1326       archive_space_size + gap_size + class_space_size;
1327 
1328   assert(total_range_size > ccs_begin_offset, "must be");
1329   if (use_windows_memory_mapping() && use_archive_base_addr) {
1330     if (base_address != nullptr) {
1331       // On Windows, we cannot safely split a reserved memory space into two (see JDK-8255917).
1332       // Hence, we optimistically reserve archive space and class space side-by-side. We only
1333       // do this for use_archive_base_addr=true since for use_archive_base_addr=false case
1334       // caller will not split the combined space for mapping, instead read the archive data
1335       // via sequential file IO.
1336       address ccs_base = base_address + archive_space_size + gap_size;
1337       archive_space_rs = ReservedSpace(archive_space_size, archive_space_alignment,
1338                                        os::vm_page_size(), (char*)base_address);
1339       class_space_rs   = ReservedSpace(class_space_size, class_space_alignment,
1340                                        os::vm_page_size(), (char*)ccs_base);
1341     }
1342     if (!archive_space_rs.is_reserved() || !class_space_rs.is_reserved()) {
1343       release_reserved_spaces(total_space_rs, archive_space_rs, class_space_rs);
1344       return nullptr;
1345     }
1346     // NMT: fix up the space tags
1347     MemTracker::record_virtual_memory_type(archive_space_rs.base(), mtClassShared);
1348     MemTracker::record_virtual_memory_type(class_space_rs.base(), mtClass);
1349   } else {
1350     if (use_archive_base_addr && base_address != nullptr) {
1351       total_space_rs = ReservedSpace(total_range_size, base_address_alignment,
1352                                      os::vm_page_size(), (char*) base_address);
1353     } else {
1354       // We did not manage to reserve at the preferred address, or were instructed to relocate. In that
1355       // case we reserve wherever possible, but the start address needs to be encodable as narrow Klass
1356       // encoding base since the archived heap objects contain nKlass IDs pre-calculated toward the start
1357       // of the shared Metaspace. That prevents us from using zero-based encoding and therefore we won't
1358       // try allocating in low-address regions.
1359       total_space_rs = Metaspace::reserve_address_space_for_compressed_classes(total_range_size, false /* optimize_for_zero_base */);
1360     }
1361 
1362     if (!total_space_rs.is_reserved()) {
1363       return nullptr;
1364     }
1365 
1366     // Paranoid checks:
1367     assert(base_address == nullptr || (address)total_space_rs.base() == base_address,
1368            "Sanity (" PTR_FORMAT " vs " PTR_FORMAT ")", p2i(base_address), p2i(total_space_rs.base()));
1369     assert(is_aligned(total_space_rs.base(), base_address_alignment), "Sanity");
1370     assert(total_space_rs.size() == total_range_size, "Sanity");
1371 
1372     // Now split up the space into ccs and cds archive. For simplicity, just leave
1373     //  the gap reserved at the end of the archive space. Do not do real splitting.
1374     archive_space_rs = total_space_rs.first_part(ccs_begin_offset,
1375                                                  (size_t)archive_space_alignment);
1376     class_space_rs = total_space_rs.last_part(ccs_begin_offset);
1377     MemTracker::record_virtual_memory_split_reserved(total_space_rs.base(), total_space_rs.size(),
1378                                                      ccs_begin_offset, mtClassShared, mtClass);
1379   }
1380   assert(is_aligned(archive_space_rs.base(), archive_space_alignment), "Sanity");
1381   assert(is_aligned(archive_space_rs.size(), archive_space_alignment), "Sanity");
1382   assert(is_aligned(class_space_rs.base(), class_space_alignment), "Sanity");
1383   assert(is_aligned(class_space_rs.size(), class_space_alignment), "Sanity");
1384 
1385 
1386   return archive_space_rs.base();
1387 
1388 #else
1389   ShouldNotReachHere();
1390   return nullptr;
1391 #endif
1392 
1393 }
1394 
1395 void MetaspaceShared::release_reserved_spaces(ReservedSpace& total_space_rs,
1396                                               ReservedSpace& archive_space_rs,
1397                                               ReservedSpace& class_space_rs) {
1398   if (total_space_rs.is_reserved()) {
1399     log_debug(cds)("Released shared space (archive + class) " INTPTR_FORMAT, p2i(total_space_rs.base()));
1400     total_space_rs.release();
1401   } else {
1402     if (archive_space_rs.is_reserved()) {
1403       log_debug(cds)("Released shared space (archive) " INTPTR_FORMAT, p2i(archive_space_rs.base()));
1404       archive_space_rs.release();
1405     }
1406     if (class_space_rs.is_reserved()) {
1407       log_debug(cds)("Released shared space (classes) " INTPTR_FORMAT, p2i(class_space_rs.base()));
1408       class_space_rs.release();
1409     }
1410   }
1411 }
1412 
1413 static int archive_regions[]     = { MetaspaceShared::rw, MetaspaceShared::ro };
1414 static int archive_regions_count = 2;
1415 
1416 MapArchiveResult MetaspaceShared::map_archive(FileMapInfo* mapinfo, char* mapped_base_address, ReservedSpace rs) {
1417   assert(CDSConfig::is_using_archive(), "must be runtime");
1418   if (mapinfo == nullptr) {
1419     return MAP_ARCHIVE_SUCCESS; // The dynamic archive has not been specified. No error has happened -- trivially succeeded.
1420   }
1421 
1422   mapinfo->set_is_mapped(false);
1423   if (mapinfo->core_region_alignment() != (size_t)core_region_alignment()) {
1424     log_info(cds)("Unable to map CDS archive -- core_region_alignment() expected: " SIZE_FORMAT
1425                   " actual: " SIZE_FORMAT, mapinfo->core_region_alignment(), core_region_alignment());
1426     return MAP_ARCHIVE_OTHER_FAILURE;
1427   }
1428 
1429   MapArchiveResult result =
1430     mapinfo->map_regions(archive_regions, archive_regions_count, mapped_base_address, rs);
1431 
1432   if (result != MAP_ARCHIVE_SUCCESS) {
1433     unmap_archive(mapinfo);
1434     return result;
1435   }
1436 
1437   if (!mapinfo->validate_shared_path_table()) {
1438     unmap_archive(mapinfo);
1439     return MAP_ARCHIVE_OTHER_FAILURE;
1440   }
1441 
1442   mapinfo->set_is_mapped(true);
1443   return MAP_ARCHIVE_SUCCESS;
1444 }
1445 
1446 void MetaspaceShared::unmap_archive(FileMapInfo* mapinfo) {
1447   assert(CDSConfig::is_using_archive(), "must be runtime");
1448   if (mapinfo != nullptr) {
1449     mapinfo->unmap_regions(archive_regions, archive_regions_count);
1450     mapinfo->unmap_region(MetaspaceShared::bm);
1451     mapinfo->set_is_mapped(false);
1452   }
1453 }
1454 
1455 // For -XX:PrintSharedArchiveAndExit
1456 class CountSharedSymbols : public SymbolClosure {
1457  private:
1458    int _count;
1459  public:
1460    CountSharedSymbols() : _count(0) {}
1461   void do_symbol(Symbol** sym) {
1462     _count++;
1463   }
1464   int total() { return _count; }
1465 
1466 };
1467 
1468 // Read the miscellaneous data from the shared file, and
1469 // serialize it out to its various destinations.
1470 
1471 void MetaspaceShared::initialize_shared_spaces() {
1472   FileMapInfo *static_mapinfo = FileMapInfo::current_info();
1473 
1474   // Verify various attributes of the archive, plus initialize the
1475   // shared string/symbol tables.
1476   char* buffer = static_mapinfo->serialized_data();
1477   intptr_t* array = (intptr_t*)buffer;
1478   ReadClosure rc(&array);
1479   serialize(&rc);
1480 
1481   // Finish up archived heap initialization. These must be
1482   // done after ReadClosure.
1483   static_mapinfo->patch_heap_embedded_pointers();
1484   ArchiveHeapLoader::finish_initialization();
1485   Universe::load_archived_object_instances();
1486 
1487   // Close the mapinfo file
1488   static_mapinfo->close();
1489 
1490   static_mapinfo->unmap_region(MetaspaceShared::bm);
1491 
1492   FileMapInfo *dynamic_mapinfo = FileMapInfo::dynamic_info();
1493   if (dynamic_mapinfo != nullptr) {
1494     intptr_t* buffer = (intptr_t*)dynamic_mapinfo->serialized_data();
1495     ReadClosure rc(&buffer);
1496     ArchiveBuilder::serialize_dynamic_archivable_items(&rc);
1497     DynamicArchive::setup_array_klasses();
1498     dynamic_mapinfo->close();
1499     dynamic_mapinfo->unmap_region(MetaspaceShared::bm);
1500   }
1501 
1502   // Set up LambdaFormInvokers::_lambdaform_lines for dynamic dump
1503   if (CDSConfig::is_dumping_dynamic_archive()) {
1504     // Read stored LF format lines stored in static archive
1505     LambdaFormInvokers::read_static_archive_invokers();
1506   }
1507 
1508   if (PrintSharedArchiveAndExit) {
1509     // Print archive names
1510     if (dynamic_mapinfo != nullptr) {
1511       tty->print_cr("\n\nBase archive name: %s", CDSConfig::static_archive_path());
1512       tty->print_cr("Base archive version %d", static_mapinfo->version());
1513     } else {
1514       tty->print_cr("Static archive name: %s", static_mapinfo->full_path());
1515       tty->print_cr("Static archive version %d", static_mapinfo->version());
1516     }
1517 
1518     SystemDictionaryShared::print_shared_archive(tty);
1519     if (dynamic_mapinfo != nullptr) {
1520       tty->print_cr("\n\nDynamic archive name: %s", dynamic_mapinfo->full_path());
1521       tty->print_cr("Dynamic archive version %d", dynamic_mapinfo->version());
1522       SystemDictionaryShared::print_shared_archive(tty, false/*dynamic*/);
1523     }
1524 
1525     // collect shared symbols and strings
1526     CountSharedSymbols cl;
1527     SymbolTable::shared_symbols_do(&cl);
1528     tty->print_cr("Number of shared symbols: %d", cl.total());
1529     tty->print_cr("Number of shared strings: %zu", StringTable::shared_entry_count());
1530     tty->print_cr("VM version: %s\r\n", static_mapinfo->vm_version());
1531     if (FileMapInfo::current_info() == nullptr || _archive_loading_failed) {
1532       tty->print_cr("archive is invalid");
1533       vm_exit(1);
1534     } else {
1535       tty->print_cr("archive is valid");
1536       vm_exit(0);
1537     }
1538   }
1539 }
1540 
1541 // JVM/TI RedefineClasses() support:
1542 bool MetaspaceShared::remap_shared_readonly_as_readwrite() {
1543   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1544 
1545   if (CDSConfig::is_using_archive()) {
1546     // remap the shared readonly space to shared readwrite, private
1547     FileMapInfo* mapinfo = FileMapInfo::current_info();
1548     if (!mapinfo->remap_shared_readonly_as_readwrite()) {
1549       return false;
1550     }
1551     if (FileMapInfo::dynamic_info() != nullptr) {
1552       mapinfo = FileMapInfo::dynamic_info();
1553       if (!mapinfo->remap_shared_readonly_as_readwrite()) {
1554         return false;
1555       }
1556     }
1557     _remapped_readwrite = true;
1558   }
1559   return true;
1560 }
1561 
1562 void MetaspaceShared::print_on(outputStream* st) {
1563   if (CDSConfig::is_using_archive()) {
1564     st->print("CDS archive(s) mapped at: ");
1565     address base = (address)MetaspaceObj::shared_metaspace_base();
1566     address static_top = (address)_shared_metaspace_static_top;
1567     address top = (address)MetaspaceObj::shared_metaspace_top();
1568     st->print("[" PTR_FORMAT "-" PTR_FORMAT "-" PTR_FORMAT "), ", p2i(base), p2i(static_top), p2i(top));
1569     st->print("size " SIZE_FORMAT ", ", top - base);
1570     st->print("SharedBaseAddress: " PTR_FORMAT ", ArchiveRelocationMode: %d.", SharedBaseAddress, ArchiveRelocationMode);
1571   } else {
1572     st->print("CDS archive(s) not mapped");
1573   }
1574   st->cr();
1575 }
--- EOF ---