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