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