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