1 /*
   2  * Copyright (c) 2012, 2025, 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 "cds/aotCacheAccess.hpp"
  26 #include "cds/aotClassInitializer.hpp"
  27 #include "cds/aotArtifactFinder.hpp"
  28 #include "cds/aotClassInitializer.hpp"
  29 #include "cds/aotClassLinker.hpp"
  30 #include "cds/aotClassLocation.hpp"
  31 #include "cds/aotConstantPoolResolver.hpp"
  32 #include "cds/aotLinkedClassBulkLoader.hpp"
  33 #include "cds/aotReferenceObjSupport.hpp"
  34 #include "cds/archiveBuilder.hpp"
  35 #include "cds/archiveHeapLoader.hpp"
  36 #include "cds/archiveHeapWriter.hpp"
  37 #include "cds/cds_globals.hpp"
  38 #include "cds/cdsConfig.hpp"
  39 #include "cds/cdsProtectionDomain.hpp"
  40 #include "cds/classListParser.hpp"
  41 #include "cds/classListWriter.hpp"
  42 #include "cds/cppVtables.hpp"
  43 #include "cds/dumpAllocStats.hpp"
  44 #include "cds/dynamicArchive.hpp"
  45 #include "cds/filemap.hpp"
  46 #include "cds/finalImageRecipes.hpp"
  47 #include "cds/heapShared.hpp"
  48 #include "cds/lambdaFormInvokers.hpp"
  49 #include "cds/lambdaProxyClassDictionary.hpp"
  50 #include "cds/metaspaceShared.hpp"
  51 #include "classfile/classLoaderDataGraph.hpp"
  52 #include "classfile/classLoaderDataShared.hpp"
  53 #include "classfile/classLoaderExt.hpp"
  54 #include "classfile/javaClasses.inline.hpp"
  55 #include "classfile/loaderConstraints.hpp"
  56 #include "classfile/modules.hpp"
  57 #include "classfile/placeholders.hpp"
  58 #include "classfile/stringTable.hpp"
  59 #include "classfile/symbolTable.hpp"
  60 #include "classfile/systemDictionary.hpp"
  61 #include "classfile/systemDictionaryShared.hpp"
  62 #include "classfile/vmClasses.hpp"
  63 #include "classfile/vmSymbols.hpp"
  64 #include "code/aotCodeCache.hpp"
  65 #include "code/codeCache.hpp"
  66 #include "compiler/compileBroker.hpp"
  67 #include "compiler/precompiler.hpp"
  68 #include "gc/shared/gcVMOperations.hpp"
  69 #include "interpreter/bytecodeStream.hpp"
  70 #include "interpreter/bytecodes.hpp"
  71 #include "jvm_io.h"
  72 #include "logging/log.hpp"
  73 #include "logging/logMessage.hpp"
  74 #include "logging/logStream.hpp"
  75 #include "memory/memoryReserver.hpp"
  76 #include "memory/metaspace.hpp"
  77 #include "memory/metaspaceClosure.hpp"
  78 #include "memory/oopFactory.hpp"
  79 #include "memory/resourceArea.hpp"
  80 #include "memory/universe.hpp"
  81 #include "nmt/memTracker.hpp"
  82 #include "oops/compressedKlass.hpp"
  83 #include "oops/instanceMirrorKlass.hpp"
  84 #include "oops/klass.inline.hpp"
  85 #include "oops/method.inline.hpp"
  86 #include "oops/objArrayOop.hpp"
  87 #include "oops/oop.inline.hpp"
  88 #include "oops/oopHandle.hpp"
  89 #include "oops/trainingData.hpp"
  90 #include "prims/jvmtiExport.hpp"
  91 #include "prims/whitebox.hpp"
  92 #include "runtime/arguments.hpp"
  93 #include "runtime/globals.hpp"
  94 #include "runtime/globals_extension.hpp"
  95 #include "runtime/handles.inline.hpp"
  96 #include "runtime/javaCalls.hpp"
  97 #include "runtime/os.inline.hpp"
  98 #include "runtime/safepointVerifiers.hpp"
  99 #include "runtime/sharedRuntime.hpp"
 100 #include "runtime/vmOperations.hpp"
 101 #include "runtime/vmThread.hpp"
 102 #include "sanitizers/leak.hpp"
 103 #include "services/management.hpp"
 104 #include "utilities/align.hpp"
 105 #include "utilities/bitMap.inline.hpp"
 106 #include "utilities/defaultStream.hpp"
 107 #include "utilities/macros.hpp"
 108 #include "utilities/ostream.hpp"
 109 #include "utilities/resourceHash.hpp"
 110 
 111 #include <sys/stat.h>
 112 
 113 ReservedSpace MetaspaceShared::_symbol_rs;
 114 VirtualSpace MetaspaceShared::_symbol_vs;
 115 bool MetaspaceShared::_archive_loading_failed = false;
 116 bool MetaspaceShared::_remapped_readwrite = false;
 117 void* MetaspaceShared::_shared_metaspace_static_top = nullptr;
 118 intx MetaspaceShared::_relocation_delta;
 119 char* MetaspaceShared::_requested_base_address;
 120 Array<Method*>* MetaspaceShared::_archived_method_handle_intrinsics = nullptr;
 121 bool MetaspaceShared::_use_optimized_module_handling = true;
 122 int volatile MetaspaceShared::_preimage_static_archive_dumped = 0;
 123 jlong MetaspaceShared::_preimage_static_archive_recording_duration = 0;
 124 
 125 // The CDS archive is divided into the following regions:
 126 //     rw  - read-write metadata
 127 //     ro  - read-only metadata and read-only tables
 128 //     hp  - heap region
 129 //     bm  - bitmap for relocating the above 7 regions.
 130 //
 131 // The rw and ro regions are linearly allocated, in the order of rw->ro.
 132 // These regions are aligned with MetaspaceShared::core_region_alignment().
 133 //
 134 // These 2 regions are populated in the following steps:
 135 // [0] All classes are loaded in MetaspaceShared::preload_classes(). All metadata are
 136 //     temporarily allocated outside of the shared regions.
 137 // [1] We enter a safepoint and allocate a buffer for the rw/ro regions.
 138 // [2] C++ vtables are copied into the rw region.
 139 // [3] ArchiveBuilder copies RW metadata into the rw region.
 140 // [4] ArchiveBuilder copies RO metadata into the ro region.
 141 // [5] SymbolTable, StringTable, SystemDictionary, and a few other read-only data
 142 //     are copied into the ro region as read-only tables.
 143 //
 144 // The heap region is written by HeapShared::write_heap().
 145 //
 146 // The bitmap region is used to relocate the ro/rw/hp regions.
 147 
 148 static DumpRegion _symbol_region("symbols");
 149 
 150 char* MetaspaceShared::symbol_space_alloc(size_t num_bytes) {
 151   return _symbol_region.allocate(num_bytes);
 152 }
 153 
 154 // os::vm_allocation_granularity() is usually 4K for most OSes. However, some platforms
 155 // such as linux-aarch64 and macos-x64 ...
 156 // it can be either 4K or 64K and on macos-aarch64 it is 16K. To generate archives that are
 157 // compatible for both settings, an alternative cds core region alignment can be enabled
 158 // at building time:
 159 //   --enable-compactible-cds-alignment
 160 // Upon successful configuration, the compactible alignment then can be defined in:
 161 //   os_linux_aarch64.cpp
 162 //   os_bsd_x86.cpp
 163 size_t MetaspaceShared::core_region_alignment() {
 164   return os::cds_core_region_alignment();
 165 }
 166 
 167 size_t MetaspaceShared::protection_zone_size() {
 168   return os::cds_core_region_alignment();
 169 }
 170 
 171 static bool shared_base_valid(char* shared_base) {
 172   // We check user input for SharedBaseAddress at dump time.
 173 
 174   // At CDS runtime, "shared_base" will be the (attempted) mapping start. It will also
 175   // be the encoding base, since the headers of archived base objects (and with Lilliput,
 176   // the prototype mark words) carry pre-computed narrow Klass IDs that refer to the mapping
 177   // start as base.
 178   //
 179   // On AARCH64, The "shared_base" may not be later usable as encoding base, depending on the
 180   // total size of the reserved area and the precomputed_narrow_klass_shift. This is checked
 181   // before reserving memory.  Here we weed out values already known to be invalid later.
 182   return AARCH64_ONLY(is_aligned(shared_base, 4 * G)) NOT_AARCH64(true);
 183 }
 184 
 185 class DumpClassListCLDClosure : public CLDClosure {
 186   static const int INITIAL_TABLE_SIZE = 1987;
 187   static const int MAX_TABLE_SIZE = 61333;
 188 
 189   fileStream *_stream;
 190   ResizeableResourceHashtable<InstanceKlass*, bool,
 191                               AnyObj::C_HEAP, mtClassShared> _dumped_classes;
 192 
 193   void dump(InstanceKlass* ik) {
 194     bool created;
 195     _dumped_classes.put_if_absent(ik, &created);
 196     if (!created) {
 197       return;
 198     }
 199     if (_dumped_classes.maybe_grow()) {
 200       log_info(cds, hashtables)("Expanded _dumped_classes table to %d", _dumped_classes.table_size());
 201     }
 202     if (ik->java_super()) {
 203       dump(ik->java_super());
 204     }
 205     Array<InstanceKlass*>* interfaces = ik->local_interfaces();
 206     int len = interfaces->length();
 207     for (int i = 0; i < len; i++) {
 208       dump(interfaces->at(i));
 209     }
 210     ClassListWriter::write_to_stream(ik, _stream);
 211   }
 212 
 213 public:
 214   DumpClassListCLDClosure(fileStream* f)
 215   : CLDClosure(), _dumped_classes(INITIAL_TABLE_SIZE, MAX_TABLE_SIZE) {
 216     _stream = f;
 217   }
 218 
 219   void do_cld(ClassLoaderData* cld) {
 220     for (Klass* klass = cld->klasses(); klass != nullptr; klass = klass->next_link()) {
 221       if (klass->is_instance_klass()) {
 222         dump(InstanceKlass::cast(klass));
 223       }
 224     }
 225   }
 226 };
 227 
 228 void MetaspaceShared::dump_loaded_classes(const char* file_name, TRAPS) {
 229   fileStream stream(file_name, "w");
 230   if (stream.is_open()) {
 231     MutexLocker lock(ClassLoaderDataGraph_lock);
 232     MutexLocker lock2(ClassListFile_lock, Mutex::_no_safepoint_check_flag);
 233     DumpClassListCLDClosure collect_classes(&stream);
 234     ClassLoaderDataGraph::loaded_cld_do(&collect_classes);
 235   } else {
 236     THROW_MSG(vmSymbols::java_io_IOException(), "Failed to open file");
 237   }
 238 }
 239 
 240 static bool shared_base_too_high(char* specified_base, char* aligned_base, size_t cds_max) {
 241   // Caller should have checked that aligned_base was successfully aligned and is not nullptr.
 242   // Comparing specified_base with nullptr is UB.
 243   assert(aligned_base != nullptr, "sanity");
 244   assert(aligned_base >= specified_base, "sanity");
 245 
 246   if (max_uintx - uintx(aligned_base) < uintx(cds_max)) {
 247     // Not enough address space to hold an archive of cds_max bytes from aligned_base.
 248     return true;
 249   } else {
 250     return false;
 251   }
 252 }
 253 
 254 static char* compute_shared_base(size_t cds_max) {
 255   char* specified_base = (char*)SharedBaseAddress;
 256   size_t alignment = MetaspaceShared::core_region_alignment();
 257   if (UseCompressedClassPointers) {
 258     alignment = MAX2(alignment, Metaspace::reserve_alignment());
 259   }
 260 
 261   if (SharedBaseAddress == 0) {
 262     // Special meaning of -XX:SharedBaseAddress=0 -> Always map archive at os-selected address.
 263     return specified_base;
 264   }
 265 
 266   char* aligned_base = can_align_up(specified_base, alignment)
 267                            ? align_up(specified_base, alignment)
 268                            : nullptr;
 269 
 270   if (aligned_base != specified_base) {
 271     log_info(cds)("SharedBaseAddress (" INTPTR_FORMAT ") aligned up to " INTPTR_FORMAT,
 272                    p2i(specified_base), p2i(aligned_base));
 273   }
 274 
 275   const char* err = nullptr;
 276   if (aligned_base == nullptr) {
 277     err = "too high";
 278   } else if (shared_base_too_high(specified_base, aligned_base, cds_max)) {
 279     err = "too high";
 280   } else if (!shared_base_valid(aligned_base)) {
 281     err = "invalid for this platform";
 282   } else {
 283     return aligned_base;
 284   }
 285 
 286   // Arguments::default_SharedBaseAddress() is hard-coded in cds_globals.hpp. It must be carefully
 287   // picked that (a) the align_up() below will always return a valid value; (b) none of
 288   // the following asserts will fail.
 289   log_warning(cds)("SharedBaseAddress (" INTPTR_FORMAT ") is %s. Reverted to " INTPTR_FORMAT,
 290                    p2i((void*)SharedBaseAddress), err,
 291                    p2i((void*)Arguments::default_SharedBaseAddress()));
 292 
 293   specified_base = (char*)Arguments::default_SharedBaseAddress();
 294   aligned_base = align_up(specified_base, alignment);
 295 
 296   // Make sure the default value of SharedBaseAddress specified in globals.hpp is sane.
 297   assert(!shared_base_too_high(specified_base, aligned_base, cds_max), "Sanity");
 298   assert(shared_base_valid(aligned_base), "Sanity");
 299   return aligned_base;
 300 }
 301 
 302 void MetaspaceShared::initialize_for_static_dump() {
 303   assert(CDSConfig::is_dumping_static_archive(), "sanity");
 304 
 305   if (CDSConfig::is_dumping_preimage_static_archive() || CDSConfig::is_dumping_final_static_archive()) {
 306     if (!((UseG1GC || UseParallelGC || UseSerialGC || UseEpsilonGC || UseShenandoahGC) && UseCompressedClassPointers)) {
 307       const char* error;
 308       if (CDSConfig::is_experimental_leyden_workflow()) {
 309         error = "Cannot create the CacheDataStore";
 310       } else if (CDSConfig::is_dumping_preimage_static_archive()) {
 311         error = "Cannot create the AOT configuration file";
 312       } else {
 313         error = "Cannot create the AOT cache";
 314       }
 315 
 316       vm_exit_during_initialization(error,
 317                                     "UseCompressedClassPointers must be enabled, and collector must be G1, Parallel, Serial, Epsilon, or Shenandoah");
 318     }
 319   }
 320 
 321   log_info(cds)("Core region alignment: %zu", core_region_alignment());
 322   // The max allowed size for CDS archive. We use this to limit SharedBaseAddress
 323   // to avoid address space wrap around.
 324   size_t cds_max;
 325   const size_t reserve_alignment = core_region_alignment();
 326 
 327 #ifdef _LP64
 328   const uint64_t UnscaledClassSpaceMax = (uint64_t(max_juint) + 1);
 329   cds_max = align_down(UnscaledClassSpaceMax, reserve_alignment);
 330 #else
 331   // We don't support archives larger than 256MB on 32-bit due to limited
 332   //  virtual address space.
 333   cds_max = align_down(256*M, reserve_alignment);
 334 #endif
 335 
 336   _requested_base_address = compute_shared_base(cds_max);
 337   SharedBaseAddress = (size_t)_requested_base_address;
 338 
 339   size_t symbol_rs_size = LP64_ONLY(3 * G) NOT_LP64(128 * M);
 340   _symbol_rs = MemoryReserver::reserve(symbol_rs_size,
 341                                        os::vm_allocation_granularity(),
 342                                        os::vm_page_size(),
 343                                        mtClassShared);
 344   if (!_symbol_rs.is_reserved()) {
 345     log_error(cds)("Unable to reserve memory for symbols: %zu bytes.", symbol_rs_size);
 346     MetaspaceShared::unrecoverable_writing_error();
 347   }
 348   _symbol_region.init(&_symbol_rs, &_symbol_vs);
 349 }
 350 
 351 // Called by universe_post_init()
 352 void MetaspaceShared::post_initialize(TRAPS) {
 353   if (CDSConfig::is_using_archive()) {
 354     int size = AOTClassLocationConfig::runtime()->length();
 355     if (size > 0) {
 356       CDSProtectionDomain::allocate_shared_data_arrays(size, CHECK);
 357     }
 358   }
 359 }
 360 
 361 // Extra java.lang.Strings to be added to the archive
 362 static GrowableArrayCHeap<OopHandle, mtClassShared>* _extra_interned_strings = nullptr;
 363 // Extra Symbols to be added to the archive
 364 static GrowableArrayCHeap<Symbol*, mtClassShared>* _extra_symbols = nullptr;
 365 // Methods managed by SystemDictionary::find_method_handle_intrinsic() to be added to the archive
 366 static GrowableArray<Method*>* _pending_method_handle_intrinsics = nullptr;
 367 
 368 void MetaspaceShared::read_extra_data(JavaThread* current, const char* filename) {
 369   _extra_interned_strings = new GrowableArrayCHeap<OopHandle, mtClassShared>(10000);
 370   _extra_symbols = new GrowableArrayCHeap<Symbol*, mtClassShared>(1000);
 371 
 372   HashtableTextDump reader(filename);
 373   reader.check_version("VERSION: 1.0");
 374 
 375   while (reader.remain() > 0) {
 376     int utf8_length;
 377     int prefix_type = reader.scan_prefix(&utf8_length);
 378     ResourceMark rm(current);
 379     if (utf8_length == 0x7fffffff) {
 380       // buf_len will overflown 32-bit value.
 381       log_error(cds)("string length too large: %d", utf8_length);
 382       MetaspaceShared::unrecoverable_loading_error();
 383     }
 384     int buf_len = utf8_length+1;
 385     char* utf8_buffer = NEW_RESOURCE_ARRAY(char, buf_len);
 386     reader.get_utf8(utf8_buffer, utf8_length);
 387     utf8_buffer[utf8_length] = '\0';
 388 
 389     if (prefix_type == HashtableTextDump::SymbolPrefix) {
 390       _extra_symbols->append(SymbolTable::new_permanent_symbol(utf8_buffer));
 391     } else{
 392       assert(prefix_type == HashtableTextDump::StringPrefix, "Sanity");
 393       ExceptionMark em(current);
 394       JavaThread* THREAD = current; // For exception macros.
 395       oop str = StringTable::intern(utf8_buffer, THREAD);
 396 
 397       if (HAS_PENDING_EXCEPTION) {
 398         log_warning(cds, heap)("[line %d] extra interned string allocation failed; size too large: %d",
 399                                reader.last_line_no(), utf8_length);
 400         CLEAR_PENDING_EXCEPTION;
 401       } else {
 402 #if INCLUDE_CDS_JAVA_HEAP
 403         if (ArchiveHeapWriter::is_string_too_large_to_archive(str)) {
 404           log_warning(cds, heap)("[line %d] extra interned string ignored; size too large: %d",
 405                                  reader.last_line_no(), utf8_length);
 406           continue;
 407         }
 408         // Make sure this string is included in the dumped interned string table.
 409         assert(str != nullptr, "must succeed");
 410         _extra_interned_strings->append(OopHandle(Universe::vm_global(), str));
 411 #endif
 412       }
 413     }
 414   }
 415 }
 416 
 417 void MetaspaceShared::make_method_handle_intrinsics_shareable() {
 418   for (int i = 0; i < _pending_method_handle_intrinsics->length(); i++) {
 419     Method* m = ArchiveBuilder::current()->get_buffered_addr(_pending_method_handle_intrinsics->at(i));
 420     m->remove_unshareable_info();
 421     // Each method has its own constant pool (which is distinct from m->method_holder()->constants());
 422     m->constants()->remove_unshareable_info();
 423   }
 424 }
 425 
 426 void MetaspaceShared::write_method_handle_intrinsics() {
 427   int len = _pending_method_handle_intrinsics->length();
 428   _archived_method_handle_intrinsics = ArchiveBuilder::new_ro_array<Method*>(len);
 429   int word_size = _archived_method_handle_intrinsics->size();
 430   for (int i = 0; i < len; i++) {
 431     Method* m = _pending_method_handle_intrinsics->at(i);
 432     ArchiveBuilder::current()->write_pointer_in_buffer(_archived_method_handle_intrinsics->adr_at(i), m);
 433     word_size += m->size() + m->constMethod()->size() + m->constants()->size();
 434     if (m->constants()->cache() != nullptr) {
 435       word_size += m->constants()->cache()->size();
 436     }
 437   }
 438   log_info(cds)("Archived %d method handle intrinsics (%d bytes)", len, word_size * BytesPerWord);
 439 }
 440 
 441 // About "serialize" --
 442 //
 443 // This is (probably a badly named) way to read/write a data stream of pointers and
 444 // miscellaneous data from/to the shared archive file. The usual code looks like this:
 445 //
 446 //     // These two global C++ variables are initialized during dump time.
 447 //     static int _archived_int;
 448 //     static MetaspaceObj* archived_ptr;
 449 //
 450 //     void MyClass::serialize(SerializeClosure* soc) {
 451 //         soc->do_int(&_archived_int);
 452 //         soc->do_int(&_archived_ptr);
 453 //     }
 454 //
 455 //     At dumptime, these two variables are stored into the CDS archive.
 456 //     At runtime, these two variables are loaded from the CDS archive.
 457 //     In addition, the pointer is relocated as necessary.
 458 //
 459 // Some of the xxx::serialize() functions may have side effects and assume that
 460 // the archive is already mapped. For example, SymbolTable::serialize_shared_table_header()
 461 // unconditionally makes the set of archived symbols available. Therefore, we put most
 462 // of these xxx::serialize() functions inside MetaspaceShared::serialize(), which
 463 // is called AFTER we made the decision to map the archive.
 464 //
 465 // However, some of the "serialized" data are used to decide whether an archive should
 466 // be mapped or not (e.g., for checking if the -Djdk.module.main property is compatible
 467 // with the archive). The xxx::serialize() functions for these data must be put inside
 468 // MetaspaceShared::early_serialize(). Such functions must not produce side effects that
 469 // assume we will always decides to map the archive.
 470 
 471 void MetaspaceShared::early_serialize(SerializeClosure* soc) {
 472   int tag = 0;
 473   soc->do_tag(--tag);
 474   CDS_JAVA_HEAP_ONLY(Modules::serialize_archived_module_info(soc);)
 475   soc->do_tag(666);
 476 }
 477 
 478 void MetaspaceShared::serialize(SerializeClosure* soc) {
 479   int tag = 0;
 480   soc->do_tag(--tag);
 481 
 482   // Verify the sizes of various metadata in the system.
 483   soc->do_tag(sizeof(Method));
 484   soc->do_tag(sizeof(ConstMethod));
 485   soc->do_tag(arrayOopDesc::base_offset_in_bytes(T_BYTE));
 486   soc->do_tag(sizeof(ConstantPool));
 487   soc->do_tag(sizeof(ConstantPoolCache));
 488   soc->do_tag(objArrayOopDesc::base_offset_in_bytes());
 489   soc->do_tag(typeArrayOopDesc::base_offset_in_bytes(T_BYTE));
 490   soc->do_tag(sizeof(Symbol));
 491 
 492   // Need to do this first, as subsequent steps may call virtual functions
 493   // in archived Metadata objects.
 494   CppVtables::serialize(soc);
 495   soc->do_tag(--tag);
 496 
 497   // Dump/restore miscellaneous metadata.
 498   JavaClasses::serialize_offsets(soc);
 499   Universe::serialize(soc);
 500   soc->do_tag(--tag);
 501 
 502   // Dump/restore references to commonly used names and signatures.
 503   vmSymbols::serialize(soc);
 504   soc->do_tag(--tag);
 505 
 506   // Dump/restore the symbol/string/subgraph_info tables
 507   SymbolTable::serialize_shared_table_header(soc);
 508   StringTable::serialize_shared_table_header(soc);
 509   HeapShared::serialize_tables(soc);
 510   SystemDictionaryShared::serialize_dictionary_headers(soc);
 511   AOTLinkedClassBulkLoader::serialize(soc, true);
 512   FinalImageRecipes::serialize(soc);
 513   TrainingData::serialize(soc);
 514   InstanceMirrorKlass::serialize_offsets(soc);
 515 
 516   // Dump/restore well known classes (pointers)
 517   SystemDictionaryShared::serialize_vm_classes(soc);
 518   soc->do_tag(--tag);
 519 
 520   CDS_JAVA_HEAP_ONLY(ClassLoaderDataShared::serialize(soc);)
 521   soc->do_ptr((void**)&_archived_method_handle_intrinsics);
 522 
 523   LambdaFormInvokers::serialize(soc);
 524   AdapterHandlerLibrary::serialize_shared_table_header(soc);
 525 
 526   soc->do_tag(666);
 527 }
 528 
 529 static void rewrite_nofast_bytecode(const methodHandle& method) {
 530   BytecodeStream bcs(method);
 531   while (!bcs.is_last_bytecode()) {
 532     Bytecodes::Code opcode = bcs.next();
 533     switch (opcode) {
 534     case Bytecodes::_getfield:      *bcs.bcp() = Bytecodes::_nofast_getfield;      break;
 535     case Bytecodes::_putfield:      *bcs.bcp() = Bytecodes::_nofast_putfield;      break;
 536     case Bytecodes::_aload_0:       *bcs.bcp() = Bytecodes::_nofast_aload_0;       break;
 537     case Bytecodes::_iload: {
 538       if (!bcs.is_wide()) {
 539         *bcs.bcp() = Bytecodes::_nofast_iload;
 540       }
 541       break;
 542     }
 543     default: break;
 544     }
 545   }
 546 }
 547 
 548 // [1] Rewrite all bytecodes as needed, so that the ConstMethod* will not be modified
 549 //     at run time by RewriteBytecodes/RewriteFrequentPairs
 550 // [2] Assign a fingerprint, so one doesn't need to be assigned at run-time.
 551 void MetaspaceShared::rewrite_nofast_bytecodes_and_calculate_fingerprints(Thread* thread, InstanceKlass* ik) {
 552   for (int i = 0; i < ik->methods()->length(); i++) {
 553     methodHandle m(thread, ik->methods()->at(i));
 554     if (ik->can_be_verified_at_dumptime() && ik->is_linked()) {
 555       rewrite_nofast_bytecode(m);
 556     }
 557     Fingerprinter fp(m);
 558     // The side effect of this call sets method's fingerprint field.
 559     fp.fingerprint();
 560   }
 561 }
 562 
 563 class VM_PopulateDumpSharedSpace : public VM_Operation {
 564 private:
 565   ArchiveHeapInfo _heap_info;
 566   FileMapInfo* _map_info;
 567   StaticArchiveBuilder& _builder;
 568 
 569   void dump_java_heap_objects();
 570   void dump_shared_symbol_table(GrowableArray<Symbol*>* symbols) {
 571     log_info(cds)("Dumping symbol table ...");
 572     SymbolTable::write_to_archive(symbols);
 573   }
 574   char* dump_early_read_only_tables();
 575   char* dump_read_only_tables(AOTClassLocationConfig*& cl_config);
 576 
 577 public:
 578 
 579   VM_PopulateDumpSharedSpace(StaticArchiveBuilder& b) :
 580     VM_Operation(), _heap_info(), _map_info(nullptr), _builder(b) {}
 581 
 582   bool skip_operation() const { return false; }
 583 
 584   VMOp_Type type() const { return VMOp_PopulateDumpSharedSpace; }
 585   ArchiveHeapInfo* heap_info()  { return &_heap_info; }
 586   FileMapInfo* map_info() const { return _map_info; }
 587   void doit();   // outline because gdb sucks
 588   bool allow_nested_vm_operations() const { return true; }
 589 }; // class VM_PopulateDumpSharedSpace
 590 
 591 class StaticArchiveBuilder : public ArchiveBuilder {
 592 public:
 593   StaticArchiveBuilder() : ArchiveBuilder() {}
 594 
 595   virtual void iterate_roots(MetaspaceClosure* it) {
 596     AOTArtifactFinder::all_cached_classes_do(it);
 597     SystemDictionaryShared::dumptime_classes_do(it);
 598     Universe::metaspace_pointers_do(it);
 599     vmSymbols::metaspace_pointers_do(it);
 600     TrainingData::iterate_roots(it);
 601 
 602     // The above code should find all the symbols that are referenced by the
 603     // archived classes. We just need to add the extra symbols which
 604     // may not be used by any of the archived classes -- these are usually
 605     // symbols that we anticipate to be used at run time, so we can store
 606     // them in the RO region, to be shared across multiple processes.
 607     if (_extra_symbols != nullptr) {
 608       for (int i = 0; i < _extra_symbols->length(); i++) {
 609         it->push(_extra_symbols->adr_at(i));
 610       }
 611     }
 612 
 613     for (int i = 0; i < _pending_method_handle_intrinsics->length(); i++) {
 614       it->push(_pending_method_handle_intrinsics->adr_at(i));
 615     }
 616   }
 617 };
 618 
 619 char* VM_PopulateDumpSharedSpace::dump_early_read_only_tables() {
 620   ArchiveBuilder::OtherROAllocMark mark;
 621 
 622   CDS_JAVA_HEAP_ONLY(Modules::dump_archived_module_info());
 623 
 624   DumpRegion* ro_region = ArchiveBuilder::current()->ro_region();
 625   char* start = ro_region->top();
 626   WriteClosure wc(ro_region);
 627   MetaspaceShared::early_serialize(&wc);
 628   return start;
 629 }
 630 
 631 char* VM_PopulateDumpSharedSpace::dump_read_only_tables(AOTClassLocationConfig*& cl_config) {
 632   ArchiveBuilder::OtherROAllocMark mark;
 633 
 634   SystemDictionaryShared::write_to_archive();
 635   cl_config = AOTClassLocationConfig::dumptime()->write_to_archive();
 636   AOTClassLinker::write_to_archive();
 637   if (CDSConfig::is_dumping_preimage_static_archive()) {
 638     FinalImageRecipes::record_recipes();
 639   }
 640 
 641   TrainingData::dump_training_data();
 642 
 643   MetaspaceShared::write_method_handle_intrinsics();
 644 
 645   // Write lambform lines into archive
 646   LambdaFormInvokers::dump_static_archive_invokers();
 647 
 648   if (AOTCodeCache::is_dumping_adapter()) {
 649     AdapterHandlerLibrary::dump_aot_adapter_table();
 650   }
 651 
 652   // Write the other data to the output array.
 653   DumpRegion* ro_region = ArchiveBuilder::current()->ro_region();
 654   char* start = ro_region->top();
 655   WriteClosure wc(ro_region);
 656   MetaspaceShared::serialize(&wc);
 657 
 658   return start;
 659 }
 660 
 661 void VM_PopulateDumpSharedSpace::doit() {
 662   if (!CDSConfig::is_dumping_final_static_archive()) {
 663     guarantee(!CDSConfig::is_using_archive(), "We should not be using an archive when we dump");
 664   }
 665 
 666   DEBUG_ONLY(SystemDictionaryShared::NoClassLoadingMark nclm);
 667 
 668   _pending_method_handle_intrinsics = new (mtClassShared) GrowableArray<Method*>(256, mtClassShared);
 669   if (CDSConfig::is_dumping_method_handles()) {
 670     // When dumping AOT-linked classes, some classes may have direct references to a method handle
 671     // intrinsic. The easiest thing is to save all of them into the AOT cache.
 672     SystemDictionary::get_all_method_handle_intrinsics(_pending_method_handle_intrinsics);
 673   }
 674 
 675   AOTClassLocationConfig::dumptime_check_nonempty_dirs();
 676 
 677   NOT_PRODUCT(SystemDictionary::verify();)
 678 
 679   // Block concurrent class unloading from changing the _dumptime_table
 680   MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
 681 
 682 #if INCLUDE_CDS_JAVA_HEAP
 683   if (CDSConfig::is_dumping_heap() && _extra_interned_strings != nullptr) {
 684     for (int i = 0; i < _extra_interned_strings->length(); i ++) {
 685       OopHandle string = _extra_interned_strings->at(i);
 686       HeapShared::add_to_dumped_interned_strings(string.resolve());
 687     }
 688   }
 689 #endif
 690 
 691   _builder.gather_source_objs();
 692   _builder.reserve_buffer();
 693 
 694   CppVtables::dumptime_init(&_builder);
 695 
 696   _builder.sort_metadata_objs();
 697   _builder.dump_rw_metadata();
 698   _builder.dump_ro_metadata();
 699   _builder.relocate_metaspaceobj_embedded_pointers();
 700 
 701   log_info(cds)("Make classes shareable");
 702   _builder.make_klasses_shareable();
 703   MetaspaceShared::make_method_handle_intrinsics_shareable();
 704 
 705   dump_java_heap_objects();
 706   dump_shared_symbol_table(_builder.symbols());
 707 
 708   char* early_serialized_data = dump_early_read_only_tables();
 709   AOTClassLocationConfig* cl_config;
 710   char* serialized_data = dump_read_only_tables(cl_config);
 711 
 712   if (CDSConfig::is_dumping_lambdas_in_legacy_mode()) {
 713     log_info(cds)("Adjust lambda proxy class dictionary");
 714     LambdaProxyClassDictionary::adjust_dumptime_table();
 715   }
 716 
 717   log_info(cds)("Make training data shareable");
 718   _builder.make_training_data_shareable();
 719 
 720   // The vtable clones contain addresses of the current process.
 721   // We don't want to write these addresses into the archive.
 722   CppVtables::zero_archived_vtables();
 723 
 724   // Write the archive file
 725   if (CDSConfig::is_dumping_final_static_archive()) {
 726     FileMapInfo::free_current_info(); // FIXME: should not free current info
 727   }
 728   const char* static_archive = CDSConfig::output_archive_path();
 729   assert(static_archive != nullptr, "sanity");
 730   _map_info = new FileMapInfo(static_archive, true);
 731   _map_info->populate_header(MetaspaceShared::core_region_alignment());
 732   _map_info->set_early_serialized_data(early_serialized_data);
 733   _map_info->set_serialized_data(serialized_data);
 734   _map_info->set_cloned_vtables(CppVtables::vtables_serialized_base());
 735   _map_info->header()->set_class_location_config(cl_config);
 736 }
 737 
 738 class CollectClassesForLinking : public KlassClosure {
 739   GrowableArray<OopHandle> _mirrors;
 740 
 741 public:
 742    CollectClassesForLinking() : _mirrors() {
 743      // ClassLoaderDataGraph::loaded_classes_do_keepalive() requires ClassLoaderDataGraph_lock.
 744      // We cannot link the classes while holding this lock (or else we may run into deadlock).
 745      // Therefore, we need to first collect all the classes, keeping them alive by
 746      // holding onto their java_mirrors in global OopHandles. We then link the classes after
 747      // releasing the lock.
 748      MutexLocker lock(ClassLoaderDataGraph_lock);
 749      ClassLoaderDataGraph::loaded_classes_do_keepalive(this);
 750    }
 751 
 752   ~CollectClassesForLinking() {
 753     for (int i = 0; i < _mirrors.length(); i++) {
 754       _mirrors.at(i).release(Universe::vm_global());
 755     }
 756   }
 757 
 758   void do_cld(ClassLoaderData* cld) {
 759     assert(cld->is_alive(), "must be");
 760   }
 761 
 762   void do_klass(Klass* k) {
 763     if (k->is_instance_klass()) {
 764       _mirrors.append(OopHandle(Universe::vm_global(), k->java_mirror()));
 765     }
 766   }
 767 
 768   const GrowableArray<OopHandle>* mirrors() const { return &_mirrors; }
 769 };
 770 
 771 // Check if we can eagerly link this class at dump time, so we can avoid the
 772 // runtime linking overhead (especially verification)
 773 bool MetaspaceShared::may_be_eagerly_linked(InstanceKlass* ik) {
 774   if (CDSConfig::preserve_all_dumptime_verification_states(ik)) {
 775     assert(ik->can_be_verified_at_dumptime(), "sanity");
 776   }
 777   if (!ik->can_be_verified_at_dumptime()) {
 778     // For old classes, try to leave them in the unlinked state, so
 779     // we can still store them in the archive. They must be
 780     // linked/verified at runtime.
 781     return false;
 782   }
 783 
 784   if (CDSConfig::is_dumping_dynamic_archive() && ik->is_shared_unregistered_class()) {
 785     // Linking of unregistered classes at this stage may cause more
 786     // classes to be resolved, resulting in calls to ClassLoader.loadClass()
 787     // that may not be expected by custom class loaders.
 788     //
 789     // It's OK to do this for the built-in loaders as we know they can
 790     // tolerate this.
 791     return false;
 792   }
 793   return true;
 794 }
 795 
 796 void MetaspaceShared::link_shared_classes(TRAPS) {
 797   AOTClassLinker::initialize();
 798   AOTClassInitializer::init_test_class(CHECK);
 799 
 800   while (true) {
 801     ResourceMark rm(THREAD);
 802     CollectClassesForLinking collect_classes;
 803     bool has_linked = false;
 804     const GrowableArray<OopHandle>* mirrors = collect_classes.mirrors();
 805     for (int i = 0; i < mirrors->length(); i++) {
 806       OopHandle mirror = mirrors->at(i);
 807       InstanceKlass* ik = InstanceKlass::cast(java_lang_Class::as_Klass(mirror.resolve()));
 808       if (may_be_eagerly_linked(ik)) {
 809         has_linked |= try_link_class(THREAD, ik);
 810       }
 811       if (CDSConfig::is_dumping_heap() && ik->is_linked() && !ik->is_initialized()) {
 812         AOTClassInitializer::maybe_preinit_class(ik, CHECK);
 813       }
 814     }
 815 
 816     if (!has_linked) {
 817       break;
 818     }
 819     // Class linking includes verification which may load more classes.
 820     // Keep scanning until we have linked no more classes.
 821   }
 822 
 823   // Resolve constant pool entries -- we don't load any new classes during this stage
 824   {
 825     ResourceMark rm(THREAD);
 826     CollectClassesForLinking collect_classes;
 827     const GrowableArray<OopHandle>* mirrors = collect_classes.mirrors();
 828     for (int i = 0; i < mirrors->length(); i++) {
 829       OopHandle mirror = mirrors->at(i);
 830       InstanceKlass* ik = InstanceKlass::cast(java_lang_Class::as_Klass(mirror.resolve()));
 831       AOTConstantPoolResolver::dumptime_resolve_constants(ik, CHECK);
 832       if (CDSConfig::is_dumping_preimage_static_archive()) {
 833         FinalImageRecipes::add_reflection_data_flags(ik, CHECK);
 834       }
 835     }
 836   }
 837 
 838   if (CDSConfig::is_dumping_final_static_archive()) {
 839     FinalImageRecipes::apply_recipes(CHECK);
 840   }
 841 }
 842 
 843 // Preload classes from a list, populate the shared spaces and dump to a
 844 // file.
 845 void MetaspaceShared::preload_and_dump(TRAPS) {
 846   CDSConfig::DumperThreadMark dumper_thread_mark(THREAD);
 847   ResourceMark rm(THREAD);
 848   HandleMark hm(THREAD);
 849 
 850   if (CDSConfig::is_dumping_final_static_archive() && AOTPrintTrainingInfo) {
 851     tty->print_cr("==================== archived_training_data ** before dumping ====================");
 852     TrainingData::print_archived_training_data_on(tty);
 853   }
 854 
 855   StaticArchiveBuilder builder;
 856   preload_and_dump_impl(builder, THREAD);
 857   if (HAS_PENDING_EXCEPTION) {
 858     if (PENDING_EXCEPTION->is_a(vmClasses::OutOfMemoryError_klass())) {
 859       log_error(cds)("Out of memory. Please run with a larger Java heap, current MaxHeapSize = "
 860                      "%zuM", MaxHeapSize/M);
 861       MetaspaceShared::writing_error();
 862     } else {
 863       log_error(cds)("%s: %s", PENDING_EXCEPTION->klass()->external_name(),
 864                      java_lang_String::as_utf8_string(java_lang_Throwable::message(PENDING_EXCEPTION)));
 865       MetaspaceShared::writing_error("Unexpected exception, use -Xlog:cds,exceptions=trace for detail");
 866     }
 867     if (CDSConfig::is_experimental_leyden_workflow()) {
 868       vm_exit(1);
 869     }
 870   }
 871 
 872   if (CDSConfig::new_aot_flags_used()) {
 873     if (CDSConfig::is_dumping_preimage_static_archive()) {
 874       // We are in the JVM that runs the training run. Continue execution,
 875       // so that it can finish all clean-up and return the correct exit
 876       // code to the OS.
 877     } else {
 878       // The JLI launcher only recognizes the "old" -Xshare:dump flag.
 879       // When the new -XX:AOTMode=create flag is used, we can't return
 880       // to the JLI launcher, as the launcher will fail when trying to
 881       // run the main class, which is not what we want.
 882       struct stat st;
 883       if (os::stat(AOTCache, &st) != 0) {
 884         tty->print_cr("AOTCache creation failed: %s", AOTCache);
 885         vm_exit(0);
 886       } else {
 887         tty->print_cr("AOTCache creation is complete: %s " INT64_FORMAT " bytes", AOTCache, (int64_t)(st.st_size));
 888         vm_exit(0);
 889       }
 890     }
 891   }
 892 }
 893 
 894 #if INCLUDE_CDS_JAVA_HEAP && defined(_LP64)
 895 void MetaspaceShared::adjust_heap_sizes_for_dumping() {
 896   if (!CDSConfig::is_dumping_heap() || UseCompressedOops) {
 897     return;
 898   }
 899   // CDS heap dumping requires all string oops to have an offset
 900   // from the heap bottom that can be encoded in 32-bit.
 901   julong max_heap_size = (julong)(4 * G);
 902 
 903   if (MinHeapSize > max_heap_size) {
 904     log_debug(cds)("Setting MinHeapSize to 4G for CDS dumping, original size = %zuM", MinHeapSize/M);
 905     FLAG_SET_ERGO(MinHeapSize, max_heap_size);
 906   }
 907   if (InitialHeapSize > max_heap_size) {
 908     log_debug(cds)("Setting InitialHeapSize to 4G for CDS dumping, original size = %zuM", InitialHeapSize/M);
 909     FLAG_SET_ERGO(InitialHeapSize, max_heap_size);
 910   }
 911   if (MaxHeapSize > max_heap_size) {
 912     log_debug(cds)("Setting MaxHeapSize to 4G for CDS dumping, original size = %zuM", MaxHeapSize/M);
 913     FLAG_SET_ERGO(MaxHeapSize, max_heap_size);
 914   }
 915 }
 916 #endif // INCLUDE_CDS_JAVA_HEAP && _LP64
 917 
 918 void MetaspaceShared::get_default_classlist(char* default_classlist, const size_t buf_size) {
 919   const char* filesep = os::file_separator();
 920   jio_snprintf(default_classlist, buf_size, "%s%slib%sclasslist",
 921                Arguments::get_java_home(), filesep, filesep);
 922 }
 923 
 924 void MetaspaceShared::preload_classes(TRAPS) {
 925   char default_classlist[JVM_MAXPATHLEN];
 926   const char* classlist_path;
 927 
 928   get_default_classlist(default_classlist, JVM_MAXPATHLEN);
 929   if (SharedClassListFile == nullptr) {
 930     classlist_path = default_classlist;
 931   } else {
 932     classlist_path = SharedClassListFile;
 933   }
 934 
 935   log_info(cds)("Loading classes to share ...");
 936   ClassListParser::parse_classlist(classlist_path,
 937                                    ClassListParser::_parse_all, CHECK);
 938   if (ExtraSharedClassListFile) {
 939     ClassListParser::parse_classlist(ExtraSharedClassListFile,
 940                                      ClassListParser::_parse_all, CHECK);
 941   }
 942   if (classlist_path != default_classlist) {
 943     struct stat statbuf;
 944     if (os::stat(default_classlist, &statbuf) == 0) {
 945       // File exists, let's use it.
 946       ClassListParser::parse_classlist(default_classlist,
 947                                        ClassListParser::_parse_lambda_forms_invokers_only, CHECK);
 948     }
 949   }
 950 
 951   // Some classes are used at CDS runtime but are not loaded, and therefore archived, at
 952   // dumptime. We can perform dummmy calls to these classes at dumptime to ensure they
 953   // are archived.
 954   exercise_runtime_cds_code(CHECK);
 955 
 956   log_info(cds)("Loading classes to share: done.");
 957 }
 958 
 959 void MetaspaceShared::exercise_runtime_cds_code(TRAPS) {
 960   // Exercise the manifest processing code
 961   const char* dummy = "Manifest-Version: 1.0\n";
 962   CDSProtectionDomain::create_jar_manifest(dummy, strlen(dummy), CHECK);
 963 
 964   // Exercise FileSystem and URL code
 965   CDSProtectionDomain::to_file_URL("dummy.jar", Handle(), CHECK);
 966 }
 967 
 968 bool MetaspaceShared::is_recording_preimage_static_archive() {
 969   if (CDSConfig::is_dumping_preimage_static_archive()) {
 970       return _preimage_static_archive_dumped == 0;
 971   }
 972   return false;
 973 }
 974 
 975 jlong MetaspaceShared::get_preimage_static_archive_recording_duration() {
 976   if (CDSConfig::is_dumping_preimage_static_archive()) {
 977     if (_preimage_static_archive_recording_duration == 0) {
 978       // The recording has not yet finished so return the current elapsed time.
 979       return Management::ticks_to_ms(os::elapsed_counter());
 980     }
 981     return _preimage_static_archive_recording_duration;
 982   }
 983   return 0;
 984 }
 985 
 986 void MetaspaceShared::preload_and_dump_impl(StaticArchiveBuilder& builder, TRAPS) {
 987   if (CDSConfig::is_dumping_preimage_static_archive()) {
 988     if (Atomic::cmpxchg(&_preimage_static_archive_dumped, 0, 1) != 0) {
 989       return;
 990     }
 991     _preimage_static_archive_recording_duration = Management::ticks_to_ms(os::elapsed_counter());
 992   }
 993 
 994   if (CDSConfig::is_dumping_classic_static_archive()) {
 995     // We are running with -Xshare:dump
 996     preload_classes(CHECK);
 997 
 998     if (SharedArchiveConfigFile) {
 999       log_info(cds)("Reading extra data from %s ...", SharedArchiveConfigFile);
1000       read_extra_data(THREAD, SharedArchiveConfigFile);
1001       log_info(cds)("Reading extra data: done.");
1002     }
1003   }
1004 
1005   if (CDSConfig::is_dumping_preimage_static_archive()) {
1006     log_info(cds)("Reading lambda form invokers from JDK default classlist ...");
1007     char default_classlist[JVM_MAXPATHLEN];
1008     get_default_classlist(default_classlist, JVM_MAXPATHLEN);
1009     struct stat statbuf;
1010     if (os::stat(default_classlist, &statbuf) == 0) {
1011       ClassListParser::parse_classlist(default_classlist,
1012                                        ClassListParser::_parse_lambda_forms_invokers_only, CHECK);
1013     }
1014   }
1015 
1016 #if INCLUDE_CDS_JAVA_HEAP
1017   if (CDSConfig::is_dumping_heap()) {
1018     assert(CDSConfig::allow_only_single_java_thread(), "Required");
1019     if (!HeapShared::is_archived_boot_layer_available(THREAD)) {
1020       log_info(cds)("archivedBootLayer not available, disabling full module graph");
1021       CDSConfig::stop_dumping_full_module_graph();
1022     }
1023     // Do this before link_shared_classes(), as the following line may load new classes.
1024     HeapShared::init_for_dumping(CHECK);
1025   }
1026 #endif
1027 
1028   if (CDSConfig::is_dumping_final_static_archive()) {
1029     if (ExtraSharedClassListFile) {
1030       log_info(cds)("Loading extra classes from %s ...", ExtraSharedClassListFile);
1031       ClassListParser::parse_classlist(ExtraSharedClassListFile,
1032                                        ClassListParser::_parse_all, CHECK);
1033     }
1034   }
1035 
1036   // Rewrite and link classes
1037   log_info(cds)("Rewriting and linking classes ...");
1038 
1039   // Link any classes which got missed. This would happen if we have loaded classes that
1040   // were not explicitly specified in the classlist. E.g., if an interface implemented by class K
1041   // fails verification, all other interfaces that were not specified in the classlist but
1042   // are implemented by K are not verified.
1043   link_shared_classes(CHECK);
1044   log_info(cds)("Rewriting and linking classes: done");
1045 
1046   TrainingData::init_dumptime_table(CHECK); // captures TrainingDataSetLocker
1047 
1048   if (CDSConfig::is_dumping_regenerated_lambdaform_invokers()) {
1049     LambdaFormInvokers::regenerate_holder_classes(CHECK);
1050   }
1051 
1052 #if INCLUDE_CDS_JAVA_HEAP
1053   if (CDSConfig::is_dumping_heap()) {
1054     ArchiveHeapWriter::init();
1055 
1056     if (CDSConfig::is_dumping_full_module_graph()) {
1057       ClassLoaderDataShared::ensure_module_entry_tables_exist();
1058       HeapShared::reset_archived_object_states(CHECK);
1059     }
1060 
1061     if (ArchiveLoaderLookupCache) {
1062       SystemDictionaryShared::create_loader_positive_lookup_cache(CHECK);
1063     }
1064 
1065     AOTReferenceObjSupport::initialize(CHECK);
1066     AOTReferenceObjSupport::stabilize_cached_reference_objects(CHECK);
1067 
1068     if (CDSConfig::is_initing_classes_at_dump_time()) {
1069       // java.lang.Class::reflectionFactory cannot be archived yet. We set this field
1070       // to null, and it will be initialized again at runtime.
1071       log_debug(cds)("Resetting Class::reflectionFactory");
1072       TempNewSymbol method_name = SymbolTable::new_symbol("resetArchivedStates");
1073       Symbol* method_sig = vmSymbols::void_method_signature();
1074       JavaValue result(T_VOID);
1075       JavaCalls::call_static(&result, vmClasses::Class_klass(),
1076                              method_name, method_sig, CHECK);
1077 
1078       // Perhaps there is a way to avoid hard-coding these names here.
1079       // See discussion in JDK-8342481.
1080     }
1081 
1082     // Do this at the very end, when no Java code will be executed. Otherwise
1083     // some new strings may be added to the intern table.
1084     StringTable::allocate_shared_strings_array(CHECK);
1085   } else {
1086     log_info(cds)("Not dumping heap, reset CDSConfig::_is_using_optimized_module_handling");
1087     CDSConfig::stop_using_optimized_module_handling();
1088   }
1089 #endif
1090 
1091   VM_PopulateDumpSharedSpace op(builder);
1092   VMThread::execute(&op);
1093   FileMapInfo* mapinfo = op.map_info();
1094   ArchiveHeapInfo* heap_info = op.heap_info();
1095 
1096   if (CDSConfig::is_dumping_final_static_archive()) {
1097     if (AOTCodeCache::is_caching_enabled()) {
1098       if (log_is_enabled(Info, cds, jit)) {
1099         AOTCacheAccess::test_heap_access_api();
1100       }
1101 
1102       // We have just created the final image. Let's run the AOT compiler
1103       if (AOTPrintTrainingInfo) {
1104         tty->print_cr("==================== archived_training_data ** after dumping ====================");
1105         TrainingData::print_archived_training_data_on(tty);
1106       }
1107 
1108       CDSConfig::enable_dumping_aot_code();
1109       {
1110         builder.start_ac_region();
1111         Precompiler::compile_cached_code(&builder, CHECK);
1112         // Write the contents to aot code region and close AOTCodeCache before packing the region
1113         AOTCodeCache::close();
1114         builder.end_ac_region();
1115       }
1116       CDSConfig::disable_dumping_aot_code();
1117     }
1118   }
1119 
1120   bool status = write_static_archive(&builder, mapinfo, heap_info);
1121   if (status && CDSConfig::is_dumping_preimage_static_archive()) {
1122     if (CDSConfig::is_experimental_leyden_workflow()) {
1123       fork_and_dump_final_static_archive_experimental_leyden_workflow(CHECK);
1124     } else {
1125       tty->print_cr("%s AOTConfiguration recorded: %s",
1126                     CDSConfig::has_temp_aot_config_file() ? "Temporary" : "", AOTConfiguration);
1127       if (CDSConfig::is_one_step_training()) {
1128         fork_and_dump_final_static_archive(CHECK);
1129       }
1130     }
1131   }
1132 
1133   if (!status) {
1134     THROW_MSG(vmSymbols::java_io_IOException(), "Encountered error while dumping");
1135   }
1136 }
1137 
1138 bool MetaspaceShared::write_static_archive(ArchiveBuilder* builder, FileMapInfo* map_info, ArchiveHeapInfo* heap_info) {
1139   // relocate the data so that it can be mapped to MetaspaceShared::requested_base_address()
1140   // without runtime relocation.
1141   builder->relocate_to_requested();
1142 
1143   map_info->open_as_output();
1144   if (!map_info->is_open()) {
1145     return false;
1146   }
1147   builder->write_archive(map_info, heap_info);
1148 
1149   if (AllowArchivingWithJavaAgent) {
1150     log_warning(cds)("This %s was created with AllowArchivingWithJavaAgent. It should be used "
1151             "for testing purposes only and should not be used in a production environment", CDSConfig::type_of_archive_being_loaded());
1152   }
1153   return true;
1154 }
1155 
1156 static void print_java_launcher(outputStream* st) {
1157   st->print("%s%sbin%sjava", Arguments::get_java_home(), os::file_separator(), os::file_separator());
1158 }
1159 
1160 static void append_args(GrowableArray<Handle>* args, const char* arg, TRAPS) {
1161   Handle string = java_lang_String::create_from_str(arg, CHECK);
1162   args->append(string);
1163 }
1164 
1165 // Pass all options in Arguments::jvm_args_array() to a child JVM process
1166 // using the JAVA_TOOL_OPTIONS environment variable.
1167 static int exec_jvm_with_java_tool_options(const char* java_launcher_path, TRAPS) {
1168   ResourceMark rm(THREAD);
1169   HandleMark hm(THREAD);
1170   GrowableArray<Handle> args;
1171 
1172   const char* cp = Arguments::get_appclasspath();
1173   if (cp != nullptr && strlen(cp) > 0 && strcmp(cp, ".") != 0) {
1174     // We cannot use "-cp", because "-cp" is only interpreted by the java launcher,
1175     // and is not interpreter by arguments.cpp when it loads args from JAVA_TOOL_OPTIONS
1176     stringStream ss;
1177     ss.print("-Djava.class.path=");
1178     ss.print_raw(cp);
1179     append_args(&args, ss.freeze(), CHECK_0);
1180     // CDS$ProcessLauncher::execWithJavaToolOptions() must unset CLASSPATH, which has
1181     // a higher priority than -Djava.class.path=
1182   }
1183 
1184   // Pass all arguments. These include those from JAVA_TOOL_OPTIONS and _JAVA_OPTIONS.
1185   for (int i = 0; i < Arguments::num_jvm_args(); i++) {
1186     const char* arg = Arguments::jvm_args_array()[i];
1187     if (strncmp("-XX:AOTMode", arg, 11) == 0) {
1188       // Filter it out. We will set AOTMode=create below.
1189     } else {
1190       append_args(&args, arg, CHECK_0);
1191     }
1192   }
1193 
1194   // We don't pass Arguments::jvm_flags_array(), as those will be added by
1195   // the child process when it loads .hotspotrc
1196 
1197   if (CDSConfig::is_experimental_leyden_workflow()) {
1198     stringStream ss;
1199     ss.print("-XX:CDSPreimage=");
1200     ss.print_raw(CDSPreimage);
1201     append_args(&args, ss.freeze(), CHECK_0);
1202   } else {
1203     if (CDSConfig::has_temp_aot_config_file()) {
1204       stringStream ss;
1205       ss.print("-XX:AOTConfiguration=");
1206       ss.print_raw(AOTConfiguration);
1207       append_args(&args, ss.freeze(), CHECK_0);
1208     }
1209     append_args(&args, "-XX:AOTMode=create", CHECK_0);
1210   }
1211 
1212   Symbol* klass_name = SymbolTable::new_symbol("jdk/internal/misc/CDS$ProcessLauncher");
1213   Klass* k = SystemDictionary::resolve_or_fail(klass_name, true, CHECK_0);
1214   Symbol* methodName = SymbolTable::new_symbol("execWithJavaToolOptions");
1215   Symbol* methodSignature = SymbolTable::new_symbol("(Ljava/lang/String;[Ljava/lang/String;)I");
1216 
1217   Handle launcher = java_lang_String::create_from_str(java_launcher_path, CHECK_0);
1218   objArrayOop array = oopFactory::new_objArray(vmClasses::String_klass(), args.length(), CHECK_0);
1219   for (int i = 0; i < args.length(); i++) {
1220     array->obj_at_put(i, args.at(i)());
1221   }
1222   objArrayHandle launcher_args(THREAD, array);
1223 
1224   // The following call will pass all options inside the JAVA_TOOL_OPTIONS env variable to
1225   // the child process. It will also clear the _JAVA_OPTIONS and CLASSPATH env variables for
1226   // the child process.
1227   //
1228   // Note: the env variables are set only for the child process. They are not changed
1229   // for the current process. See java.lang.ProcessBuilder::environment().
1230   JavaValue result(T_OBJECT);
1231   JavaCallArguments javacall_args(2);
1232   javacall_args.push_oop(launcher);
1233   javacall_args.push_oop(launcher_args);
1234   JavaCalls::call_static(&result,
1235                           InstanceKlass::cast(k),
1236                           methodName,
1237                           methodSignature,
1238                           &javacall_args,
1239                           CHECK_0);
1240   return result.get_jint();
1241 }
1242 
1243 // This is for debugging purposes only (-XX:+CDSManualFinalImage) so we don't bother
1244 // quoating any special characters. The user should avoid using special chars.
1245 static void print_vm_arguments(outputStream* st) {
1246   const char* cp = Arguments::get_appclasspath();
1247   if (cp != nullptr && strlen(cp) > 0 && strcmp(cp, ".") != 0) {
1248     st->print(" -cp ");  st->print_raw(cp);
1249   }
1250   for (int i = 0; i < Arguments::num_jvm_args(); i++) {
1251     st->print(" %s", Arguments::jvm_args_array()[i]);
1252   }
1253 }
1254 
1255 void MetaspaceShared::fork_and_dump_final_static_archive_experimental_leyden_workflow(TRAPS) {
1256   assert(CDSConfig::is_dumping_preimage_static_archive(), "sanity");
1257 
1258   ResourceMark rm;
1259   stringStream ss;
1260   print_java_launcher(&ss);
1261 
1262   if (CDSManualFinalImage) {
1263     print_vm_arguments(&ss);
1264     ss.print(" -XX:CDSPreimage=%s", SharedArchiveFile);
1265     const char* cmd = ss.freeze();
1266 
1267     tty->print_cr("-XX:+CDSManualFinalImage is specified");
1268     tty->print_cr("Please manually execute the following command to create the final CDS image:");
1269     tty->print("    "); tty->print_raw_cr(cmd);
1270 
1271     // The following is useful if the dumping was trigger by a script that builds
1272     // a complex command-line.
1273     tty->print_cr("Note: to recreate the preimage only:");
1274     tty->print_cr("    rm -f %s", CacheDataStore);
1275     tty->print("    ");
1276     print_java_launcher(tty);
1277     print_vm_arguments(tty);
1278     if (Arguments::java_command() != nullptr) {
1279       tty->print(" %s", Arguments::java_command());
1280     }
1281     tty->cr();
1282   } else {
1283     const char* cmd = ss.freeze();
1284     log_info(cds)("Launching child process to create final CDS image:");
1285     log_info(cds)("    %s", cmd);
1286     int status = exec_jvm_with_java_tool_options(cmd, CHECK);
1287     if (status != 0) {
1288       log_error(cds)("Child process finished; status = %d", status);
1289       log_error(cds)("To reproduce the error");
1290       ResourceMark rm;
1291       LogStream ls(Log(cds)::error());
1292       ls.print("    "); ls.print_raw_cr(cmd);
1293 
1294       // The following is useful if the dumping was trigger by a script that builds
1295       // a complex command-line.
1296       ls.print_cr("Note: to recreate the preimage only:");
1297       ls.print_cr("    rm -f %s", CacheDataStore);
1298       ls.print("    ");
1299       print_java_launcher(&ls);
1300       print_vm_arguments(&ls);
1301       ls.print(" -XX:+UnlockDiagnosticVMOptions -XX:+CDSManualFinalImage");
1302       if (Arguments::java_command() != nullptr) {
1303         ls.print(" %s", Arguments::java_command());
1304       }
1305       ls.cr();
1306 
1307       vm_direct_exit(status);
1308     } else {
1309       log_info(cds)("Child process finished; status = %d", status);
1310       // On Windows, need WRITE permission to remove the file.
1311       WINDOWS_ONLY(chmod(CDSPreimage, _S_IREAD | _S_IWRITE));
1312       status = remove(CDSPreimage);
1313       if (status != 0) {
1314         log_error(cds)("Failed to remove CDSPreimage file %s", CDSPreimage);
1315       } else {
1316         log_info(cds)("Removed CDSPreimage file %s", CDSPreimage);
1317       }
1318     }
1319   }
1320 }
1321 
1322 void MetaspaceShared::fork_and_dump_final_static_archive(TRAPS) {
1323   assert(CDSConfig::is_dumping_preimage_static_archive(), "sanity");
1324 
1325   ResourceMark rm;
1326   stringStream ss;
1327   print_java_launcher(&ss);
1328   const char* cmd = ss.freeze();
1329   tty->print_cr("Launching child process %s to assemble AOT cache %s using configuration %s", cmd, AOTCacheOutput, AOTConfiguration);
1330   int status = exec_jvm_with_java_tool_options(cmd, CHECK);
1331   if (status != 0) {
1332     log_error(cds)("Child process failed; status = %d", status);
1333     // We leave the temp config file for debugging
1334   } else if (CDSConfig::has_temp_aot_config_file()) {
1335     const char* tmp_config = AOTConfiguration;
1336     // On Windows, need WRITE permission to remove the file.
1337     WINDOWS_ONLY(chmod(tmp_config, _S_IREAD | _S_IWRITE));
1338     status = remove(tmp_config);
1339     if (status != 0) {
1340       log_error(cds)("Failed to remove temporary AOT configuration file %s", tmp_config);
1341     } else {
1342       tty->print_cr("Removed temporary AOT configuration file %s", tmp_config);
1343     }
1344   }
1345 }
1346 
1347 // Returns true if the class's status has changed.
1348 bool MetaspaceShared::try_link_class(JavaThread* current, InstanceKlass* ik) {
1349   ExceptionMark em(current);
1350   JavaThread* THREAD = current; // For exception macros.
1351   assert(CDSConfig::is_dumping_archive(), "sanity");
1352 
1353   if (ik->is_shared() && !CDSConfig::is_dumping_final_static_archive()) {
1354     assert(CDSConfig::is_dumping_dynamic_archive(), "must be");
1355     return false;
1356   }
1357 
1358   if (ik->is_loaded() && !ik->is_linked() && ik->can_be_verified_at_dumptime() &&
1359       !SystemDictionaryShared::has_class_failed_verification(ik)) {
1360     bool saved = BytecodeVerificationLocal;
1361     if (ik->is_shared_unregistered_class() && ik->class_loader() == nullptr) {
1362       // The verification decision is based on BytecodeVerificationRemote
1363       // for non-system classes. Since we are using the null classloader
1364       // to load non-system classes for customized class loaders during dumping,
1365       // we need to temporarily change BytecodeVerificationLocal to be the same as
1366       // BytecodeVerificationRemote. Note this can cause the parent system
1367       // classes also being verified. The extra overhead is acceptable during
1368       // dumping.
1369       BytecodeVerificationLocal = BytecodeVerificationRemote;
1370     }
1371     ik->link_class(THREAD);
1372     if (HAS_PENDING_EXCEPTION) {
1373       ResourceMark rm(THREAD);
1374       log_warning(cds)("Preload Warning: Verification failed for %s",
1375                     ik->external_name());
1376       CLEAR_PENDING_EXCEPTION;
1377       SystemDictionaryShared::set_class_has_failed_verification(ik);
1378     } else {
1379       assert(!SystemDictionaryShared::has_class_failed_verification(ik), "sanity");
1380       ik->compute_has_loops_flag_for_methods();
1381     }
1382     BytecodeVerificationLocal = saved;
1383     return true;
1384   } else {
1385     return false;
1386   }
1387 }
1388 
1389 void VM_PopulateDumpSharedSpace::dump_java_heap_objects() {
1390   if (CDSConfig::is_dumping_heap()) {
1391     HeapShared::write_heap(&_heap_info);
1392   } else if (!CDSConfig::is_dumping_preimage_static_archive()) {
1393     CDSConfig::log_reasons_for_not_dumping_heap();
1394   }
1395 }
1396 
1397 void MetaspaceShared::set_shared_metaspace_range(void* base, void *static_top, void* top) {
1398   assert(base <= static_top && static_top <= top, "must be");
1399   _shared_metaspace_static_top = static_top;
1400   MetaspaceObj::set_shared_metaspace_range(base, top);
1401 }
1402 
1403 bool MetaspaceShared::is_shared_dynamic(void* p) {
1404   if ((p < MetaspaceObj::shared_metaspace_top()) &&
1405       (p >= _shared_metaspace_static_top)) {
1406     return true;
1407   } else {
1408     return false;
1409   }
1410 }
1411 
1412 bool MetaspaceShared::is_shared_static(void* p) {
1413   if (is_in_shared_metaspace(p) && !is_shared_dynamic(p)) {
1414     return true;
1415   } else {
1416     return false;
1417   }
1418 }
1419 
1420 // This function is called when the JVM is unable to load the specified archive(s) due to one
1421 // of the following conditions.
1422 // - There's an error that indicates that the archive(s) files were corrupt or otherwise damaged.
1423 // - When -XX:+RequireSharedSpaces is specified, AND the JVM cannot load the archive(s) due
1424 //   to version or classpath mismatch.
1425 void MetaspaceShared::unrecoverable_loading_error(const char* message) {
1426   log_error(cds)("An error has occurred while processing the %s.", CDSConfig::type_of_archive_being_loaded());
1427   if (message != nullptr) {
1428     log_error(cds)("%s", message);
1429   }
1430 
1431   if (CDSConfig::is_dumping_final_static_archive()) {
1432     vm_exit_during_initialization("Must be a valid AOT configuration generated by the current JVM", AOTConfiguration);
1433   } else if (CDSConfig::new_aot_flags_used()) {
1434     vm_exit_during_initialization("Unable to use AOT cache.", nullptr);
1435   } else {
1436     vm_exit_during_initialization("Unable to use shared archive.", nullptr);
1437   }
1438 }
1439 
1440 // This function is called when the JVM is unable to write the specified CDS archive due to an
1441 // unrecoverable error.
1442 void MetaspaceShared::unrecoverable_writing_error(const char* message) {
1443   writing_error(message);
1444   vm_direct_exit(1);
1445 }
1446 
1447 // This function is called when the JVM is unable to write the specified CDS archive due to a
1448 // an error. The error will be propagated
1449 void MetaspaceShared::writing_error(const char* message) {
1450   log_error(cds)("An error has occurred while writing the shared archive file.");
1451   if (message != nullptr) {
1452     log_error(cds)("%s", message);
1453   }
1454 }
1455 
1456 void MetaspaceShared::initialize_runtime_shared_and_meta_spaces() {
1457   assert(CDSConfig::is_using_archive(), "Must be called when UseSharedSpaces is enabled");
1458   MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE;
1459 
1460   FileMapInfo* static_mapinfo = FileMapInfo::current_info();
1461   FileMapInfo* dynamic_mapinfo = nullptr;
1462 
1463   if (static_mapinfo != nullptr) {
1464     log_info(cds)("Core region alignment: %zu", static_mapinfo->core_region_alignment());
1465     dynamic_mapinfo = open_dynamic_archive();
1466 
1467     log_info(cds)("ArchiveRelocationMode: %d", ArchiveRelocationMode);
1468 
1469     // First try to map at the requested address
1470     result = map_archives(static_mapinfo, dynamic_mapinfo, true);
1471     if (result == MAP_ARCHIVE_MMAP_FAILURE) {
1472       // Mapping has failed (probably due to ASLR). Let's map at an address chosen
1473       // by the OS.
1474       log_info(cds)("Try to map archive(s) at an alternative address");
1475       result = map_archives(static_mapinfo, dynamic_mapinfo, false);
1476     }
1477   }
1478 
1479   if (result == MAP_ARCHIVE_SUCCESS) {
1480     bool dynamic_mapped = (dynamic_mapinfo != nullptr && dynamic_mapinfo->is_mapped());
1481     char* cds_base = static_mapinfo->mapped_base();
1482     char* cds_end =  dynamic_mapped ? dynamic_mapinfo->mapped_end() : static_mapinfo->mapped_end();
1483     // Register CDS memory region with LSan.
1484     LSAN_REGISTER_ROOT_REGION(cds_base, cds_end - cds_base);
1485     set_shared_metaspace_range(cds_base, static_mapinfo->mapped_end(), cds_end);
1486     _relocation_delta = static_mapinfo->relocation_delta();
1487     _requested_base_address = static_mapinfo->requested_base_address();
1488     if (dynamic_mapped) {
1489       // turn AutoCreateSharedArchive off if successfully mapped
1490       AutoCreateSharedArchive = false;
1491     }
1492   } else {
1493     set_shared_metaspace_range(nullptr, nullptr, nullptr);
1494     if (CDSConfig::is_dumping_dynamic_archive()) {
1495       log_warning(cds)("-XX:ArchiveClassesAtExit is unsupported when base CDS archive is not loaded. Run with -Xlog:cds for more info.");
1496     }
1497     UseSharedSpaces = false;
1498     // The base archive cannot be mapped. We cannot dump the dynamic shared archive.
1499     AutoCreateSharedArchive = false;
1500     CDSConfig::disable_dumping_dynamic_archive();
1501     log_info(cds)("Unable to map shared spaces");
1502     if (PrintSharedArchiveAndExit) {
1503       MetaspaceShared::unrecoverable_loading_error("Unable to use shared archive.");
1504     } else if (RequireSharedSpaces) {
1505       MetaspaceShared::unrecoverable_loading_error("Unable to map shared spaces");
1506     } else if (CDSConfig::is_dumping_final_static_archive()) {
1507       assert(CDSPreimage != nullptr, "must be");
1508       log_error(cds)("Unable to map shared spaces for CDSPreimage = %s", CDSPreimage);
1509       MetaspaceShared::unrecoverable_loading_error();
1510     }
1511   }
1512 
1513   // If mapping failed and -XShare:on, the vm should exit
1514   bool has_failed = false;
1515   if (static_mapinfo != nullptr && !static_mapinfo->is_mapped()) {
1516     has_failed = true;
1517     delete static_mapinfo;
1518   }
1519   if (dynamic_mapinfo != nullptr && !dynamic_mapinfo->is_mapped()) {
1520     has_failed = true;
1521     delete dynamic_mapinfo;
1522   }
1523   if (RequireSharedSpaces && has_failed) {
1524     // static archive mapped but dynamic archive failed
1525       MetaspaceShared::unrecoverable_loading_error("Unable to map shared spaces");
1526   }
1527 }
1528 
1529 // This is called very early at VM start up to get the size of the cached_code region
1530 void MetaspaceShared::open_static_archive() {
1531   if (!UseSharedSpaces) { // FIXME -- is this still needed??
1532     return;
1533   }
1534   const char* static_archive = CDSConfig::input_static_archive_path();
1535   assert(static_archive != nullptr, "sanity");
1536   FileMapInfo* mapinfo = new FileMapInfo(static_archive, true);
1537   if (!mapinfo->open_as_input()) {
1538     delete(mapinfo);
1539   } else {
1540     FileMapRegion* r = mapinfo->region_at(MetaspaceShared::ac);
1541     AOTCacheAccess::set_aot_code_region_size(r->used_aligned());
1542   }
1543 }
1544 
1545 FileMapInfo* MetaspaceShared::open_dynamic_archive() {
1546   if (CDSConfig::is_dumping_dynamic_archive()) {
1547     return nullptr;
1548   }
1549   const char* dynamic_archive = CDSConfig::input_dynamic_archive_path();
1550   if (dynamic_archive == nullptr) {
1551     return nullptr;
1552   }
1553 
1554   FileMapInfo* mapinfo = new FileMapInfo(dynamic_archive, false);
1555   if (!mapinfo->open_as_input()) {
1556     delete(mapinfo);
1557     if (RequireSharedSpaces) {
1558       MetaspaceShared::unrecoverable_loading_error("Failed to initialize dynamic archive");
1559     }
1560     return nullptr;
1561   }
1562   return mapinfo;
1563 }
1564 
1565 // use_requested_addr:
1566 //  true  = map at FileMapHeader::_requested_base_address
1567 //  false = map at an alternative address picked by OS.
1568 MapArchiveResult MetaspaceShared::map_archives(FileMapInfo* static_mapinfo, FileMapInfo* dynamic_mapinfo,
1569                                                bool use_requested_addr) {
1570   if (use_requested_addr && static_mapinfo->requested_base_address() == nullptr) {
1571     log_info(cds)("Archive(s) were created with -XX:SharedBaseAddress=0. Always map at os-selected address.");
1572     return MAP_ARCHIVE_MMAP_FAILURE;
1573   }
1574 
1575   PRODUCT_ONLY(if (ArchiveRelocationMode == 1 && use_requested_addr) {
1576       // For product build only -- this is for benchmarking the cost of doing relocation.
1577       // For debug builds, the check is done below, after reserving the space, for better test coverage
1578       // (see comment below).
1579       log_info(cds)("ArchiveRelocationMode == 1: always map archive(s) at an alternative address");
1580       return MAP_ARCHIVE_MMAP_FAILURE;
1581     });
1582 
1583   if (ArchiveRelocationMode == 2 && !use_requested_addr) {
1584     log_info(cds)("ArchiveRelocationMode == 2: never map archive(s) at an alternative address");
1585     return MAP_ARCHIVE_MMAP_FAILURE;
1586   };
1587 
1588   if (dynamic_mapinfo != nullptr) {
1589     // Ensure that the OS won't be able to allocate new memory spaces between the two
1590     // archives, or else it would mess up the simple comparison in MetaspaceObj::is_shared().
1591     assert(static_mapinfo->mapping_end_offset() == dynamic_mapinfo->mapping_base_offset(), "no gap");
1592   }
1593 
1594   ReservedSpace total_space_rs, archive_space_rs, class_space_rs;
1595   MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE;
1596   size_t prot_zone_size = 0;
1597   char* mapped_base_address = reserve_address_space_for_archives(static_mapinfo,
1598                                                                  dynamic_mapinfo,
1599                                                                  use_requested_addr,
1600                                                                  total_space_rs,
1601                                                                  archive_space_rs,
1602                                                                  class_space_rs);
1603   if (mapped_base_address == nullptr) {
1604     result = MAP_ARCHIVE_MMAP_FAILURE;
1605     log_debug(cds)("Failed to reserve spaces (use_requested_addr=%u)", (unsigned)use_requested_addr);
1606   } else {
1607 
1608     if (Metaspace::using_class_space()) {
1609       prot_zone_size = protection_zone_size();
1610     }
1611 
1612 #ifdef ASSERT
1613     // Some sanity checks after reserving address spaces for archives
1614     //  and class space.
1615     assert(archive_space_rs.is_reserved(), "Sanity");
1616     if (Metaspace::using_class_space()) {
1617       assert(archive_space_rs.base() == mapped_base_address &&
1618           archive_space_rs.size() > protection_zone_size(),
1619           "Archive space must lead and include the protection zone");
1620       // Class space must closely follow the archive space. Both spaces
1621       //  must be aligned correctly.
1622       assert(class_space_rs.is_reserved() && class_space_rs.size() > 0,
1623              "A class space should have been reserved");
1624       assert(class_space_rs.base() >= archive_space_rs.end(),
1625              "class space should follow the cds archive space");
1626       assert(is_aligned(archive_space_rs.base(),
1627                         core_region_alignment()),
1628              "Archive space misaligned");
1629       assert(is_aligned(class_space_rs.base(),
1630                         Metaspace::reserve_alignment()),
1631              "class space misaligned");
1632     }
1633 #endif // ASSERT
1634 
1635     log_info(cds)("Reserved archive_space_rs [" INTPTR_FORMAT " - " INTPTR_FORMAT "] (%zu) bytes%s",
1636                    p2i(archive_space_rs.base()), p2i(archive_space_rs.end()), archive_space_rs.size(),
1637                    (prot_zone_size > 0 ? " (includes protection zone)" : ""));
1638     log_info(cds)("Reserved class_space_rs   [" INTPTR_FORMAT " - " INTPTR_FORMAT "] (%zu) bytes",
1639                    p2i(class_space_rs.base()), p2i(class_space_rs.end()), class_space_rs.size());
1640 
1641     if (MetaspaceShared::use_windows_memory_mapping()) {
1642       // We have now reserved address space for the archives, and will map in
1643       //  the archive files into this space.
1644       //
1645       // Special handling for Windows: on Windows we cannot map a file view
1646       //  into an existing memory mapping. So, we unmap the address range we
1647       //  just reserved again, which will make it available for mapping the
1648       //  archives.
1649       // Reserving this range has not been for naught however since it makes
1650       //  us reasonably sure the address range is available.
1651       //
1652       // But still it may fail, since between unmapping the range and mapping
1653       //  in the archive someone else may grab the address space. Therefore
1654       //  there is a fallback in FileMap::map_region() where we just read in
1655       //  the archive files sequentially instead of mapping it in. We couple
1656       //  this with use_requested_addr, since we're going to patch all the
1657       //  pointers anyway so there's no benefit to mmap.
1658       if (use_requested_addr) {
1659         assert(!total_space_rs.is_reserved(), "Should not be reserved for Windows");
1660         log_info(cds)("Windows mmap workaround: releasing archive space.");
1661         MemoryReserver::release(archive_space_rs);
1662         // Mark as not reserved
1663         archive_space_rs = {};
1664         // The protection zone is part of the archive:
1665         // See comment above, the Windows way of loading CDS is to mmap the individual
1666         // parts of the archive into the address region we just vacated. The protection
1667         // zone will not be mapped (and, in fact, does not exist as physical region in
1668         // the archive). Therefore, after removing the archive space above, we must
1669         // re-reserve the protection zone part lest something else gets mapped into that
1670         // area later.
1671         if (prot_zone_size > 0) {
1672           assert(prot_zone_size >= os::vm_allocation_granularity(), "must be"); // not just page size!
1673           char* p = os::attempt_reserve_memory_at(mapped_base_address, prot_zone_size,
1674                                                   mtClassShared);
1675           assert(p == mapped_base_address || p == nullptr, "must be");
1676           if (p == nullptr) {
1677             log_debug(cds)("Failed to re-reserve protection zone");
1678             return MAP_ARCHIVE_MMAP_FAILURE;
1679           }
1680         }
1681       }
1682     }
1683 
1684     if (prot_zone_size > 0) {
1685       os::commit_memory(mapped_base_address, prot_zone_size, false); // will later be protected
1686       // Before mapping the core regions into the newly established address space, we mark
1687       // start and the end of the future protection zone with canaries. That way we easily
1688       // catch mapping errors (accidentally mapping data into the future protection zone).
1689       *(mapped_base_address) = 'P';
1690       *(mapped_base_address + prot_zone_size - 1) = 'P';
1691     }
1692 
1693     MapArchiveResult static_result = map_archive(static_mapinfo, mapped_base_address, archive_space_rs);
1694     MapArchiveResult dynamic_result = (static_result == MAP_ARCHIVE_SUCCESS) ?
1695                                      map_archive(dynamic_mapinfo, mapped_base_address, archive_space_rs) : MAP_ARCHIVE_OTHER_FAILURE;
1696 
1697     DEBUG_ONLY(if (ArchiveRelocationMode == 1 && use_requested_addr) {
1698       // This is for simulating mmap failures at the requested address. In
1699       //  debug builds, we do it here (after all archives have possibly been
1700       //  mapped), so we can thoroughly test the code for failure handling
1701       //  (releasing all allocated resource, etc).
1702       log_info(cds)("ArchiveRelocationMode == 1: always map archive(s) at an alternative address");
1703       if (static_result == MAP_ARCHIVE_SUCCESS) {
1704         static_result = MAP_ARCHIVE_MMAP_FAILURE;
1705       }
1706       if (dynamic_result == MAP_ARCHIVE_SUCCESS) {
1707         dynamic_result = MAP_ARCHIVE_MMAP_FAILURE;
1708       }
1709     });
1710 
1711     if (static_result == MAP_ARCHIVE_SUCCESS) {
1712       if (dynamic_result == MAP_ARCHIVE_SUCCESS) {
1713         result = MAP_ARCHIVE_SUCCESS;
1714       } else if (dynamic_result == MAP_ARCHIVE_OTHER_FAILURE) {
1715         assert(dynamic_mapinfo != nullptr && !dynamic_mapinfo->is_mapped(), "must have failed");
1716         // No need to retry mapping the dynamic archive again, as it will never succeed
1717         // (bad file, etc) -- just keep the base archive.
1718         log_warning(cds, dynamic)("Unable to use shared archive. The top archive failed to load: %s",
1719                                   dynamic_mapinfo->full_path());
1720         result = MAP_ARCHIVE_SUCCESS;
1721         // TODO, we can give the unused space for the dynamic archive to class_space_rs, but there's no
1722         // easy API to do that right now.
1723       } else {
1724         result = MAP_ARCHIVE_MMAP_FAILURE;
1725       }
1726     } else if (static_result == MAP_ARCHIVE_OTHER_FAILURE) {
1727       result = MAP_ARCHIVE_OTHER_FAILURE;
1728     } else {
1729       result = MAP_ARCHIVE_MMAP_FAILURE;
1730     }
1731   }
1732 
1733   if (result == MAP_ARCHIVE_SUCCESS) {
1734     SharedBaseAddress = (size_t)mapped_base_address;
1735 #ifdef _LP64
1736     if (Metaspace::using_class_space()) {
1737       assert(prot_zone_size > 0 &&
1738              *(mapped_base_address) == 'P' &&
1739              *(mapped_base_address + prot_zone_size - 1) == 'P',
1740              "Protection zone was overwritten?");
1741       // Set up ccs in metaspace.
1742       Metaspace::initialize_class_space(class_space_rs);
1743 
1744       // Set up compressed Klass pointer encoding: the encoding range must
1745       //  cover both archive and class space.
1746       const address encoding_base = (address)mapped_base_address;
1747       const address klass_range_start = encoding_base + prot_zone_size;
1748       const size_t klass_range_size = (address)class_space_rs.end() - klass_range_start;
1749       if (INCLUDE_CDS_JAVA_HEAP || UseCompactObjectHeaders) {
1750         // The CDS archive may contain narrow Klass IDs that were precomputed at archive generation time:
1751         // - every archived java object header (only if INCLUDE_CDS_JAVA_HEAP)
1752         // - every archived Klass' prototype   (only if +UseCompactObjectHeaders)
1753         //
1754         // In order for those IDs to still be valid, we need to dictate base and shift: base should be the
1755         // mapping start (including protection zone), shift should be the shift used at archive generation time.
1756         CompressedKlassPointers::initialize_for_given_encoding(
1757           klass_range_start, klass_range_size,
1758           encoding_base, ArchiveBuilder::precomputed_narrow_klass_shift() // precomputed encoding, see ArchiveBuilder
1759         );
1760       } else {
1761         // Let JVM freely choose encoding base and shift
1762         CompressedKlassPointers::initialize(klass_range_start, klass_range_size);
1763       }
1764       CompressedKlassPointers::establish_protection_zone(encoding_base, prot_zone_size);
1765 
1766       // map_or_load_heap_region() compares the current narrow oop and klass encodings
1767       // with the archived ones, so it must be done after all encodings are determined.
1768       static_mapinfo->map_or_load_heap_region();
1769     }
1770 #endif // _LP64
1771     log_info(cds)("initial optimized module handling: %s", CDSConfig::is_using_optimized_module_handling() ? "enabled" : "disabled");
1772     log_info(cds)("initial full module graph: %s", CDSConfig::is_using_full_module_graph() ? "enabled" : "disabled");
1773   } else {
1774     unmap_archive(static_mapinfo);
1775     unmap_archive(dynamic_mapinfo);
1776     release_reserved_spaces(total_space_rs, archive_space_rs, class_space_rs);
1777   }
1778 
1779   return result;
1780 }
1781 
1782 
1783 // This will reserve two address spaces suitable to house Klass structures, one
1784 //  for the cds archives (static archive and optionally dynamic archive) and
1785 //  optionally one move for ccs.
1786 //
1787 // Since both spaces must fall within the compressed class pointer encoding
1788 //  range, they are allocated close to each other.
1789 //
1790 // Space for archives will be reserved first, followed by a potential gap,
1791 //  followed by the space for ccs:
1792 //
1793 // +-- Base address             A        B                     End
1794 // |                            |        |                      |
1795 // v                            v        v                      v
1796 // +-------------+--------------+        +----------------------+
1797 // | static arc  | [dyn. arch]  | [gap]  | compr. class space   |
1798 // +-------------+--------------+        +----------------------+
1799 //
1800 // (The gap may result from different alignment requirements between metaspace
1801 //  and CDS)
1802 //
1803 // If UseCompressedClassPointers is disabled, only one address space will be
1804 //  reserved:
1805 //
1806 // +-- Base address             End
1807 // |                            |
1808 // v                            v
1809 // +-------------+--------------+
1810 // | static arc  | [dyn. arch]  |
1811 // +-------------+--------------+
1812 //
1813 // Base address: If use_archive_base_addr address is true, the Base address is
1814 //  determined by the address stored in the static archive. If
1815 //  use_archive_base_addr address is false, this base address is determined
1816 //  by the platform.
1817 //
1818 // If UseCompressedClassPointers=1, the range encompassing both spaces will be
1819 //  suitable to en/decode narrow Klass pointers: the base will be valid for
1820 //  encoding, the range [Base, End) and not surpass the max. range for that encoding.
1821 //
1822 // Return:
1823 //
1824 // - On success:
1825 //    - total_space_rs will be reserved as whole for archive_space_rs and
1826 //      class_space_rs if UseCompressedClassPointers is true.
1827 //      On Windows, try reserve archive_space_rs and class_space_rs
1828 //      separately first if use_archive_base_addr is true.
1829 //    - archive_space_rs will be reserved and large enough to host static and
1830 //      if needed dynamic archive: [Base, A).
1831 //      archive_space_rs.base and size will be aligned to CDS reserve
1832 //      granularity.
1833 //    - class_space_rs: If UseCompressedClassPointers=1, class_space_rs will
1834 //      be reserved. Its start address will be aligned to metaspace reserve
1835 //      alignment, which may differ from CDS alignment. It will follow the cds
1836 //      archive space, close enough such that narrow class pointer encoding
1837 //      covers both spaces.
1838 //      If UseCompressedClassPointers=0, class_space_rs remains unreserved.
1839 // - On error: null is returned and the spaces remain unreserved.
1840 char* MetaspaceShared::reserve_address_space_for_archives(FileMapInfo* static_mapinfo,
1841                                                           FileMapInfo* dynamic_mapinfo,
1842                                                           bool use_archive_base_addr,
1843                                                           ReservedSpace& total_space_rs,
1844                                                           ReservedSpace& archive_space_rs,
1845                                                           ReservedSpace& class_space_rs) {
1846 
1847   address const base_address = (address) (use_archive_base_addr ? static_mapinfo->requested_base_address() : nullptr);
1848   const size_t archive_space_alignment = core_region_alignment();
1849 
1850   // Size and requested location of the archive_space_rs (for both static and dynamic archives)
1851   size_t archive_end_offset  = (dynamic_mapinfo == nullptr) ? static_mapinfo->mapping_end_offset() : dynamic_mapinfo->mapping_end_offset();
1852   size_t archive_space_size = align_up(archive_end_offset, archive_space_alignment);
1853 
1854   if (!Metaspace::using_class_space()) {
1855     // Get the simple case out of the way first:
1856     // no compressed class space, simple allocation.
1857 
1858     // When running without class space, requested archive base should be aligned to cds core alignment.
1859     assert(is_aligned(base_address, archive_space_alignment),
1860              "Archive base address unaligned: " PTR_FORMAT ", needs alignment: %zu.",
1861              p2i(base_address), archive_space_alignment);
1862 
1863     archive_space_rs = MemoryReserver::reserve((char*)base_address,
1864                                                archive_space_size,
1865                                                archive_space_alignment,
1866                                                os::vm_page_size(),
1867                                                mtNone);
1868     if (archive_space_rs.is_reserved()) {
1869       assert(base_address == nullptr ||
1870              (address)archive_space_rs.base() == base_address, "Sanity");
1871       // Register archive space with NMT.
1872       MemTracker::record_virtual_memory_tag(archive_space_rs, mtClassShared);
1873       return archive_space_rs.base();
1874     }
1875     return nullptr;
1876   }
1877 
1878 #ifdef _LP64
1879 
1880   // Complex case: two spaces adjacent to each other, both to be addressable
1881   //  with narrow class pointers.
1882   // We reserve the whole range spanning both spaces, then split that range up.
1883 
1884   const size_t class_space_alignment = Metaspace::reserve_alignment();
1885 
1886   // When running with class space, requested archive base must satisfy both cds core alignment
1887   // and class space alignment.
1888   const size_t base_address_alignment = MAX2(class_space_alignment, archive_space_alignment);
1889   assert(is_aligned(base_address, base_address_alignment),
1890            "Archive base address unaligned: " PTR_FORMAT ", needs alignment: %zu.",
1891            p2i(base_address), base_address_alignment);
1892 
1893   size_t class_space_size = CompressedClassSpaceSize;
1894   assert(CompressedClassSpaceSize > 0 &&
1895          is_aligned(CompressedClassSpaceSize, class_space_alignment),
1896          "CompressedClassSpaceSize malformed: %zu", CompressedClassSpaceSize);
1897 
1898   const size_t ccs_begin_offset = align_up(archive_space_size, class_space_alignment);
1899   const size_t gap_size = ccs_begin_offset - archive_space_size;
1900 
1901   // Reduce class space size if it would not fit into the Klass encoding range
1902   constexpr size_t max_encoding_range_size = 4 * G;
1903   guarantee(archive_space_size < max_encoding_range_size - class_space_alignment, "Archive too large");
1904   if ((archive_space_size + gap_size + class_space_size) > max_encoding_range_size) {
1905     class_space_size = align_down(max_encoding_range_size - archive_space_size - gap_size, class_space_alignment);
1906     log_info(metaspace)("CDS initialization: reducing class space size from %zu to %zu",
1907         CompressedClassSpaceSize, class_space_size);
1908     FLAG_SET_ERGO(CompressedClassSpaceSize, class_space_size);
1909   }
1910 
1911   const size_t total_range_size =
1912       archive_space_size + gap_size + class_space_size;
1913 
1914   // Test that class space base address plus shift can be decoded by aarch64, when restored.
1915   const int precomputed_narrow_klass_shift = ArchiveBuilder::precomputed_narrow_klass_shift();
1916   if (!CompressedKlassPointers::check_klass_decode_mode(base_address, precomputed_narrow_klass_shift,
1917                                                         total_range_size)) {
1918     log_info(cds)("CDS initialization: Cannot use SharedBaseAddress " PTR_FORMAT " with precomputed shift %d.",
1919                   p2i(base_address), precomputed_narrow_klass_shift);
1920     use_archive_base_addr = false;
1921   }
1922 
1923   assert(total_range_size > ccs_begin_offset, "must be");
1924   if (use_windows_memory_mapping() && use_archive_base_addr) {
1925     if (base_address != nullptr) {
1926       // On Windows, we cannot safely split a reserved memory space into two (see JDK-8255917).
1927       // Hence, we optimistically reserve archive space and class space side-by-side. We only
1928       // do this for use_archive_base_addr=true since for use_archive_base_addr=false case
1929       // caller will not split the combined space for mapping, instead read the archive data
1930       // via sequential file IO.
1931       address ccs_base = base_address + archive_space_size + gap_size;
1932       archive_space_rs = MemoryReserver::reserve((char*)base_address,
1933                                                  archive_space_size,
1934                                                  archive_space_alignment,
1935                                                  os::vm_page_size(),
1936                                                  mtNone);
1937       class_space_rs   = MemoryReserver::reserve((char*)ccs_base,
1938                                                  class_space_size,
1939                                                  class_space_alignment,
1940                                                  os::vm_page_size(),
1941                                                  mtNone);
1942     }
1943     if (!archive_space_rs.is_reserved() || !class_space_rs.is_reserved()) {
1944       release_reserved_spaces(total_space_rs, archive_space_rs, class_space_rs);
1945       return nullptr;
1946     }
1947     MemTracker::record_virtual_memory_tag(archive_space_rs, mtClassShared);
1948     MemTracker::record_virtual_memory_tag(class_space_rs, mtClass);
1949   } else {
1950     if (use_archive_base_addr && base_address != nullptr) {
1951       total_space_rs = MemoryReserver::reserve((char*) base_address,
1952                                                total_range_size,
1953                                                base_address_alignment,
1954                                                os::vm_page_size(),
1955                                                mtNone);
1956     } else {
1957       // We did not manage to reserve at the preferred address, or were instructed to relocate. In that
1958       // case we reserve wherever possible, but the start address needs to be encodable as narrow Klass
1959       // encoding base since the archived heap objects contain narrow Klass IDs pre-calculated toward the start
1960       // of the shared Metaspace. That prevents us from using zero-based encoding and therefore we won't
1961       // try allocating in low-address regions.
1962       total_space_rs = Metaspace::reserve_address_space_for_compressed_classes(total_range_size, false /* optimize_for_zero_base */);
1963     }
1964 
1965     if (!total_space_rs.is_reserved()) {
1966       return nullptr;
1967     }
1968 
1969     // Paranoid checks:
1970     assert(!use_archive_base_addr || (address)total_space_rs.base() == base_address,
1971            "Sanity (" PTR_FORMAT " vs " PTR_FORMAT ")", p2i(base_address), p2i(total_space_rs.base()));
1972     assert(is_aligned(total_space_rs.base(), base_address_alignment), "Sanity");
1973     assert(total_space_rs.size() == total_range_size, "Sanity");
1974 
1975     // Now split up the space into ccs and cds archive. For simplicity, just leave
1976     //  the gap reserved at the end of the archive space. Do not do real splitting.
1977     archive_space_rs = total_space_rs.first_part(ccs_begin_offset,
1978                                                  (size_t)archive_space_alignment);
1979     class_space_rs = total_space_rs.last_part(ccs_begin_offset);
1980     MemTracker::record_virtual_memory_split_reserved(total_space_rs.base(), total_space_rs.size(),
1981                                                      ccs_begin_offset, mtClassShared, mtClass);
1982   }
1983   assert(is_aligned(archive_space_rs.base(), archive_space_alignment), "Sanity");
1984   assert(is_aligned(archive_space_rs.size(), archive_space_alignment), "Sanity");
1985   assert(is_aligned(class_space_rs.base(), class_space_alignment), "Sanity");
1986   assert(is_aligned(class_space_rs.size(), class_space_alignment), "Sanity");
1987 
1988 
1989   return archive_space_rs.base();
1990 
1991 #else
1992   ShouldNotReachHere();
1993   return nullptr;
1994 #endif
1995 
1996 }
1997 
1998 void MetaspaceShared::release_reserved_spaces(ReservedSpace& total_space_rs,
1999                                               ReservedSpace& archive_space_rs,
2000                                               ReservedSpace& class_space_rs) {
2001   if (total_space_rs.is_reserved()) {
2002     log_debug(cds)("Released shared space (archive + class) " INTPTR_FORMAT, p2i(total_space_rs.base()));
2003     MemoryReserver::release(total_space_rs);
2004     total_space_rs = {};
2005   } else {
2006     if (archive_space_rs.is_reserved()) {
2007       log_debug(cds)("Released shared space (archive) " INTPTR_FORMAT, p2i(archive_space_rs.base()));
2008       MemoryReserver::release(archive_space_rs);
2009       archive_space_rs = {};
2010     }
2011     if (class_space_rs.is_reserved()) {
2012       log_debug(cds)("Released shared space (classes) " INTPTR_FORMAT, p2i(class_space_rs.base()));
2013       MemoryReserver::release(class_space_rs);
2014       class_space_rs = {};
2015     }
2016   }
2017 }
2018 
2019 static int archive_regions[]     = { MetaspaceShared::rw, MetaspaceShared::ro };
2020 static int archive_regions_count = 2;
2021 
2022 MapArchiveResult MetaspaceShared::map_archive(FileMapInfo* mapinfo, char* mapped_base_address, ReservedSpace rs) {
2023   assert(CDSConfig::is_using_archive(), "must be runtime");
2024   if (mapinfo == nullptr) {
2025     return MAP_ARCHIVE_SUCCESS; // The dynamic archive has not been specified. No error has happened -- trivially succeeded.
2026   }
2027 
2028   if (!mapinfo->validate_aot_class_linking()) {
2029     return MAP_ARCHIVE_OTHER_FAILURE;
2030   }
2031 
2032   mapinfo->set_is_mapped(false);
2033   if (mapinfo->core_region_alignment() != (size_t)core_region_alignment()) {
2034     log_info(cds)("Unable to map CDS archive -- core_region_alignment() expected: %zu"
2035                   " actual: %zu", mapinfo->core_region_alignment(), core_region_alignment());
2036     return MAP_ARCHIVE_OTHER_FAILURE;
2037   }
2038 
2039   MapArchiveResult result =
2040     mapinfo->map_regions(archive_regions, archive_regions_count, mapped_base_address, rs);
2041 
2042   if (result != MAP_ARCHIVE_SUCCESS) {
2043     unmap_archive(mapinfo);
2044     return result;
2045   }
2046 
2047   if (!mapinfo->validate_class_location()) {
2048     unmap_archive(mapinfo);
2049     return MAP_ARCHIVE_OTHER_FAILURE;
2050   }
2051 
2052   if (mapinfo->is_static()) {
2053     // Currently, only static archive uses early serialized data.
2054     char* buffer = mapinfo->early_serialized_data();
2055     intptr_t* array = (intptr_t*)buffer;
2056     ReadClosure rc(&array, (intptr_t)mapped_base_address);
2057     early_serialize(&rc);
2058   }
2059 
2060   if (!mapinfo->validate_aot_class_linking()) {
2061     unmap_archive(mapinfo);
2062     return MAP_ARCHIVE_OTHER_FAILURE;
2063   }
2064 
2065   mapinfo->set_is_mapped(true);
2066   return MAP_ARCHIVE_SUCCESS;
2067 }
2068 
2069 void MetaspaceShared::unmap_archive(FileMapInfo* mapinfo) {
2070   assert(CDSConfig::is_using_archive(), "must be runtime");
2071   if (mapinfo != nullptr) {
2072     mapinfo->unmap_regions(archive_regions, archive_regions_count);
2073     mapinfo->unmap_region(MetaspaceShared::bm);
2074     mapinfo->set_is_mapped(false);
2075   }
2076 }
2077 
2078 // For -XX:PrintSharedArchiveAndExit
2079 class CountSharedSymbols : public SymbolClosure {
2080  private:
2081    int _count;
2082  public:
2083    CountSharedSymbols() : _count(0) {}
2084   void do_symbol(Symbol** sym) {
2085     _count++;
2086   }
2087   int total() { return _count; }
2088 
2089 };
2090 
2091 // Read the miscellaneous data from the shared file, and
2092 // serialize it out to its various destinations.
2093 
2094 void MetaspaceShared::initialize_shared_spaces() {
2095   FileMapInfo *static_mapinfo = FileMapInfo::current_info();
2096 
2097   // Verify various attributes of the archive, plus initialize the
2098   // shared string/symbol tables.
2099   char* buffer = static_mapinfo->serialized_data();
2100   intptr_t* array = (intptr_t*)buffer;
2101   ReadClosure rc(&array, (intptr_t)SharedBaseAddress);
2102   serialize(&rc);
2103 
2104   // Finish up archived heap initialization. These must be
2105   // done after ReadClosure.
2106   static_mapinfo->patch_heap_embedded_pointers();
2107   ArchiveHeapLoader::finish_initialization();
2108   Universe::load_archived_object_instances();
2109   AOTCodeCache::initialize();
2110 
2111   // Close the mapinfo file
2112   static_mapinfo->close();
2113 
2114   static_mapinfo->unmap_region(MetaspaceShared::bm);
2115 
2116   FileMapInfo *dynamic_mapinfo = FileMapInfo::dynamic_info();
2117   if (dynamic_mapinfo != nullptr) {
2118     intptr_t* buffer = (intptr_t*)dynamic_mapinfo->serialized_data();
2119     ReadClosure rc(&buffer, (intptr_t)SharedBaseAddress);
2120     ArchiveBuilder::serialize_dynamic_archivable_items(&rc);
2121     DynamicArchive::setup_array_klasses();
2122     dynamic_mapinfo->close();
2123     dynamic_mapinfo->unmap_region(MetaspaceShared::bm);
2124   }
2125 
2126   LogStreamHandle(Info, cds) lsh;
2127   if (lsh.is_enabled()) {
2128     lsh.print("Using AOT-linked classes: %s (static archive: %s aot-linked classes",
2129               BOOL_TO_STR(CDSConfig::is_using_aot_linked_classes()),
2130               static_mapinfo->header()->has_aot_linked_classes() ? "has" : "no");
2131     if (dynamic_mapinfo != nullptr) {
2132       lsh.print(", dynamic archive: %s aot-linked classes",
2133                 dynamic_mapinfo->header()->has_aot_linked_classes() ? "has" : "no");
2134     }
2135     lsh.print_cr(")");
2136   }
2137 
2138   // Set up LambdaFormInvokers::_lambdaform_lines for dynamic dump
2139   if (CDSConfig::is_dumping_dynamic_archive()) {
2140     // Read stored LF format lines stored in static archive
2141     LambdaFormInvokers::read_static_archive_invokers();
2142   }
2143 
2144   if (PrintSharedArchiveAndExit) {
2145     // Print archive names
2146     if (dynamic_mapinfo != nullptr) {
2147       tty->print_cr("\n\nBase archive name: %s", CDSConfig::input_static_archive_path());
2148       tty->print_cr("Base archive version %d", static_mapinfo->version());
2149     } else {
2150       tty->print_cr("Static archive name: %s", static_mapinfo->full_path());
2151       tty->print_cr("Static archive version %d", static_mapinfo->version());
2152     }
2153 
2154     SystemDictionaryShared::print_shared_archive(tty);
2155     if (dynamic_mapinfo != nullptr) {
2156       tty->print_cr("\n\nDynamic archive name: %s", dynamic_mapinfo->full_path());
2157       tty->print_cr("Dynamic archive version %d", dynamic_mapinfo->version());
2158       SystemDictionaryShared::print_shared_archive(tty, false/*dynamic*/);
2159     }
2160     TrainingData::print_archived_training_data_on(tty);
2161 
2162     if (AOTCodeCache::is_on_for_use()) {
2163       tty->print_cr("\n\nAOT Code");
2164       AOTCodeCache::print_on(tty);
2165     }
2166 
2167     // collect shared symbols and strings
2168     CountSharedSymbols cl;
2169     SymbolTable::shared_symbols_do(&cl);
2170     tty->print_cr("Number of shared symbols: %d", cl.total());
2171     tty->print_cr("Number of shared strings: %zu", StringTable::shared_entry_count());
2172     tty->print_cr("VM version: %s\r\n", static_mapinfo->vm_version());
2173     if (FileMapInfo::current_info() == nullptr || _archive_loading_failed) {
2174       tty->print_cr("archive is invalid");
2175       vm_exit(1);
2176     } else {
2177       tty->print_cr("archive is valid");
2178       vm_exit(0);
2179     }
2180   }
2181 }
2182 
2183 // JVM/TI RedefineClasses() support:
2184 bool MetaspaceShared::remap_shared_readonly_as_readwrite() {
2185   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
2186 
2187   if (CDSConfig::is_using_archive()) {
2188     // remap the shared readonly space to shared readwrite, private
2189     FileMapInfo* mapinfo = FileMapInfo::current_info();
2190     if (!mapinfo->remap_shared_readonly_as_readwrite()) {
2191       return false;
2192     }
2193     if (FileMapInfo::dynamic_info() != nullptr) {
2194       mapinfo = FileMapInfo::dynamic_info();
2195       if (!mapinfo->remap_shared_readonly_as_readwrite()) {
2196         return false;
2197       }
2198     }
2199     _remapped_readwrite = true;
2200   }
2201   return true;
2202 }
2203 
2204 void MetaspaceShared::print_on(outputStream* st) {
2205   if (CDSConfig::is_using_archive()) {
2206     st->print("CDS archive(s) mapped at: ");
2207     address base = (address)MetaspaceObj::shared_metaspace_base();
2208     address static_top = (address)_shared_metaspace_static_top;
2209     address top = (address)MetaspaceObj::shared_metaspace_top();
2210     st->print("[" PTR_FORMAT "-" PTR_FORMAT "-" PTR_FORMAT "), ", p2i(base), p2i(static_top), p2i(top));
2211     st->print("size %zu, ", top - base);
2212     st->print("SharedBaseAddress: " PTR_FORMAT ", ArchiveRelocationMode: %d.", SharedBaseAddress, ArchiveRelocationMode);
2213   } else {
2214     st->print("CDS archive(s) not mapped");
2215   }
2216   st->cr();
2217 }