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