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