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