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