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