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