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