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::load_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);
 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   CDSConfig::set_is_at_aot_safepoint(true);
 679 
 680   if (!CDSConfig::is_dumping_final_static_archive()) {
 681     guarantee(!CDSConfig::is_using_archive(), "We should not be using an archive when we dump");
 682   }
 683 
 684   DEBUG_ONLY(SystemDictionaryShared::NoClassLoadingMark nclm);
 685 
 686   _pending_method_handle_intrinsics = new (mtClassShared) GrowableArray<Method*>(256, mtClassShared);
 687   if (CDSConfig::is_dumping_method_handles()) {
 688     // When dumping AOT-linked classes, some classes may have direct references to a method handle
 689     // intrinsic. The easiest thing is to save all of them into the AOT cache.
 690     SystemDictionary::get_all_method_handle_intrinsics(_pending_method_handle_intrinsics);
 691   }
 692 
 693   AOTClassLocationConfig::dumptime_check_nonempty_dirs();
 694 
 695   NOT_PRODUCT(SystemDictionary::verify();)
 696 
 697   // Block concurrent class unloading from changing the _dumptime_table
 698   MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
 699 
 700   _builder.gather_source_objs();
 701   _builder.reserve_buffer();
 702 
 703   CppVtables::dumptime_init(&_builder);
 704 
 705   _builder.sort_metadata_objs();
 706   _builder.dump_rw_metadata();
 707   _builder.dump_ro_metadata();
 708   _builder.relocate_metaspaceobj_embedded_pointers();
 709 
 710   log_info(aot)("Make classes shareable");
 711   _builder.make_klasses_shareable();
 712   AOTMetaspace::make_method_handle_intrinsics_shareable();
 713 
 714   dump_java_heap_objects();
 715   dump_shared_symbol_table(_builder.symbols());
 716 
 717   char* early_serialized_data = dump_early_read_only_tables();
 718   AOTClassLocationConfig* cl_config;
 719   char* serialized_data = dump_read_only_tables(cl_config);
 720 
 721   if (CDSConfig::is_dumping_lambdas_in_legacy_mode()) {
 722     log_info(aot)("Adjust lambda proxy class dictionary");
 723     LambdaProxyClassDictionary::adjust_dumptime_table();
 724   }
 725 
 726   log_info(cds)("Make training data shareable");
 727   _builder.make_training_data_shareable();
 728 
 729   // The vtable clones contain addresses of the current process.
 730   // We don't want to write these addresses into the archive.
 731   CppVtables::zero_archived_vtables();
 732 
 733   // Write the archive file
 734   if (CDSConfig::is_dumping_final_static_archive()) {
 735     FileMapInfo::free_current_info(); // FIXME: should not free current info
 736   }
 737   const char* static_archive = CDSConfig::output_archive_path();
 738   assert(static_archive != nullptr, "sanity");
 739   _map_info = new FileMapInfo(static_archive, true);
 740   _map_info->populate_header(AOTMetaspace::core_region_alignment());
 741   _map_info->set_early_serialized_data(early_serialized_data);
 742   _map_info->set_serialized_data(serialized_data);
 743   _map_info->set_cloned_vtables(CppVtables::vtables_serialized_base());
 744   _map_info->header()->set_class_location_config(cl_config);
 745 
 746   HeapShared::delete_tables_with_raw_oops();
 747   CDSConfig::set_is_at_aot_safepoint(false);
 748 }
 749 
 750 class CollectClassesForLinking : public KlassClosure {
 751   GrowableArray<OopHandle> _mirrors;
 752 
 753 public:
 754    CollectClassesForLinking() : _mirrors() {
 755      // ClassLoaderDataGraph::loaded_classes_do_keepalive() requires ClassLoaderDataGraph_lock.
 756      // We cannot link the classes while holding this lock (or else we may run into deadlock).
 757      // Therefore, we need to first collect all the classes, keeping them alive by
 758      // holding onto their java_mirrors in global OopHandles. We then link the classes after
 759      // releasing the lock.
 760      MutexLocker lock(ClassLoaderDataGraph_lock);
 761      ClassLoaderDataGraph::loaded_classes_do_keepalive(this);
 762    }
 763 
 764   ~CollectClassesForLinking() {
 765     for (int i = 0; i < _mirrors.length(); i++) {
 766       _mirrors.at(i).release(Universe::vm_global());
 767     }
 768   }
 769 
 770   void do_cld(ClassLoaderData* cld) {
 771     assert(cld->is_alive(), "must be");
 772   }
 773 
 774   void do_klass(Klass* k) {
 775     if (k->is_instance_klass()) {
 776       _mirrors.append(OopHandle(Universe::vm_global(), k->java_mirror()));
 777     }
 778   }
 779 
 780   const GrowableArray<OopHandle>* mirrors() const { return &_mirrors; }
 781 };
 782 
 783 // Check if we can eagerly link this class at dump time, so we can avoid the
 784 // runtime linking overhead (especially verification)
 785 bool AOTMetaspace::may_be_eagerly_linked(InstanceKlass* ik) {
 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_all_loaded_classes(JavaThread* current) {
 805   while (true) {
 806     ResourceMark rm(current);
 807     CollectClassesForLinking collect_classes;
 808     bool has_linked = false;
 809     const GrowableArray<OopHandle>* mirrors = collect_classes.mirrors();
 810     for (int i = 0; i < mirrors->length(); i++) {
 811       OopHandle mirror = mirrors->at(i);
 812       InstanceKlass* ik = java_lang_Class::as_InstanceKlass(mirror.resolve());
 813       if (may_be_eagerly_linked(ik)) {
 814         has_linked |= try_link_class(current, ik);
 815       }
 816       if (CDSConfig::is_dumping_heap() && ik->is_linked() && !ik->is_initialized()) {
 817         AOTClassInitializer::maybe_preinit_class(ik, current);
 818       }
 819     }
 820 
 821     if (!has_linked) {
 822       break;
 823     }
 824     // Class linking includes verification which may load more classes.
 825     // Keep scanning until we have linked no more classes.
 826   }
 827 }
 828 
 829 void AOTMetaspace::link_shared_classes(TRAPS) {
 830   AOTClassLinker::initialize();
 831   AOTClassInitializer::init_test_class(CHECK);
 832 
 833   if (CDSConfig::is_dumping_final_static_archive()) {
 834     FinalImageRecipes::apply_recipes(CHECK);
 835   }
 836 
 837   link_all_loaded_classes(THREAD);
 838 
 839   // Eargerly resolve all string constants in constant pools
 840   {
 841     ResourceMark rm(THREAD);
 842     CollectClassesForLinking collect_classes;
 843     const GrowableArray<OopHandle>* mirrors = collect_classes.mirrors();
 844     for (int i = 0; i < mirrors->length(); i++) {
 845       OopHandle mirror = mirrors->at(i);
 846       InstanceKlass* ik = java_lang_Class::as_InstanceKlass(mirror.resolve());
 847       AOTConstantPoolResolver::preresolve_string_cp_entries(ik, CHECK);
 848       if (CDSConfig::is_dumping_preimage_static_archive()) {
 849         FinalImageRecipes::add_reflection_data_flags(ik, CHECK);
 850       }
 851     }
 852   }
 853 }
 854 
 855 void AOTMetaspace::dump_static_archive(TRAPS) {
 856   CDSConfig::DumperThreadMark dumper_thread_mark(THREAD);
 857   ResourceMark rm(THREAD);
 858   HandleMark hm(THREAD);
 859 
 860   if (CDSConfig::is_dumping_final_static_archive() && AOTPrintTrainingInfo) {
 861     tty->print_cr("==================== archived_training_data ** before dumping ====================");
 862     TrainingData::print_archived_training_data_on(tty);
 863   }
 864 
 865   StaticArchiveBuilder builder;
 866   dump_static_archive_impl(builder, THREAD);
 867   if (HAS_PENDING_EXCEPTION) {
 868     if (PENDING_EXCEPTION->is_a(vmClasses::OutOfMemoryError_klass())) {
 869       aot_log_error(aot)("Out of memory. Please run with a larger Java heap, current MaxHeapSize = "
 870                      "%zuM", MaxHeapSize/M);
 871       AOTMetaspace::writing_error();
 872     } else {
 873       oop message = java_lang_Throwable::message(PENDING_EXCEPTION);
 874       aot_log_error(aot)("%s: %s", PENDING_EXCEPTION->klass()->external_name(),
 875                          message == nullptr ? "(null)" : java_lang_String::as_utf8_string(message));
 876       AOTMetaspace::writing_error(err_msg("Unexpected exception, use -Xlog:aot%s,exceptions=trace for detail",
 877                                              CDSConfig::new_aot_flags_used() ? "" : ",cds"));
 878     }
 879   }
 880 
 881   if (CDSConfig::new_aot_flags_used()) {
 882     if (CDSConfig::is_dumping_preimage_static_archive()) {
 883       // We are in the JVM that runs the training run. Continue execution,
 884       // so that it can finish all clean-up and return the correct exit
 885       // code to the OS.
 886     } else {
 887       // The JLI launcher only recognizes the "old" -Xshare:dump flag.
 888       // When the new -XX:AOTMode=create flag is used, we can't return
 889       // to the JLI launcher, as the launcher will fail when trying to
 890       // run the main class, which is not what we want.
 891       struct stat st;
 892       if (os::stat(AOTCache, &st) != 0) {
 893         tty->print_cr("AOTCache creation failed: %s", AOTCache);
 894       } else {
 895         tty->print_cr("AOTCache creation is complete: %s " INT64_FORMAT " bytes", AOTCache, (int64_t)(st.st_size));
 896       }
 897       vm_direct_exit(0);
 898     }
 899   }
 900 }
 901 
 902 #if INCLUDE_CDS_JAVA_HEAP && defined(_LP64)
 903 void AOTMetaspace::adjust_heap_sizes_for_dumping() {
 904   if (!CDSConfig::is_dumping_heap() || UseCompressedOops) {
 905     return;
 906   }
 907   // CDS heap dumping requires all string oops to have an offset
 908   // from the heap bottom that can be encoded in 32-bit.
 909   julong max_heap_size = (julong)(4 * G);
 910 
 911   if (MinHeapSize > max_heap_size) {
 912     log_debug(aot)("Setting MinHeapSize to 4G for CDS dumping, original size = %zuM", MinHeapSize/M);
 913     FLAG_SET_ERGO(MinHeapSize, max_heap_size);
 914   }
 915   if (InitialHeapSize > max_heap_size) {
 916     log_debug(aot)("Setting InitialHeapSize to 4G for CDS dumping, original size = %zuM", InitialHeapSize/M);
 917     FLAG_SET_ERGO(InitialHeapSize, max_heap_size);
 918   }
 919   if (MaxHeapSize > max_heap_size) {
 920     log_debug(aot)("Setting MaxHeapSize to 4G for CDS dumping, original size = %zuM", MaxHeapSize/M);
 921     FLAG_SET_ERGO(MaxHeapSize, max_heap_size);
 922   }
 923 }
 924 #endif // INCLUDE_CDS_JAVA_HEAP && _LP64
 925 
 926 void AOTMetaspace::get_default_classlist(char* default_classlist, const size_t buf_size) {
 927   const char* filesep = os::file_separator();
 928   jio_snprintf(default_classlist, buf_size, "%s%slib%sclasslist",
 929                Arguments::get_java_home(), filesep, filesep);
 930 }
 931 
 932 void AOTMetaspace::load_classes(TRAPS) {
 933   char default_classlist[JVM_MAXPATHLEN];
 934   const char* classlist_path;
 935 
 936   get_default_classlist(default_classlist, JVM_MAXPATHLEN);
 937   if (SharedClassListFile == nullptr) {
 938     classlist_path = default_classlist;
 939   } else {
 940     classlist_path = SharedClassListFile;
 941   }
 942 
 943   aot_log_info(aot)("Loading classes to share ...");
 944   ClassListParser::parse_classlist(classlist_path,
 945                                    ClassListParser::_parse_all, CHECK);
 946   if (ExtraSharedClassListFile) {
 947     ClassListParser::parse_classlist(ExtraSharedClassListFile,
 948                                      ClassListParser::_parse_all, CHECK);
 949   }
 950   if (classlist_path != default_classlist) {
 951     struct stat statbuf;
 952     if (os::stat(default_classlist, &statbuf) == 0) {
 953       // File exists, let's use it.
 954       ClassListParser::parse_classlist(default_classlist,
 955                                        ClassListParser::_parse_lambda_forms_invokers_only, CHECK);
 956     }
 957   }
 958 
 959   // Some classes are used at CDS runtime but are not yet loaded at this point.
 960   // We can perform dummmy calls to these classes at dumptime to ensure they
 961   // are archived.
 962   exercise_runtime_cds_code(CHECK);
 963 
 964   aot_log_info(aot)("Loading classes to share: done.");
 965 }
 966 
 967 void AOTMetaspace::exercise_runtime_cds_code(TRAPS) {
 968   // Exercise the manifest processing code
 969   const char* dummy = "Manifest-Version: 1.0\n";
 970   CDSProtectionDomain::create_jar_manifest(dummy, strlen(dummy), CHECK);
 971 
 972   // Exercise FileSystem and URL code
 973   CDSProtectionDomain::to_file_URL("dummy.jar", Handle(), CHECK);
 974 }
 975 
 976 bool AOTMetaspace::is_recording_preimage_static_archive() {
 977   if (CDSConfig::is_dumping_preimage_static_archive()) {
 978       return _preimage_static_archive_dumped == 0;
 979   }
 980   return false;
 981 }
 982 
 983 jlong AOTMetaspace::get_preimage_static_archive_recording_duration() {
 984   if (CDSConfig::is_dumping_preimage_static_archive()) {
 985     if (_preimage_static_archive_recording_duration == 0) {
 986       // The recording has not yet finished so return the current elapsed time.
 987       return Management::ticks_to_ms(os::elapsed_counter());
 988     }
 989     return _preimage_static_archive_recording_duration;
 990   }
 991   return 0;
 992 }
 993 
 994 void AOTMetaspace::dump_static_archive_impl(StaticArchiveBuilder& builder, TRAPS) {
 995   if (CDSConfig::is_dumping_preimage_static_archive()) {
 996     if (AtomicAccess::cmpxchg(&_preimage_static_archive_dumped, 0, 1) != 0) {
 997       return;
 998     }
 999     _preimage_static_archive_recording_duration = Management::ticks_to_ms(os::elapsed_counter());
1000   }
1001 
1002   if (CDSConfig::is_dumping_classic_static_archive()) {
1003     // We are running with -Xshare:dump
1004     load_classes(CHECK);
1005 
1006     if (SharedArchiveConfigFile) {
1007       log_info(aot)("Reading extra data from %s ...", SharedArchiveConfigFile);
1008       read_extra_data(THREAD, SharedArchiveConfigFile);
1009       log_info(aot)("Reading extra data: done.");
1010     }
1011   }
1012 
1013   if (CDSConfig::is_dumping_preimage_static_archive()) {
1014     log_info(aot)("Reading lambda form invokers from JDK default classlist ...");
1015     char default_classlist[JVM_MAXPATHLEN];
1016     get_default_classlist(default_classlist, JVM_MAXPATHLEN);
1017     struct stat statbuf;
1018     if (os::stat(default_classlist, &statbuf) == 0) {
1019       ClassListParser::parse_classlist(default_classlist,
1020                                        ClassListParser::_parse_lambda_forms_invokers_only, CHECK);
1021     }
1022   }
1023 
1024 #if INCLUDE_CDS_JAVA_HEAP
1025   if (CDSConfig::is_dumping_heap()) {
1026     assert(CDSConfig::allow_only_single_java_thread(), "Required");
1027     if (!HeapShared::is_archived_boot_layer_available(THREAD)) {
1028       report_loading_error("archivedBootLayer not available, disabling full module graph");
1029       CDSConfig::stop_dumping_full_module_graph();
1030     }
1031     // Do this before link_shared_classes(), as the following line may load new classes.
1032     HeapShared::init_for_dumping(CHECK);
1033   }
1034 #endif
1035 
1036   if (CDSConfig::is_dumping_final_static_archive()) {
1037     if (ExtraSharedClassListFile) {
1038       log_info(aot)("Loading extra classes from %s ...", ExtraSharedClassListFile);
1039       ClassListParser::parse_classlist(ExtraSharedClassListFile,
1040                                        ClassListParser::_parse_all, CHECK);
1041     }
1042   }
1043 
1044   // Rewrite and link classes
1045   log_info(aot)("Rewriting and linking classes ...");
1046 
1047   // Link any classes which got missed. This would happen if we have loaded classes that
1048   // were not explicitly specified in the classlist. E.g., if an interface implemented by class K
1049   // fails verification, all other interfaces that were not specified in the classlist but
1050   // are implemented by K are not verified.
1051   link_shared_classes(CHECK);
1052   log_info(aot)("Rewriting and linking classes: done");
1053   TrainingData::init_dumptime_table(CHECK); // captures TrainingDataSetLocker
1054 
1055   if (CDSConfig::is_dumping_regenerated_lambdaform_invokers()) {
1056     LambdaFormInvokers::regenerate_holder_classes(CHECK);
1057   }
1058 
1059 #if INCLUDE_CDS_JAVA_HEAP
1060   if (CDSConfig::is_dumping_heap()) {
1061     ArchiveHeapWriter::init();
1062 
1063     if (CDSConfig::is_dumping_full_module_graph()) {
1064       ClassLoaderDataShared::ensure_module_entry_tables_exist();
1065       HeapShared::reset_archived_object_states(CHECK);
1066     }
1067 
1068     if (ArchiveLoaderLookupCache) {
1069       SystemDictionaryShared::create_loader_positive_lookup_cache(CHECK);
1070     }
1071 
1072     AOTReferenceObjSupport::initialize(CHECK);
1073     AOTReferenceObjSupport::stabilize_cached_reference_objects(CHECK);
1074 
1075     if (CDSConfig::is_initing_classes_at_dump_time()) {
1076       // java.lang.Class::reflectionFactory cannot be archived yet. We set this field
1077       // to null, and it will be initialized again at runtime.
1078       log_debug(aot)("Resetting Class::reflectionFactory");
1079       TempNewSymbol method_name = SymbolTable::new_symbol("resetArchivedStates");
1080       Symbol* method_sig = vmSymbols::void_method_signature();
1081       JavaValue result(T_VOID);
1082       JavaCalls::call_static(&result, vmClasses::Class_klass(),
1083                              method_name, method_sig, CHECK);
1084 
1085       // Perhaps there is a way to avoid hard-coding these names here.
1086       // See discussion in JDK-8342481.
1087     }
1088 
1089     // Do this at the very end, when no Java code will be executed. Otherwise
1090     // some new strings may be added to the intern table.
1091     StringTable::allocate_shared_strings_array(CHECK);
1092   } else {
1093     log_info(aot)("Not dumping heap, reset CDSConfig::_is_using_optimized_module_handling");
1094     CDSConfig::stop_using_optimized_module_handling();
1095   }
1096 #endif
1097 
1098   VM_PopulateDumpSharedSpace op(builder);
1099   VMThread::execute(&op);
1100   FileMapInfo* mapinfo = op.map_info();
1101   ArchiveHeapInfo* heap_info = op.heap_info();
1102 
1103   if (CDSConfig::is_dumping_final_static_archive()) {
1104     if (AOTCodeCache::is_caching_enabled()) {
1105       if (log_is_enabled(Info, cds, jit)) {
1106         AOTCacheAccess::test_heap_access_api();
1107       }
1108 
1109       // We have just created the final image. Let's run the AOT compiler
1110       if (AOTPrintTrainingInfo) {
1111         tty->print_cr("==================== archived_training_data ** after dumping ====================");
1112         TrainingData::print_archived_training_data_on(tty);
1113       }
1114 
1115       {
1116         builder.start_ac_region();
1117         if (AOTCodeCache::is_dumping_code()) {
1118           CDSConfig::enable_dumping_aot_code();
1119           log_info(aot)("Compiling AOT code");
1120           Precompiler::compile_aot_code(&builder, CHECK);
1121           log_info(aot)("Finished compiling AOT code");
1122           CDSConfig::disable_dumping_aot_code();
1123         }
1124         // Write the contents to aot code region and close AOTCodeCache before packing the region
1125         AOTCodeCache::close();
1126         log_info(aot)("Dumped AOT code Cache");
1127         builder.end_ac_region();
1128       }
1129     }
1130   }
1131 
1132   bool status = write_static_archive(&builder, mapinfo, heap_info);
1133   if (status && CDSConfig::is_dumping_preimage_static_archive()) {
1134     tty->print_cr("%s AOTConfiguration recorded: %s",
1135                   CDSConfig::has_temp_aot_config_file() ? "Temporary" : "", AOTConfiguration);
1136     if (CDSConfig::is_single_command_training()) {
1137       fork_and_dump_final_static_archive(CHECK);
1138     }
1139   }
1140 
1141   if (!status) {
1142     THROW_MSG(vmSymbols::java_io_IOException(), "Encountered error while dumping");
1143   }
1144 }
1145 
1146 bool AOTMetaspace::write_static_archive(ArchiveBuilder* builder, FileMapInfo* map_info, ArchiveHeapInfo* heap_info) {
1147   // relocate the data so that it can be mapped to AOTMetaspace::requested_base_address()
1148   // without runtime relocation.
1149   builder->relocate_to_requested();
1150 
1151   map_info->open_as_output();
1152   if (!map_info->is_open()) {
1153     return false;
1154   }
1155   builder->write_archive(map_info, heap_info);
1156   return true;
1157 }
1158 
1159 static void print_java_launcher(outputStream* st) {
1160   st->print("%s%sbin%sjava", Arguments::get_java_home(), os::file_separator(), os::file_separator());
1161 }
1162 
1163 static void append_args(GrowableArray<Handle>* args, const char* arg, TRAPS) {
1164   Handle string = java_lang_String::create_from_str(arg, CHECK);
1165   args->append(string);
1166 }
1167 
1168 // Pass all options in Arguments::jvm_args_array() to a child JVM process
1169 // using the JAVA_TOOL_OPTIONS environment variable.
1170 static int exec_jvm_with_java_tool_options(const char* java_launcher_path, TRAPS) {
1171   ResourceMark rm(THREAD);
1172   HandleMark hm(THREAD);
1173   GrowableArray<Handle> args;
1174 
1175   const char* cp = Arguments::get_appclasspath();
1176   if (cp != nullptr && strlen(cp) > 0 && strcmp(cp, ".") != 0) {
1177     // We cannot use "-cp", because "-cp" is only interpreted by the java launcher,
1178     // and is not interpreter by arguments.cpp when it loads args from JAVA_TOOL_OPTIONS
1179     stringStream ss;
1180     ss.print("-Djava.class.path=");
1181     ss.print_raw(cp);
1182     append_args(&args, ss.freeze(), CHECK_0);
1183     // CDS$ProcessLauncher::execWithJavaToolOptions() must unset CLASSPATH, which has
1184     // a higher priority than -Djava.class.path=
1185   }
1186 
1187   // Pass all arguments. These include those from JAVA_TOOL_OPTIONS and _JAVA_OPTIONS.
1188   for (int i = 0; i < Arguments::num_jvm_args(); i++) {
1189     const char* arg = Arguments::jvm_args_array()[i];
1190     if (strstr(arg, "-XX:AOTCacheOutput=") == arg || // arg starts with ...
1191         strstr(arg, "-XX:AOTConfiguration=") == arg ||
1192         strstr(arg, "-XX:AOTMode=") == arg) {
1193       // Filter these out. They wiill be set below.
1194     } else {
1195       append_args(&args, arg, CHECK_0);
1196     }
1197   }
1198 
1199   // Note: because we are running in AOTMode=record, JDK_AOT_VM_OPTIONS have not been
1200   // parsed, so they are not in Arguments::jvm_args_array. If JDK_AOT_VM_OPTIONS is in
1201   // the environment, it will be inherited and parsed by the child JVM process
1202   // in Arguments::parse_java_tool_options_environment_variable().
1203   precond(strcmp(AOTMode, "record") == 0);
1204 
1205   // We don't pass Arguments::jvm_flags_array(), as those will be added by
1206   // the child process when it loads .hotspotrc
1207 
1208   {
1209     // If AOTCacheOutput contains %p, it should have been already substituted with the
1210     // pid of the training process.
1211     stringStream ss;
1212     ss.print("-XX:AOTCacheOutput=");
1213     ss.print_raw(AOTCacheOutput);
1214     append_args(&args, ss.freeze(), CHECK_0);
1215   }
1216   {
1217     // If AOTCacheConfiguration contains %p, it should have been already substituted with the
1218     // pid of the training process.
1219     // If AOTCacheConfiguration was not explicitly specified, it should have been assigned a
1220     // temporary file name.
1221     stringStream ss;
1222     ss.print("-XX:AOTConfiguration=");
1223     ss.print_raw(AOTConfiguration);
1224     append_args(&args, ss.freeze(), CHECK_0);
1225   }
1226 
1227   append_args(&args, "-XX:AOTMode=create", CHECK_0);
1228 
1229   Symbol* klass_name = SymbolTable::new_symbol("jdk/internal/misc/CDS$ProcessLauncher");
1230   Klass* k = SystemDictionary::resolve_or_fail(klass_name, true, CHECK_0);
1231   Symbol* methodName = SymbolTable::new_symbol("execWithJavaToolOptions");
1232   Symbol* methodSignature = SymbolTable::new_symbol("(Ljava/lang/String;[Ljava/lang/String;)I");
1233 
1234   Handle launcher = java_lang_String::create_from_str(java_launcher_path, CHECK_0);
1235   objArrayOop array = oopFactory::new_objArray(vmClasses::String_klass(), args.length(), CHECK_0);
1236   for (int i = 0; i < args.length(); i++) {
1237     array->obj_at_put(i, args.at(i)());
1238   }
1239   objArrayHandle launcher_args(THREAD, array);
1240 
1241   // The following call will pass all options inside the JAVA_TOOL_OPTIONS env variable to
1242   // the child process. It will also clear the _JAVA_OPTIONS and CLASSPATH env variables for
1243   // the child process.
1244   //
1245   // Note: the env variables are set only for the child process. They are not changed
1246   // for the current process. See java.lang.ProcessBuilder::environment().
1247   JavaValue result(T_OBJECT);
1248   JavaCallArguments javacall_args(2);
1249   javacall_args.push_oop(launcher);
1250   javacall_args.push_oop(launcher_args);
1251   JavaCalls::call_static(&result,
1252                           InstanceKlass::cast(k),
1253                           methodName,
1254                           methodSignature,
1255                           &javacall_args,
1256                           CHECK_0);
1257   return result.get_jint();
1258 }
1259 
1260 void AOTMetaspace::fork_and_dump_final_static_archive(TRAPS) {
1261   assert(CDSConfig::is_dumping_preimage_static_archive(), "sanity");
1262 
1263   ResourceMark rm;
1264   stringStream ss;
1265   print_java_launcher(&ss);
1266   const char* cmd = ss.freeze();
1267   tty->print_cr("Launching child process %s to assemble AOT cache %s using configuration %s", cmd, AOTCacheOutput, AOTConfiguration);
1268   int status = exec_jvm_with_java_tool_options(cmd, CHECK);
1269   if (status != 0) {
1270     log_error(aot)("Child process failed; status = %d", status);
1271     // We leave the temp config file for debugging
1272   } else if (CDSConfig::has_temp_aot_config_file()) {
1273     const char* tmp_config = AOTConfiguration;
1274     // On Windows, need WRITE permission to remove the file.
1275     WINDOWS_ONLY(chmod(tmp_config, _S_IREAD | _S_IWRITE));
1276     status = remove(tmp_config);
1277     if (status != 0) {
1278       log_error(aot)("Failed to remove temporary AOT configuration file %s", tmp_config);
1279     } else {
1280       tty->print_cr("Removed temporary AOT configuration file %s", tmp_config);
1281     }
1282   }
1283 }
1284 
1285 // Returns true if the class's status has changed.
1286 bool AOTMetaspace::try_link_class(JavaThread* current, InstanceKlass* ik) {
1287   ExceptionMark em(current);
1288   JavaThread* THREAD = current; // For exception macros.
1289   assert(CDSConfig::is_dumping_archive(), "sanity");
1290 
1291   if (ik->in_aot_cache() && !CDSConfig::is_dumping_final_static_archive()) {
1292     assert(CDSConfig::is_dumping_dynamic_archive(), "must be");
1293     return false;
1294   }
1295 
1296   if (ik->is_loaded() && !ik->is_linked() && ik->can_be_verified_at_dumptime() &&
1297       !SystemDictionaryShared::has_class_failed_verification(ik)) {
1298     bool saved = BytecodeVerificationLocal;
1299     if (ik->defined_by_other_loaders() && ik->class_loader() == nullptr) {
1300       // The verification decision is based on BytecodeVerificationRemote
1301       // for non-system classes. Since we are using the null classloader
1302       // to load non-system classes for customized class loaders during dumping,
1303       // we need to temporarily change BytecodeVerificationLocal to be the same as
1304       // BytecodeVerificationRemote. Note this can cause the parent system
1305       // classes also being verified. The extra overhead is acceptable during
1306       // dumping.
1307       BytecodeVerificationLocal = BytecodeVerificationRemote;
1308     }
1309     ik->link_class(THREAD);
1310     if (HAS_PENDING_EXCEPTION) {
1311       ResourceMark rm(THREAD);
1312       aot_log_warning(aot)("Preload Warning: Verification failed for %s",
1313                     ik->external_name());
1314       CLEAR_PENDING_EXCEPTION;
1315       SystemDictionaryShared::set_class_has_failed_verification(ik);
1316     } else {
1317       assert(!SystemDictionaryShared::has_class_failed_verification(ik), "sanity");
1318       ik->compute_has_loops_flag_for_methods();
1319     }
1320     BytecodeVerificationLocal = saved;
1321     return true;
1322   } else {
1323     return false;
1324   }
1325 }
1326 
1327 void VM_PopulateDumpSharedSpace::dump_java_heap_objects() {
1328   if (CDSConfig::is_dumping_heap()) {
1329     HeapShared::write_heap(&_heap_info);
1330   } else if (!CDSConfig::is_dumping_preimage_static_archive()) {
1331     CDSConfig::log_reasons_for_not_dumping_heap();
1332   }
1333 }
1334 
1335 void AOTMetaspace::set_aot_metaspace_range(void* base, void *static_top, void* top) {
1336   assert(base <= static_top && static_top <= top, "must be");
1337   _aot_metaspace_static_top = static_top;
1338   MetaspaceObj::set_aot_metaspace_range(base, top);
1339 }
1340 
1341 bool AOTMetaspace::in_aot_cache_dynamic_region(void* p) {
1342   if ((p < MetaspaceObj::aot_metaspace_top()) &&
1343       (p >= _aot_metaspace_static_top)) {
1344     return true;
1345   } else {
1346     return false;
1347   }
1348 }
1349 
1350 bool AOTMetaspace::in_aot_cache_static_region(void* p) {
1351   if (in_aot_cache(p) && !in_aot_cache_dynamic_region(p)) {
1352     return true;
1353   } else {
1354     return false;
1355   }
1356 }
1357 
1358 // This function is called when the JVM is unable to load the specified archive(s) due to one
1359 // of the following conditions.
1360 // - There's an error that indicates that the archive(s) files were corrupt or otherwise damaged.
1361 // - When -XX:+RequireSharedSpaces is specified, AND the JVM cannot load the archive(s) due
1362 //   to version or classpath mismatch.
1363 void AOTMetaspace::unrecoverable_loading_error(const char* message) {
1364   report_loading_error("%s", message);
1365 
1366   if (CDSConfig::is_dumping_final_static_archive()) {
1367     vm_exit_during_initialization("Must be a valid AOT configuration generated by the current JVM", AOTConfiguration);
1368   } else if (CDSConfig::new_aot_flags_used()) {
1369     vm_exit_during_initialization("Unable to use AOT cache.", nullptr);
1370   } else {
1371     vm_exit_during_initialization("Unable to use shared archive. Unrecoverable archive loading error (run with -Xlog:aot,cds for details)", message);
1372   }
1373 }
1374 
1375 void AOTMetaspace::report_loading_error(const char* format, ...) {
1376   // When using AOT cache, errors messages are always printed on the error channel.
1377   LogStream ls_aot(LogLevel::Error, LogTagSetMapping<LOG_TAGS(aot)>::tagset());
1378 
1379   // If we are loading load the default CDS archive, it may fail due to incompatible VM options.
1380   // Print at the info level to avoid excessive verbosity.
1381   // However, if the user has specified a CDS archive (or AOT cache), they would be interested in
1382   // knowing that the loading fails, so we print at the error level.
1383   LogLevelType level = (!CDSConfig::is_using_archive() || CDSConfig::is_using_only_default_archive()) ?
1384                         LogLevel::Info : LogLevel::Error;
1385   LogStream ls_cds(level, LogTagSetMapping<LOG_TAGS(cds)>::tagset());
1386 
1387   LogStream& ls = CDSConfig::new_aot_flags_used() ? ls_aot : ls_cds;
1388   if (!ls.is_enabled()) {
1389     return;
1390   }
1391 
1392   va_list ap;
1393   va_start(ap, format);
1394 
1395   static bool printed_error = false;
1396   if (!printed_error) { // No need for locks. Loading error checks happen only in main thread.
1397     ls.print_cr("An error has occurred while processing the %s. Run with -Xlog:%s for details.",
1398                 CDSConfig::type_of_archive_being_loaded(), CDSConfig::new_aot_flags_used() ? "aot" : "aot,cds");
1399     printed_error = true;
1400   }
1401   ls.vprint_cr(format, ap);
1402 
1403   va_end(ap);
1404 }
1405 
1406 // This function is called when the JVM is unable to write the specified CDS archive due to an
1407 // unrecoverable error.
1408 void AOTMetaspace::unrecoverable_writing_error(const char* message) {
1409   writing_error(message);
1410   vm_direct_exit(1);
1411 }
1412 
1413 // This function is called when the JVM is unable to write the specified CDS archive due to a
1414 // an error. The error will be propagated
1415 void AOTMetaspace::writing_error(const char* message) {
1416   aot_log_error(aot)("An error has occurred while writing the shared archive file.");
1417   if (message != nullptr) {
1418     aot_log_error(aot)("%s", message);
1419   }
1420 }
1421 
1422 void AOTMetaspace::initialize_runtime_shared_and_meta_spaces() {
1423   assert(CDSConfig::is_using_archive(), "Must be called when UseSharedSpaces is enabled");
1424   MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE;
1425 
1426   FileMapInfo* static_mapinfo = FileMapInfo::current_info();
1427   FileMapInfo* dynamic_mapinfo = nullptr;
1428 
1429   if (static_mapinfo != nullptr) {
1430     aot_log_info(aot)("Core region alignment: %zu", static_mapinfo->core_region_alignment());
1431     dynamic_mapinfo = open_dynamic_archive();
1432 
1433     aot_log_info(aot)("ArchiveRelocationMode: %d", ArchiveRelocationMode);
1434 
1435     // First try to map at the requested address
1436     result = map_archives(static_mapinfo, dynamic_mapinfo, true);
1437     if (result == MAP_ARCHIVE_MMAP_FAILURE) {
1438       // Mapping has failed (probably due to ASLR). Let's map at an address chosen
1439       // by the OS.
1440       aot_log_info(aot)("Try to map archive(s) at an alternative address");
1441       result = map_archives(static_mapinfo, dynamic_mapinfo, false);
1442     }
1443   }
1444 
1445   if (result == MAP_ARCHIVE_SUCCESS) {
1446     bool dynamic_mapped = (dynamic_mapinfo != nullptr && dynamic_mapinfo->is_mapped());
1447     char* cds_base = static_mapinfo->mapped_base();
1448     char* cds_end =  dynamic_mapped ? dynamic_mapinfo->mapped_end() : static_mapinfo->mapped_end();
1449     // Register CDS memory region with LSan.
1450     LSAN_REGISTER_ROOT_REGION(cds_base, cds_end - cds_base);
1451     set_aot_metaspace_range(cds_base, static_mapinfo->mapped_end(), cds_end);
1452     _relocation_delta = static_mapinfo->relocation_delta();
1453     _requested_base_address = static_mapinfo->requested_base_address();
1454     if (dynamic_mapped) {
1455       // turn AutoCreateSharedArchive off if successfully mapped
1456       AutoCreateSharedArchive = false;
1457     }
1458   } else {
1459     set_aot_metaspace_range(nullptr, nullptr, nullptr);
1460     if (CDSConfig::is_dumping_dynamic_archive()) {
1461       aot_log_warning(aot)("-XX:ArchiveClassesAtExit is unsupported when base CDS archive is not loaded. Run with -Xlog:cds for more info.");
1462     }
1463     UseSharedSpaces = false;
1464     // The base archive cannot be mapped. We cannot dump the dynamic shared archive.
1465     AutoCreateSharedArchive = false;
1466     CDSConfig::disable_dumping_dynamic_archive();
1467     if (PrintSharedArchiveAndExit) {
1468       AOTMetaspace::unrecoverable_loading_error("Unable to use shared archive.");
1469     } else {
1470       if (RequireSharedSpaces) {
1471         AOTMetaspace::unrecoverable_loading_error("Unable to map shared spaces");
1472       } else {
1473         report_loading_error("Unable to map shared spaces");
1474       }
1475     }
1476   }
1477 
1478   // If mapping failed and -XShare:on, the vm should exit
1479   bool has_failed = false;
1480   if (static_mapinfo != nullptr && !static_mapinfo->is_mapped()) {
1481     has_failed = true;
1482     delete static_mapinfo;
1483   }
1484   if (dynamic_mapinfo != nullptr && !dynamic_mapinfo->is_mapped()) {
1485     has_failed = true;
1486     delete dynamic_mapinfo;
1487   }
1488   if (RequireSharedSpaces && has_failed) {
1489     // static archive mapped but dynamic archive failed
1490       AOTMetaspace::unrecoverable_loading_error("Unable to map shared spaces");
1491   }
1492 }
1493 
1494 // This is called very early at VM start up to get the size of the cached_code region
1495 void AOTMetaspace::open_static_archive() {
1496   if (!UseSharedSpaces) { // FIXME -- is this still needed??
1497     return;
1498   }
1499   const char* static_archive = CDSConfig::input_static_archive_path();
1500   assert(static_archive != nullptr, "sanity");
1501   FileMapInfo* mapinfo = new FileMapInfo(static_archive, true);
1502   if (!mapinfo->open_as_input()) {
1503     delete(mapinfo);
1504     log_info(cds)("Opening of static archive %s failed", static_archive);
1505   } else {
1506     FileMapRegion* r = mapinfo->region_at(AOTMetaspace::ac);
1507     AOTCacheAccess::set_aot_code_region_size(r->used_aligned());
1508   }
1509 }
1510 
1511 FileMapInfo* AOTMetaspace::open_dynamic_archive() {
1512   if (CDSConfig::is_dumping_dynamic_archive()) {
1513     return nullptr;
1514   }
1515   const char* dynamic_archive = CDSConfig::input_dynamic_archive_path();
1516   if (dynamic_archive == nullptr) {
1517     return nullptr;
1518   }
1519 
1520   FileMapInfo* mapinfo = new FileMapInfo(dynamic_archive, false);
1521   if (!mapinfo->open_as_input()) {
1522     delete(mapinfo);
1523     if (RequireSharedSpaces) {
1524       AOTMetaspace::unrecoverable_loading_error("Failed to initialize dynamic archive");
1525     }
1526     return nullptr;
1527   }
1528   return mapinfo;
1529 }
1530 
1531 // use_requested_addr:
1532 //  true  = map at FileMapHeader::_requested_base_address
1533 //  false = map at an alternative address picked by OS.
1534 MapArchiveResult AOTMetaspace::map_archives(FileMapInfo* static_mapinfo, FileMapInfo* dynamic_mapinfo,
1535                                             bool use_requested_addr) {
1536   if (use_requested_addr && static_mapinfo->requested_base_address() == nullptr) {
1537     aot_log_info(aot)("Archive(s) were created with -XX:SharedBaseAddress=0. Always map at os-selected address.");
1538     return MAP_ARCHIVE_MMAP_FAILURE;
1539   }
1540 
1541   PRODUCT_ONLY(if (ArchiveRelocationMode == 1 && use_requested_addr) {
1542       // For product build only -- this is for benchmarking the cost of doing relocation.
1543       // For debug builds, the check is done below, after reserving the space, for better test coverage
1544       // (see comment below).
1545       aot_log_info(aot)("ArchiveRelocationMode == 1: always map archive(s) at an alternative address");
1546       return MAP_ARCHIVE_MMAP_FAILURE;
1547     });
1548 
1549   if (ArchiveRelocationMode == 2 && !use_requested_addr) {
1550     aot_log_info(aot)("ArchiveRelocationMode == 2: never map archive(s) at an alternative address");
1551     return MAP_ARCHIVE_MMAP_FAILURE;
1552   };
1553 
1554   if (dynamic_mapinfo != nullptr) {
1555     // Ensure that the OS won't be able to allocate new memory spaces between the two
1556     // archives, or else it would mess up the simple comparison in MetaspaceObj::in_aot_cache().
1557     assert(static_mapinfo->mapping_end_offset() == dynamic_mapinfo->mapping_base_offset(), "no gap");
1558   }
1559 
1560   ReservedSpace total_space_rs, archive_space_rs, class_space_rs;
1561   MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE;
1562   size_t prot_zone_size = 0;
1563   char* mapped_base_address = reserve_address_space_for_archives(static_mapinfo,
1564                                                                  dynamic_mapinfo,
1565                                                                  use_requested_addr,
1566                                                                  total_space_rs,
1567                                                                  archive_space_rs,
1568                                                                  class_space_rs);
1569   if (mapped_base_address == nullptr) {
1570     result = MAP_ARCHIVE_MMAP_FAILURE;
1571     aot_log_debug(aot)("Failed to reserve spaces (use_requested_addr=%u)", (unsigned)use_requested_addr);
1572   } else {
1573 
1574     if (Metaspace::using_class_space()) {
1575       prot_zone_size = protection_zone_size();
1576     }
1577 
1578 #ifdef ASSERT
1579     // Some sanity checks after reserving address spaces for archives
1580     //  and class space.
1581     assert(archive_space_rs.is_reserved(), "Sanity");
1582     if (Metaspace::using_class_space()) {
1583       assert(archive_space_rs.base() == mapped_base_address &&
1584           archive_space_rs.size() > protection_zone_size(),
1585           "Archive space must lead and include the protection zone");
1586       // Class space must closely follow the archive space. Both spaces
1587       //  must be aligned correctly.
1588       assert(class_space_rs.is_reserved() && class_space_rs.size() > 0,
1589              "A class space should have been reserved");
1590       assert(class_space_rs.base() >= archive_space_rs.end(),
1591              "class space should follow the cds archive space");
1592       assert(is_aligned(archive_space_rs.base(),
1593                         core_region_alignment()),
1594              "Archive space misaligned");
1595       assert(is_aligned(class_space_rs.base(),
1596                         Metaspace::reserve_alignment()),
1597              "class space misaligned");
1598     }
1599 #endif // ASSERT
1600 
1601     aot_log_info(aot)("Reserved archive_space_rs [" INTPTR_FORMAT " - " INTPTR_FORMAT "] (%zu) bytes%s",
1602                    p2i(archive_space_rs.base()), p2i(archive_space_rs.end()), archive_space_rs.size(),
1603                    (prot_zone_size > 0 ? " (includes protection zone)" : ""));
1604     aot_log_info(aot)("Reserved class_space_rs   [" INTPTR_FORMAT " - " INTPTR_FORMAT "] (%zu) bytes",
1605                    p2i(class_space_rs.base()), p2i(class_space_rs.end()), class_space_rs.size());
1606 
1607     if (AOTMetaspace::use_windows_memory_mapping()) {
1608       // We have now reserved address space for the archives, and will map in
1609       //  the archive files into this space.
1610       //
1611       // Special handling for Windows: on Windows we cannot map a file view
1612       //  into an existing memory mapping. So, we unmap the address range we
1613       //  just reserved again, which will make it available for mapping the
1614       //  archives.
1615       // Reserving this range has not been for naught however since it makes
1616       //  us reasonably sure the address range is available.
1617       //
1618       // But still it may fail, since between unmapping the range and mapping
1619       //  in the archive someone else may grab the address space. Therefore
1620       //  there is a fallback in FileMap::map_region() where we just read in
1621       //  the archive files sequentially instead of mapping it in. We couple
1622       //  this with use_requested_addr, since we're going to patch all the
1623       //  pointers anyway so there's no benefit to mmap.
1624       if (use_requested_addr) {
1625         assert(!total_space_rs.is_reserved(), "Should not be reserved for Windows");
1626         aot_log_info(aot)("Windows mmap workaround: releasing archive space.");
1627         MemoryReserver::release(archive_space_rs);
1628         // Mark as not reserved
1629         archive_space_rs = {};
1630         // The protection zone is part of the archive:
1631         // See comment above, the Windows way of loading CDS is to mmap the individual
1632         // parts of the archive into the address region we just vacated. The protection
1633         // zone will not be mapped (and, in fact, does not exist as physical region in
1634         // the archive). Therefore, after removing the archive space above, we must
1635         // re-reserve the protection zone part lest something else gets mapped into that
1636         // area later.
1637         if (prot_zone_size > 0) {
1638           assert(prot_zone_size >= os::vm_allocation_granularity(), "must be"); // not just page size!
1639           char* p = os::attempt_reserve_memory_at(mapped_base_address, prot_zone_size,
1640                                                   mtClassShared);
1641           assert(p == mapped_base_address || p == nullptr, "must be");
1642           if (p == nullptr) {
1643             aot_log_debug(aot)("Failed to re-reserve protection zone");
1644             return MAP_ARCHIVE_MMAP_FAILURE;
1645           }
1646         }
1647       }
1648     }
1649 
1650     if (prot_zone_size > 0) {
1651       os::commit_memory(mapped_base_address, prot_zone_size, false); // will later be protected
1652       // Before mapping the core regions into the newly established address space, we mark
1653       // start and the end of the future protection zone with canaries. That way we easily
1654       // catch mapping errors (accidentally mapping data into the future protection zone).
1655       *(mapped_base_address) = 'P';
1656       *(mapped_base_address + prot_zone_size - 1) = 'P';
1657     }
1658 
1659     MapArchiveResult static_result = map_archive(static_mapinfo, mapped_base_address, archive_space_rs);
1660     MapArchiveResult dynamic_result = (static_result == MAP_ARCHIVE_SUCCESS) ?
1661                                      map_archive(dynamic_mapinfo, mapped_base_address, archive_space_rs) : MAP_ARCHIVE_OTHER_FAILURE;
1662 
1663     DEBUG_ONLY(if (ArchiveRelocationMode == 1 && use_requested_addr) {
1664       // This is for simulating mmap failures at the requested address. In
1665       //  debug builds, we do it here (after all archives have possibly been
1666       //  mapped), so we can thoroughly test the code for failure handling
1667       //  (releasing all allocated resource, etc).
1668       aot_log_info(aot)("ArchiveRelocationMode == 1: always map archive(s) at an alternative address");
1669       if (static_result == MAP_ARCHIVE_SUCCESS) {
1670         static_result = MAP_ARCHIVE_MMAP_FAILURE;
1671       }
1672       if (dynamic_result == MAP_ARCHIVE_SUCCESS) {
1673         dynamic_result = MAP_ARCHIVE_MMAP_FAILURE;
1674       }
1675     });
1676 
1677     if (static_result == MAP_ARCHIVE_SUCCESS) {
1678       if (dynamic_result == MAP_ARCHIVE_SUCCESS) {
1679         result = MAP_ARCHIVE_SUCCESS;
1680       } else if (dynamic_result == MAP_ARCHIVE_OTHER_FAILURE) {
1681         assert(dynamic_mapinfo != nullptr && !dynamic_mapinfo->is_mapped(), "must have failed");
1682         // No need to retry mapping the dynamic archive again, as it will never succeed
1683         // (bad file, etc) -- just keep the base archive.
1684         log_warning(cds, dynamic)("Unable to use shared archive. The top archive failed to load: %s",
1685                                   dynamic_mapinfo->full_path());
1686         result = MAP_ARCHIVE_SUCCESS;
1687         // TODO, we can give the unused space for the dynamic archive to class_space_rs, but there's no
1688         // easy API to do that right now.
1689       } else {
1690         result = MAP_ARCHIVE_MMAP_FAILURE;
1691       }
1692     } else if (static_result == MAP_ARCHIVE_OTHER_FAILURE) {
1693       result = MAP_ARCHIVE_OTHER_FAILURE;
1694     } else {
1695       result = MAP_ARCHIVE_MMAP_FAILURE;
1696     }
1697   }
1698 
1699   if (result == MAP_ARCHIVE_SUCCESS) {
1700     SharedBaseAddress = (size_t)mapped_base_address;
1701 #ifdef _LP64
1702     if (Metaspace::using_class_space()) {
1703       assert(prot_zone_size > 0 &&
1704              *(mapped_base_address) == 'P' &&
1705              *(mapped_base_address + prot_zone_size - 1) == 'P',
1706              "Protection zone was overwritten?");
1707       // Set up ccs in metaspace.
1708       Metaspace::initialize_class_space(class_space_rs);
1709 
1710       // Set up compressed Klass pointer encoding: the encoding range must
1711       //  cover both archive and class space.
1712       const address klass_range_start = (address)mapped_base_address;
1713       const size_t klass_range_size = (address)class_space_rs.end() - klass_range_start;
1714       if (INCLUDE_CDS_JAVA_HEAP || UseCompactObjectHeaders) {
1715         // The CDS archive may contain narrow Klass IDs that were precomputed at archive generation time:
1716         // - every archived java object header (only if INCLUDE_CDS_JAVA_HEAP)
1717         // - every archived Klass' prototype   (only if +UseCompactObjectHeaders)
1718         //
1719         // In order for those IDs to still be valid, we need to dictate base and shift: base should be the
1720         // mapping start (including protection zone), shift should be the shift used at archive generation time.
1721         CompressedKlassPointers::initialize_for_given_encoding(
1722           klass_range_start, klass_range_size,
1723           klass_range_start, ArchiveBuilder::precomputed_narrow_klass_shift() // precomputed encoding, see ArchiveBuilder
1724         );
1725         assert(CompressedKlassPointers::base() == klass_range_start, "must be");
1726       } else {
1727         // Let JVM freely choose encoding base and shift
1728         CompressedKlassPointers::initialize(klass_range_start, klass_range_size);
1729         assert(CompressedKlassPointers::base() == nullptr ||
1730                CompressedKlassPointers::base() == klass_range_start, "must be");
1731       }
1732       // Establish protection zone, but only if we need one
1733       if (CompressedKlassPointers::base() == klass_range_start) {
1734         CompressedKlassPointers::establish_protection_zone(klass_range_start, prot_zone_size);
1735       }
1736 
1737       // map_or_load_heap_region() compares the current narrow oop and klass encodings
1738       // with the archived ones, so it must be done after all encodings are determined.
1739       static_mapinfo->map_or_load_heap_region();
1740     }
1741 #endif // _LP64
1742     log_info(aot)("initial optimized module handling: %s", CDSConfig::is_using_optimized_module_handling() ? "enabled" : "disabled");
1743     log_info(aot)("initial full module graph: %s", CDSConfig::is_using_full_module_graph() ? "enabled" : "disabled");
1744   } else {
1745     unmap_archive(static_mapinfo);
1746     unmap_archive(dynamic_mapinfo);
1747     release_reserved_spaces(total_space_rs, archive_space_rs, class_space_rs);
1748   }
1749 
1750   return result;
1751 }
1752 
1753 
1754 // This will reserve two address spaces suitable to house Klass structures, one
1755 //  for the cds archives (static archive and optionally dynamic archive) and
1756 //  optionally one move for ccs.
1757 //
1758 // Since both spaces must fall within the compressed class pointer encoding
1759 //  range, they are allocated close to each other.
1760 //
1761 // Space for archives will be reserved first, followed by a potential gap,
1762 //  followed by the space for ccs:
1763 //
1764 // +-- Base address             A        B                     End
1765 // |                            |        |                      |
1766 // v                            v        v                      v
1767 // +-------------+--------------+        +----------------------+
1768 // | static arc  | [dyn. arch]  | [gap]  | compr. class space   |
1769 // +-------------+--------------+        +----------------------+
1770 //
1771 // (The gap may result from different alignment requirements between metaspace
1772 //  and CDS)
1773 //
1774 // If UseCompressedClassPointers is disabled, only one address space will be
1775 //  reserved:
1776 //
1777 // +-- Base address             End
1778 // |                            |
1779 // v                            v
1780 // +-------------+--------------+
1781 // | static arc  | [dyn. arch]  |
1782 // +-------------+--------------+
1783 //
1784 // Base address: If use_archive_base_addr address is true, the Base address is
1785 //  determined by the address stored in the static archive. If
1786 //  use_archive_base_addr address is false, this base address is determined
1787 //  by the platform.
1788 //
1789 // If UseCompressedClassPointers=1, the range encompassing both spaces will be
1790 //  suitable to en/decode narrow Klass pointers: the base will be valid for
1791 //  encoding, the range [Base, End) and not surpass the max. range for that encoding.
1792 //
1793 // Return:
1794 //
1795 // - On success:
1796 //    - total_space_rs will be reserved as whole for archive_space_rs and
1797 //      class_space_rs if UseCompressedClassPointers is true.
1798 //      On Windows, try reserve archive_space_rs and class_space_rs
1799 //      separately first if use_archive_base_addr is true.
1800 //    - archive_space_rs will be reserved and large enough to host static and
1801 //      if needed dynamic archive: [Base, A).
1802 //      archive_space_rs.base and size will be aligned to CDS reserve
1803 //      granularity.
1804 //    - class_space_rs: If UseCompressedClassPointers=1, class_space_rs will
1805 //      be reserved. Its start address will be aligned to metaspace reserve
1806 //      alignment, which may differ from CDS alignment. It will follow the cds
1807 //      archive space, close enough such that narrow class pointer encoding
1808 //      covers both spaces.
1809 //      If UseCompressedClassPointers=0, class_space_rs remains unreserved.
1810 // - On error: null is returned and the spaces remain unreserved.
1811 char* AOTMetaspace::reserve_address_space_for_archives(FileMapInfo* static_mapinfo,
1812                                                        FileMapInfo* dynamic_mapinfo,
1813                                                        bool use_archive_base_addr,
1814                                                        ReservedSpace& total_space_rs,
1815                                                        ReservedSpace& archive_space_rs,
1816                                                        ReservedSpace& class_space_rs) {
1817 
1818   address const base_address = (address) (use_archive_base_addr ? static_mapinfo->requested_base_address() : nullptr);
1819   const size_t archive_space_alignment = core_region_alignment();
1820 
1821   // Size and requested location of the archive_space_rs (for both static and dynamic archives)
1822   size_t archive_end_offset  = (dynamic_mapinfo == nullptr) ? static_mapinfo->mapping_end_offset() : dynamic_mapinfo->mapping_end_offset();
1823   size_t archive_space_size = align_up(archive_end_offset, archive_space_alignment);
1824 
1825   if (!Metaspace::using_class_space()) {
1826     // Get the simple case out of the way first:
1827     // no compressed class space, simple allocation.
1828 
1829     // When running without class space, requested archive base should be aligned to cds core alignment.
1830     assert(is_aligned(base_address, archive_space_alignment),
1831              "Archive base address unaligned: " PTR_FORMAT ", needs alignment: %zu.",
1832              p2i(base_address), archive_space_alignment);
1833 
1834     archive_space_rs = MemoryReserver::reserve((char*)base_address,
1835                                                archive_space_size,
1836                                                archive_space_alignment,
1837                                                os::vm_page_size(),
1838                                                mtNone);
1839     if (archive_space_rs.is_reserved()) {
1840       assert(base_address == nullptr ||
1841              (address)archive_space_rs.base() == base_address, "Sanity");
1842       // Register archive space with NMT.
1843       MemTracker::record_virtual_memory_tag(archive_space_rs, mtClassShared);
1844       return archive_space_rs.base();
1845     }
1846     return nullptr;
1847   }
1848 
1849 #ifdef _LP64
1850 
1851   // Complex case: two spaces adjacent to each other, both to be addressable
1852   //  with narrow class pointers.
1853   // We reserve the whole range spanning both spaces, then split that range up.
1854 
1855   const size_t class_space_alignment = Metaspace::reserve_alignment();
1856 
1857   // When running with class space, requested archive base must satisfy both cds core alignment
1858   // and class space alignment.
1859   const size_t base_address_alignment = MAX2(class_space_alignment, archive_space_alignment);
1860   assert(is_aligned(base_address, base_address_alignment),
1861            "Archive base address unaligned: " PTR_FORMAT ", needs alignment: %zu.",
1862            p2i(base_address), base_address_alignment);
1863 
1864   size_t class_space_size = CompressedClassSpaceSize;
1865   assert(CompressedClassSpaceSize > 0 &&
1866          is_aligned(CompressedClassSpaceSize, class_space_alignment),
1867          "CompressedClassSpaceSize malformed: %zu", CompressedClassSpaceSize);
1868 
1869   const size_t ccs_begin_offset = align_up(archive_space_size, class_space_alignment);
1870   const size_t gap_size = ccs_begin_offset - archive_space_size;
1871 
1872   // Reduce class space size if it would not fit into the Klass encoding range
1873   constexpr size_t max_encoding_range_size = 4 * G;
1874   guarantee(archive_space_size < max_encoding_range_size - class_space_alignment, "Archive too large");
1875   if ((archive_space_size + gap_size + class_space_size) > max_encoding_range_size) {
1876     class_space_size = align_down(max_encoding_range_size - archive_space_size - gap_size, class_space_alignment);
1877     log_info(metaspace)("CDS initialization: reducing class space size from %zu to %zu",
1878         CompressedClassSpaceSize, class_space_size);
1879     FLAG_SET_ERGO(CompressedClassSpaceSize, class_space_size);
1880   }
1881 
1882   const size_t total_range_size =
1883       archive_space_size + gap_size + class_space_size;
1884 
1885   // Test that class space base address plus shift can be decoded by aarch64, when restored.
1886   const int precomputed_narrow_klass_shift = ArchiveBuilder::precomputed_narrow_klass_shift();
1887   if (!CompressedKlassPointers::check_klass_decode_mode(base_address, precomputed_narrow_klass_shift,
1888                                                         total_range_size)) {
1889     aot_log_info(aot)("CDS initialization: Cannot use SharedBaseAddress " PTR_FORMAT " with precomputed shift %d.",
1890                   p2i(base_address), precomputed_narrow_klass_shift);
1891     use_archive_base_addr = false;
1892   }
1893 
1894   assert(total_range_size > ccs_begin_offset, "must be");
1895   if (use_windows_memory_mapping() && use_archive_base_addr) {
1896     if (base_address != nullptr) {
1897       // On Windows, we cannot safely split a reserved memory space into two (see JDK-8255917).
1898       // Hence, we optimistically reserve archive space and class space side-by-side. We only
1899       // do this for use_archive_base_addr=true since for use_archive_base_addr=false case
1900       // caller will not split the combined space for mapping, instead read the archive data
1901       // via sequential file IO.
1902       address ccs_base = base_address + archive_space_size + gap_size;
1903       archive_space_rs = MemoryReserver::reserve((char*)base_address,
1904                                                  archive_space_size,
1905                                                  archive_space_alignment,
1906                                                  os::vm_page_size(),
1907                                                  mtNone);
1908       class_space_rs   = MemoryReserver::reserve((char*)ccs_base,
1909                                                  class_space_size,
1910                                                  class_space_alignment,
1911                                                  os::vm_page_size(),
1912                                                  mtNone);
1913     }
1914     if (!archive_space_rs.is_reserved() || !class_space_rs.is_reserved()) {
1915       release_reserved_spaces(total_space_rs, archive_space_rs, class_space_rs);
1916       return nullptr;
1917     }
1918     MemTracker::record_virtual_memory_tag(archive_space_rs, mtClassShared);
1919     MemTracker::record_virtual_memory_tag(class_space_rs, mtClass);
1920   } else {
1921     if (use_archive_base_addr && base_address != nullptr) {
1922       total_space_rs = MemoryReserver::reserve((char*) base_address,
1923                                                total_range_size,
1924                                                base_address_alignment,
1925                                                os::vm_page_size(),
1926                                                mtNone);
1927     } else {
1928       // We did not manage to reserve at the preferred address, or were instructed to relocate. In that
1929       // case we reserve wherever possible, but the start address needs to be encodable as narrow Klass
1930       // encoding base since the archived heap objects contain narrow Klass IDs pre-calculated toward the start
1931       // of the shared Metaspace. That prevents us from using zero-based encoding and therefore we won't
1932       // try allocating in low-address regions.
1933       total_space_rs = Metaspace::reserve_address_space_for_compressed_classes(total_range_size, false /* optimize_for_zero_base */);
1934     }
1935 
1936     if (!total_space_rs.is_reserved()) {
1937       return nullptr;
1938     }
1939 
1940     // Paranoid checks:
1941     assert(!use_archive_base_addr || (address)total_space_rs.base() == base_address,
1942            "Sanity (" PTR_FORMAT " vs " PTR_FORMAT ")", p2i(base_address), p2i(total_space_rs.base()));
1943     assert(is_aligned(total_space_rs.base(), base_address_alignment), "Sanity");
1944     assert(total_space_rs.size() == total_range_size, "Sanity");
1945 
1946     // Now split up the space into ccs and cds archive. For simplicity, just leave
1947     //  the gap reserved at the end of the archive space. Do not do real splitting.
1948     archive_space_rs = total_space_rs.first_part(ccs_begin_offset,
1949                                                  (size_t)archive_space_alignment);
1950     class_space_rs = total_space_rs.last_part(ccs_begin_offset);
1951     MemTracker::record_virtual_memory_split_reserved(total_space_rs.base(), total_space_rs.size(),
1952                                                      ccs_begin_offset, mtClassShared, mtClass);
1953   }
1954   assert(is_aligned(archive_space_rs.base(), archive_space_alignment), "Sanity");
1955   assert(is_aligned(archive_space_rs.size(), archive_space_alignment), "Sanity");
1956   assert(is_aligned(class_space_rs.base(), class_space_alignment), "Sanity");
1957   assert(is_aligned(class_space_rs.size(), class_space_alignment), "Sanity");
1958 
1959 
1960   return archive_space_rs.base();
1961 
1962 #else
1963   ShouldNotReachHere();
1964   return nullptr;
1965 #endif
1966 
1967 }
1968 
1969 void AOTMetaspace::release_reserved_spaces(ReservedSpace& total_space_rs,
1970                                            ReservedSpace& archive_space_rs,
1971                                            ReservedSpace& class_space_rs) {
1972   if (total_space_rs.is_reserved()) {
1973     aot_log_debug(aot)("Released shared space (archive + class) " INTPTR_FORMAT, p2i(total_space_rs.base()));
1974     MemoryReserver::release(total_space_rs);
1975     total_space_rs = {};
1976   } else {
1977     if (archive_space_rs.is_reserved()) {
1978       aot_log_debug(aot)("Released shared space (archive) " INTPTR_FORMAT, p2i(archive_space_rs.base()));
1979       MemoryReserver::release(archive_space_rs);
1980       archive_space_rs = {};
1981     }
1982     if (class_space_rs.is_reserved()) {
1983       aot_log_debug(aot)("Released shared space (classes) " INTPTR_FORMAT, p2i(class_space_rs.base()));
1984       MemoryReserver::release(class_space_rs);
1985       class_space_rs = {};
1986     }
1987   }
1988 }
1989 
1990 static int archive_regions[]     = { AOTMetaspace::rw, AOTMetaspace::ro };
1991 static int archive_regions_count = 2;
1992 
1993 MapArchiveResult AOTMetaspace::map_archive(FileMapInfo* mapinfo, char* mapped_base_address, ReservedSpace rs) {
1994   assert(CDSConfig::is_using_archive(), "must be runtime");
1995   if (mapinfo == nullptr) {
1996     return MAP_ARCHIVE_SUCCESS; // The dynamic archive has not been specified. No error has happened -- trivially succeeded.
1997   }
1998 
1999   if (!mapinfo->validate_aot_class_linking()) {
2000     return MAP_ARCHIVE_OTHER_FAILURE;
2001   }
2002 
2003   mapinfo->set_is_mapped(false);
2004   if (mapinfo->core_region_alignment() != (size_t)core_region_alignment()) {
2005     report_loading_error("Unable to map CDS archive -- core_region_alignment() expected: %zu"
2006                          " actual: %zu", mapinfo->core_region_alignment(), core_region_alignment());
2007     return MAP_ARCHIVE_OTHER_FAILURE;
2008   }
2009 
2010   MapArchiveResult result =
2011     mapinfo->map_regions(archive_regions, archive_regions_count, mapped_base_address, rs);
2012 
2013   if (result != MAP_ARCHIVE_SUCCESS) {
2014     unmap_archive(mapinfo);
2015     return result;
2016   }
2017 
2018   if (!mapinfo->validate_class_location()) {
2019     unmap_archive(mapinfo);
2020     return MAP_ARCHIVE_OTHER_FAILURE;
2021   }
2022 
2023   if (mapinfo->is_static()) {
2024     // Currently, only static archive uses early serialized data.
2025     char* buffer = mapinfo->early_serialized_data();
2026     intptr_t* array = (intptr_t*)buffer;
2027     ReadClosure rc(&array, (intptr_t)mapped_base_address);
2028     early_serialize(&rc);
2029   }
2030 
2031   if (!mapinfo->validate_aot_class_linking()) {
2032     unmap_archive(mapinfo);
2033     return MAP_ARCHIVE_OTHER_FAILURE;
2034   }
2035 
2036   mapinfo->set_is_mapped(true);
2037   return MAP_ARCHIVE_SUCCESS;
2038 }
2039 
2040 void AOTMetaspace::unmap_archive(FileMapInfo* mapinfo) {
2041   assert(CDSConfig::is_using_archive(), "must be runtime");
2042   if (mapinfo != nullptr) {
2043     mapinfo->unmap_regions(archive_regions, archive_regions_count);
2044     mapinfo->unmap_region(AOTMetaspace::bm);
2045     mapinfo->set_is_mapped(false);
2046   }
2047 }
2048 
2049 // For -XX:PrintSharedArchiveAndExit
2050 class CountSharedSymbols : public SymbolClosure {
2051  private:
2052    int _count;
2053  public:
2054    CountSharedSymbols() : _count(0) {}
2055   void do_symbol(Symbol** sym) {
2056     _count++;
2057   }
2058   int total() { return _count; }
2059 
2060 };
2061 
2062 // Read the miscellaneous data from the shared file, and
2063 // serialize it out to its various destinations.
2064 
2065 void AOTMetaspace::initialize_shared_spaces() {
2066   FileMapInfo *static_mapinfo = FileMapInfo::current_info();
2067   FileMapInfo *dynamic_mapinfo = FileMapInfo::dynamic_info();
2068 
2069   // Verify various attributes of the archive, plus initialize the
2070   // shared string/symbol tables.
2071   char* buffer = static_mapinfo->serialized_data();
2072   intptr_t* array = (intptr_t*)buffer;
2073   ReadClosure rc(&array, (intptr_t)SharedBaseAddress);
2074   serialize(&rc);
2075 
2076   // Finish up archived heap initialization. These must be
2077   // done after ReadClosure.
2078   static_mapinfo->patch_heap_embedded_pointers();
2079   ArchiveHeapLoader::finish_initialization();
2080   Universe::load_archived_object_instances();
2081   AOTCodeCache::initialize();
2082 
2083   if (dynamic_mapinfo != nullptr) {
2084     intptr_t* buffer = (intptr_t*)dynamic_mapinfo->serialized_data();
2085     ReadClosure rc(&buffer, (intptr_t)SharedBaseAddress);
2086     DynamicArchive::serialize(&rc);
2087     DynamicArchive::setup_array_klasses();
2088   }
2089 
2090   LogStreamHandle(Info, aot) lsh;
2091   if (lsh.is_enabled()) {
2092     lsh.print("Using AOT-linked classes: %s (static archive: %s aot-linked classes",
2093               BOOL_TO_STR(CDSConfig::is_using_aot_linked_classes()),
2094               static_mapinfo->header()->has_aot_linked_classes() ? "has" : "no");
2095     if (dynamic_mapinfo != nullptr) {
2096       lsh.print(", dynamic archive: %s aot-linked classes",
2097                 dynamic_mapinfo->header()->has_aot_linked_classes() ? "has" : "no");
2098     }
2099     lsh.print_cr(")");
2100   }
2101 
2102   // Set up LambdaFormInvokers::_lambdaform_lines for dynamic dump
2103   if (CDSConfig::is_dumping_dynamic_archive()) {
2104     // Read stored LF format lines stored in static archive
2105     LambdaFormInvokers::read_static_archive_invokers();
2106   }
2107 
2108   if (PrintSharedArchiveAndExit) {
2109     // Print archive names
2110     if (dynamic_mapinfo != nullptr) {
2111       tty->print_cr("\n\nBase archive name: %s", CDSConfig::input_static_archive_path());
2112       tty->print_cr("Base archive version %d", static_mapinfo->version());
2113     } else {
2114       tty->print_cr("Static archive name: %s", static_mapinfo->full_path());
2115       tty->print_cr("Static archive version %d", static_mapinfo->version());
2116     }
2117 
2118     SystemDictionaryShared::print_shared_archive(tty);
2119     if (dynamic_mapinfo != nullptr) {
2120       tty->print_cr("\n\nDynamic archive name: %s", dynamic_mapinfo->full_path());
2121       tty->print_cr("Dynamic archive version %d", dynamic_mapinfo->version());
2122       SystemDictionaryShared::print_shared_archive(tty, false/*dynamic*/);
2123     }
2124 
2125     TrainingData::print_archived_training_data_on(tty);
2126 
2127     AOTCodeCache::print_on(tty);
2128 
2129     // collect shared symbols and strings
2130     CountSharedSymbols cl;
2131     SymbolTable::shared_symbols_do(&cl);
2132     tty->print_cr("Number of shared symbols: %d", cl.total());
2133     tty->print_cr("Number of shared strings: %zu", StringTable::shared_entry_count());
2134     tty->print_cr("VM version: %s\r\n", static_mapinfo->vm_version());
2135     if (FileMapInfo::current_info() == nullptr || _archive_loading_failed) {
2136       tty->print_cr("archive is invalid");
2137       vm_exit(1);
2138     } else {
2139       tty->print_cr("archive is valid");
2140       vm_exit(0);
2141     }
2142   }
2143 }
2144 
2145 // JVM/TI RedefineClasses() support:
2146 bool AOTMetaspace::remap_shared_readonly_as_readwrite() {
2147   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
2148 
2149   if (CDSConfig::is_using_archive()) {
2150     // remap the shared readonly space to shared readwrite, private
2151     FileMapInfo* mapinfo = FileMapInfo::current_info();
2152     if (!mapinfo->remap_shared_readonly_as_readwrite()) {
2153       return false;
2154     }
2155     if (FileMapInfo::dynamic_info() != nullptr) {
2156       mapinfo = FileMapInfo::dynamic_info();
2157       if (!mapinfo->remap_shared_readonly_as_readwrite()) {
2158         return false;
2159       }
2160     }
2161     _remapped_readwrite = true;
2162   }
2163   return true;
2164 }
2165 
2166 void AOTMetaspace::print_on(outputStream* st) {
2167   if (CDSConfig::is_using_archive()) {
2168     st->print("CDS archive(s) mapped at: ");
2169     address base = (address)MetaspaceObj::aot_metaspace_base();
2170     address static_top = (address)_aot_metaspace_static_top;
2171     address top = (address)MetaspaceObj::aot_metaspace_top();
2172     st->print("[" PTR_FORMAT "-" PTR_FORMAT "-" PTR_FORMAT "), ", p2i(base), p2i(static_top), p2i(top));
2173     st->print("size %zu, ", top - base);
2174     st->print("SharedBaseAddress: " PTR_FORMAT ", ArchiveRelocationMode: %d.", SharedBaseAddress, ArchiveRelocationMode);
2175   } else {
2176     st->print("CDS archive(s) not mapped");
2177   }
2178   st->cr();
2179 }