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