1 /*
   2  * Copyright (c) 2012, 2021, 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 "jvm_io.h"
  27 #include "cds/archiveBuilder.hpp"
  28 #include "cds/cdsProtectionDomain.hpp"
  29 #include "cds/classListWriter.hpp"
  30 #include "cds/classListParser.hpp"
  31 #include "cds/cppVtables.hpp"
  32 #include "cds/dumpAllocStats.hpp"
  33 #include "cds/filemap.hpp"
  34 #include "cds/heapShared.hpp"
  35 #include "cds/lambdaFormInvokers.hpp"
  36 #include "cds/metaspaceShared.hpp"
  37 #include "classfile/classLoaderDataGraph.hpp"
  38 #include "classfile/classLoaderDataShared.hpp"
  39 #include "classfile/classLoaderExt.hpp"
  40 #include "classfile/javaClasses.inline.hpp"
  41 #include "classfile/loaderConstraints.hpp"
  42 #include "classfile/placeholders.hpp"
  43 #include "classfile/symbolTable.hpp"
  44 #include "classfile/stringTable.hpp"
  45 #include "classfile/systemDictionary.hpp"
  46 #include "classfile/systemDictionaryShared.hpp"
  47 #include "classfile/vmClasses.hpp"
  48 #include "classfile/vmSymbols.hpp"
  49 #include "code/codeCache.hpp"
  50 #include "gc/shared/gcVMOperations.hpp"
  51 #include "interpreter/bytecodeStream.hpp"
  52 #include "interpreter/bytecodes.hpp"
  53 #include "logging/log.hpp"
  54 #include "logging/logMessage.hpp"
  55 #include "logging/logStream.hpp"
  56 #include "memory/metaspace.hpp"
  57 #include "memory/metaspaceClosure.hpp"
  58 #include "memory/resourceArea.hpp"
  59 #include "memory/universe.hpp"
  60 #include "oops/compressedOops.inline.hpp"
  61 #include "oops/flatArrayKlass.hpp"
  62 #include "oops/inlineKlass.hpp"
  63 #include "oops/instanceMirrorKlass.hpp"
  64 #include "oops/klass.inline.hpp"
  65 #include "oops/objArrayOop.hpp"
  66 #include "oops/oop.inline.hpp"
  67 #include "oops/oopHandle.hpp"
  68 #include "prims/jvmtiExport.hpp"
  69 #include "runtime/arguments.hpp"
  70 #include "runtime/handles.inline.hpp"
  71 #include "runtime/os.hpp"
  72 #include "runtime/safepointVerifiers.hpp"
  73 #include "runtime/sharedRuntime.hpp"
  74 #include "runtime/vmThread.hpp"
  75 #include "runtime/vmOperations.hpp"
  76 #include "services/memTracker.hpp"
  77 #include "utilities/align.hpp"
  78 #include "utilities/bitMap.inline.hpp"
  79 #include "utilities/ostream.hpp"
  80 #include "utilities/defaultStream.hpp"
  81 #include "utilities/resourceHash.hpp"
  82 #if INCLUDE_G1GC
  83 #include "gc/g1/g1CollectedHeap.inline.hpp"
  84 #endif
  85 
  86 ReservedSpace MetaspaceShared::_symbol_rs;
  87 VirtualSpace MetaspaceShared::_symbol_vs;
  88 bool MetaspaceShared::_has_error_classes;
  89 bool MetaspaceShared::_archive_loading_failed = false;
  90 bool MetaspaceShared::_remapped_readwrite = false;
  91 void* MetaspaceShared::_shared_metaspace_static_top = NULL;
  92 intx MetaspaceShared::_relocation_delta;
  93 char* MetaspaceShared::_requested_base_address;
  94 bool MetaspaceShared::_use_optimized_module_handling = true;
  95 bool MetaspaceShared::_use_full_module_graph = true;
  96 
  97 // The CDS archive is divided into the following regions:
  98 //     rw  - read-write metadata
  99 //     ro  - read-only metadata and read-only tables
 100 //
 101 //     ca0 - closed archive heap space #0
 102 //     ca1 - closed archive heap space #1 (may be empty)
 103 //     oa0 - open archive heap space #0
 104 //     oa1 - open archive heap space #1 (may be empty)
 105 //
 106 //     bm  - bitmap for relocating the above 7 regions.
 107 //
 108 // The rw and ro regions are linearly allocated, in the order of rw->ro.
 109 // These regions are aligned with MetaspaceShared::core_region_alignment().
 110 //
 111 // These 2 regions are populated in the following steps:
 112 // [0] All classes are loaded in MetaspaceShared::preload_classes(). All metadata are
 113 //     temporarily allocated outside of the shared regions.
 114 // [1] We enter a safepoint and allocate a buffer for the rw/ro regions.
 115 // [2] C++ vtables are copied into the rw region.
 116 // [3] ArchiveBuilder copies RW metadata into the rw region.
 117 // [4] ArchiveBuilder copies RO metadata into the ro region.
 118 // [5] SymbolTable, StringTable, SystemDictionary, and a few other read-only data
 119 //     are copied into the ro region as read-only tables.
 120 //
 121 // The ca0/ca1 and oa0/oa1 regions are populated inside HeapShared::archive_objects.
 122 // Their layout is independent of the rw/ro regions.
 123 
 124 static DumpRegion _symbol_region("symbols");
 125 
 126 char* MetaspaceShared::symbol_space_alloc(size_t num_bytes) {
 127   return _symbol_region.allocate(num_bytes);
 128 }
 129 
 130 // os::vm_allocation_granularity() is usually 4K for most OSes. However, on Linux/aarch64,
 131 // it can be either 4K or 64K and on Macosx-arm it is 16K. To generate archives that are
 132 // compatible for both settings, an alternative cds core region alignment can be enabled
 133 // at building time:
 134 //   --enable-compactible-cds-alignment
 135 // Upon successful configuration, the compactible alignment then can be defined as in:
 136 //   os_linux_aarch64.hpp
 137 // which is the highest page size configured on the platform.
 138 size_t MetaspaceShared::core_region_alignment() {
 139 #if defined(CDS_CORE_REGION_ALIGNMENT)
 140   return CDS_CORE_REGION_ALIGNMENT;
 141 #else
 142   return (size_t)os::vm_allocation_granularity();
 143 #endif // CDS_CORE_REGION_ALIGNMENT
 144 }
 145 
 146 static bool shared_base_valid(char* shared_base) {
 147 #ifdef _LP64
 148   return CompressedKlassPointers::is_valid_base((address)shared_base);
 149 #else
 150   return true;
 151 #endif
 152 }
 153 
 154 class DumpClassListCLDClosure : public CLDClosure {
 155   static const int INITIAL_TABLE_SIZE = 1987;
 156   static const int MAX_TABLE_SIZE = 61333;
 157 
 158   fileStream *_stream;
 159   ResizeableResourceHashtable<InstanceKlass*, bool,
 160                               ResourceObj::C_HEAP, mtClassShared> _dumped_classes;
 161 
 162   void dump(InstanceKlass* ik) {
 163     bool created;
 164     _dumped_classes.put_if_absent(ik, &created);
 165     if (!created) {
 166       return;
 167     }
 168     if (_dumped_classes.maybe_grow(MAX_TABLE_SIZE)) {
 169       log_info(cds, hashtables)("Expanded _dumped_classes table to %d", _dumped_classes.table_size());
 170     }
 171     if (ik->java_super()) {
 172       dump(ik->java_super());
 173     }
 174     Array<InstanceKlass*>* interfaces = ik->local_interfaces();
 175     int len = interfaces->length();
 176     for (int i = 0; i < len; i++) {
 177       dump(interfaces->at(i));
 178     }
 179     ClassListWriter::write_to_stream(ik, _stream);
 180   }
 181 
 182 public:
 183   DumpClassListCLDClosure(fileStream* f)
 184   : CLDClosure(), _dumped_classes(INITIAL_TABLE_SIZE) {
 185     _stream = f;
 186   }
 187 
 188   void do_cld(ClassLoaderData* cld) {
 189     for (Klass* klass = cld->klasses(); klass != NULL; klass = klass->next_link()) {
 190       if (klass->is_instance_klass()) {
 191         dump(InstanceKlass::cast(klass));
 192       }
 193     }
 194   }
 195 };
 196 
 197 void MetaspaceShared::dump_loaded_classes(const char* file_name, TRAPS) {
 198   fileStream stream(file_name, "w");
 199   if (stream.is_open()) {
 200     MutexLocker lock(ClassLoaderDataGraph_lock);
 201     MutexLocker lock2(ClassListFile_lock, Mutex::_no_safepoint_check_flag);
 202     DumpClassListCLDClosure collect_classes(&stream);
 203     ClassLoaderDataGraph::loaded_cld_do(&collect_classes);
 204   } else {
 205     THROW_MSG(vmSymbols::java_io_IOException(), "Failed to open file");
 206   }
 207 }
 208 
 209 static bool shared_base_too_high(char* specified_base, char* aligned_base, size_t cds_max) {
 210   if (specified_base != NULL && aligned_base < specified_base) {
 211     // SharedBaseAddress is very high (e.g., 0xffffffffffffff00) so
 212     // align_up(SharedBaseAddress, MetaspaceShared::core_region_alignment()) has wrapped around.
 213     return true;
 214   }
 215   if (max_uintx - uintx(aligned_base) < uintx(cds_max)) {
 216     // The end of the archive will wrap around
 217     return true;
 218   }
 219 
 220   return false;
 221 }
 222 
 223 static char* compute_shared_base(size_t cds_max) {
 224   char* specified_base = (char*)SharedBaseAddress;
 225   char* aligned_base = align_up(specified_base, MetaspaceShared::core_region_alignment());
 226 
 227   const char* err = NULL;
 228   if (shared_base_too_high(specified_base, aligned_base, cds_max)) {
 229     err = "too high";
 230   } else if (!shared_base_valid(aligned_base)) {
 231     err = "invalid for this platform";
 232   } else {
 233     return aligned_base;
 234   }
 235 
 236   log_warning(cds)("SharedBaseAddress (" INTPTR_FORMAT ") is %s. Reverted to " INTPTR_FORMAT,
 237                    p2i((void*)SharedBaseAddress), err,
 238                    p2i((void*)Arguments::default_SharedBaseAddress()));
 239 
 240   specified_base = (char*)Arguments::default_SharedBaseAddress();
 241   aligned_base = align_up(specified_base, MetaspaceShared::core_region_alignment());
 242 
 243   // Make sure the default value of SharedBaseAddress specified in globals.hpp is sane.
 244   assert(!shared_base_too_high(specified_base, aligned_base, cds_max), "Sanity");
 245   assert(shared_base_valid(aligned_base), "Sanity");
 246   return aligned_base;
 247 }
 248 
 249 void MetaspaceShared::initialize_for_static_dump() {
 250   assert(DumpSharedSpaces, "should be called for dump time only");
 251   log_info(cds)("Core region alignment: " SIZE_FORMAT, core_region_alignment());
 252   // The max allowed size for CDS archive. We use this to limit SharedBaseAddress
 253   // to avoid address space wrap around.
 254   size_t cds_max;
 255   const size_t reserve_alignment = core_region_alignment();
 256 
 257 #ifdef _LP64
 258   const uint64_t UnscaledClassSpaceMax = (uint64_t(max_juint) + 1);
 259   cds_max = align_down(UnscaledClassSpaceMax, reserve_alignment);
 260 #else
 261   // We don't support archives larger than 256MB on 32-bit due to limited
 262   //  virtual address space.
 263   cds_max = align_down(256*M, reserve_alignment);
 264 #endif
 265 
 266   _requested_base_address = compute_shared_base(cds_max);
 267   SharedBaseAddress = (size_t)_requested_base_address;
 268 
 269   size_t symbol_rs_size = LP64_ONLY(3 * G) NOT_LP64(128 * M);
 270   _symbol_rs = ReservedSpace(symbol_rs_size);
 271   if (!_symbol_rs.is_reserved()) {
 272     vm_exit_during_initialization("Unable to reserve memory for symbols",
 273                                   err_msg(SIZE_FORMAT " bytes.", symbol_rs_size));
 274   }
 275   _symbol_region.init(&_symbol_rs, &_symbol_vs);
 276 }
 277 
 278 // Called by universe_post_init()
 279 void MetaspaceShared::post_initialize(TRAPS) {
 280   if (UseSharedSpaces) {
 281     int size = FileMapInfo::get_number_of_shared_paths();
 282     if (size > 0) {
 283       CDSProtectionDomain::allocate_shared_data_arrays(size, CHECK);
 284       if (!DynamicDumpSharedSpaces) {
 285         FileMapInfo* info;
 286         if (FileMapInfo::dynamic_info() == NULL) {
 287           info = FileMapInfo::current_info();
 288         } else {
 289           info = FileMapInfo::dynamic_info();
 290         }
 291         ClassLoaderExt::init_paths_start_index(info->app_class_paths_start_index());
 292         ClassLoaderExt::init_app_module_paths_start_index(info->app_module_paths_start_index());
 293       }
 294     }
 295   }
 296 }
 297 
 298 static GrowableArrayCHeap<OopHandle, mtClassShared>* _extra_interned_strings = NULL;
 299 static GrowableArrayCHeap<Symbol*, mtClassShared>* _extra_symbols = NULL;
 300 
 301 void MetaspaceShared::read_extra_data(JavaThread* current, const char* filename) {
 302   _extra_interned_strings = new GrowableArrayCHeap<OopHandle, mtClassShared>(10000);
 303   _extra_symbols = new GrowableArrayCHeap<Symbol*, mtClassShared>(1000);
 304 
 305   HashtableTextDump reader(filename);
 306   reader.check_version("VERSION: 1.0");
 307 
 308   while (reader.remain() > 0) {
 309     int utf8_length;
 310     int prefix_type = reader.scan_prefix(&utf8_length);
 311     ResourceMark rm(current);
 312     if (utf8_length == 0x7fffffff) {
 313       // buf_len will overflown 32-bit value.
 314       vm_exit_during_initialization(err_msg("string length too large: %d", utf8_length));
 315     }
 316     int buf_len = utf8_length+1;
 317     char* utf8_buffer = NEW_RESOURCE_ARRAY(char, buf_len);
 318     reader.get_utf8(utf8_buffer, utf8_length);
 319     utf8_buffer[utf8_length] = '\0';
 320 
 321     if (prefix_type == HashtableTextDump::SymbolPrefix) {
 322       _extra_symbols->append(SymbolTable::new_permanent_symbol(utf8_buffer));
 323     } else{
 324       assert(prefix_type == HashtableTextDump::StringPrefix, "Sanity");
 325       ExceptionMark em(current);
 326       JavaThread* THREAD = current; // For exception macros.
 327       oop str = StringTable::intern(utf8_buffer, THREAD);
 328 
 329       if (HAS_PENDING_EXCEPTION) {
 330         log_warning(cds, heap)("[line %d] extra interned string allocation failed; size too large: %d",
 331                                reader.last_line_no(), utf8_length);
 332         CLEAR_PENDING_EXCEPTION;
 333       } else {
 334 #if INCLUDE_G1GC
 335         if (UseG1GC) {
 336           typeArrayOop body = java_lang_String::value(str);
 337           const HeapRegion* hr = G1CollectedHeap::heap()->heap_region_containing(body);
 338           if (hr->is_humongous()) {
 339             // Don't keep it alive, so it will be GC'ed before we dump the strings, in order
 340             // to maximize free heap space and minimize fragmentation.
 341             log_warning(cds, heap)("[line %d] extra interned string ignored; size too large: %d",
 342                                 reader.last_line_no(), utf8_length);
 343             continue;
 344           }
 345         }
 346 #endif
 347         // Make sure this string is included in the dumped interned string table.
 348         assert(str != NULL, "must succeed");
 349         _extra_interned_strings->append(OopHandle(Universe::vm_global(), str));
 350       }
 351     }
 352   }
 353 }
 354 
 355 // Read/write a data stream for restoring/preserving metadata pointers and
 356 // miscellaneous data from/to the shared archive file.
 357 
 358 void MetaspaceShared::serialize(SerializeClosure* soc) {
 359   int tag = 0;
 360   soc->do_tag(--tag);
 361 
 362   // Verify the sizes of various metadata in the system.
 363   soc->do_tag(sizeof(Method));
 364   soc->do_tag(sizeof(ConstMethod));
 365   soc->do_tag(arrayOopDesc::base_offset_in_bytes(T_BYTE));
 366   soc->do_tag(sizeof(ConstantPool));
 367   soc->do_tag(sizeof(ConstantPoolCache));
 368   soc->do_tag(objArrayOopDesc::base_offset_in_bytes());
 369   soc->do_tag(typeArrayOopDesc::base_offset_in_bytes(T_BYTE));
 370   soc->do_tag(sizeof(Symbol));
 371 
 372   // Need to do this first, as subsequent steps may call virtual functions
 373   // in archived Metadata objects.
 374   CppVtables::serialize(soc);
 375   soc->do_tag(--tag);
 376 
 377   // Dump/restore miscellaneous metadata.
 378   JavaClasses::serialize_offsets(soc);
 379   Universe::serialize(soc);
 380   soc->do_tag(--tag);
 381 
 382   // Dump/restore references to commonly used names and signatures.
 383   vmSymbols::serialize(soc);
 384   soc->do_tag(--tag);
 385 
 386   // Dump/restore the symbol/string/subgraph_info tables
 387   SymbolTable::serialize_shared_table_header(soc);
 388   StringTable::serialize_shared_table_header(soc);
 389   HeapShared::serialize_subgraph_info_table_header(soc);
 390   SystemDictionaryShared::serialize_dictionary_headers(soc);
 391 
 392   InstanceMirrorKlass::serialize_offsets(soc);
 393 
 394   // Dump/restore well known classes (pointers)
 395   SystemDictionaryShared::serialize_vm_classes(soc);
 396   soc->do_tag(--tag);
 397 
 398   CDS_JAVA_HEAP_ONLY(ClassLoaderDataShared::serialize(soc);)
 399 
 400   LambdaFormInvokers::serialize(soc);
 401   soc->do_tag(666);
 402 }
 403 
 404 static void rewrite_nofast_bytecode(const methodHandle& method) {
 405   BytecodeStream bcs(method);
 406   while (!bcs.is_last_bytecode()) {
 407     Bytecodes::Code opcode = bcs.next();
 408     switch (opcode) {
 409     case Bytecodes::_getfield:      *bcs.bcp() = Bytecodes::_nofast_getfield;      break;
 410     case Bytecodes::_putfield:      *bcs.bcp() = Bytecodes::_nofast_putfield;      break;
 411     case Bytecodes::_aload_0:       *bcs.bcp() = Bytecodes::_nofast_aload_0;       break;
 412     case Bytecodes::_iload: {
 413       if (!bcs.is_wide()) {
 414         *bcs.bcp() = Bytecodes::_nofast_iload;
 415       }
 416       break;
 417     }
 418     default: break;
 419     }
 420   }
 421 }
 422 
 423 // [1] Rewrite all bytecodes as needed, so that the ConstMethod* will not be modified
 424 //     at run time by RewriteBytecodes/RewriteFrequentPairs
 425 // [2] Assign a fingerprint, so one doesn't need to be assigned at run-time.
 426 void MetaspaceShared::rewrite_nofast_bytecodes_and_calculate_fingerprints(Thread* thread, InstanceKlass* ik) {
 427   for (int i = 0; i < ik->methods()->length(); i++) {
 428     methodHandle m(thread, ik->methods()->at(i));
 429     if (ik->can_be_verified_at_dumptime() && ik->is_linked()) {
 430       rewrite_nofast_bytecode(m);
 431     }
 432     Fingerprinter fp(m);
 433     // The side effect of this call sets method's fingerprint field.
 434     fp.fingerprint();
 435   }
 436 }
 437 
 438 class VM_PopulateDumpSharedSpace : public VM_GC_Operation {
 439 private:
 440   GrowableArray<MemRegion> *_closed_heap_regions;
 441   GrowableArray<MemRegion> *_open_heap_regions;
 442 
 443   GrowableArray<ArchiveHeapOopmapInfo> *_closed_heap_oopmaps;
 444   GrowableArray<ArchiveHeapOopmapInfo> *_open_heap_oopmaps;
 445 
 446   void dump_java_heap_objects(GrowableArray<Klass*>* klasses) NOT_CDS_JAVA_HEAP_RETURN;
 447   void dump_heap_oopmaps() NOT_CDS_JAVA_HEAP_RETURN;
 448   void dump_heap_oopmaps(GrowableArray<MemRegion>* regions,
 449                                  GrowableArray<ArchiveHeapOopmapInfo>* oopmaps);
 450   void dump_shared_symbol_table(GrowableArray<Symbol*>* symbols) {
 451     log_info(cds)("Dumping symbol table ...");
 452     SymbolTable::write_to_archive(symbols);
 453   }
 454   char* dump_read_only_tables();
 455 
 456 public:
 457 
 458   VM_PopulateDumpSharedSpace() :
 459     VM_GC_Operation(0 /* total collections, ignored */, GCCause::_archive_time_gc),
 460     _closed_heap_regions(NULL),
 461     _open_heap_regions(NULL),
 462     _closed_heap_oopmaps(NULL),
 463     _open_heap_oopmaps(NULL) {}
 464 
 465   bool skip_operation() const { return false; }
 466 
 467   VMOp_Type type() const { return VMOp_PopulateDumpSharedSpace; }
 468   void doit();   // outline because gdb sucks
 469   bool allow_nested_vm_operations() const { return true; }
 470 }; // class VM_PopulateDumpSharedSpace
 471 
 472 class StaticArchiveBuilder : public ArchiveBuilder {
 473 public:
 474   StaticArchiveBuilder() : ArchiveBuilder() {}
 475 
 476   virtual void iterate_roots(MetaspaceClosure* it, bool is_relocating_pointers) {
 477     FileMapInfo::metaspace_pointers_do(it, false);
 478     SystemDictionaryShared::dumptime_classes_do(it);
 479     Universe::metaspace_pointers_do(it);
 480     vmSymbols::metaspace_pointers_do(it);
 481 
 482     // The above code should find all the symbols that are referenced by the
 483     // archived classes. We just need to add the extra symbols which
 484     // may not be used by any of the archived classes -- these are usually
 485     // symbols that we anticipate to be used at run time, so we can store
 486     // them in the RO region, to be shared across multiple processes.
 487     if (_extra_symbols != NULL) {
 488       for (int i = 0; i < _extra_symbols->length(); i++) {
 489         it->push(_extra_symbols->adr_at(i));
 490       }
 491     }
 492   }
 493 };
 494 
 495 char* VM_PopulateDumpSharedSpace::dump_read_only_tables() {
 496   ArchiveBuilder::OtherROAllocMark mark;
 497 
 498   SystemDictionaryShared::write_to_archive();
 499 
 500   // Write lambform lines into archive
 501   LambdaFormInvokers::dump_static_archive_invokers();
 502   // Write the other data to the output array.
 503   DumpRegion* ro_region = ArchiveBuilder::current()->ro_region();
 504   char* start = ro_region->top();
 505   WriteClosure wc(ro_region);
 506   MetaspaceShared::serialize(&wc);
 507 
 508   // Write the bitmaps for patching the archive heap regions
 509   dump_heap_oopmaps();
 510 
 511   return start;
 512 }
 513 
 514 void VM_PopulateDumpSharedSpace::doit() {
 515   HeapShared::run_full_gc_in_vm_thread();
 516 
 517   DEBUG_ONLY(SystemDictionaryShared::NoClassLoadingMark nclm);
 518 
 519   FileMapInfo::check_nonempty_dir_in_shared_path_table();
 520 
 521   NOT_PRODUCT(SystemDictionary::verify();)
 522 
 523   // Block concurrent class unloading from changing the _dumptime_table
 524   MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
 525   SystemDictionaryShared::check_excluded_classes();
 526 
 527   StaticArchiveBuilder builder;
 528   builder.gather_source_objs();
 529   builder.reserve_buffer();
 530 
 531   char* cloned_vtables = CppVtables::dumptime_init(&builder);
 532 
 533   builder.dump_rw_metadata();
 534   builder.dump_ro_metadata();
 535   builder.relocate_metaspaceobj_embedded_pointers();
 536 
 537   // Dump supported java heap objects
 538   dump_java_heap_objects(builder.klasses());
 539 
 540   builder.relocate_roots();
 541   dump_shared_symbol_table(builder.symbols());
 542 
 543   builder.relocate_vm_classes();
 544 
 545   log_info(cds)("Make classes shareable");
 546   builder.make_klasses_shareable();
 547 
 548   char* serialized_data = dump_read_only_tables();
 549 
 550   SystemDictionaryShared::adjust_lambda_proxy_class_dictionary();
 551 
 552   // The vtable clones contain addresses of the current process.
 553   // We don't want to write these addresses into the archive.
 554   CppVtables::zero_archived_vtables();
 555 
 556   // relocate the data so that it can be mapped to MetaspaceShared::requested_base_address()
 557   // without runtime relocation.
 558   builder.relocate_to_requested();
 559 
 560   // Write the archive file
 561   FileMapInfo* mapinfo = new FileMapInfo(true);
 562   mapinfo->populate_header(MetaspaceShared::core_region_alignment());
 563   mapinfo->set_serialized_data(serialized_data);
 564   mapinfo->set_cloned_vtables(cloned_vtables);
 565   mapinfo->open_for_write();
 566   builder.write_archive(mapinfo,
 567                         _closed_heap_regions,
 568                         _open_heap_regions,
 569                         _closed_heap_oopmaps,
 570                         _open_heap_oopmaps);
 571 
 572   if (PrintSystemDictionaryAtExit) {
 573     SystemDictionary::print();
 574   }
 575 
 576   if (AllowArchivingWithJavaAgent) {
 577     warning("This archive was created with AllowArchivingWithJavaAgent. It should be used "
 578             "for testing purposes only and should not be used in a production environment");
 579   }
 580 
 581   // There may be pending VM operations. We have changed some global states
 582   // (such as vmClasses::_klasses) that may cause these VM operations
 583   // to fail. For safety, forget these operations and exit the VM directly.
 584   vm_direct_exit(0);
 585 }
 586 
 587 class CollectCLDClosure : public CLDClosure {
 588   GrowableArray<ClassLoaderData*> _loaded_cld;
 589   GrowableArray<Handle> _loaded_cld_handles; // keep the CLDs alive
 590   Thread* _current_thread;
 591 public:
 592   CollectCLDClosure(Thread* thread) : _current_thread(thread) {}
 593   ~CollectCLDClosure() {
 594     for (int i = 0; i < _loaded_cld.length(); i++) {
 595       ClassLoaderData* cld = _loaded_cld.at(i);
 596     }
 597   }
 598   void do_cld(ClassLoaderData* cld) {
 599     if (!cld->is_unloading()) {
 600       _loaded_cld.append(cld);
 601       _loaded_cld_handles.append(Handle(_current_thread, cld->holder_phantom()));
 602     }
 603   }
 604 
 605   int nof_cld() const                { return _loaded_cld.length(); }
 606   ClassLoaderData* cld_at(int index) { return _loaded_cld.at(index); }
 607 };
 608 
 609 // Check if we can eagerly link this class at dump time, so we can avoid the
 610 // runtime linking overhead (especially verification)
 611 bool MetaspaceShared::may_be_eagerly_linked(InstanceKlass* ik) {
 612   if (!ik->can_be_verified_at_dumptime()) {
 613     // For old classes, try to leave them in the unlinked state, so
 614     // we can still store them in the archive. They must be
 615     // linked/verified at runtime.
 616     return false;
 617   }
 618   if (DynamicDumpSharedSpaces && ik->is_shared_unregistered_class()) {
 619     // Linking of unregistered classes at this stage may cause more
 620     // classes to be resolved, resulting in calls to ClassLoader.loadClass()
 621     // that may not be expected by custom class loaders.
 622     //
 623     // It's OK to do this for the built-in loaders as we know they can
 624     // tolerate this. (Note that unregistered classes are loaded by the NULL
 625     // loader during DumpSharedSpaces).
 626     return false;
 627   }
 628   return true;
 629 }
 630 
 631 bool MetaspaceShared::link_class_for_cds(InstanceKlass* ik, TRAPS) {
 632   // Link the class to cause the bytecodes to be rewritten and the
 633   // cpcache to be created. Class verification is done according
 634   // to -Xverify setting.
 635   bool res = MetaspaceShared::try_link_class(THREAD, ik);
 636 
 637   if (DumpSharedSpaces) {
 638     // The following function is used to resolve all Strings in the statically
 639     // dumped classes to archive all the Strings. The archive heap is not supported
 640     // for the dynamic archive.
 641     ik->constants()->resolve_class_constants(CHECK_(false)); // may throw OOM when interning strings.
 642   }
 643   return res;
 644 }
 645 
 646 void MetaspaceShared::link_shared_classes(TRAPS) {
 647   LambdaFormInvokers::regenerate_holder_classes(CHECK);
 648 
 649   // Collect all loaded ClassLoaderData.
 650   CollectCLDClosure collect_cld(THREAD);
 651   {
 652     // ClassLoaderDataGraph::loaded_cld_do requires ClassLoaderDataGraph_lock.
 653     // We cannot link the classes while holding this lock (or else we may run into deadlock).
 654     // Therefore, we need to first collect all the CLDs, and then link their classes after
 655     // releasing the lock.
 656     MutexLocker lock(ClassLoaderDataGraph_lock);
 657     ClassLoaderDataGraph::loaded_cld_do(&collect_cld);
 658   }
 659 
 660   while (true) {
 661     bool has_linked = false;
 662     for (int i = 0; i < collect_cld.nof_cld(); i++) {
 663       ClassLoaderData* cld = collect_cld.cld_at(i);
 664       for (Klass* klass = cld->klasses(); klass != NULL; klass = klass->next_link()) {
 665         if (klass->is_instance_klass()) {
 666           InstanceKlass* ik = InstanceKlass::cast(klass);
 667           if (may_be_eagerly_linked(ik)) {
 668             has_linked |= link_class_for_cds(ik, CHECK);
 669           }
 670         }
 671       }
 672     }
 673 
 674     if (!has_linked) {
 675       break;
 676     }
 677     // Class linking includes verification which may load more classes.
 678     // Keep scanning until we have linked no more classes.
 679   }
 680 }
 681 
 682 void MetaspaceShared::prepare_for_dumping() {
 683   Arguments::assert_is_dumping_archive();
 684   Arguments::check_unsupported_dumping_properties();
 685 
 686   ClassLoader::initialize_shared_path(JavaThread::current());
 687 }
 688 
 689 // Preload classes from a list, populate the shared spaces and dump to a
 690 // file.
 691 void MetaspaceShared::preload_and_dump() {
 692   EXCEPTION_MARK;
 693   ResourceMark rm(THREAD);
 694   preload_and_dump_impl(THREAD);
 695   if (HAS_PENDING_EXCEPTION) {
 696     if (PENDING_EXCEPTION->is_a(vmClasses::OutOfMemoryError_klass())) {
 697       vm_direct_exit(-1,  err_msg("Out of memory. Please run with a larger Java heap, current MaxHeapSize = "
 698                                   SIZE_FORMAT "M", MaxHeapSize/M));
 699     } else {
 700       log_error(cds)("%s: %s", PENDING_EXCEPTION->klass()->external_name(),
 701                      java_lang_String::as_utf8_string(java_lang_Throwable::message(PENDING_EXCEPTION)));
 702       vm_direct_exit(-1, "VM exits due to exception, use -Xlog:cds,exceptions=trace for detail");
 703     }
 704   } else {
 705     // On success, the VM_PopulateDumpSharedSpace op should have
 706     // exited the VM.
 707     ShouldNotReachHere();
 708   }
 709 }
 710 
 711 void MetaspaceShared::preload_classes(TRAPS) {
 712   char default_classlist[JVM_MAXPATHLEN];
 713   const char* classlist_path;
 714 
 715   if (SharedClassListFile == NULL) {
 716     // Construct the path to the class list (in jre/lib)
 717     // Walk up two directories from the location of the VM and
 718     // optionally tack on "lib" (depending on platform)
 719     os::jvm_path(default_classlist, sizeof(default_classlist));
 720     for (int i = 0; i < 3; i++) {
 721       char *end = strrchr(default_classlist, *os::file_separator());
 722       if (end != NULL) *end = '\0';
 723     }
 724     int classlist_path_len = (int)strlen(default_classlist);
 725     if (classlist_path_len >= 3) {
 726       if (strcmp(default_classlist + classlist_path_len - 3, "lib") != 0) {
 727         if (classlist_path_len < JVM_MAXPATHLEN - 4) {
 728           jio_snprintf(default_classlist + classlist_path_len,
 729                        sizeof(default_classlist) - classlist_path_len,
 730                        "%slib", os::file_separator());
 731           classlist_path_len += 4;
 732         }
 733       }
 734     }
 735     if (classlist_path_len < JVM_MAXPATHLEN - 10) {
 736       jio_snprintf(default_classlist + classlist_path_len,
 737                    sizeof(default_classlist) - classlist_path_len,
 738                    "%sclasslist", os::file_separator());
 739     }
 740     classlist_path = default_classlist;
 741   } else {
 742     classlist_path = SharedClassListFile;
 743   }
 744 
 745   log_info(cds)("Loading classes to share ...");
 746   _has_error_classes = false;
 747   int class_count = parse_classlist(classlist_path, CHECK);
 748   if (ExtraSharedClassListFile) {
 749     class_count += parse_classlist(ExtraSharedClassListFile, CHECK);
 750   }
 751 
 752   // Exercise the manifest processing code to ensure classes used by CDS at runtime
 753   // are always archived
 754   const char* dummy = "Manifest-Version: 1.0\n";
 755   CDSProtectionDomain::create_jar_manifest(dummy, strlen(dummy), CHECK);
 756 
 757   log_info(cds)("Loading classes to share: done.");
 758   log_info(cds)("Shared spaces: preloaded %d classes", class_count);
 759 }
 760 
 761 void MetaspaceShared::preload_and_dump_impl(TRAPS) {
 762   preload_classes(CHECK);
 763 
 764   if (SharedArchiveConfigFile) {
 765     log_info(cds)("Reading extra data from %s ...", SharedArchiveConfigFile);
 766     read_extra_data(THREAD, SharedArchiveConfigFile);
 767     log_info(cds)("Reading extra data: done.");
 768   }
 769 
 770   HeapShared::init_for_dumping(CHECK);
 771 
 772   // Rewrite and link classes
 773   log_info(cds)("Rewriting and linking classes ...");
 774 
 775   // Link any classes which got missed. This would happen if we have loaded classes that
 776   // were not explicitly specified in the classlist. E.g., if an interface implemented by class K
 777   // fails verification, all other interfaces that were not specified in the classlist but
 778   // are implemented by K are not verified.
 779   link_shared_classes(CHECK);
 780   log_info(cds)("Rewriting and linking classes: done");
 781 
 782 #if INCLUDE_CDS_JAVA_HEAP
 783     if (use_full_module_graph()) {
 784       HeapShared::reset_archived_object_states(CHECK);
 785     }
 786 #endif
 787 
 788   VM_PopulateDumpSharedSpace op;
 789   VMThread::execute(&op);
 790 }
 791 
 792 
 793 int MetaspaceShared::parse_classlist(const char* classlist_path, TRAPS) {
 794   ClassListParser parser(classlist_path);
 795   return parser.parse(THREAD); // returns the number of classes loaded.
 796 }
 797 
 798 // Returns true if the class's status has changed.
 799 bool MetaspaceShared::try_link_class(JavaThread* current, InstanceKlass* ik) {
 800   ExceptionMark em(current);
 801   JavaThread* THREAD = current; // For exception macros.
 802   Arguments::assert_is_dumping_archive();
 803   if (ik->is_loaded() && !ik->is_linked() && ik->can_be_verified_at_dumptime() &&
 804       !SystemDictionaryShared::has_class_failed_verification(ik)) {
 805     bool saved = BytecodeVerificationLocal;
 806     if (ik->is_shared_unregistered_class() && ik->class_loader() == NULL) {
 807       // The verification decision is based on BytecodeVerificationRemote
 808       // for non-system classes. Since we are using the NULL classloader
 809       // to load non-system classes for customized class loaders during dumping,
 810       // we need to temporarily change BytecodeVerificationLocal to be the same as
 811       // BytecodeVerificationRemote. Note this can cause the parent system
 812       // classes also being verified. The extra overhead is acceptable during
 813       // dumping.
 814       BytecodeVerificationLocal = BytecodeVerificationRemote;
 815     }
 816     ik->link_class(THREAD);
 817     if (HAS_PENDING_EXCEPTION) {
 818       ResourceMark rm(THREAD);
 819       log_warning(cds)("Preload Warning: Verification failed for %s",
 820                     ik->external_name());
 821       CLEAR_PENDING_EXCEPTION;
 822       SystemDictionaryShared::set_class_has_failed_verification(ik);
 823       _has_error_classes = true;
 824     }
 825     BytecodeVerificationLocal = saved;
 826     return true;
 827   } else {
 828     return false;
 829   }
 830 }
 831 
 832 #if INCLUDE_CDS_JAVA_HEAP
 833 void VM_PopulateDumpSharedSpace::dump_java_heap_objects(GrowableArray<Klass*>* klasses) {
 834   if(!HeapShared::can_write()) {
 835     log_info(cds)(
 836       "Archived java heap is not supported as UseG1GC, "
 837       "UseCompressedOops and UseCompressedClassPointers are required."
 838       "Current settings: UseG1GC=%s, UseCompressedOops=%s, UseCompressedClassPointers=%s.",
 839       BOOL_TO_STR(UseG1GC), BOOL_TO_STR(UseCompressedOops),
 840       BOOL_TO_STR(UseCompressedClassPointers));
 841     return;
 842   }
 843   // Find all the interned strings that should be dumped.
 844   int i;
 845   for (i = 0; i < klasses->length(); i++) {
 846     Klass* k = klasses->at(i);
 847     if (k->is_instance_klass()) {
 848       InstanceKlass* ik = InstanceKlass::cast(k);
 849       if (ik->is_linked()) {
 850         ik->constants()->add_dumped_interned_strings();
 851       }
 852     }
 853   }
 854   if (_extra_interned_strings != NULL) {
 855     for (i = 0; i < _extra_interned_strings->length(); i ++) {
 856       OopHandle string = _extra_interned_strings->at(i);
 857       HeapShared::add_to_dumped_interned_strings(string.resolve());
 858     }
 859   }
 860 
 861   // The closed and open archive heap space has maximum two regions.
 862   // See FileMapInfo::write_heap_regions() for details.
 863   _closed_heap_regions = new GrowableArray<MemRegion>(2);
 864   _open_heap_regions = new GrowableArray<MemRegion>(2);
 865   HeapShared::archive_objects(_closed_heap_regions, _open_heap_regions);
 866   ArchiveBuilder::OtherROAllocMark mark;
 867   HeapShared::write_subgraph_info_table();
 868 }
 869 
 870 void VM_PopulateDumpSharedSpace::dump_heap_oopmaps() {
 871   if (HeapShared::can_write()) {
 872     _closed_heap_oopmaps = new GrowableArray<ArchiveHeapOopmapInfo>(2);
 873     dump_heap_oopmaps(_closed_heap_regions, _closed_heap_oopmaps);
 874 
 875     _open_heap_oopmaps = new GrowableArray<ArchiveHeapOopmapInfo>(2);
 876     dump_heap_oopmaps(_open_heap_regions, _open_heap_oopmaps);
 877   }
 878 }
 879 
 880 void VM_PopulateDumpSharedSpace::dump_heap_oopmaps(GrowableArray<MemRegion>* regions,
 881                                                    GrowableArray<ArchiveHeapOopmapInfo>* oopmaps) {
 882   for (int i=0; i<regions->length(); i++) {
 883     ResourceBitMap oopmap = HeapShared::calculate_oopmap(regions->at(i));
 884     size_t size_in_bits = oopmap.size();
 885     size_t size_in_bytes = oopmap.size_in_bytes();
 886     uintptr_t* buffer = (uintptr_t*)NEW_C_HEAP_ARRAY(char, size_in_bytes, mtInternal);
 887     oopmap.write_to(buffer, size_in_bytes);
 888     log_info(cds, heap)("Oopmap = " INTPTR_FORMAT " (" SIZE_FORMAT_W(6) " bytes) for heap region "
 889                         INTPTR_FORMAT " (" SIZE_FORMAT_W(8) " bytes)",
 890                         p2i(buffer), size_in_bytes,
 891                         p2i(regions->at(i).start()), regions->at(i).byte_size());
 892 
 893     ArchiveHeapOopmapInfo info;
 894     info._oopmap = (address)buffer;
 895     info._oopmap_size_in_bits = size_in_bits;
 896     info._oopmap_size_in_bytes = size_in_bytes;
 897     oopmaps->append(info);
 898   }
 899 }
 900 #endif // INCLUDE_CDS_JAVA_HEAP
 901 
 902 void MetaspaceShared::set_shared_metaspace_range(void* base, void *static_top, void* top) {
 903   assert(base <= static_top && static_top <= top, "must be");
 904   _shared_metaspace_static_top = static_top;
 905   MetaspaceObj::set_shared_metaspace_range(base, top);
 906 }
 907 
 908 // Return true if given address is in the misc data region
 909 bool MetaspaceShared::is_in_shared_region(const void* p, int idx) {
 910   return UseSharedSpaces && FileMapInfo::current_info()->is_in_shared_region(p, idx);
 911 }
 912 
 913 bool MetaspaceShared::is_shared_dynamic(void* p) {
 914   if ((p < MetaspaceObj::shared_metaspace_top()) &&
 915       (p >= _shared_metaspace_static_top)) {
 916     return true;
 917   } else {
 918     return false;
 919   }
 920 }
 921 
 922 void MetaspaceShared::initialize_runtime_shared_and_meta_spaces() {
 923   assert(UseSharedSpaces, "Must be called when UseSharedSpaces is enabled");
 924   MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE;
 925 
 926   FileMapInfo* static_mapinfo = open_static_archive();
 927   FileMapInfo* dynamic_mapinfo = NULL;
 928 
 929   if (static_mapinfo != NULL) {
 930     log_info(cds)("Core region alignment: " SIZE_FORMAT, static_mapinfo->core_region_alignment());
 931     dynamic_mapinfo = open_dynamic_archive();
 932 
 933     // First try to map at the requested address
 934     result = map_archives(static_mapinfo, dynamic_mapinfo, true);
 935     if (result == MAP_ARCHIVE_MMAP_FAILURE) {
 936       // Mapping has failed (probably due to ASLR). Let's map at an address chosen
 937       // by the OS.
 938       log_info(cds)("Try to map archive(s) at an alternative address");
 939       result = map_archives(static_mapinfo, dynamic_mapinfo, false);
 940     }
 941   }
 942 
 943   if (result == MAP_ARCHIVE_SUCCESS) {
 944     bool dynamic_mapped = (dynamic_mapinfo != NULL && dynamic_mapinfo->is_mapped());
 945     char* cds_base = static_mapinfo->mapped_base();
 946     char* cds_end =  dynamic_mapped ? dynamic_mapinfo->mapped_end() : static_mapinfo->mapped_end();
 947     set_shared_metaspace_range(cds_base, static_mapinfo->mapped_end(), cds_end);
 948     _relocation_delta = static_mapinfo->relocation_delta();
 949     _requested_base_address = static_mapinfo->requested_base_address();
 950     if (dynamic_mapped) {
 951       FileMapInfo::set_shared_path_table(dynamic_mapinfo);
 952     } else {
 953       FileMapInfo::set_shared_path_table(static_mapinfo);
 954     }
 955   } else {
 956     set_shared_metaspace_range(NULL, NULL, NULL);
 957     UseSharedSpaces = false;
 958     FileMapInfo::fail_continue("Unable to map shared spaces");
 959     if (PrintSharedArchiveAndExit) {
 960       vm_exit_during_initialization("Unable to use shared archive.");
 961     }
 962   }
 963 
 964   if (static_mapinfo != NULL && !static_mapinfo->is_mapped()) {
 965     delete static_mapinfo;
 966   }
 967   if (dynamic_mapinfo != NULL && !dynamic_mapinfo->is_mapped()) {
 968     delete dynamic_mapinfo;
 969   }
 970 }
 971 
 972 FileMapInfo* MetaspaceShared::open_static_archive() {
 973   FileMapInfo* mapinfo = new FileMapInfo(true);
 974   if (!mapinfo->initialize()) {
 975     delete(mapinfo);
 976     return NULL;
 977   }
 978   return mapinfo;
 979 }
 980 
 981 FileMapInfo* MetaspaceShared::open_dynamic_archive() {
 982   if (DynamicDumpSharedSpaces) {
 983     return NULL;
 984   }
 985   if (Arguments::GetSharedDynamicArchivePath() == NULL) {
 986     return NULL;
 987   }
 988 
 989   FileMapInfo* mapinfo = new FileMapInfo(false);
 990   if (!mapinfo->initialize()) {
 991     delete(mapinfo);
 992     return NULL;
 993   }
 994   return mapinfo;
 995 }
 996 
 997 // use_requested_addr:
 998 //  true  = map at FileMapHeader::_requested_base_address
 999 //  false = map at an alternative address picked by OS.
1000 MapArchiveResult MetaspaceShared::map_archives(FileMapInfo* static_mapinfo, FileMapInfo* dynamic_mapinfo,
1001                                                bool use_requested_addr) {
1002   if (use_requested_addr && static_mapinfo->requested_base_address() == NULL) {
1003     log_info(cds)("Archive(s) were created with -XX:SharedBaseAddress=0. Always map at os-selected address.");
1004     return MAP_ARCHIVE_MMAP_FAILURE;
1005   }
1006 
1007   PRODUCT_ONLY(if (ArchiveRelocationMode == 1 && use_requested_addr) {
1008       // For product build only -- this is for benchmarking the cost of doing relocation.
1009       // For debug builds, the check is done below, after reserving the space, for better test coverage
1010       // (see comment below).
1011       log_info(cds)("ArchiveRelocationMode == 1: always map archive(s) at an alternative address");
1012       return MAP_ARCHIVE_MMAP_FAILURE;
1013     });
1014 
1015   if (ArchiveRelocationMode == 2 && !use_requested_addr) {
1016     log_info(cds)("ArchiveRelocationMode == 2: never map archive(s) at an alternative address");
1017     return MAP_ARCHIVE_MMAP_FAILURE;
1018   };
1019 
1020   if (dynamic_mapinfo != NULL) {
1021     // Ensure that the OS won't be able to allocate new memory spaces between the two
1022     // archives, or else it would mess up the simple comparision in MetaspaceObj::is_shared().
1023     assert(static_mapinfo->mapping_end_offset() == dynamic_mapinfo->mapping_base_offset(), "no gap");
1024   }
1025 
1026   ReservedSpace total_space_rs, archive_space_rs, class_space_rs;
1027   MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE;
1028   char* mapped_base_address = reserve_address_space_for_archives(static_mapinfo,
1029                                                                  dynamic_mapinfo,
1030                                                                  use_requested_addr,
1031                                                                  total_space_rs,
1032                                                                  archive_space_rs,
1033                                                                  class_space_rs);
1034   if (mapped_base_address == NULL) {
1035     result = MAP_ARCHIVE_MMAP_FAILURE;
1036     log_debug(cds)("Failed to reserve spaces (use_requested_addr=%u)", (unsigned)use_requested_addr);
1037   } else {
1038 
1039 #ifdef ASSERT
1040     // Some sanity checks after reserving address spaces for archives
1041     //  and class space.
1042     assert(archive_space_rs.is_reserved(), "Sanity");
1043     if (Metaspace::using_class_space()) {
1044       // Class space must closely follow the archive space. Both spaces
1045       //  must be aligned correctly.
1046       assert(class_space_rs.is_reserved(),
1047              "A class space should have been reserved");
1048       assert(class_space_rs.base() >= archive_space_rs.end(),
1049              "class space should follow the cds archive space");
1050       assert(is_aligned(archive_space_rs.base(),
1051                         core_region_alignment()),
1052              "Archive space misaligned");
1053       assert(is_aligned(class_space_rs.base(),
1054                         Metaspace::reserve_alignment()),
1055              "class space misaligned");
1056     }
1057 #endif // ASSERT
1058 
1059     log_info(cds)("Reserved archive_space_rs [" INTPTR_FORMAT " - " INTPTR_FORMAT "] (" SIZE_FORMAT ") bytes",
1060                    p2i(archive_space_rs.base()), p2i(archive_space_rs.end()), archive_space_rs.size());
1061     log_info(cds)("Reserved class_space_rs   [" INTPTR_FORMAT " - " INTPTR_FORMAT "] (" SIZE_FORMAT ") bytes",
1062                    p2i(class_space_rs.base()), p2i(class_space_rs.end()), class_space_rs.size());
1063 
1064     if (MetaspaceShared::use_windows_memory_mapping()) {
1065       // We have now reserved address space for the archives, and will map in
1066       //  the archive files into this space.
1067       //
1068       // Special handling for Windows: on Windows we cannot map a file view
1069       //  into an existing memory mapping. So, we unmap the address range we
1070       //  just reserved again, which will make it available for mapping the
1071       //  archives.
1072       // Reserving this range has not been for naught however since it makes
1073       //  us reasonably sure the address range is available.
1074       //
1075       // But still it may fail, since between unmapping the range and mapping
1076       //  in the archive someone else may grab the address space. Therefore
1077       //  there is a fallback in FileMap::map_region() where we just read in
1078       //  the archive files sequentially instead of mapping it in. We couple
1079       //  this with use_requested_addr, since we're going to patch all the
1080       //  pointers anyway so there's no benefit to mmap.
1081       if (use_requested_addr) {
1082         assert(!total_space_rs.is_reserved(), "Should not be reserved for Windows");
1083         log_info(cds)("Windows mmap workaround: releasing archive space.");
1084         archive_space_rs.release();
1085       }
1086     }
1087     MapArchiveResult static_result = map_archive(static_mapinfo, mapped_base_address, archive_space_rs);
1088     MapArchiveResult dynamic_result = (static_result == MAP_ARCHIVE_SUCCESS) ?
1089                                      map_archive(dynamic_mapinfo, mapped_base_address, archive_space_rs) : MAP_ARCHIVE_OTHER_FAILURE;
1090 
1091     DEBUG_ONLY(if (ArchiveRelocationMode == 1 && use_requested_addr) {
1092       // This is for simulating mmap failures at the requested address. In
1093       //  debug builds, we do it here (after all archives have possibly been
1094       //  mapped), so we can thoroughly test the code for failure handling
1095       //  (releasing all allocated resource, etc).
1096       log_info(cds)("ArchiveRelocationMode == 1: always map archive(s) at an alternative address");
1097       if (static_result == MAP_ARCHIVE_SUCCESS) {
1098         static_result = MAP_ARCHIVE_MMAP_FAILURE;
1099       }
1100       if (dynamic_result == MAP_ARCHIVE_SUCCESS) {
1101         dynamic_result = MAP_ARCHIVE_MMAP_FAILURE;
1102       }
1103     });
1104 
1105     if (static_result == MAP_ARCHIVE_SUCCESS) {
1106       if (dynamic_result == MAP_ARCHIVE_SUCCESS) {
1107         result = MAP_ARCHIVE_SUCCESS;
1108       } else if (dynamic_result == MAP_ARCHIVE_OTHER_FAILURE) {
1109         assert(dynamic_mapinfo != NULL && !dynamic_mapinfo->is_mapped(), "must have failed");
1110         // No need to retry mapping the dynamic archive again, as it will never succeed
1111         // (bad file, etc) -- just keep the base archive.
1112         log_warning(cds, dynamic)("Unable to use shared archive. The top archive failed to load: %s",
1113                                   dynamic_mapinfo->full_path());
1114         result = MAP_ARCHIVE_SUCCESS;
1115         // TODO, we can give the unused space for the dynamic archive to class_space_rs, but there's no
1116         // easy API to do that right now.
1117       } else {
1118         result = MAP_ARCHIVE_MMAP_FAILURE;
1119       }
1120     } else if (static_result == MAP_ARCHIVE_OTHER_FAILURE) {
1121       result = MAP_ARCHIVE_OTHER_FAILURE;
1122     } else {
1123       result = MAP_ARCHIVE_MMAP_FAILURE;
1124     }
1125   }
1126 
1127   if (result == MAP_ARCHIVE_SUCCESS) {
1128     SharedBaseAddress = (size_t)mapped_base_address;
1129     LP64_ONLY({
1130         if (Metaspace::using_class_space()) {
1131           // Set up ccs in metaspace.
1132           Metaspace::initialize_class_space(class_space_rs);
1133 
1134           // Set up compressed Klass pointer encoding: the encoding range must
1135           //  cover both archive and class space.
1136           address cds_base = (address)static_mapinfo->mapped_base();
1137           address ccs_end = (address)class_space_rs.end();
1138           assert(ccs_end > cds_base, "Sanity check");
1139           CompressedKlassPointers::initialize(cds_base, ccs_end - cds_base);
1140 
1141           // map_heap_regions() compares the current narrow oop and klass encodings
1142           // with the archived ones, so it must be done after all encodings are determined.
1143           static_mapinfo->map_or_load_heap_regions();
1144         }
1145       });
1146     log_info(cds)("optimized module handling: %s", MetaspaceShared::use_optimized_module_handling() ? "enabled" : "disabled");
1147     log_info(cds)("full module graph: %s", MetaspaceShared::use_full_module_graph() ? "enabled" : "disabled");
1148   } else {
1149     unmap_archive(static_mapinfo);
1150     unmap_archive(dynamic_mapinfo);
1151     release_reserved_spaces(total_space_rs, archive_space_rs, class_space_rs);
1152   }
1153 
1154   return result;
1155 }
1156 
1157 
1158 // This will reserve two address spaces suitable to house Klass structures, one
1159 //  for the cds archives (static archive and optionally dynamic archive) and
1160 //  optionally one move for ccs.
1161 //
1162 // Since both spaces must fall within the compressed class pointer encoding
1163 //  range, they are allocated close to each other.
1164 //
1165 // Space for archives will be reserved first, followed by a potential gap,
1166 //  followed by the space for ccs:
1167 //
1168 // +-- Base address             A        B                     End
1169 // |                            |        |                      |
1170 // v                            v        v                      v
1171 // +-------------+--------------+        +----------------------+
1172 // | static arc  | [dyn. arch]  | [gap]  | compr. class space   |
1173 // +-------------+--------------+        +----------------------+
1174 //
1175 // (The gap may result from different alignment requirements between metaspace
1176 //  and CDS)
1177 //
1178 // If UseCompressedClassPointers is disabled, only one address space will be
1179 //  reserved:
1180 //
1181 // +-- Base address             End
1182 // |                            |
1183 // v                            v
1184 // +-------------+--------------+
1185 // | static arc  | [dyn. arch]  |
1186 // +-------------+--------------+
1187 //
1188 // Base address: If use_archive_base_addr address is true, the Base address is
1189 //  determined by the address stored in the static archive. If
1190 //  use_archive_base_addr address is false, this base address is determined
1191 //  by the platform.
1192 //
1193 // If UseCompressedClassPointers=1, the range encompassing both spaces will be
1194 //  suitable to en/decode narrow Klass pointers: the base will be valid for
1195 //  encoding, the range [Base, End) not surpass KlassEncodingMetaspaceMax.
1196 //
1197 // Return:
1198 //
1199 // - On success:
1200 //    - total_space_rs will be reserved as whole for archive_space_rs and
1201 //      class_space_rs if UseCompressedClassPointers is true.
1202 //      On Windows, try reserve archive_space_rs and class_space_rs
1203 //      separately first if use_archive_base_addr is true.
1204 //    - archive_space_rs will be reserved and large enough to host static and
1205 //      if needed dynamic archive: [Base, A).
1206 //      archive_space_rs.base and size will be aligned to CDS reserve
1207 //      granularity.
1208 //    - class_space_rs: If UseCompressedClassPointers=1, class_space_rs will
1209 //      be reserved. Its start address will be aligned to metaspace reserve
1210 //      alignment, which may differ from CDS alignment. It will follow the cds
1211 //      archive space, close enough such that narrow class pointer encoding
1212 //      covers both spaces.
1213 //      If UseCompressedClassPointers=0, class_space_rs remains unreserved.
1214 // - On error: NULL is returned and the spaces remain unreserved.
1215 char* MetaspaceShared::reserve_address_space_for_archives(FileMapInfo* static_mapinfo,
1216                                                           FileMapInfo* dynamic_mapinfo,
1217                                                           bool use_archive_base_addr,
1218                                                           ReservedSpace& total_space_rs,
1219                                                           ReservedSpace& archive_space_rs,
1220                                                           ReservedSpace& class_space_rs) {
1221 
1222   address const base_address = (address) (use_archive_base_addr ? static_mapinfo->requested_base_address() : NULL);
1223   const size_t archive_space_alignment = core_region_alignment();
1224 
1225   // Size and requested location of the archive_space_rs (for both static and dynamic archives)
1226   assert(static_mapinfo->mapping_base_offset() == 0, "Must be");
1227   size_t archive_end_offset  = (dynamic_mapinfo == NULL) ? static_mapinfo->mapping_end_offset() : dynamic_mapinfo->mapping_end_offset();
1228   size_t archive_space_size = align_up(archive_end_offset, archive_space_alignment);
1229 
1230   // If a base address is given, it must have valid alignment and be suitable as encoding base.
1231   if (base_address != NULL) {
1232     assert(is_aligned(base_address, archive_space_alignment),
1233            "Archive base address invalid: " PTR_FORMAT ".", p2i(base_address));
1234     if (Metaspace::using_class_space()) {
1235       assert(CompressedKlassPointers::is_valid_base(base_address),
1236              "Archive base address invalid: " PTR_FORMAT ".", p2i(base_address));
1237     }
1238   }
1239 
1240   if (!Metaspace::using_class_space()) {
1241     // Get the simple case out of the way first:
1242     // no compressed class space, simple allocation.
1243     archive_space_rs = ReservedSpace(archive_space_size, archive_space_alignment,
1244                                      os::vm_page_size(), (char*)base_address);
1245     if (archive_space_rs.is_reserved()) {
1246       assert(base_address == NULL ||
1247              (address)archive_space_rs.base() == base_address, "Sanity");
1248       // Register archive space with NMT.
1249       MemTracker::record_virtual_memory_type(archive_space_rs.base(), mtClassShared);
1250       return archive_space_rs.base();
1251     }
1252     return NULL;
1253   }
1254 
1255 #ifdef _LP64
1256 
1257   // Complex case: two spaces adjacent to each other, both to be addressable
1258   //  with narrow class pointers.
1259   // We reserve the whole range spanning both spaces, then split that range up.
1260 
1261   const size_t class_space_alignment = Metaspace::reserve_alignment();
1262 
1263   // To simplify matters, lets assume that metaspace alignment will always be
1264   //  equal or a multiple of archive alignment.
1265   assert(is_power_of_2(class_space_alignment) &&
1266                        is_power_of_2(archive_space_alignment) &&
1267                        class_space_alignment >= archive_space_alignment,
1268                        "Sanity");
1269 
1270   const size_t class_space_size = CompressedClassSpaceSize;
1271   assert(CompressedClassSpaceSize > 0 &&
1272          is_aligned(CompressedClassSpaceSize, class_space_alignment),
1273          "CompressedClassSpaceSize malformed: "
1274          SIZE_FORMAT, CompressedClassSpaceSize);
1275 
1276   const size_t ccs_begin_offset = align_up(base_address + archive_space_size,
1277                                            class_space_alignment) - base_address;
1278   const size_t gap_size = ccs_begin_offset - archive_space_size;
1279 
1280   const size_t total_range_size =
1281       align_up(archive_space_size + gap_size + class_space_size, core_region_alignment());
1282 
1283   assert(total_range_size > ccs_begin_offset, "must be");
1284   if (use_windows_memory_mapping() && use_archive_base_addr) {
1285     if (base_address != nullptr) {
1286       // On Windows, we cannot safely split a reserved memory space into two (see JDK-8255917).
1287       // Hence, we optimistically reserve archive space and class space side-by-side. We only
1288       // do this for use_archive_base_addr=true since for use_archive_base_addr=false case
1289       // caller will not split the combined space for mapping, instead read the archive data
1290       // via sequential file IO.
1291       address ccs_base = base_address + archive_space_size + gap_size;
1292       archive_space_rs = ReservedSpace(archive_space_size, archive_space_alignment,
1293                                        os::vm_page_size(), (char*)base_address);
1294       class_space_rs   = ReservedSpace(class_space_size, class_space_alignment,
1295                                        os::vm_page_size(), (char*)ccs_base);
1296     }
1297     if (!archive_space_rs.is_reserved() || !class_space_rs.is_reserved()) {
1298       release_reserved_spaces(total_space_rs, archive_space_rs, class_space_rs);
1299       return NULL;
1300     }
1301   } else {
1302     if (use_archive_base_addr && base_address != nullptr) {
1303       total_space_rs = ReservedSpace(total_range_size, archive_space_alignment,
1304                                      os::vm_page_size(), (char*) base_address);
1305     } else {
1306       // Reserve at any address, but leave it up to the platform to choose a good one.
1307       total_space_rs = Metaspace::reserve_address_space_for_compressed_classes(total_range_size);
1308     }
1309 
1310     if (!total_space_rs.is_reserved()) {
1311       return NULL;
1312     }
1313 
1314     // Paranoid checks:
1315     assert(base_address == NULL || (address)total_space_rs.base() == base_address,
1316            "Sanity (" PTR_FORMAT " vs " PTR_FORMAT ")", p2i(base_address), p2i(total_space_rs.base()));
1317     assert(is_aligned(total_space_rs.base(), archive_space_alignment), "Sanity");
1318     assert(total_space_rs.size() == total_range_size, "Sanity");
1319     assert(CompressedKlassPointers::is_valid_base((address)total_space_rs.base()), "Sanity");
1320 
1321     // Now split up the space into ccs and cds archive. For simplicity, just leave
1322     //  the gap reserved at the end of the archive space. Do not do real splitting.
1323     archive_space_rs = total_space_rs.first_part(ccs_begin_offset,
1324                                                  (size_t)archive_space_alignment);
1325     class_space_rs = total_space_rs.last_part(ccs_begin_offset);
1326     MemTracker::record_virtual_memory_split_reserved(total_space_rs.base(), total_space_rs.size(),
1327                                                      ccs_begin_offset);
1328   }
1329   assert(is_aligned(archive_space_rs.base(), archive_space_alignment), "Sanity");
1330   assert(is_aligned(archive_space_rs.size(), archive_space_alignment), "Sanity");
1331   assert(is_aligned(class_space_rs.base(), class_space_alignment), "Sanity");
1332   assert(is_aligned(class_space_rs.size(), class_space_alignment), "Sanity");
1333 
1334   // NMT: fix up the space tags
1335   MemTracker::record_virtual_memory_type(archive_space_rs.base(), mtClassShared);
1336   MemTracker::record_virtual_memory_type(class_space_rs.base(), mtClass);
1337 
1338   return archive_space_rs.base();
1339 
1340 #else
1341   ShouldNotReachHere();
1342   return NULL;
1343 #endif
1344 
1345 }
1346 
1347 void MetaspaceShared::release_reserved_spaces(ReservedSpace& total_space_rs,
1348                                               ReservedSpace& archive_space_rs,
1349                                               ReservedSpace& class_space_rs) {
1350   if (total_space_rs.is_reserved()) {
1351     log_debug(cds)("Released shared space (archive + class) " INTPTR_FORMAT, p2i(total_space_rs.base()));
1352     total_space_rs.release();
1353   } else {
1354     if (archive_space_rs.is_reserved()) {
1355       log_debug(cds)("Released shared space (archive) " INTPTR_FORMAT, p2i(archive_space_rs.base()));
1356       archive_space_rs.release();
1357     }
1358     if (class_space_rs.is_reserved()) {
1359       log_debug(cds)("Released shared space (classes) " INTPTR_FORMAT, p2i(class_space_rs.base()));
1360       class_space_rs.release();
1361     }
1362   }
1363 }
1364 
1365 static int archive_regions[]     = { MetaspaceShared::rw, MetaspaceShared::ro };
1366 static int archive_regions_count = 2;
1367 
1368 MapArchiveResult MetaspaceShared::map_archive(FileMapInfo* mapinfo, char* mapped_base_address, ReservedSpace rs) {
1369   assert(UseSharedSpaces, "must be runtime");
1370   if (mapinfo == NULL) {
1371     return MAP_ARCHIVE_SUCCESS; // The dynamic archive has not been specified. No error has happened -- trivially succeeded.
1372   }
1373 
1374   mapinfo->set_is_mapped(false);
1375   if (mapinfo->core_region_alignment() != (size_t)core_region_alignment()) {
1376     log_info(cds)("Unable to map CDS archive -- core_region_alignment() expected: " SIZE_FORMAT
1377                   " actual: " SIZE_FORMAT, mapinfo->core_region_alignment(), core_region_alignment());
1378     return MAP_ARCHIVE_OTHER_FAILURE;
1379   }
1380 
1381   MapArchiveResult result =
1382     mapinfo->map_regions(archive_regions, archive_regions_count, mapped_base_address, rs);
1383 
1384   if (result != MAP_ARCHIVE_SUCCESS) {
1385     unmap_archive(mapinfo);
1386     return result;
1387   }
1388 
1389   if (!mapinfo->validate_shared_path_table()) {
1390     unmap_archive(mapinfo);
1391     return MAP_ARCHIVE_OTHER_FAILURE;
1392   }
1393 
1394   mapinfo->set_is_mapped(true);
1395   return MAP_ARCHIVE_SUCCESS;
1396 }
1397 
1398 void MetaspaceShared::unmap_archive(FileMapInfo* mapinfo) {
1399   assert(UseSharedSpaces, "must be runtime");
1400   if (mapinfo != NULL) {
1401     mapinfo->unmap_regions(archive_regions, archive_regions_count);
1402     mapinfo->unmap_region(MetaspaceShared::bm);
1403     mapinfo->set_is_mapped(false);
1404   }
1405 }
1406 
1407 // For -XX:PrintSharedArchiveAndExit
1408 class CountSharedSymbols : public SymbolClosure {
1409  private:
1410    int _count;
1411  public:
1412    CountSharedSymbols() : _count(0) {}
1413   void do_symbol(Symbol** sym) {
1414     _count++;
1415   }
1416   int total() { return _count; }
1417 
1418 };
1419 
1420 // Read the miscellaneous data from the shared file, and
1421 // serialize it out to its various destinations.
1422 
1423 void MetaspaceShared::initialize_shared_spaces() {
1424   FileMapInfo *static_mapinfo = FileMapInfo::current_info();
1425 
1426   // Verify various attributes of the archive, plus initialize the
1427   // shared string/symbol tables.
1428   char* buffer = static_mapinfo->serialized_data();
1429   intptr_t* array = (intptr_t*)buffer;
1430   ReadClosure rc(&array);
1431   serialize(&rc);
1432 
1433   // Initialize the run-time symbol table.
1434   SymbolTable::create_table();
1435 
1436   // Finish up archived heap initialization. These must be
1437   // done after ReadClosure.
1438   static_mapinfo->patch_heap_embedded_pointers();
1439   HeapShared::finish_initialization();
1440 
1441   // Close the mapinfo file
1442   static_mapinfo->close();
1443 
1444   static_mapinfo->unmap_region(MetaspaceShared::bm);
1445 
1446   FileMapInfo *dynamic_mapinfo = FileMapInfo::dynamic_info();
1447   if (dynamic_mapinfo != NULL) {
1448     intptr_t* buffer = (intptr_t*)dynamic_mapinfo->serialized_data();
1449     ReadClosure rc(&buffer);
1450     SymbolTable::serialize_shared_table_header(&rc, false);
1451     SystemDictionaryShared::serialize_dictionary_headers(&rc, false);
1452     dynamic_mapinfo->close();
1453     dynamic_mapinfo->unmap_region(MetaspaceShared::bm);
1454   }
1455 
1456   // Set up LambdaFormInvokers::_lambdaform_lines for dynamic dump
1457   if (DynamicDumpSharedSpaces) {
1458     // Read stored LF format lines stored in static archive
1459     LambdaFormInvokers::read_static_archive_invokers();
1460   }
1461 
1462   if (PrintSharedArchiveAndExit) {
1463     // Print archive names
1464     if (dynamic_mapinfo != nullptr) {
1465       tty->print_cr("\n\nBase archive name: %s", Arguments::GetSharedArchivePath());
1466       tty->print_cr("Base archive version %d", static_mapinfo->version());
1467     } else {
1468       tty->print_cr("Static archive name: %s", static_mapinfo->full_path());
1469       tty->print_cr("Static archive version %d", static_mapinfo->version());
1470     }
1471 
1472     SystemDictionaryShared::print_shared_archive(tty);
1473     if (dynamic_mapinfo != nullptr) {
1474       tty->print_cr("\n\nDynamic archive name: %s", dynamic_mapinfo->full_path());
1475       tty->print_cr("Dynamic archive version %d", dynamic_mapinfo->version());
1476       SystemDictionaryShared::print_shared_archive(tty, false/*dynamic*/);
1477     }
1478 
1479     // collect shared symbols and strings
1480     CountSharedSymbols cl;
1481     SymbolTable::shared_symbols_do(&cl);
1482     tty->print_cr("Number of shared symbols: %d", cl.total());
1483     tty->print_cr("Number of shared strings: %zu", StringTable::shared_entry_count());
1484     tty->print_cr("VM version: %s\r\n", static_mapinfo->vm_version());
1485     if (FileMapInfo::current_info() == NULL || _archive_loading_failed) {
1486       tty->print_cr("archive is invalid");
1487       vm_exit(1);
1488     } else {
1489       tty->print_cr("archive is valid");
1490       vm_exit(0);
1491     }
1492   }
1493 }
1494 
1495 // JVM/TI RedefineClasses() support:
1496 bool MetaspaceShared::remap_shared_readonly_as_readwrite() {
1497   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1498 
1499   if (UseSharedSpaces) {
1500     // remap the shared readonly space to shared readwrite, private
1501     FileMapInfo* mapinfo = FileMapInfo::current_info();
1502     if (!mapinfo->remap_shared_readonly_as_readwrite()) {
1503       return false;
1504     }
1505     if (FileMapInfo::dynamic_info() != NULL) {
1506       mapinfo = FileMapInfo::dynamic_info();
1507       if (!mapinfo->remap_shared_readonly_as_readwrite()) {
1508         return false;
1509       }
1510     }
1511     _remapped_readwrite = true;
1512   }
1513   return true;
1514 }
1515 
1516 bool MetaspaceShared::use_full_module_graph() {
1517 #if INCLUDE_CDS_JAVA_HEAP
1518   if (ClassLoaderDataShared::is_full_module_graph_loaded()) {
1519     return true;
1520   }
1521 #endif
1522   bool result = _use_optimized_module_handling && _use_full_module_graph;
1523   if (DumpSharedSpaces) {
1524     result &= HeapShared::can_write();
1525   } else if (UseSharedSpaces) {
1526     result &= HeapShared::can_use();
1527   } else {
1528     result = false;
1529   }
1530 
1531   if (result && UseSharedSpaces) {
1532     // Classes used by the archived full module graph are loaded in JVMTI early phase.
1533     assert(!(JvmtiExport::should_post_class_file_load_hook() && JvmtiExport::has_early_class_hook_env()),
1534            "CDS should be disabled if early class hooks are enabled");
1535   }
1536   return result;
1537 }
1538 
1539 void MetaspaceShared::print_on(outputStream* st) {
1540   if (UseSharedSpaces) {
1541     st->print("CDS archive(s) mapped at: ");
1542     address base = (address)MetaspaceObj::shared_metaspace_base();
1543     address static_top = (address)_shared_metaspace_static_top;
1544     address top = (address)MetaspaceObj::shared_metaspace_top();
1545     st->print("[" PTR_FORMAT "-" PTR_FORMAT "-" PTR_FORMAT "), ", p2i(base), p2i(static_top), p2i(top));
1546     st->print("size " SIZE_FORMAT ", ", top - base);
1547     st->print("SharedBaseAddress: " PTR_FORMAT ", ArchiveRelocationMode: %d.", SharedBaseAddress, (int)ArchiveRelocationMode);
1548   } else {
1549     st->print("CDS archive(s) not mapped");
1550   }
1551   st->cr();
1552 }
--- EOF ---