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