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