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