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