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