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