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