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