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