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   FileMapInfo* _map_info;
 493   StaticArchiveBuilder& _builder;
 494 
 495   void dump_java_heap_objects(GrowableArray<Klass*>* klasses) NOT_CDS_JAVA_HEAP_RETURN;
 496   void dump_shared_symbol_table(GrowableArray<Symbol*>* symbols) {
 497     log_info(cds)("Dumping symbol table ...");
 498     SymbolTable::write_to_archive(symbols);
 499   }
 500   char* dump_read_only_tables();
 501 
 502 public:
 503 
 504   VM_PopulateDumpSharedSpace(StaticArchiveBuilder& b) :
 505     VM_Operation(), _heap_info(), _map_info(nullptr), _builder(b) {}
 506 
 507   bool skip_operation() const { return false; }
 508 
 509   VMOp_Type type() const { return VMOp_PopulateDumpSharedSpace; }
 510   ArchiveHeapInfo* heap_info()  { return &_heap_info; }
 511   FileMapInfo* map_info() const { return _map_info; }
 512   void doit();   // outline because gdb sucks
 513   bool allow_nested_vm_operations() const { return true; }
 514 }; // class VM_PopulateDumpSharedSpace
 515 
 516 class StaticArchiveBuilder : public ArchiveBuilder {
 517 public:
 518   StaticArchiveBuilder() : ArchiveBuilder() {}
 519 
 520   virtual void iterate_roots(MetaspaceClosure* it) {
 521     FileMapInfo::metaspace_pointers_do(it);
 522     SystemDictionaryShared::dumptime_classes_do(it);
 523     Universe::metaspace_pointers_do(it);
 524     vmSymbols::metaspace_pointers_do(it);
 525     TrainingData::iterate_roots(it);
 526 
 527     // The above code should find all the symbols that are referenced by the
 528     // archived classes. We just need to add the extra symbols which
 529     // may not be used by any of the archived classes -- these are usually
 530     // symbols that we anticipate to be used at run time, so we can store
 531     // them in the RO region, to be shared across multiple processes.
 532     if (_extra_symbols != nullptr) {
 533       for (int i = 0; i < _extra_symbols->length(); i++) {
 534         it->push(_extra_symbols->adr_at(i));
 535       }
 536     }
 537 
 538     for (int i = 0; i < _method_handle_intrinsics->length(); i++) {
 539       it->push(_method_handle_intrinsics->adr_at(i));
 540     }
 541   }
 542 };
 543 
 544 char* VM_PopulateDumpSharedSpace::dump_read_only_tables() {
 545   ArchiveBuilder::OtherROAllocMark mark;
 546 
 547   SystemDictionaryShared::write_to_archive();
 548   ClassPreloader::record_initiated_classes(true);
 549   ClassPreloader::record_unregistered_classes();
 550   TrainingData::dump_training_data();
 551   MetaspaceShared::write_method_handle_intrinsics();
 552 
 553   // Write lambform lines into archive
 554   LambdaFormInvokers::dump_static_archive_invokers();
 555   // Write module name into archive
 556   CDS_JAVA_HEAP_ONLY(Modules::dump_main_module_name();)
 557   // Write the other data to the output array.
 558   DumpRegion* ro_region = ArchiveBuilder::current()->ro_region();
 559   char* start = ro_region->top();
 560   WriteClosure wc(ro_region);
 561   MetaspaceShared::serialize(&wc);
 562 
 563   return start;
 564 }
 565 
 566 void VM_PopulateDumpSharedSpace::doit() {
 567   //guarantee(!CDSConfig::is_using_archive(), "We should not be using an archive when we dump");
 568 
 569   DEBUG_ONLY(SystemDictionaryShared::NoClassLoadingMark nclm);
 570 
 571   FileMapInfo::check_nonempty_dir_in_shared_path_table();
 572 
 573   NOT_PRODUCT(SystemDictionary::verify();)
 574 
 575   // Block concurrent class unloading from changing the _dumptime_table
 576   MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
 577 
 578   HeapShared::start_finding_archivable_hidden_classes();
 579   SystemDictionaryShared::check_excluded_classes();
 580   HeapShared::end_finding_archivable_hidden_classes();
 581 
 582   _builder.gather_source_objs();
 583   _builder.reserve_buffer();
 584 
 585   CppVtables::dumptime_init(&_builder);
 586 
 587   _builder.sort_metadata_objs();
 588   _builder.dump_rw_metadata();
 589   _builder.dump_ro_metadata();
 590   _builder.relocate_metaspaceobj_embedded_pointers();
 591 
 592   dump_java_heap_objects(_builder.klasses());
 593   dump_shared_symbol_table(_builder.symbols());
 594 
 595   {
 596     ArchiveBuilder::OtherROAllocMark mark;
 597     ClassPreloader::record_preloaded_classes(true);
 598     if (CDSConfig::is_dumping_preimage_static_archive()) {
 599       FinalImageRecipes::record_recipes();
 600     }
 601   }
 602 
 603   log_info(cds)("Make classes shareable");
 604   _builder.make_klasses_shareable();
 605   MetaspaceShared::make_method_handle_intrinsics_shareable();
 606 
 607   char* serialized_data = dump_read_only_tables();
 608 
 609   SystemDictionaryShared::adjust_lambda_proxy_class_dictionary();
 610 
 611   log_info(cds)("Adjust method info dictionary");
 612   SystemDictionaryShared::adjust_method_info_dictionary();
 613 
 614   log_info(cds)("Make training data shareable");
 615   _builder.make_training_data_shareable();
 616 
 617   // The vtable clones contain addresses of the current process.
 618   // We don't want to write these addresses into the archive.
 619   CppVtables::zero_archived_vtables();
 620 
 621   // Write the archive file
 622   const char* static_archive;
 623   if (CDSConfig::is_dumping_final_static_archive()) {
 624     static_archive = CacheDataStore;
 625     assert(FileMapInfo::current_info() != nullptr, "sanity");
 626     delete FileMapInfo::current_info();
 627   } else {
 628     static_archive = CDSConfig::static_archive_path();
 629   }
 630   assert(static_archive != nullptr, "SharedArchiveFile not set?");
 631   _map_info = new FileMapInfo(static_archive, true);
 632   _map_info->populate_header(MetaspaceShared::core_region_alignment());
 633   _map_info->set_serialized_data(serialized_data);
 634   _map_info->set_cloned_vtables(CppVtables::vtables_serialized_base());
 635 }
 636 
 637 class CollectCLDClosure : public CLDClosure {
 638   GrowableArray<ClassLoaderData*> _loaded_cld;
 639   GrowableArray<OopHandle> _loaded_cld_handles; // keep the CLDs alive
 640   Thread* _current_thread;
 641 public:
 642   CollectCLDClosure(Thread* thread) : _current_thread(thread) {}
 643   ~CollectCLDClosure() {
 644     for (int i = 0; i < _loaded_cld_handles.length(); i++) {
 645       _loaded_cld_handles.at(i).release(Universe::vm_global());
 646     }
 647   }
 648   void do_cld(ClassLoaderData* cld) {
 649     assert(cld->is_alive(), "must be");
 650     _loaded_cld.append(cld);
 651     _loaded_cld_handles.append(OopHandle(Universe::vm_global(), cld->holder()));
 652   }
 653 
 654   int nof_cld() const                { return _loaded_cld.length(); }
 655   ClassLoaderData* cld_at(int index) { return _loaded_cld.at(index); }
 656 };
 657 
 658 // Check if we can eagerly link this class at dump time, so we can avoid the
 659 // runtime linking overhead (especially verification)
 660 bool MetaspaceShared::may_be_eagerly_linked(InstanceKlass* ik) {
 661   if (CDSConfig::preserve_all_dumptime_verification_states(ik)) {
 662     assert(ik->can_be_verified_at_dumptime(), "sanity");
 663   }
 664   if (!ik->can_be_verified_at_dumptime()) {
 665     // For old classes, try to leave them in the unlinked state, so
 666     // we can still store them in the archive. They must be
 667     // linked/verified at runtime.
 668     return false;
 669   }
 670 
 671   if (CDSConfig::is_dumping_dynamic_archive() && ik->is_shared_unregistered_class()) {
 672     // Linking of unregistered classes at this stage may cause more
 673     // classes to be resolved, resulting in calls to ClassLoader.loadClass()
 674     // that may not be expected by custom class loaders.
 675     //
 676     // It's OK to do this for the built-in loaders as we know they can
 677     // tolerate this.
 678     return false;
 679   }
 680   return true;
 681 }
 682 
 683 void MetaspaceShared::link_shared_classes(bool jcmd_request, TRAPS) {
 684   ClassPreloader::initialize();
 685   ClassPrelinker::initialize();
 686 
 687   if (!jcmd_request && !CDSConfig::is_dumping_dynamic_archive()
 688       && !CDSConfig::is_dumping_preimage_static_archive()
 689       && !CDSConfig::is_dumping_final_static_archive()) {
 690     // If we have regenerated invoker classes in the dynamic archive,
 691     // they will conflict with the resolved CONSTANT_Klass references that are stored
 692     // in the static archive. This is not easy to handle. Let's disable
 693     // it for dynamic archive for now.
 694     LambdaFormInvokers::regenerate_holder_classes(CHECK);
 695   }
 696 
 697   // Collect all loaded ClassLoaderData.
 698   CollectCLDClosure collect_cld(THREAD);
 699   {
 700     // ClassLoaderDataGraph::loaded_cld_do requires ClassLoaderDataGraph_lock.
 701     // We cannot link the classes while holding this lock (or else we may run into deadlock).
 702     // Therefore, we need to first collect all the CLDs, and then link their classes after
 703     // releasing the lock.
 704     MutexLocker lock(ClassLoaderDataGraph_lock);
 705     ClassLoaderDataGraph::loaded_cld_do(&collect_cld);
 706   }
 707 
 708   while (true) {
 709     bool has_linked = false;
 710     for (int i = 0; i < collect_cld.nof_cld(); i++) {
 711       ClassLoaderData* cld = collect_cld.cld_at(i);
 712       for (Klass* klass = cld->klasses(); klass != nullptr; klass = klass->next_link()) {
 713         if (klass->is_instance_klass()) {
 714           InstanceKlass* ik = InstanceKlass::cast(klass);
 715           if (may_be_eagerly_linked(ik)) {
 716             has_linked |= try_link_class(THREAD, ik);
 717           }
 718           if (CDSConfig::is_dumping_heap() && ik->is_linked() && !ik->is_initialized()) {
 719             ClassPreinitializer::maybe_preinit_class(ik, CHECK);
 720           }
 721         }
 722       }
 723     }
 724 
 725     if (!has_linked) {
 726       break;
 727     }
 728     // Class linking includes verification which may load more classes.
 729     // Keep scanning until we have linked no more classes.
 730   }
 731 
 732   // Resolve constant pool entries -- we don't load any new classes during this stage
 733   for (int i = 0; i < collect_cld.nof_cld(); i++) {
 734     ClassLoaderData* cld = collect_cld.cld_at(i);
 735     for (Klass* klass = cld->klasses(); klass != nullptr; klass = klass->next_link()) {
 736       if (klass->is_instance_klass()) {
 737         InstanceKlass* ik = InstanceKlass::cast(klass);
 738         ClassPrelinker::dumptime_resolve_constants(ik, CHECK);
 739         if (CDSConfig::is_dumping_preimage_static_archive()) {
 740           FinalImageRecipes::add_reflection_data_flags(ik, CHECK);
 741         }
 742       }
 743     }
 744   }
 745 
 746   if (CDSConfig::is_dumping_preimage_static_archive()) {
 747     // Do this after all classes are verified by the above loop.
 748     // Any classes loaded from here on will be automatically excluded, so
 749     // there's no need to force verification or resolve CP entries. 
 750     RecordTraining = false;
 751     SystemDictionaryShared::ignore_new_classes();
 752     LambdaFormInvokers::regenerate_holder_classes(CHECK);
 753     RecordTraining = true;
 754   }
 755 
 756   if (CDSConfig::is_dumping_final_static_archive()) {
 757     FinalImageRecipes::apply_recipes(CHECK);
 758   }
 759 }
 760 
 761 void MetaspaceShared::prepare_for_dumping() {
 762   assert(CDSConfig::is_dumping_archive(), "sanity");
 763   CDSConfig::check_unsupported_dumping_module_options();
 764   ClassLoader::initialize_shared_path(JavaThread::current());
 765 }
 766 
 767 // Preload classes from a list, populate the shared spaces and dump to a
 768 // file.
 769 void MetaspaceShared::preload_and_dump(TRAPS) {
 770   ResourceMark rm(THREAD);
 771   HandleMark hm(THREAD);
 772 
 773   if (CDSConfig::is_dumping_final_static_archive() && PrintTrainingInfo) {
 774     tty->print_cr("==================== archived_training_data ** before dumping ====================");
 775     TrainingData::print_archived_training_data_on(tty);
 776   }
 777 
 778   StaticArchiveBuilder builder;
 779   preload_and_dump_impl(builder, THREAD);
 780   if (HAS_PENDING_EXCEPTION) {
 781     if (PENDING_EXCEPTION->is_a(vmClasses::OutOfMemoryError_klass())) {
 782       log_error(cds)("Out of memory. Please run with a larger Java heap, current MaxHeapSize = "
 783                      SIZE_FORMAT "M", MaxHeapSize/M);
 784       MetaspaceShared::writing_error();
 785     } else {
 786       log_error(cds)("%s: %s", PENDING_EXCEPTION->klass()->external_name(),
 787                      java_lang_String::as_utf8_string(java_lang_Throwable::message(PENDING_EXCEPTION)));
 788       MetaspaceShared::writing_error("Unexpected exception, use -Xlog:cds,exceptions=trace for detail");
 789     }
 790   }
 791 }
 792 
 793 #if INCLUDE_CDS_JAVA_HEAP && defined(_LP64)
 794 void MetaspaceShared::adjust_heap_sizes_for_dumping() {
 795   if (!CDSConfig::is_dumping_heap() || UseCompressedOops) {
 796     return;
 797   }
 798   // CDS heap dumping requires all string oops to have an offset
 799   // from the heap bottom that can be encoded in 32-bit.
 800   julong max_heap_size = (julong)(4 * G);
 801 
 802   if (MinHeapSize > max_heap_size) {
 803     log_debug(cds)("Setting MinHeapSize to 4G for CDS dumping, original size = " SIZE_FORMAT "M", MinHeapSize/M);
 804     FLAG_SET_ERGO(MinHeapSize, max_heap_size);
 805   }
 806   if (InitialHeapSize > max_heap_size) {
 807     log_debug(cds)("Setting InitialHeapSize to 4G for CDS dumping, original size = " SIZE_FORMAT "M", InitialHeapSize/M);
 808     FLAG_SET_ERGO(InitialHeapSize, max_heap_size);
 809   }
 810   if (MaxHeapSize > max_heap_size) {
 811     log_debug(cds)("Setting MaxHeapSize to 4G for CDS dumping, original size = " SIZE_FORMAT "M", MaxHeapSize/M);
 812     FLAG_SET_ERGO(MaxHeapSize, max_heap_size);
 813   }
 814 }
 815 #endif // INCLUDE_CDS_JAVA_HEAP && _LP64
 816 
 817 void MetaspaceShared::get_default_classlist(char* default_classlist, const size_t buf_size) {
 818   // Construct the path to the class list (in jre/lib)
 819   // Walk up two directories from the location of the VM and
 820   // optionally tack on "lib" (depending on platform)
 821   os::jvm_path(default_classlist, (jint)(buf_size));
 822   for (int i = 0; i < 3; i++) {
 823     char *end = strrchr(default_classlist, *os::file_separator());
 824     if (end != nullptr) *end = '\0';
 825   }
 826   size_t classlist_path_len = strlen(default_classlist);
 827   if (classlist_path_len >= 3) {
 828     if (strcmp(default_classlist + classlist_path_len - 3, "lib") != 0) {
 829       if (classlist_path_len < buf_size - 4) {
 830         jio_snprintf(default_classlist + classlist_path_len,
 831                      buf_size - classlist_path_len,
 832                      "%slib", os::file_separator());
 833         classlist_path_len += 4;
 834       }
 835     }
 836   }
 837   if (classlist_path_len < buf_size - 10) {
 838     jio_snprintf(default_classlist + classlist_path_len,
 839                  buf_size - classlist_path_len,
 840                  "%sclasslist", os::file_separator());
 841   }
 842 }
 843 
 844 void MetaspaceShared::preload_classes(TRAPS) {
 845   char default_classlist[JVM_MAXPATHLEN];
 846   const char* classlist_path;
 847 
 848   get_default_classlist(default_classlist, sizeof(default_classlist));
 849   if (SharedClassListFile == nullptr) {
 850     classlist_path = default_classlist;
 851   } else {
 852     classlist_path = SharedClassListFile;
 853   }
 854 
 855   log_info(cds)("Loading classes to share ...");
 856   ClassListParser::parse_classlist(classlist_path,
 857                                    ClassListParser::_parse_all, CHECK);
 858   if (ExtraSharedClassListFile) {
 859     ClassListParser::parse_classlist(ExtraSharedClassListFile,
 860                                      ClassListParser::_parse_all, CHECK);
 861   }
 862   if (classlist_path != default_classlist) {
 863     struct stat statbuf;
 864     if (os::stat(default_classlist, &statbuf) == 0) {
 865       // File exists, let's use it.
 866       ClassListParser::parse_classlist(default_classlist,
 867                                        ClassListParser::_parse_lambda_forms_invokers_only, CHECK);
 868     }
 869   }
 870 
 871   // Exercise the manifest processing code to ensure classes used by CDS at runtime
 872   // are always archived
 873   const char* dummy = "Manifest-Version: 1.0\n";
 874   CDSProtectionDomain::create_jar_manifest(dummy, strlen(dummy), CHECK);
 875 
 876   log_info(cds)("Loading classes to share: done.");
 877 }
 878 
 879 void MetaspaceShared::preload_and_dump_impl(StaticArchiveBuilder& builder, TRAPS) {
 880   if (CDSConfig::is_dumping_classic_static_archive()) {
 881     // We are running with -Xshare:dump
 882     preload_classes(CHECK);
 883 
 884     if (SharedArchiveConfigFile) {
 885       log_info(cds)("Reading extra data from %s ...", SharedArchiveConfigFile);
 886       read_extra_data(THREAD, SharedArchiveConfigFile);
 887       log_info(cds)("Reading extra data: done.");
 888     }
 889   }
 890 
 891   if (CDSConfig::is_dumping_preimage_static_archive()) {
 892     log_info(cds)("Reading lambda form invokers of in JDK default classlist ...");
 893     char default_classlist[JVM_MAXPATHLEN];
 894     get_default_classlist(default_classlist, sizeof(default_classlist));
 895     struct stat statbuf;
 896     if (os::stat(default_classlist, &statbuf) == 0) {
 897       ClassListParser::parse_classlist(default_classlist,
 898                                        ClassListParser::_parse_lambda_forms_invokers_only, CHECK);
 899     }
 900   }
 901 
 902 #if INCLUDE_CDS_JAVA_HEAP
 903   if (CDSConfig::is_dumping_invokedynamic()) {
 904     // We also assume no other Java threads are running
 905     // This makes sure that the MethodType and MethodTypeForm objects are clean.
 906     JavaValue result(T_VOID);
 907     JavaCalls::call_static(&result, vmClasses::MethodType_klass(),
 908                            vmSymbols::dumpSharedArchive(),
 909                            vmSymbols::void_method_signature(),
 910                            CHECK);
 911   }
 912 #endif
 913 
 914   // Rewrite and link classes
 915   log_info(cds)("Rewriting and linking classes ...");
 916   // Link any classes which got missed. This would happen if we have loaded classes that
 917   // were not explicitly specified in the classlist. E.g., if an interface implemented by class K
 918   // fails verification, all other interfaces that were not specified in the classlist but
 919   // are implemented by K are not verified.
 920   link_shared_classes(false/*not from jcmd*/, CHECK);
 921   log_info(cds)("Rewriting and linking classes: done");
 922 
 923   if (CDSConfig::is_dumping_final_static_archive()) {
 924     assert(RecordTraining == false, "must be");
 925     RecordTraining = true;
 926   }
 927 
 928   TrainingData::init_dumptime_table(CHECK); // captures TrainingDataSetLocker
 929 
 930   _method_handle_intrinsics = new (mtClassShared) GrowableArray<Method*>(256, mtClassShared);
 931   SystemDictionary::get_all_method_handle_intrinsics(_method_handle_intrinsics);
 932 
 933 #if INCLUDE_CDS_JAVA_HEAP
 934   if (CDSConfig::is_dumping_heap()) {
 935     if (!HeapShared::is_archived_boot_layer_available(THREAD)) {
 936       log_info(cds)("archivedBootLayer not available, disabling full module graph");
 937       CDSConfig::stop_dumping_full_module_graph();
 938     }
 939     HeapShared::init_for_dumping(CHECK);
 940     ArchiveHeapWriter::init();
 941     if (CDSConfig::is_dumping_full_module_graph()) {
 942       HeapShared::reset_archived_object_states(CHECK);
 943     }
 944 
 945     if (ArchiveLoaderLookupCache) {
 946       SystemDictionaryShared::create_loader_positive_lookup_cache(CHECK);
 947     }
 948 
 949     // Do this at the very end, when no Java code will be executed. Otherwise
 950     // some new strings may be added to the intern table.
 951     StringTable::allocate_shared_strings_array(CHECK);
 952   }
 953 #endif
 954 
 955   VM_PopulateDumpSharedSpace op(builder);
 956   VMThread::execute(&op);
 957   FileMapInfo* mapinfo = op.map_info();
 958   ArchiveHeapInfo* heap_info = op.heap_info();
 959   bool status;
 960   if (CDSConfig::is_dumping_preimage_static_archive()) {
 961     if ((status = write_static_archive(&builder, mapinfo, heap_info))) {
 962       fork_and_dump_final_static_archive();
 963     }
 964   } else if (CDSConfig::is_dumping_final_static_archive()) {
 965     RecordTraining = false;
 966     if (StoreCachedCode && CachedCodeFile != nullptr) { // FIXME: new workflow -- remove the CachedCodeFile flag
 967       if (log_is_enabled(Info, cds, jit)) {
 968         CDSAccess::test_heap_access_api();
 969       }
 970 
 971       // We have just created the final image. Let's run the AOT compiler
 972       if (PrintTrainingInfo) {
 973         tty->print_cr("==================== archived_training_data ** after dumping ====================");
 974         TrainingData::print_archived_training_data_on(tty);
 975       }
 976 
 977       CDSConfig::enable_dumping_cached_code();
 978       {
 979         builder.start_cc_region();
 980         Precompiler::compile_cached_code(&builder, CHECK);
 981         builder.end_cc_region();
 982       }
 983       CDSConfig::disable_dumping_cached_code();
 984 
 985       SCCache::close(); // Write final data and close archive
 986     }
 987     status = write_static_archive(&builder, mapinfo, heap_info);
 988   } else {
 989     status = write_static_archive(&builder, mapinfo, heap_info);
 990   }
 991 
 992   if (!status) {
 993     THROW_MSG(vmSymbols::java_io_IOException(), "Encountered error while dumping");
 994   }
 995 }
 996 
 997 bool MetaspaceShared::write_static_archive(ArchiveBuilder* builder, FileMapInfo* map_info, ArchiveHeapInfo* heap_info) {
 998   // relocate the data so that it can be mapped to MetaspaceShared::requested_base_address()
 999   // without runtime relocation.
1000   builder->relocate_to_requested();
1001 
1002   map_info->open_for_write();
1003   if (!map_info->is_open()) {
1004     return false;
1005   }
1006   builder->write_archive(map_info, heap_info);
1007 
1008   if (AllowArchivingWithJavaAgent) {
1009     log_warning(cds)("This archive was created with AllowArchivingWithJavaAgent. It should be used "
1010             "for testing purposes only and should not be used in a production environment");
1011   }
1012   return true;
1013 }
1014 
1015 static void print_java_launcher(outputStream* st) {
1016   st->print("%s%sbin%sjava", Arguments::get_java_home(), os::file_separator(), os::file_separator());
1017 }
1018 
1019 static void print_vm_arguments(outputStream* st) {
1020   const char* cp = Arguments::get_appclasspath();
1021   if (cp != nullptr && strlen(cp) > 0 && strcmp(cp, ".") != 0) {
1022     st->print(" -cp ");  st->print_raw(cp);
1023   }
1024   for (int i = 0; i < Arguments::num_jvm_flags(); i++) {
1025     st->print(" %s", Arguments::jvm_flags_array()[i]);
1026   }
1027   for (int i = 0; i < Arguments::num_jvm_args(); i++) {
1028     st->print(" %s", Arguments::jvm_args_array()[i]);
1029   }
1030 }
1031 
1032 void MetaspaceShared::fork_and_dump_final_static_archive() {
1033   assert(CDSConfig::is_dumping_preimage_static_archive(), "sanity");
1034 
1035   ResourceMark rm;
1036   stringStream ss;
1037   print_java_launcher(&ss);
1038   print_vm_arguments(&ss);
1039   ss.print(" -XX:CDSPreimage=%s", SharedArchiveFile);
1040 
1041   const char* cmd = ss.freeze();
1042   if (CDSManualFinalImage) {
1043     tty->print_cr("-XX:+CDSManualFinalImage is specified");
1044     tty->print_cr("Please manually execute the following command to create the final CDS image:");
1045     tty->print("    "); tty->print_raw_cr(cmd);
1046 
1047     // The following is useful if the dumping was trigger by a script that builds
1048     // a complex command-line.
1049     tty->print_cr("Note: to recreate the preimage only:");
1050     tty->print_cr("    rm -f %s", CacheDataStore);
1051     tty->print("    ");
1052     print_java_launcher(tty);
1053     print_vm_arguments(tty);
1054     if (Arguments::java_command() != nullptr) {
1055       tty->print(" %s", Arguments::java_command());
1056     }
1057     tty->cr();
1058   } else {
1059     // FIXME: space characters are not properly quoated. E.g.,
1060     //      java -Dfoo='a b c' HelloWorld
1061     log_info(cds)("Launching child process to create final CDS image:");
1062     log_info(cds)("    %s", cmd);
1063     int status = os::fork_and_exec(cmd);
1064     if (status != 0) {
1065       log_error(cds)("Child process finished; status = %d", status);
1066       log_error(cds)("To reproduce the error");
1067       ResourceMark rm;
1068       LogStream ls(Log(cds)::error());
1069       ls.print("    "); ls.print_raw_cr(cmd);
1070 
1071       // The following is useful if the dumping was trigger by a script that builds
1072       // a complex command-line.
1073       ls.print_cr("Note: to recreate the preimage only:");
1074       ls.print_cr("    rm -f %s", CacheDataStore);
1075       ls.print("    ");
1076       print_java_launcher(&ls);
1077       print_vm_arguments(&ls);
1078       ls.print(" -XX:+UnlockDiagnosticVMOptions -XX:+CDSManualFinalImage");
1079       if (Arguments::java_command() != nullptr) {
1080         ls.print(" %s", Arguments::java_command());
1081       }
1082       ls.cr();
1083 
1084       vm_direct_exit(status);
1085     } else {
1086       log_info(cds)("Child process finished; status = %d", status);
1087       status = remove(SharedArchiveFile);
1088       if (status != 0) {
1089         log_error(cds)("Failed to remove CDSPreimage file %s", SharedArchiveFile);
1090       } else {
1091         log_info(cds)("Removed CDSPreimage file %s", SharedArchiveFile);
1092       }
1093     }
1094   }
1095 }
1096 
1097 // Returns true if the class's status has changed.
1098 bool MetaspaceShared::try_link_class(JavaThread* current, InstanceKlass* ik) {
1099   ExceptionMark em(current);
1100   JavaThread* THREAD = current; // For exception macros.
1101   assert(CDSConfig::is_dumping_archive(), "sanity");
1102 
1103   if (ik->is_shared() && !CDSConfig::is_dumping_final_static_archive()) {
1104     assert(CDSConfig::is_dumping_dynamic_archive(), "must be");
1105     return false;
1106   }
1107 
1108   if (ik->is_loaded() && !ik->is_linked() && ik->can_be_verified_at_dumptime() &&
1109       !SystemDictionaryShared::has_class_failed_verification(ik)) {
1110     bool saved = BytecodeVerificationLocal;
1111     if (ik->is_shared_unregistered_class() && ik->class_loader() == nullptr) {
1112       // The verification decision is based on BytecodeVerificationRemote
1113       // for non-system classes. Since we are using the null classloader
1114       // to load non-system classes for customized class loaders during dumping,
1115       // we need to temporarily change BytecodeVerificationLocal to be the same as
1116       // BytecodeVerificationRemote. Note this can cause the parent system
1117       // classes also being verified. The extra overhead is acceptable during
1118       // dumping.
1119       BytecodeVerificationLocal = BytecodeVerificationRemote;
1120     }
1121     ik->link_class(THREAD);
1122     if (HAS_PENDING_EXCEPTION) {
1123       ResourceMark rm(THREAD);
1124       log_warning(cds)("Preload Warning: Verification failed for %s",
1125                     ik->external_name());
1126       CLEAR_PENDING_EXCEPTION;
1127       SystemDictionaryShared::set_class_has_failed_verification(ik);
1128     }
1129     ik->compute_has_loops_flag_for_methods();
1130     BytecodeVerificationLocal = saved;
1131     return true;
1132   } else {
1133     return false;
1134   }
1135 }
1136 
1137 #if INCLUDE_CDS_JAVA_HEAP
1138 void VM_PopulateDumpSharedSpace::dump_java_heap_objects(GrowableArray<Klass*>* klasses) {
1139   if(!HeapShared::can_write()) {
1140     if (!CDSConfig::is_dumping_preimage_static_archive()) {
1141      log_info(cds)(
1142       "Archived java heap is not supported as UseG1GC "
1143       "and UseCompressedClassPointers are required."
1144       "Current settings: UseG1GC=%s, UseCompressedClassPointers=%s.",
1145       BOOL_TO_STR(UseG1GC), BOOL_TO_STR(UseCompressedClassPointers));
1146     }
1147     return;
1148   }
1149   // Find all the interned strings that should be dumped.
1150   int i;
1151   for (i = 0; i < klasses->length(); i++) {
1152     Klass* k = klasses->at(i);
1153     if (k->is_instance_klass()) {
1154       InstanceKlass* ik = InstanceKlass::cast(k);
1155       if (ik->is_linked()) {
1156         ik->constants()->add_dumped_interned_strings();
1157       }
1158     }
1159   }
1160   if (_extra_interned_strings != nullptr) {
1161     for (i = 0; i < _extra_interned_strings->length(); i ++) {
1162       OopHandle string = _extra_interned_strings->at(i);
1163       HeapShared::add_to_dumped_interned_strings(string.resolve());
1164     }
1165   }
1166 
1167   HeapShared::archive_objects(&_heap_info);
1168   ArchiveBuilder::OtherROAllocMark mark;
1169   HeapShared::write_subgraph_info_table();
1170 }
1171 #endif // INCLUDE_CDS_JAVA_HEAP
1172 
1173 void MetaspaceShared::set_shared_metaspace_range(void* base, void *static_top, void* top) {
1174   assert(base <= static_top && static_top <= top, "must be");
1175   _shared_metaspace_static_top = static_top;
1176   MetaspaceObj::set_shared_metaspace_range(base, top);
1177 }
1178 
1179 bool MetaspaceShared::is_shared_dynamic(void* p) {
1180   if ((p < MetaspaceObj::shared_metaspace_top()) &&
1181       (p >= _shared_metaspace_static_top)) {
1182     return true;
1183   } else {
1184     return false;
1185   }
1186 }
1187 
1188 bool MetaspaceShared::is_shared_static(void* p) {
1189   if (is_in_shared_metaspace(p) && !is_shared_dynamic(p)) {
1190     return true;
1191   } else {
1192     return false;
1193   }
1194 }
1195 
1196 // This function is called when the JVM is unable to load the specified archive(s) due to one
1197 // of the following conditions.
1198 // - There's an error that indicates that the archive(s) files were corrupt or otherwise damaged.
1199 // - When -XX:+RequireSharedSpaces is specified, AND the JVM cannot load the archive(s) due
1200 //   to version or classpath mismatch.
1201 void MetaspaceShared::unrecoverable_loading_error(const char* message) {
1202   log_error(cds)("An error has occurred while processing the shared archive file.");
1203   if (message != nullptr) {
1204     log_error(cds)("%s", message);
1205   }
1206   vm_exit_during_initialization("Unable to use shared archive.", nullptr);
1207 }
1208 
1209 // This function is called when the JVM is unable to write the specified CDS archive due to an
1210 // unrecoverable error.
1211 void MetaspaceShared::unrecoverable_writing_error(const char* message) {
1212   writing_error(message);
1213   vm_direct_exit(1);
1214 }
1215 
1216 // This function is called when the JVM is unable to write the specified CDS archive due to a
1217 // an error. The error will be propagated
1218 void MetaspaceShared::writing_error(const char* message) {
1219   log_error(cds)("An error has occurred while writing the shared archive file.");
1220   if (message != nullptr) {
1221     log_error(cds)("%s", message);
1222   }
1223 }
1224 
1225 void MetaspaceShared::initialize_runtime_shared_and_meta_spaces() {
1226   assert(CDSConfig::is_using_archive(), "Must be called when UseSharedSpaces is enabled");
1227   MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE;
1228 
1229   FileMapInfo* static_mapinfo = FileMapInfo::current_info();
1230   FileMapInfo* dynamic_mapinfo = nullptr;
1231 
1232   if (static_mapinfo != nullptr) {
1233     log_info(cds)("Core region alignment: " SIZE_FORMAT, static_mapinfo->core_region_alignment());
1234     dynamic_mapinfo = open_dynamic_archive();
1235 
1236     // First try to map at the requested address
1237     result = map_archives(static_mapinfo, dynamic_mapinfo, true);
1238     if (result == MAP_ARCHIVE_MMAP_FAILURE) {
1239       // Mapping has failed (probably due to ASLR). Let's map at an address chosen
1240       // by the OS.
1241       log_info(cds)("Try to map archive(s) at an alternative address");
1242       result = map_archives(static_mapinfo, dynamic_mapinfo, false);
1243     }
1244   }
1245 
1246   if (result == MAP_ARCHIVE_SUCCESS) {
1247     bool dynamic_mapped = (dynamic_mapinfo != nullptr && dynamic_mapinfo->is_mapped());
1248     char* cds_base = static_mapinfo->mapped_base();
1249     char* cds_end =  dynamic_mapped ? dynamic_mapinfo->mapped_end() : static_mapinfo->mapped_end();
1250     // Register CDS memory region with LSan.
1251     LSAN_REGISTER_ROOT_REGION(cds_base, cds_end - cds_base);
1252     set_shared_metaspace_range(cds_base, static_mapinfo->mapped_end(), cds_end);
1253     _relocation_delta = static_mapinfo->relocation_delta();
1254     _requested_base_address = static_mapinfo->requested_base_address();
1255     if (dynamic_mapped) {
1256       FileMapInfo::set_shared_path_table(dynamic_mapinfo);
1257       // turn AutoCreateSharedArchive off if successfully mapped
1258       AutoCreateSharedArchive = false;
1259     } else {
1260       FileMapInfo::set_shared_path_table(static_mapinfo);
1261     }
1262   } else {
1263     set_shared_metaspace_range(nullptr, nullptr, nullptr);
1264     if (CDSConfig::is_dumping_dynamic_archive()) {
1265       log_warning(cds)("-XX:ArchiveClassesAtExit is unsupported when base CDS archive is not loaded. Run with -Xlog:cds for more info.");
1266     }
1267     UseSharedSpaces = false;
1268     // The base archive cannot be mapped. We cannot dump the dynamic shared archive.
1269     AutoCreateSharedArchive = false;
1270     CDSConfig::disable_dumping_dynamic_archive();
1271     log_info(cds)("Unable to map shared spaces");
1272     if (PrintSharedArchiveAndExit) {
1273       MetaspaceShared::unrecoverable_loading_error("Unable to use shared archive.");
1274     } else if (RequireSharedSpaces) {
1275       MetaspaceShared::unrecoverable_loading_error("Unable to map shared spaces");
1276     } else if (CDSConfig::is_dumping_final_static_archive()) {
1277       assert(CDSPreimage != nullptr, "must be");
1278       log_error(cds)("Unable to map shared spaces for CDSPreimage = %s", CDSPreimage);
1279       MetaspaceShared::unrecoverable_loading_error();
1280     }
1281   }
1282 
1283   // If mapping failed and -XShare:on, the vm should exit
1284   bool has_failed = false;
1285   if (static_mapinfo != nullptr && !static_mapinfo->is_mapped()) {
1286     has_failed = true;
1287     delete static_mapinfo;
1288   }
1289   if (dynamic_mapinfo != nullptr && !dynamic_mapinfo->is_mapped()) {
1290     has_failed = true;
1291     delete dynamic_mapinfo;
1292   }
1293   if (RequireSharedSpaces && has_failed) {
1294     // static archive mapped but dynamic archive failed
1295       MetaspaceShared::unrecoverable_loading_error("Unable to map shared spaces");
1296   }
1297 }
1298 
1299 // This is called very early at VM start up to get the size of the cached_code region, which
1300 // is used in CodeCache::initialize_heaps()
1301 void MetaspaceShared::open_static_archive() {
1302   if (!UseSharedSpaces) {
1303     return;
1304   }
1305   const char* static_archive = CDSConfig::static_archive_path();
1306   assert(static_archive != nullptr, "sanity");
1307   FileMapInfo* mapinfo = new FileMapInfo(static_archive, true);
1308   if (!mapinfo->initialize()) {
1309     delete(mapinfo);
1310   } else {
1311     FileMapRegion* r = mapinfo->region_at(MetaspaceShared::cc);
1312     CDSAccess::set_cached_code_size(r->used());
1313   }
1314 }
1315 
1316 FileMapInfo* MetaspaceShared::open_dynamic_archive() {
1317   if (CDSConfig::is_dumping_dynamic_archive()) {
1318     return nullptr;
1319   }
1320   const char* dynamic_archive = CDSConfig::dynamic_archive_path();
1321   if (dynamic_archive == nullptr) {
1322     return nullptr;
1323   }
1324 
1325   FileMapInfo* mapinfo = new FileMapInfo(dynamic_archive, false);
1326   if (!mapinfo->initialize()) {
1327     delete(mapinfo);
1328     if (RequireSharedSpaces) {
1329       MetaspaceShared::unrecoverable_loading_error("Failed to initialize dynamic archive");
1330     }
1331     return nullptr;
1332   }
1333   return mapinfo;
1334 }
1335 
1336 // use_requested_addr:
1337 //  true  = map at FileMapHeader::_requested_base_address
1338 //  false = map at an alternative address picked by OS.
1339 MapArchiveResult MetaspaceShared::map_archives(FileMapInfo* static_mapinfo, FileMapInfo* dynamic_mapinfo,
1340                                                bool use_requested_addr) {
1341   if (use_requested_addr && static_mapinfo->requested_base_address() == nullptr) {
1342     log_info(cds)("Archive(s) were created with -XX:SharedBaseAddress=0. Always map at os-selected address.");
1343     return MAP_ARCHIVE_MMAP_FAILURE;
1344   }
1345 
1346   PRODUCT_ONLY(if (ArchiveRelocationMode == 1 && use_requested_addr) {
1347       // For product build only -- this is for benchmarking the cost of doing relocation.
1348       // For debug builds, the check is done below, after reserving the space, for better test coverage
1349       // (see comment below).
1350       log_info(cds)("ArchiveRelocationMode == 1: always map archive(s) at an alternative address");
1351       return MAP_ARCHIVE_MMAP_FAILURE;
1352     });
1353 
1354   if (ArchiveRelocationMode == 2 && !use_requested_addr) {
1355     log_info(cds)("ArchiveRelocationMode == 2: never map archive(s) at an alternative address");
1356     return MAP_ARCHIVE_MMAP_FAILURE;
1357   };
1358 
1359   if (dynamic_mapinfo != nullptr) {
1360     // Ensure that the OS won't be able to allocate new memory spaces between the two
1361     // archives, or else it would mess up the simple comparison in MetaspaceObj::is_shared().
1362     assert(static_mapinfo->mapping_end_offset() == dynamic_mapinfo->mapping_base_offset(), "no gap");
1363   }
1364 
1365   ReservedSpace total_space_rs, archive_space_rs, class_space_rs;
1366   MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE;
1367   char* mapped_base_address = reserve_address_space_for_archives(static_mapinfo,
1368                                                                  dynamic_mapinfo,
1369                                                                  use_requested_addr,
1370                                                                  total_space_rs,
1371                                                                  archive_space_rs,
1372                                                                  class_space_rs);
1373   if (mapped_base_address == nullptr) {
1374     result = MAP_ARCHIVE_MMAP_FAILURE;
1375     log_debug(cds)("Failed to reserve spaces (use_requested_addr=%u)", (unsigned)use_requested_addr);
1376   } else {
1377 
1378 #ifdef ASSERT
1379     // Some sanity checks after reserving address spaces for archives
1380     //  and class space.
1381     assert(archive_space_rs.is_reserved(), "Sanity");
1382     if (Metaspace::using_class_space()) {
1383       // Class space must closely follow the archive space. Both spaces
1384       //  must be aligned correctly.
1385       assert(class_space_rs.is_reserved(),
1386              "A class space should have been reserved");
1387       assert(class_space_rs.base() >= archive_space_rs.end(),
1388              "class space should follow the cds archive space");
1389       assert(is_aligned(archive_space_rs.base(),
1390                         core_region_alignment()),
1391              "Archive space misaligned");
1392       assert(is_aligned(class_space_rs.base(),
1393                         Metaspace::reserve_alignment()),
1394              "class space misaligned");
1395     }
1396 #endif // ASSERT
1397 
1398     log_info(cds)("Reserved archive_space_rs [" INTPTR_FORMAT " - " INTPTR_FORMAT "] (" SIZE_FORMAT ") bytes",
1399                    p2i(archive_space_rs.base()), p2i(archive_space_rs.end()), archive_space_rs.size());
1400     log_info(cds)("Reserved class_space_rs   [" INTPTR_FORMAT " - " INTPTR_FORMAT "] (" SIZE_FORMAT ") bytes",
1401                    p2i(class_space_rs.base()), p2i(class_space_rs.end()), class_space_rs.size());
1402 
1403     if (MetaspaceShared::use_windows_memory_mapping()) {
1404       // We have now reserved address space for the archives, and will map in
1405       //  the archive files into this space.
1406       //
1407       // Special handling for Windows: on Windows we cannot map a file view
1408       //  into an existing memory mapping. So, we unmap the address range we
1409       //  just reserved again, which will make it available for mapping the
1410       //  archives.
1411       // Reserving this range has not been for naught however since it makes
1412       //  us reasonably sure the address range is available.
1413       //
1414       // But still it may fail, since between unmapping the range and mapping
1415       //  in the archive someone else may grab the address space. Therefore
1416       //  there is a fallback in FileMap::map_region() where we just read in
1417       //  the archive files sequentially instead of mapping it in. We couple
1418       //  this with use_requested_addr, since we're going to patch all the
1419       //  pointers anyway so there's no benefit to mmap.
1420       if (use_requested_addr) {
1421         assert(!total_space_rs.is_reserved(), "Should not be reserved for Windows");
1422         log_info(cds)("Windows mmap workaround: releasing archive space.");
1423         archive_space_rs.release();
1424       }
1425     }
1426     MapArchiveResult static_result = map_archive(static_mapinfo, mapped_base_address, archive_space_rs);
1427     MapArchiveResult dynamic_result = (static_result == MAP_ARCHIVE_SUCCESS) ?
1428                                      map_archive(dynamic_mapinfo, mapped_base_address, archive_space_rs) : MAP_ARCHIVE_OTHER_FAILURE;
1429 
1430     DEBUG_ONLY(if (ArchiveRelocationMode == 1 && use_requested_addr) {
1431       // This is for simulating mmap failures at the requested address. In
1432       //  debug builds, we do it here (after all archives have possibly been
1433       //  mapped), so we can thoroughly test the code for failure handling
1434       //  (releasing all allocated resource, etc).
1435       log_info(cds)("ArchiveRelocationMode == 1: always map archive(s) at an alternative address");
1436       if (static_result == MAP_ARCHIVE_SUCCESS) {
1437         static_result = MAP_ARCHIVE_MMAP_FAILURE;
1438       }
1439       if (dynamic_result == MAP_ARCHIVE_SUCCESS) {
1440         dynamic_result = MAP_ARCHIVE_MMAP_FAILURE;
1441       }
1442     });
1443 
1444     if (static_result == MAP_ARCHIVE_SUCCESS) {
1445       if (dynamic_result == MAP_ARCHIVE_SUCCESS) {
1446         result = MAP_ARCHIVE_SUCCESS;
1447       } else if (dynamic_result == MAP_ARCHIVE_OTHER_FAILURE) {
1448         assert(dynamic_mapinfo != nullptr && !dynamic_mapinfo->is_mapped(), "must have failed");
1449         // No need to retry mapping the dynamic archive again, as it will never succeed
1450         // (bad file, etc) -- just keep the base archive.
1451         log_warning(cds, dynamic)("Unable to use shared archive. The top archive failed to load: %s",
1452                                   dynamic_mapinfo->full_path());
1453         result = MAP_ARCHIVE_SUCCESS;
1454         // TODO, we can give the unused space for the dynamic archive to class_space_rs, but there's no
1455         // easy API to do that right now.
1456       } else {
1457         result = MAP_ARCHIVE_MMAP_FAILURE;
1458       }
1459     } else if (static_result == MAP_ARCHIVE_OTHER_FAILURE) {
1460       result = MAP_ARCHIVE_OTHER_FAILURE;
1461     } else {
1462       result = MAP_ARCHIVE_MMAP_FAILURE;
1463     }
1464   }
1465 
1466   if (result == MAP_ARCHIVE_SUCCESS) {
1467     SharedBaseAddress = (size_t)mapped_base_address;
1468 #ifdef _LP64
1469         if (Metaspace::using_class_space()) {
1470           // Set up ccs in metaspace.
1471           Metaspace::initialize_class_space(class_space_rs);
1472 
1473           // Set up compressed Klass pointer encoding: the encoding range must
1474           //  cover both archive and class space.
1475           address cds_base = (address)static_mapinfo->mapped_base();
1476           address ccs_end = (address)class_space_rs.end();
1477           assert(ccs_end > cds_base, "Sanity check");
1478 #if INCLUDE_CDS_JAVA_HEAP
1479           // We archived objects with pre-computed narrow Klass id. Set up encoding such that these Ids stay valid.
1480           address precomputed_narrow_klass_base = cds_base;
1481           const int precomputed_narrow_klass_shift = ArchiveHeapWriter::precomputed_narrow_klass_shift;
1482           CompressedKlassPointers::initialize_for_given_encoding(
1483             cds_base, ccs_end - cds_base, // Klass range
1484             precomputed_narrow_klass_base, precomputed_narrow_klass_shift // precomputed encoding, see ArchiveHeapWriter
1485             );
1486 #else
1487           CompressedKlassPointers::initialize (
1488             cds_base, ccs_end - cds_base // Klass range
1489             );
1490 #endif // INCLUDE_CDS_JAVA_HEAP
1491           // map_or_load_heap_region() compares the current narrow oop and klass encodings
1492           // with the archived ones, so it must be done after all encodings are determined.
1493           static_mapinfo->map_or_load_heap_region();
1494         }
1495 #endif // _LP64
1496     log_info(cds)("initial optimized module handling: %s", CDSConfig::is_using_optimized_module_handling() ? "enabled" : "disabled");
1497     log_info(cds)("initial full module graph: %s", CDSConfig::is_using_full_module_graph() ? "enabled" : "disabled");
1498   } else {
1499     unmap_archive(static_mapinfo);
1500     unmap_archive(dynamic_mapinfo);
1501     release_reserved_spaces(total_space_rs, archive_space_rs, class_space_rs);
1502   }
1503 
1504   return result;
1505 }
1506 
1507 
1508 // This will reserve two address spaces suitable to house Klass structures, one
1509 //  for the cds archives (static archive and optionally dynamic archive) and
1510 //  optionally one move for ccs.
1511 //
1512 // Since both spaces must fall within the compressed class pointer encoding
1513 //  range, they are allocated close to each other.
1514 //
1515 // Space for archives will be reserved first, followed by a potential gap,
1516 //  followed by the space for ccs:
1517 //
1518 // +-- Base address             A        B                     End
1519 // |                            |        |                      |
1520 // v                            v        v                      v
1521 // +-------------+--------------+        +----------------------+
1522 // | static arc  | [dyn. arch]  | [gap]  | compr. class space   |
1523 // +-------------+--------------+        +----------------------+
1524 //
1525 // (The gap may result from different alignment requirements between metaspace
1526 //  and CDS)
1527 //
1528 // If UseCompressedClassPointers is disabled, only one address space will be
1529 //  reserved:
1530 //
1531 // +-- Base address             End
1532 // |                            |
1533 // v                            v
1534 // +-------------+--------------+
1535 // | static arc  | [dyn. arch]  |
1536 // +-------------+--------------+
1537 //
1538 // Base address: If use_archive_base_addr address is true, the Base address is
1539 //  determined by the address stored in the static archive. If
1540 //  use_archive_base_addr address is false, this base address is determined
1541 //  by the platform.
1542 //
1543 // If UseCompressedClassPointers=1, the range encompassing both spaces will be
1544 //  suitable to en/decode narrow Klass pointers: the base will be valid for
1545 //  encoding, the range [Base, End) not surpass KlassEncodingMetaspaceMax.
1546 //
1547 // Return:
1548 //
1549 // - On success:
1550 //    - total_space_rs will be reserved as whole for archive_space_rs and
1551 //      class_space_rs if UseCompressedClassPointers is true.
1552 //      On Windows, try reserve archive_space_rs and class_space_rs
1553 //      separately first if use_archive_base_addr is true.
1554 //    - archive_space_rs will be reserved and large enough to host static and
1555 //      if needed dynamic archive: [Base, A).
1556 //      archive_space_rs.base and size will be aligned to CDS reserve
1557 //      granularity.
1558 //    - class_space_rs: If UseCompressedClassPointers=1, class_space_rs will
1559 //      be reserved. Its start address will be aligned to metaspace reserve
1560 //      alignment, which may differ from CDS alignment. It will follow the cds
1561 //      archive space, close enough such that narrow class pointer encoding
1562 //      covers both spaces.
1563 //      If UseCompressedClassPointers=0, class_space_rs remains unreserved.
1564 // - On error: null is returned and the spaces remain unreserved.
1565 char* MetaspaceShared::reserve_address_space_for_archives(FileMapInfo* static_mapinfo,
1566                                                           FileMapInfo* dynamic_mapinfo,
1567                                                           bool use_archive_base_addr,
1568                                                           ReservedSpace& total_space_rs,
1569                                                           ReservedSpace& archive_space_rs,
1570                                                           ReservedSpace& class_space_rs) {
1571 
1572   address const base_address = (address) (use_archive_base_addr ? static_mapinfo->requested_base_address() : nullptr);
1573   const size_t archive_space_alignment = core_region_alignment();
1574 
1575   // Size and requested location of the archive_space_rs (for both static and dynamic archives)
1576   assert(static_mapinfo->mapping_base_offset() == 0, "Must be");
1577   size_t archive_end_offset  = (dynamic_mapinfo == nullptr) ? static_mapinfo->mapping_end_offset() : dynamic_mapinfo->mapping_end_offset();
1578   size_t archive_space_size = align_up(archive_end_offset, archive_space_alignment);
1579 
1580   if (!Metaspace::using_class_space()) {
1581     // Get the simple case out of the way first:
1582     // no compressed class space, simple allocation.
1583 
1584     // When running without class space, requested archive base should be aligned to cds core alignment.
1585     assert(is_aligned(base_address, archive_space_alignment),
1586              "Archive base address unaligned: " PTR_FORMAT ", needs alignment: %zu.",
1587              p2i(base_address), archive_space_alignment);
1588 
1589     archive_space_rs = ReservedSpace(archive_space_size, archive_space_alignment,
1590                                      os::vm_page_size(), (char*)base_address);
1591     if (archive_space_rs.is_reserved()) {
1592       assert(base_address == nullptr ||
1593              (address)archive_space_rs.base() == base_address, "Sanity");
1594       // Register archive space with NMT.
1595       MemTracker::record_virtual_memory_type(archive_space_rs.base(), mtClassShared);
1596       return archive_space_rs.base();
1597     }
1598     return nullptr;
1599   }
1600 
1601 #ifdef _LP64
1602 
1603   // Complex case: two spaces adjacent to each other, both to be addressable
1604   //  with narrow class pointers.
1605   // We reserve the whole range spanning both spaces, then split that range up.
1606 
1607   const size_t class_space_alignment = Metaspace::reserve_alignment();
1608 
1609   // When running with class space, requested archive base must satisfy both cds core alignment
1610   // and class space alignment.
1611   const size_t base_address_alignment = MAX2(class_space_alignment, archive_space_alignment);
1612   assert(is_aligned(base_address, base_address_alignment),
1613            "Archive base address unaligned: " PTR_FORMAT ", needs alignment: %zu.",
1614            p2i(base_address), base_address_alignment);
1615 
1616   size_t class_space_size = CompressedClassSpaceSize;
1617   assert(CompressedClassSpaceSize > 0 &&
1618          is_aligned(CompressedClassSpaceSize, class_space_alignment),
1619          "CompressedClassSpaceSize malformed: "
1620          SIZE_FORMAT, CompressedClassSpaceSize);
1621 
1622   const size_t ccs_begin_offset = align_up(archive_space_size, class_space_alignment);
1623   const size_t gap_size = ccs_begin_offset - archive_space_size;
1624 
1625   // Reduce class space size if it would not fit into the Klass encoding range
1626   constexpr size_t max_encoding_range_size = 4 * G;
1627   guarantee(archive_space_size < max_encoding_range_size - class_space_alignment, "Archive too large");
1628   if ((archive_space_size + gap_size + class_space_size) > max_encoding_range_size) {
1629     class_space_size = align_down(max_encoding_range_size - archive_space_size - gap_size, class_space_alignment);
1630     log_info(metaspace)("CDS initialization: reducing class space size from " SIZE_FORMAT " to " SIZE_FORMAT,
1631         CompressedClassSpaceSize, class_space_size);
1632     FLAG_SET_ERGO(CompressedClassSpaceSize, class_space_size);
1633   }
1634 
1635   const size_t total_range_size =
1636       archive_space_size + gap_size + class_space_size;
1637 
1638   assert(total_range_size > ccs_begin_offset, "must be");
1639   if (use_windows_memory_mapping() && use_archive_base_addr) {
1640     if (base_address != nullptr) {
1641       // On Windows, we cannot safely split a reserved memory space into two (see JDK-8255917).
1642       // Hence, we optimistically reserve archive space and class space side-by-side. We only
1643       // do this for use_archive_base_addr=true since for use_archive_base_addr=false case
1644       // caller will not split the combined space for mapping, instead read the archive data
1645       // via sequential file IO.
1646       address ccs_base = base_address + archive_space_size + gap_size;
1647       archive_space_rs = ReservedSpace(archive_space_size, archive_space_alignment,
1648                                        os::vm_page_size(), (char*)base_address);
1649       class_space_rs   = ReservedSpace(class_space_size, class_space_alignment,
1650                                        os::vm_page_size(), (char*)ccs_base);
1651     }
1652     if (!archive_space_rs.is_reserved() || !class_space_rs.is_reserved()) {
1653       release_reserved_spaces(total_space_rs, archive_space_rs, class_space_rs);
1654       return nullptr;
1655     }
1656     // NMT: fix up the space tags
1657     MemTracker::record_virtual_memory_type(archive_space_rs.base(), mtClassShared);
1658     MemTracker::record_virtual_memory_type(class_space_rs.base(), mtClass);
1659   } else {
1660     if (use_archive_base_addr && base_address != nullptr) {
1661       total_space_rs = ReservedSpace(total_range_size, base_address_alignment,
1662                                      os::vm_page_size(), (char*) base_address);
1663     } else {
1664       // We did not manage to reserve at the preferred address, or were instructed to relocate. In that
1665       // case we reserve wherever possible, but the start address needs to be encodable as narrow Klass
1666       // encoding base since the archived heap objects contain nKlass IDs pre-calculated toward the start
1667       // of the shared Metaspace. That prevents us from using zero-based encoding and therefore we won't
1668       // try allocating in low-address regions.
1669       total_space_rs = Metaspace::reserve_address_space_for_compressed_classes(total_range_size, false /* optimize_for_zero_base */);
1670     }
1671 
1672     if (!total_space_rs.is_reserved()) {
1673       return nullptr;
1674     }
1675 
1676     // Paranoid checks:
1677     assert(base_address == nullptr || (address)total_space_rs.base() == base_address,
1678            "Sanity (" PTR_FORMAT " vs " PTR_FORMAT ")", p2i(base_address), p2i(total_space_rs.base()));
1679     assert(is_aligned(total_space_rs.base(), base_address_alignment), "Sanity");
1680     assert(total_space_rs.size() == total_range_size, "Sanity");
1681 
1682     // Now split up the space into ccs and cds archive. For simplicity, just leave
1683     //  the gap reserved at the end of the archive space. Do not do real splitting.
1684     archive_space_rs = total_space_rs.first_part(ccs_begin_offset,
1685                                                  (size_t)archive_space_alignment);
1686     class_space_rs = total_space_rs.last_part(ccs_begin_offset);
1687     MemTracker::record_virtual_memory_split_reserved(total_space_rs.base(), total_space_rs.size(),
1688                                                      ccs_begin_offset, mtClassShared, mtClass);
1689   }
1690   assert(is_aligned(archive_space_rs.base(), archive_space_alignment), "Sanity");
1691   assert(is_aligned(archive_space_rs.size(), archive_space_alignment), "Sanity");
1692   assert(is_aligned(class_space_rs.base(), class_space_alignment), "Sanity");
1693   assert(is_aligned(class_space_rs.size(), class_space_alignment), "Sanity");
1694 
1695 
1696   return archive_space_rs.base();
1697 
1698 #else
1699   ShouldNotReachHere();
1700   return nullptr;
1701 #endif
1702 
1703 }
1704 
1705 void MetaspaceShared::release_reserved_spaces(ReservedSpace& total_space_rs,
1706                                               ReservedSpace& archive_space_rs,
1707                                               ReservedSpace& class_space_rs) {
1708   if (total_space_rs.is_reserved()) {
1709     log_debug(cds)("Released shared space (archive + class) " INTPTR_FORMAT, p2i(total_space_rs.base()));
1710     total_space_rs.release();
1711   } else {
1712     if (archive_space_rs.is_reserved()) {
1713       log_debug(cds)("Released shared space (archive) " INTPTR_FORMAT, p2i(archive_space_rs.base()));
1714       archive_space_rs.release();
1715     }
1716     if (class_space_rs.is_reserved()) {
1717       log_debug(cds)("Released shared space (classes) " INTPTR_FORMAT, p2i(class_space_rs.base()));
1718       class_space_rs.release();
1719     }
1720   }
1721 }
1722 
1723 static int archive_regions[]     = { MetaspaceShared::rw, MetaspaceShared::ro };
1724 static int archive_regions_count = 2;
1725 
1726 MapArchiveResult MetaspaceShared::map_archive(FileMapInfo* mapinfo, char* mapped_base_address, ReservedSpace rs) {
1727   assert(CDSConfig::is_using_archive(), "must be runtime");
1728   if (mapinfo == nullptr) {
1729     return MAP_ARCHIVE_SUCCESS; // The dynamic archive has not been specified. No error has happened -- trivially succeeded.
1730   }
1731 
1732   if (!mapinfo->validate_leyden_config()) {
1733     return MAP_ARCHIVE_OTHER_FAILURE;
1734   }
1735 
1736   mapinfo->set_is_mapped(false);
1737   if (mapinfo->core_region_alignment() != (size_t)core_region_alignment()) {
1738     log_info(cds)("Unable to map CDS archive -- core_region_alignment() expected: " SIZE_FORMAT
1739                   " actual: " SIZE_FORMAT, mapinfo->core_region_alignment(), core_region_alignment());
1740     return MAP_ARCHIVE_OTHER_FAILURE;
1741   }
1742 
1743   MapArchiveResult result =
1744     mapinfo->map_regions(archive_regions, archive_regions_count, mapped_base_address, rs);
1745 
1746   if (result != MAP_ARCHIVE_SUCCESS) {
1747     unmap_archive(mapinfo);
1748     return result;
1749   }
1750 
1751   if (!mapinfo->validate_shared_path_table()) {
1752     unmap_archive(mapinfo);
1753     return MAP_ARCHIVE_OTHER_FAILURE;
1754   }
1755 
1756   mapinfo->set_is_mapped(true);
1757   return MAP_ARCHIVE_SUCCESS;
1758 }
1759 
1760 void MetaspaceShared::unmap_archive(FileMapInfo* mapinfo) {
1761   assert(CDSConfig::is_using_archive(), "must be runtime");
1762   if (mapinfo != nullptr) {
1763     mapinfo->unmap_regions(archive_regions, archive_regions_count);
1764     mapinfo->unmap_region(MetaspaceShared::bm);
1765     mapinfo->set_is_mapped(false);
1766   }
1767 }
1768 
1769 // For -XX:PrintSharedArchiveAndExit
1770 class CountSharedSymbols : public SymbolClosure {
1771  private:
1772    int _count;
1773  public:
1774    CountSharedSymbols() : _count(0) {}
1775   void do_symbol(Symbol** sym) {
1776     _count++;
1777   }
1778   int total() { return _count; }
1779 
1780 };
1781 
1782 // Read the miscellaneous data from the shared file, and
1783 // serialize it out to its various destinations.
1784 
1785 void MetaspaceShared::initialize_shared_spaces() {
1786   FileMapInfo *static_mapinfo = FileMapInfo::current_info();
1787 
1788   // Verify various attributes of the archive, plus initialize the
1789   // shared string/symbol tables.
1790   char* buffer = static_mapinfo->serialized_data();
1791   intptr_t* array = (intptr_t*)buffer;
1792   ReadClosure rc(&array);
1793   serialize(&rc);
1794 
1795   // Finish up archived heap initialization. These must be
1796   // done after ReadClosure.
1797   static_mapinfo->patch_heap_embedded_pointers();
1798   ArchiveHeapLoader::finish_initialization();
1799   Universe::load_archived_object_instances();
1800   SCCache::new_workflow_load_cache();
1801 
1802   // Close the mapinfo file
1803   static_mapinfo->close();
1804 
1805   static_mapinfo->unmap_region(MetaspaceShared::bm);
1806 
1807   FileMapInfo *dynamic_mapinfo = FileMapInfo::dynamic_info();
1808   if (dynamic_mapinfo != nullptr) {
1809     intptr_t* buffer = (intptr_t*)dynamic_mapinfo->serialized_data();
1810     ReadClosure rc(&buffer);
1811     ArchiveBuilder::serialize_dynamic_archivable_items(&rc);
1812     DynamicArchive::setup_array_klasses();
1813     dynamic_mapinfo->close();
1814     dynamic_mapinfo->unmap_region(MetaspaceShared::bm);
1815   }
1816 
1817   // Set up LambdaFormInvokers::_lambdaform_lines for dynamic dump
1818   if (CDSConfig::is_dumping_dynamic_archive()) {
1819     // Read stored LF format lines stored in static archive
1820     LambdaFormInvokers::read_static_archive_invokers();
1821   }
1822 
1823   if (PrintSharedArchiveAndExit) {
1824     // Print archive names
1825     if (dynamic_mapinfo != nullptr) {
1826       tty->print_cr("\n\nBase archive name: %s", CDSConfig::static_archive_path());
1827       tty->print_cr("Base archive version %d", static_mapinfo->version());
1828     } else {
1829       tty->print_cr("Static archive name: %s", static_mapinfo->full_path());
1830       tty->print_cr("Static archive version %d", static_mapinfo->version());
1831     }
1832 
1833     SystemDictionaryShared::print_shared_archive(tty);
1834     if (dynamic_mapinfo != nullptr) {
1835       tty->print_cr("\n\nDynamic archive name: %s", dynamic_mapinfo->full_path());
1836       tty->print_cr("Dynamic archive version %d", dynamic_mapinfo->version());
1837       SystemDictionaryShared::print_shared_archive(tty, false/*dynamic*/);
1838     }
1839     TrainingData::print_archived_training_data_on(tty);
1840 
1841     if (LoadCachedCode) {
1842       tty->print_cr("\n\nCached Code file: %s", CachedCodeFile);
1843       SCCache::print_on(tty);
1844     }
1845 
1846     // collect shared symbols and strings
1847     CountSharedSymbols cl;
1848     SymbolTable::shared_symbols_do(&cl);
1849     tty->print_cr("Number of shared symbols: %d", cl.total());
1850     tty->print_cr("Number of shared strings: %zu", StringTable::shared_entry_count());
1851     tty->print_cr("VM version: %s\r\n", static_mapinfo->vm_version());
1852     if (FileMapInfo::current_info() == nullptr || _archive_loading_failed) {
1853       tty->print_cr("archive is invalid");
1854       vm_exit(1);
1855     } else {
1856       tty->print_cr("archive is valid");
1857       vm_exit(0);
1858     }
1859   }
1860 }
1861 
1862 // JVM/TI RedefineClasses() support:
1863 bool MetaspaceShared::remap_shared_readonly_as_readwrite() {
1864   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1865 
1866   if (CDSConfig::is_using_archive()) {
1867     // remap the shared readonly space to shared readwrite, private
1868     FileMapInfo* mapinfo = FileMapInfo::current_info();
1869     if (!mapinfo->remap_shared_readonly_as_readwrite()) {
1870       return false;
1871     }
1872     if (FileMapInfo::dynamic_info() != nullptr) {
1873       mapinfo = FileMapInfo::dynamic_info();
1874       if (!mapinfo->remap_shared_readonly_as_readwrite()) {
1875         return false;
1876       }
1877     }
1878     _remapped_readwrite = true;
1879   }
1880   return true;
1881 }
1882 
1883 void MetaspaceShared::print_on(outputStream* st) {
1884   if (CDSConfig::is_using_archive()) {
1885     st->print("CDS archive(s) mapped at: ");
1886     address base = (address)MetaspaceObj::shared_metaspace_base();
1887     address static_top = (address)_shared_metaspace_static_top;
1888     address top = (address)MetaspaceObj::shared_metaspace_top();
1889     st->print("[" PTR_FORMAT "-" PTR_FORMAT "-" PTR_FORMAT "), ", p2i(base), p2i(static_top), p2i(top));
1890     st->print("size " SIZE_FORMAT ", ", top - base);
1891     st->print("SharedBaseAddress: " PTR_FORMAT ", ArchiveRelocationMode: %d.", SharedBaseAddress, ArchiveRelocationMode);
1892   } else {
1893     st->print("CDS archive(s) not mapped");
1894   }
1895   st->cr();
1896 }