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