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