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