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