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