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<OopHandle> _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_handles.length(); i++) {
 593       _loaded_cld_handles.at(i).release(Universe::vm_global());
 594     }
 595   }
 596   void do_cld(ClassLoaderData* cld) {
 597     assert(cld->is_alive(), "must be");
 598     _loaded_cld.append(cld);
 599     _loaded_cld_handles.append(OopHandle(Universe::vm_global(), cld->holder_phantom()));
 600   }
 601 
 602   int nof_cld() const                { return _loaded_cld.length(); }
 603   ClassLoaderData* cld_at(int index) { return _loaded_cld.at(index); }
 604 };
 605 
 606 // Check if we can eagerly link this class at dump time, so we can avoid the
 607 // runtime linking overhead (especially verification)
 608 bool MetaspaceShared::may_be_eagerly_linked(InstanceKlass* ik) {
 609   if (!ik->can_be_verified_at_dumptime()) {
 610     // For old classes, try to leave them in the unlinked state, so
 611     // we can still store them in the archive. They must be
 612     // linked/verified at runtime.
 613     return false;
 614   }
 615   if (DynamicDumpSharedSpaces && ik->is_shared_unregistered_class()) {
 616     // Linking of unregistered classes at this stage may cause more
 617     // classes to be resolved, resulting in calls to ClassLoader.loadClass()
 618     // that may not be expected by custom class loaders.
 619     //
 620     // It's OK to do this for the built-in loaders as we know they can
 621     // tolerate this. (Note that unregistered classes are loaded by the NULL
 622     // loader during DumpSharedSpaces).
 623     return false;
 624   }
 625   return true;
 626 }
 627 
 628 bool MetaspaceShared::link_class_for_cds(InstanceKlass* ik, TRAPS) {
 629   // Link the class to cause the bytecodes to be rewritten and the
 630   // cpcache to be created. Class verification is done according
 631   // to -Xverify setting.
 632   bool res = MetaspaceShared::try_link_class(THREAD, ik);
 633 
 634   if (DumpSharedSpaces) {
 635     // The following function is used to resolve all Strings in the statically
 636     // dumped classes to archive all the Strings. The archive heap is not supported
 637     // for the dynamic archive.
 638     ik->constants()->resolve_class_constants(CHECK_(false)); // may throw OOM when interning strings.
 639   }
 640   return res;
 641 }
 642 
 643 void MetaspaceShared::link_shared_classes(TRAPS) {
 644   LambdaFormInvokers::regenerate_holder_classes(CHECK);
 645 
 646   // Collect all loaded ClassLoaderData.
 647   CollectCLDClosure collect_cld(THREAD);
 648   {
 649     // ClassLoaderDataGraph::loaded_cld_do requires ClassLoaderDataGraph_lock.
 650     // We cannot link the classes while holding this lock (or else we may run into deadlock).
 651     // Therefore, we need to first collect all the CLDs, and then link their classes after
 652     // releasing the lock.
 653     MutexLocker lock(ClassLoaderDataGraph_lock);
 654     ClassLoaderDataGraph::loaded_cld_do(&collect_cld);
 655   }
 656 
 657   while (true) {
 658     bool has_linked = false;
 659     for (int i = 0; i < collect_cld.nof_cld(); i++) {
 660       ClassLoaderData* cld = collect_cld.cld_at(i);
 661       for (Klass* klass = cld->klasses(); klass != NULL; klass = klass->next_link()) {
 662         if (klass->is_instance_klass()) {
 663           InstanceKlass* ik = InstanceKlass::cast(klass);
 664           if (may_be_eagerly_linked(ik)) {
 665             has_linked |= link_class_for_cds(ik, CHECK);
 666           }
 667         }
 668       }
 669     }
 670 
 671     if (!has_linked) {
 672       break;
 673     }
 674     // Class linking includes verification which may load more classes.
 675     // Keep scanning until we have linked no more classes.
 676   }
 677 }
 678 
 679 void MetaspaceShared::prepare_for_dumping() {
 680   Arguments::assert_is_dumping_archive();
 681   Arguments::check_unsupported_dumping_properties();
 682 
 683   ClassLoader::initialize_shared_path(JavaThread::current());
 684 }
 685 
 686 // Preload classes from a list, populate the shared spaces and dump to a
 687 // file.
 688 void MetaspaceShared::preload_and_dump() {
 689   EXCEPTION_MARK;
 690   ResourceMark rm(THREAD);
 691   preload_and_dump_impl(THREAD);
 692   if (HAS_PENDING_EXCEPTION) {
 693     if (PENDING_EXCEPTION->is_a(vmClasses::OutOfMemoryError_klass())) {
 694       vm_direct_exit(-1,  err_msg("Out of memory. Please run with a larger Java heap, current MaxHeapSize = "
 695                                   SIZE_FORMAT "M", MaxHeapSize/M));
 696     } else {
 697       log_error(cds)("%s: %s", PENDING_EXCEPTION->klass()->external_name(),
 698                      java_lang_String::as_utf8_string(java_lang_Throwable::message(PENDING_EXCEPTION)));
 699       vm_direct_exit(-1, "VM exits due to exception, use -Xlog:cds,exceptions=trace for detail");
 700     }
 701   } else {
 702     // On success, the VM_PopulateDumpSharedSpace op should have
 703     // exited the VM.
 704     ShouldNotReachHere();
 705   }
 706 }
 707 
 708 void MetaspaceShared::preload_classes(TRAPS) {
 709   char default_classlist[JVM_MAXPATHLEN];
 710   const char* classlist_path;
 711 
 712   if (SharedClassListFile == NULL) {
 713     // Construct the path to the class list (in jre/lib)
 714     // Walk up two directories from the location of the VM and
 715     // optionally tack on "lib" (depending on platform)
 716     os::jvm_path(default_classlist, sizeof(default_classlist));
 717     for (int i = 0; i < 3; i++) {
 718       char *end = strrchr(default_classlist, *os::file_separator());
 719       if (end != NULL) *end = '\0';
 720     }
 721     int classlist_path_len = (int)strlen(default_classlist);
 722     if (classlist_path_len >= 3) {
 723       if (strcmp(default_classlist + classlist_path_len - 3, "lib") != 0) {
 724         if (classlist_path_len < JVM_MAXPATHLEN - 4) {
 725           jio_snprintf(default_classlist + classlist_path_len,
 726                        sizeof(default_classlist) - classlist_path_len,
 727                        "%slib", os::file_separator());
 728           classlist_path_len += 4;
 729         }
 730       }
 731     }
 732     if (classlist_path_len < JVM_MAXPATHLEN - 10) {
 733       jio_snprintf(default_classlist + classlist_path_len,
 734                    sizeof(default_classlist) - classlist_path_len,
 735                    "%sclasslist", os::file_separator());
 736     }
 737     classlist_path = default_classlist;
 738   } else {
 739     classlist_path = SharedClassListFile;
 740   }
 741 
 742   log_info(cds)("Loading classes to share ...");
 743   _has_error_classes = false;
 744   int class_count = parse_classlist(classlist_path, CHECK);
 745   if (ExtraSharedClassListFile) {
 746     class_count += parse_classlist(ExtraSharedClassListFile, CHECK);
 747   }
 748 
 749   // Exercise the manifest processing code to ensure classes used by CDS at runtime
 750   // are always archived
 751   const char* dummy = "Manifest-Version: 1.0\n";
 752   CDSProtectionDomain::create_jar_manifest(dummy, strlen(dummy), CHECK);
 753 
 754   log_info(cds)("Loading classes to share: done.");
 755   log_info(cds)("Shared spaces: preloaded %d classes", class_count);
 756 }
 757 
 758 void MetaspaceShared::preload_and_dump_impl(TRAPS) {
 759   preload_classes(CHECK);
 760 
 761   if (SharedArchiveConfigFile) {
 762     log_info(cds)("Reading extra data from %s ...", SharedArchiveConfigFile);
 763     read_extra_data(THREAD, SharedArchiveConfigFile);
 764     log_info(cds)("Reading extra data: done.");
 765   }
 766 
 767   HeapShared::init_for_dumping(CHECK);
 768 
 769   // Rewrite and link classes
 770   log_info(cds)("Rewriting and linking classes ...");
 771 
 772   // Link any classes which got missed. This would happen if we have loaded classes that
 773   // were not explicitly specified in the classlist. E.g., if an interface implemented by class K
 774   // fails verification, all other interfaces that were not specified in the classlist but
 775   // are implemented by K are not verified.
 776   link_shared_classes(CHECK);
 777   log_info(cds)("Rewriting and linking classes: done");
 778 
 779 #if INCLUDE_CDS_JAVA_HEAP
 780     if (use_full_module_graph()) {
 781       HeapShared::reset_archived_object_states(CHECK);
 782     }
 783 #endif
 784 
 785   VM_PopulateDumpSharedSpace op;
 786   VMThread::execute(&op);
 787 }
 788 
 789 
 790 int MetaspaceShared::parse_classlist(const char* classlist_path, TRAPS) {
 791   ClassListParser parser(classlist_path);
 792   return parser.parse(THREAD); // returns the number of classes loaded.
 793 }
 794 
 795 // Returns true if the class's status has changed.
 796 bool MetaspaceShared::try_link_class(JavaThread* current, InstanceKlass* ik) {
 797   ExceptionMark em(current);
 798   JavaThread* THREAD = current; // For exception macros.
 799   Arguments::assert_is_dumping_archive();
 800   if (ik->is_loaded() && !ik->is_linked() && ik->can_be_verified_at_dumptime() &&
 801       !SystemDictionaryShared::has_class_failed_verification(ik)) {
 802     bool saved = BytecodeVerificationLocal;
 803     if (ik->is_shared_unregistered_class() && ik->class_loader() == NULL) {
 804       // The verification decision is based on BytecodeVerificationRemote
 805       // for non-system classes. Since we are using the NULL classloader
 806       // to load non-system classes for customized class loaders during dumping,
 807       // we need to temporarily change BytecodeVerificationLocal to be the same as
 808       // BytecodeVerificationRemote. Note this can cause the parent system
 809       // classes also being verified. The extra overhead is acceptable during
 810       // dumping.
 811       BytecodeVerificationLocal = BytecodeVerificationRemote;
 812     }
 813     ik->link_class(THREAD);
 814     if (HAS_PENDING_EXCEPTION) {
 815       ResourceMark rm(THREAD);
 816       log_warning(cds)("Preload Warning: Verification failed for %s",
 817                     ik->external_name());
 818       CLEAR_PENDING_EXCEPTION;
 819       SystemDictionaryShared::set_class_has_failed_verification(ik);
 820       _has_error_classes = true;
 821     }
 822     BytecodeVerificationLocal = saved;
 823     return true;
 824   } else {
 825     return false;
 826   }
 827 }
 828 
 829 #if INCLUDE_CDS_JAVA_HEAP
 830 void VM_PopulateDumpSharedSpace::dump_java_heap_objects(GrowableArray<Klass*>* klasses) {
 831   if(!HeapShared::can_write()) {
 832     log_info(cds)(
 833       "Archived java heap is not supported as UseG1GC, "
 834       "UseCompressedOops and UseCompressedClassPointers are required."
 835       "Current settings: UseG1GC=%s, UseCompressedOops=%s, UseCompressedClassPointers=%s.",
 836       BOOL_TO_STR(UseG1GC), BOOL_TO_STR(UseCompressedOops),
 837       BOOL_TO_STR(UseCompressedClassPointers));
 838     return;
 839   }
 840   // Find all the interned strings that should be dumped.
 841   int i;
 842   for (i = 0; i < klasses->length(); i++) {
 843     Klass* k = klasses->at(i);
 844     if (k->is_instance_klass()) {
 845       InstanceKlass* ik = InstanceKlass::cast(k);
 846       if (ik->is_linked()) {
 847         ik->constants()->add_dumped_interned_strings();
 848       }
 849     }
 850   }
 851   if (_extra_interned_strings != NULL) {
 852     for (i = 0; i < _extra_interned_strings->length(); i ++) {
 853       OopHandle string = _extra_interned_strings->at(i);
 854       HeapShared::add_to_dumped_interned_strings(string.resolve());
 855     }
 856   }
 857 
 858   // The closed and open archive heap space has maximum two regions.
 859   // See FileMapInfo::write_heap_regions() for details.
 860   _closed_heap_regions = new GrowableArray<MemRegion>(2);
 861   _open_heap_regions = new GrowableArray<MemRegion>(2);
 862   HeapShared::archive_objects(_closed_heap_regions, _open_heap_regions);
 863   ArchiveBuilder::OtherROAllocMark mark;
 864   HeapShared::write_subgraph_info_table();
 865 }
 866 
 867 void VM_PopulateDumpSharedSpace::dump_heap_oopmaps() {
 868   if (HeapShared::can_write()) {
 869     _closed_heap_oopmaps = new GrowableArray<ArchiveHeapOopmapInfo>(2);
 870     dump_heap_oopmaps(_closed_heap_regions, _closed_heap_oopmaps);
 871 
 872     _open_heap_oopmaps = new GrowableArray<ArchiveHeapOopmapInfo>(2);
 873     dump_heap_oopmaps(_open_heap_regions, _open_heap_oopmaps);
 874   }
 875 }
 876 
 877 void VM_PopulateDumpSharedSpace::dump_heap_oopmaps(GrowableArray<MemRegion>* regions,
 878                                                    GrowableArray<ArchiveHeapOopmapInfo>* oopmaps) {
 879   for (int i=0; i<regions->length(); i++) {
 880     ResourceBitMap oopmap = HeapShared::calculate_oopmap(regions->at(i));
 881     size_t size_in_bits = oopmap.size();
 882     size_t size_in_bytes = oopmap.size_in_bytes();
 883     uintptr_t* buffer = (uintptr_t*)NEW_C_HEAP_ARRAY(char, size_in_bytes, mtInternal);
 884     oopmap.write_to(buffer, size_in_bytes);
 885     log_info(cds, heap)("Oopmap = " INTPTR_FORMAT " (" SIZE_FORMAT_W(6) " bytes) for heap region "
 886                         INTPTR_FORMAT " (" SIZE_FORMAT_W(8) " bytes)",
 887                         p2i(buffer), size_in_bytes,
 888                         p2i(regions->at(i).start()), regions->at(i).byte_size());
 889 
 890     ArchiveHeapOopmapInfo info;
 891     info._oopmap = (address)buffer;
 892     info._oopmap_size_in_bits = size_in_bits;
 893     info._oopmap_size_in_bytes = size_in_bytes;
 894     oopmaps->append(info);
 895   }
 896 }
 897 #endif // INCLUDE_CDS_JAVA_HEAP
 898 
 899 void MetaspaceShared::set_shared_metaspace_range(void* base, void *static_top, void* top) {
 900   assert(base <= static_top && static_top <= top, "must be");
 901   _shared_metaspace_static_top = static_top;
 902   MetaspaceObj::set_shared_metaspace_range(base, top);
 903 }
 904 
 905 // Return true if given address is in the misc data region
 906 bool MetaspaceShared::is_in_shared_region(const void* p, int idx) {
 907   return UseSharedSpaces && FileMapInfo::current_info()->is_in_shared_region(p, idx);
 908 }
 909 
 910 bool MetaspaceShared::is_shared_dynamic(void* p) {
 911   if ((p < MetaspaceObj::shared_metaspace_top()) &&
 912       (p >= _shared_metaspace_static_top)) {
 913     return true;
 914   } else {
 915     return false;
 916   }
 917 }
 918 
 919 void MetaspaceShared::initialize_runtime_shared_and_meta_spaces() {
 920   assert(UseSharedSpaces, "Must be called when UseSharedSpaces is enabled");
 921   MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE;
 922 
 923   FileMapInfo* static_mapinfo = open_static_archive();
 924   FileMapInfo* dynamic_mapinfo = NULL;
 925 
 926   if (static_mapinfo != NULL) {
 927     log_info(cds)("Core region alignment: " SIZE_FORMAT, static_mapinfo->core_region_alignment());
 928     dynamic_mapinfo = open_dynamic_archive();
 929 
 930     // First try to map at the requested address
 931     result = map_archives(static_mapinfo, dynamic_mapinfo, true);
 932     if (result == MAP_ARCHIVE_MMAP_FAILURE) {
 933       // Mapping has failed (probably due to ASLR). Let's map at an address chosen
 934       // by the OS.
 935       log_info(cds)("Try to map archive(s) at an alternative address");
 936       result = map_archives(static_mapinfo, dynamic_mapinfo, false);
 937     }
 938   }
 939 
 940   if (result == MAP_ARCHIVE_SUCCESS) {
 941     bool dynamic_mapped = (dynamic_mapinfo != NULL && dynamic_mapinfo->is_mapped());
 942     char* cds_base = static_mapinfo->mapped_base();
 943     char* cds_end =  dynamic_mapped ? dynamic_mapinfo->mapped_end() : static_mapinfo->mapped_end();
 944     set_shared_metaspace_range(cds_base, static_mapinfo->mapped_end(), cds_end);
 945     _relocation_delta = static_mapinfo->relocation_delta();
 946     _requested_base_address = static_mapinfo->requested_base_address();
 947     if (dynamic_mapped) {
 948       FileMapInfo::set_shared_path_table(dynamic_mapinfo);
 949     } else {
 950       FileMapInfo::set_shared_path_table(static_mapinfo);
 951     }
 952   } else {
 953     set_shared_metaspace_range(NULL, NULL, NULL);
 954     UseSharedSpaces = false;
 955     FileMapInfo::fail_continue("Unable to map shared spaces");
 956     if (PrintSharedArchiveAndExit) {
 957       vm_exit_during_initialization("Unable to use shared archive.");
 958     }
 959   }
 960 
 961   if (static_mapinfo != NULL && !static_mapinfo->is_mapped()) {
 962     delete static_mapinfo;
 963   }
 964   if (dynamic_mapinfo != NULL && !dynamic_mapinfo->is_mapped()) {
 965     delete dynamic_mapinfo;
 966   }
 967 }
 968 
 969 FileMapInfo* MetaspaceShared::open_static_archive() {
 970   FileMapInfo* mapinfo = new FileMapInfo(true);
 971   if (!mapinfo->initialize()) {
 972     delete(mapinfo);
 973     return NULL;
 974   }
 975   return mapinfo;
 976 }
 977 
 978 FileMapInfo* MetaspaceShared::open_dynamic_archive() {
 979   if (DynamicDumpSharedSpaces) {
 980     return NULL;
 981   }
 982   if (Arguments::GetSharedDynamicArchivePath() == NULL) {
 983     return NULL;
 984   }
 985 
 986   FileMapInfo* mapinfo = new FileMapInfo(false);
 987   if (!mapinfo->initialize()) {
 988     delete(mapinfo);
 989     return NULL;
 990   }
 991   return mapinfo;
 992 }
 993 
 994 // use_requested_addr:
 995 //  true  = map at FileMapHeader::_requested_base_address
 996 //  false = map at an alternative address picked by OS.
 997 MapArchiveResult MetaspaceShared::map_archives(FileMapInfo* static_mapinfo, FileMapInfo* dynamic_mapinfo,
 998                                                bool use_requested_addr) {
 999   if (use_requested_addr && static_mapinfo->requested_base_address() == NULL) {
1000     log_info(cds)("Archive(s) were created with -XX:SharedBaseAddress=0. Always map at os-selected address.");
1001     return MAP_ARCHIVE_MMAP_FAILURE;
1002   }
1003 
1004   PRODUCT_ONLY(if (ArchiveRelocationMode == 1 && use_requested_addr) {
1005       // For product build only -- this is for benchmarking the cost of doing relocation.
1006       // For debug builds, the check is done below, after reserving the space, for better test coverage
1007       // (see comment below).
1008       log_info(cds)("ArchiveRelocationMode == 1: always map archive(s) at an alternative address");
1009       return MAP_ARCHIVE_MMAP_FAILURE;
1010     });
1011 
1012   if (ArchiveRelocationMode == 2 && !use_requested_addr) {
1013     log_info(cds)("ArchiveRelocationMode == 2: never map archive(s) at an alternative address");
1014     return MAP_ARCHIVE_MMAP_FAILURE;
1015   };
1016 
1017   if (dynamic_mapinfo != NULL) {
1018     // Ensure that the OS won't be able to allocate new memory spaces between the two
1019     // archives, or else it would mess up the simple comparision in MetaspaceObj::is_shared().
1020     assert(static_mapinfo->mapping_end_offset() == dynamic_mapinfo->mapping_base_offset(), "no gap");
1021   }
1022 
1023   ReservedSpace total_space_rs, archive_space_rs, class_space_rs;
1024   MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE;
1025   char* mapped_base_address = reserve_address_space_for_archives(static_mapinfo,
1026                                                                  dynamic_mapinfo,
1027                                                                  use_requested_addr,
1028                                                                  total_space_rs,
1029                                                                  archive_space_rs,
1030                                                                  class_space_rs);
1031   if (mapped_base_address == NULL) {
1032     result = MAP_ARCHIVE_MMAP_FAILURE;
1033     log_debug(cds)("Failed to reserve spaces (use_requested_addr=%u)", (unsigned)use_requested_addr);
1034   } else {
1035 
1036 #ifdef ASSERT
1037     // Some sanity checks after reserving address spaces for archives
1038     //  and class space.
1039     assert(archive_space_rs.is_reserved(), "Sanity");
1040     if (Metaspace::using_class_space()) {
1041       // Class space must closely follow the archive space. Both spaces
1042       //  must be aligned correctly.
1043       assert(class_space_rs.is_reserved(),
1044              "A class space should have been reserved");
1045       assert(class_space_rs.base() >= archive_space_rs.end(),
1046              "class space should follow the cds archive space");
1047       assert(is_aligned(archive_space_rs.base(),
1048                         core_region_alignment()),
1049              "Archive space misaligned");
1050       assert(is_aligned(class_space_rs.base(),
1051                         Metaspace::reserve_alignment()),
1052              "class space misaligned");
1053     }
1054 #endif // ASSERT
1055 
1056     log_info(cds)("Reserved archive_space_rs [" INTPTR_FORMAT " - " INTPTR_FORMAT "] (" SIZE_FORMAT ") bytes",
1057                    p2i(archive_space_rs.base()), p2i(archive_space_rs.end()), archive_space_rs.size());
1058     log_info(cds)("Reserved class_space_rs   [" INTPTR_FORMAT " - " INTPTR_FORMAT "] (" SIZE_FORMAT ") bytes",
1059                    p2i(class_space_rs.base()), p2i(class_space_rs.end()), class_space_rs.size());
1060 
1061     if (MetaspaceShared::use_windows_memory_mapping()) {
1062       // We have now reserved address space for the archives, and will map in
1063       //  the archive files into this space.
1064       //
1065       // Special handling for Windows: on Windows we cannot map a file view
1066       //  into an existing memory mapping. So, we unmap the address range we
1067       //  just reserved again, which will make it available for mapping the
1068       //  archives.
1069       // Reserving this range has not been for naught however since it makes
1070       //  us reasonably sure the address range is available.
1071       //
1072       // But still it may fail, since between unmapping the range and mapping
1073       //  in the archive someone else may grab the address space. Therefore
1074       //  there is a fallback in FileMap::map_region() where we just read in
1075       //  the archive files sequentially instead of mapping it in. We couple
1076       //  this with use_requested_addr, since we're going to patch all the
1077       //  pointers anyway so there's no benefit to mmap.
1078       if (use_requested_addr) {
1079         assert(!total_space_rs.is_reserved(), "Should not be reserved for Windows");
1080         log_info(cds)("Windows mmap workaround: releasing archive space.");
1081         archive_space_rs.release();
1082       }
1083     }
1084     MapArchiveResult static_result = map_archive(static_mapinfo, mapped_base_address, archive_space_rs);
1085     MapArchiveResult dynamic_result = (static_result == MAP_ARCHIVE_SUCCESS) ?
1086                                      map_archive(dynamic_mapinfo, mapped_base_address, archive_space_rs) : MAP_ARCHIVE_OTHER_FAILURE;
1087 
1088     DEBUG_ONLY(if (ArchiveRelocationMode == 1 && use_requested_addr) {
1089       // This is for simulating mmap failures at the requested address. In
1090       //  debug builds, we do it here (after all archives have possibly been
1091       //  mapped), so we can thoroughly test the code for failure handling
1092       //  (releasing all allocated resource, etc).
1093       log_info(cds)("ArchiveRelocationMode == 1: always map archive(s) at an alternative address");
1094       if (static_result == MAP_ARCHIVE_SUCCESS) {
1095         static_result = MAP_ARCHIVE_MMAP_FAILURE;
1096       }
1097       if (dynamic_result == MAP_ARCHIVE_SUCCESS) {
1098         dynamic_result = MAP_ARCHIVE_MMAP_FAILURE;
1099       }
1100     });
1101 
1102     if (static_result == MAP_ARCHIVE_SUCCESS) {
1103       if (dynamic_result == MAP_ARCHIVE_SUCCESS) {
1104         result = MAP_ARCHIVE_SUCCESS;
1105       } else if (dynamic_result == MAP_ARCHIVE_OTHER_FAILURE) {
1106         assert(dynamic_mapinfo != NULL && !dynamic_mapinfo->is_mapped(), "must have failed");
1107         // No need to retry mapping the dynamic archive again, as it will never succeed
1108         // (bad file, etc) -- just keep the base archive.
1109         log_warning(cds, dynamic)("Unable to use shared archive. The top archive failed to load: %s",
1110                                   dynamic_mapinfo->full_path());
1111         result = MAP_ARCHIVE_SUCCESS;
1112         // TODO, we can give the unused space for the dynamic archive to class_space_rs, but there's no
1113         // easy API to do that right now.
1114       } else {
1115         result = MAP_ARCHIVE_MMAP_FAILURE;
1116       }
1117     } else if (static_result == MAP_ARCHIVE_OTHER_FAILURE) {
1118       result = MAP_ARCHIVE_OTHER_FAILURE;
1119     } else {
1120       result = MAP_ARCHIVE_MMAP_FAILURE;
1121     }
1122   }
1123 
1124   if (result == MAP_ARCHIVE_SUCCESS) {
1125     SharedBaseAddress = (size_t)mapped_base_address;
1126     LP64_ONLY({
1127         if (Metaspace::using_class_space()) {
1128           // Set up ccs in metaspace.
1129           Metaspace::initialize_class_space(class_space_rs);
1130 
1131           // Set up compressed Klass pointer encoding: the encoding range must
1132           //  cover both archive and class space.
1133           address cds_base = (address)static_mapinfo->mapped_base();
1134           address ccs_end = (address)class_space_rs.end();
1135           assert(ccs_end > cds_base, "Sanity check");
1136           CompressedKlassPointers::initialize(cds_base, ccs_end - cds_base);
1137 
1138           // map_heap_regions() compares the current narrow oop and klass encodings
1139           // with the archived ones, so it must be done after all encodings are determined.
1140           static_mapinfo->map_or_load_heap_regions();
1141         }
1142       });
1143     log_info(cds)("optimized module handling: %s", MetaspaceShared::use_optimized_module_handling() ? "enabled" : "disabled");
1144     log_info(cds)("full module graph: %s", MetaspaceShared::use_full_module_graph() ? "enabled" : "disabled");
1145   } else {
1146     unmap_archive(static_mapinfo);
1147     unmap_archive(dynamic_mapinfo);
1148     release_reserved_spaces(total_space_rs, archive_space_rs, class_space_rs);
1149   }
1150 
1151   return result;
1152 }
1153 
1154 
1155 // This will reserve two address spaces suitable to house Klass structures, one
1156 //  for the cds archives (static archive and optionally dynamic archive) and
1157 //  optionally one move for ccs.
1158 //
1159 // Since both spaces must fall within the compressed class pointer encoding
1160 //  range, they are allocated close to each other.
1161 //
1162 // Space for archives will be reserved first, followed by a potential gap,
1163 //  followed by the space for ccs:
1164 //
1165 // +-- Base address             A        B                     End
1166 // |                            |        |                      |
1167 // v                            v        v                      v
1168 // +-------------+--------------+        +----------------------+
1169 // | static arc  | [dyn. arch]  | [gap]  | compr. class space   |
1170 // +-------------+--------------+        +----------------------+
1171 //
1172 // (The gap may result from different alignment requirements between metaspace
1173 //  and CDS)
1174 //
1175 // If UseCompressedClassPointers is disabled, only one address space will be
1176 //  reserved:
1177 //
1178 // +-- Base address             End
1179 // |                            |
1180 // v                            v
1181 // +-------------+--------------+
1182 // | static arc  | [dyn. arch]  |
1183 // +-------------+--------------+
1184 //
1185 // Base address: If use_archive_base_addr address is true, the Base address is
1186 //  determined by the address stored in the static archive. If
1187 //  use_archive_base_addr address is false, this base address is determined
1188 //  by the platform.
1189 //
1190 // If UseCompressedClassPointers=1, the range encompassing both spaces will be
1191 //  suitable to en/decode narrow Klass pointers: the base will be valid for
1192 //  encoding, the range [Base, End) not surpass KlassEncodingMetaspaceMax.
1193 //
1194 // Return:
1195 //
1196 // - On success:
1197 //    - total_space_rs will be reserved as whole for archive_space_rs and
1198 //      class_space_rs if UseCompressedClassPointers is true.
1199 //      On Windows, try reserve archive_space_rs and class_space_rs
1200 //      separately first if use_archive_base_addr is true.
1201 //    - archive_space_rs will be reserved and large enough to host static and
1202 //      if needed dynamic archive: [Base, A).
1203 //      archive_space_rs.base and size will be aligned to CDS reserve
1204 //      granularity.
1205 //    - class_space_rs: If UseCompressedClassPointers=1, class_space_rs will
1206 //      be reserved. Its start address will be aligned to metaspace reserve
1207 //      alignment, which may differ from CDS alignment. It will follow the cds
1208 //      archive space, close enough such that narrow class pointer encoding
1209 //      covers both spaces.
1210 //      If UseCompressedClassPointers=0, class_space_rs remains unreserved.
1211 // - On error: NULL is returned and the spaces remain unreserved.
1212 char* MetaspaceShared::reserve_address_space_for_archives(FileMapInfo* static_mapinfo,
1213                                                           FileMapInfo* dynamic_mapinfo,
1214                                                           bool use_archive_base_addr,
1215                                                           ReservedSpace& total_space_rs,
1216                                                           ReservedSpace& archive_space_rs,
1217                                                           ReservedSpace& class_space_rs) {
1218 
1219   address const base_address = (address) (use_archive_base_addr ? static_mapinfo->requested_base_address() : NULL);
1220   const size_t archive_space_alignment = core_region_alignment();
1221 
1222   // Size and requested location of the archive_space_rs (for both static and dynamic archives)
1223   assert(static_mapinfo->mapping_base_offset() == 0, "Must be");
1224   size_t archive_end_offset  = (dynamic_mapinfo == NULL) ? static_mapinfo->mapping_end_offset() : dynamic_mapinfo->mapping_end_offset();
1225   size_t archive_space_size = align_up(archive_end_offset, archive_space_alignment);
1226 
1227   // If a base address is given, it must have valid alignment and be suitable as encoding base.
1228   if (base_address != NULL) {
1229     assert(is_aligned(base_address, archive_space_alignment),
1230            "Archive base address invalid: " PTR_FORMAT ".", p2i(base_address));
1231     if (Metaspace::using_class_space()) {
1232       assert(CompressedKlassPointers::is_valid_base(base_address),
1233              "Archive base address invalid: " PTR_FORMAT ".", p2i(base_address));
1234     }
1235   }
1236 
1237   if (!Metaspace::using_class_space()) {
1238     // Get the simple case out of the way first:
1239     // no compressed class space, simple allocation.
1240     archive_space_rs = ReservedSpace(archive_space_size, archive_space_alignment,
1241                                      os::vm_page_size(), (char*)base_address);
1242     if (archive_space_rs.is_reserved()) {
1243       assert(base_address == NULL ||
1244              (address)archive_space_rs.base() == base_address, "Sanity");
1245       // Register archive space with NMT.
1246       MemTracker::record_virtual_memory_type(archive_space_rs.base(), mtClassShared);
1247       return archive_space_rs.base();
1248     }
1249     return NULL;
1250   }
1251 
1252 #ifdef _LP64
1253 
1254   // Complex case: two spaces adjacent to each other, both to be addressable
1255   //  with narrow class pointers.
1256   // We reserve the whole range spanning both spaces, then split that range up.
1257 
1258   const size_t class_space_alignment = Metaspace::reserve_alignment();
1259 
1260   // To simplify matters, lets assume that metaspace alignment will always be
1261   //  equal or a multiple of archive alignment.
1262   assert(is_power_of_2(class_space_alignment) &&
1263                        is_power_of_2(archive_space_alignment) &&
1264                        class_space_alignment >= archive_space_alignment,
1265                        "Sanity");
1266 
1267   const size_t class_space_size = CompressedClassSpaceSize;
1268   assert(CompressedClassSpaceSize > 0 &&
1269          is_aligned(CompressedClassSpaceSize, class_space_alignment),
1270          "CompressedClassSpaceSize malformed: "
1271          SIZE_FORMAT, CompressedClassSpaceSize);
1272 
1273   const size_t ccs_begin_offset = align_up(base_address + archive_space_size,
1274                                            class_space_alignment) - base_address;
1275   const size_t gap_size = ccs_begin_offset - archive_space_size;
1276 
1277   const size_t total_range_size =
1278       align_up(archive_space_size + gap_size + class_space_size, core_region_alignment());
1279 
1280   assert(total_range_size > ccs_begin_offset, "must be");
1281   if (use_windows_memory_mapping() && use_archive_base_addr) {
1282     if (base_address != nullptr) {
1283       // On Windows, we cannot safely split a reserved memory space into two (see JDK-8255917).
1284       // Hence, we optimistically reserve archive space and class space side-by-side. We only
1285       // do this for use_archive_base_addr=true since for use_archive_base_addr=false case
1286       // caller will not split the combined space for mapping, instead read the archive data
1287       // via sequential file IO.
1288       address ccs_base = base_address + archive_space_size + gap_size;
1289       archive_space_rs = ReservedSpace(archive_space_size, archive_space_alignment,
1290                                        os::vm_page_size(), (char*)base_address);
1291       class_space_rs   = ReservedSpace(class_space_size, class_space_alignment,
1292                                        os::vm_page_size(), (char*)ccs_base);
1293     }
1294     if (!archive_space_rs.is_reserved() || !class_space_rs.is_reserved()) {
1295       release_reserved_spaces(total_space_rs, archive_space_rs, class_space_rs);
1296       return NULL;
1297     }
1298   } else {
1299     if (use_archive_base_addr && base_address != nullptr) {
1300       total_space_rs = ReservedSpace(total_range_size, archive_space_alignment,
1301                                      os::vm_page_size(), (char*) base_address);
1302     } else {
1303       // Reserve at any address, but leave it up to the platform to choose a good one.
1304       total_space_rs = Metaspace::reserve_address_space_for_compressed_classes(total_range_size);
1305     }
1306 
1307     if (!total_space_rs.is_reserved()) {
1308       return NULL;
1309     }
1310 
1311     // Paranoid checks:
1312     assert(base_address == NULL || (address)total_space_rs.base() == base_address,
1313            "Sanity (" PTR_FORMAT " vs " PTR_FORMAT ")", p2i(base_address), p2i(total_space_rs.base()));
1314     assert(is_aligned(total_space_rs.base(), archive_space_alignment), "Sanity");
1315     assert(total_space_rs.size() == total_range_size, "Sanity");
1316     assert(CompressedKlassPointers::is_valid_base((address)total_space_rs.base()), "Sanity");
1317 
1318     // Now split up the space into ccs and cds archive. For simplicity, just leave
1319     //  the gap reserved at the end of the archive space. Do not do real splitting.
1320     archive_space_rs = total_space_rs.first_part(ccs_begin_offset,
1321                                                  (size_t)archive_space_alignment);
1322     class_space_rs = total_space_rs.last_part(ccs_begin_offset);
1323     MemTracker::record_virtual_memory_split_reserved(total_space_rs.base(), total_space_rs.size(),
1324                                                      ccs_begin_offset);
1325   }
1326   assert(is_aligned(archive_space_rs.base(), archive_space_alignment), "Sanity");
1327   assert(is_aligned(archive_space_rs.size(), archive_space_alignment), "Sanity");
1328   assert(is_aligned(class_space_rs.base(), class_space_alignment), "Sanity");
1329   assert(is_aligned(class_space_rs.size(), class_space_alignment), "Sanity");
1330 
1331   // NMT: fix up the space tags
1332   MemTracker::record_virtual_memory_type(archive_space_rs.base(), mtClassShared);
1333   MemTracker::record_virtual_memory_type(class_space_rs.base(), mtClass);
1334 
1335   return archive_space_rs.base();
1336 
1337 #else
1338   ShouldNotReachHere();
1339   return NULL;
1340 #endif
1341 
1342 }
1343 
1344 void MetaspaceShared::release_reserved_spaces(ReservedSpace& total_space_rs,
1345                                               ReservedSpace& archive_space_rs,
1346                                               ReservedSpace& class_space_rs) {
1347   if (total_space_rs.is_reserved()) {
1348     log_debug(cds)("Released shared space (archive + class) " INTPTR_FORMAT, p2i(total_space_rs.base()));
1349     total_space_rs.release();
1350   } else {
1351     if (archive_space_rs.is_reserved()) {
1352       log_debug(cds)("Released shared space (archive) " INTPTR_FORMAT, p2i(archive_space_rs.base()));
1353       archive_space_rs.release();
1354     }
1355     if (class_space_rs.is_reserved()) {
1356       log_debug(cds)("Released shared space (classes) " INTPTR_FORMAT, p2i(class_space_rs.base()));
1357       class_space_rs.release();
1358     }
1359   }
1360 }
1361 
1362 static int archive_regions[]     = { MetaspaceShared::rw, MetaspaceShared::ro };
1363 static int archive_regions_count = 2;
1364 
1365 MapArchiveResult MetaspaceShared::map_archive(FileMapInfo* mapinfo, char* mapped_base_address, ReservedSpace rs) {
1366   assert(UseSharedSpaces, "must be runtime");
1367   if (mapinfo == NULL) {
1368     return MAP_ARCHIVE_SUCCESS; // The dynamic archive has not been specified. No error has happened -- trivially succeeded.
1369   }
1370 
1371   mapinfo->set_is_mapped(false);
1372   if (mapinfo->core_region_alignment() != (size_t)core_region_alignment()) {
1373     log_info(cds)("Unable to map CDS archive -- core_region_alignment() expected: " SIZE_FORMAT
1374                   " actual: " SIZE_FORMAT, mapinfo->core_region_alignment(), core_region_alignment());
1375     return MAP_ARCHIVE_OTHER_FAILURE;
1376   }
1377 
1378   MapArchiveResult result =
1379     mapinfo->map_regions(archive_regions, archive_regions_count, mapped_base_address, rs);
1380 
1381   if (result != MAP_ARCHIVE_SUCCESS) {
1382     unmap_archive(mapinfo);
1383     return result;
1384   }
1385 
1386   if (!mapinfo->validate_shared_path_table()) {
1387     unmap_archive(mapinfo);
1388     return MAP_ARCHIVE_OTHER_FAILURE;
1389   }
1390 
1391   mapinfo->set_is_mapped(true);
1392   return MAP_ARCHIVE_SUCCESS;
1393 }
1394 
1395 void MetaspaceShared::unmap_archive(FileMapInfo* mapinfo) {
1396   assert(UseSharedSpaces, "must be runtime");
1397   if (mapinfo != NULL) {
1398     mapinfo->unmap_regions(archive_regions, archive_regions_count);
1399     mapinfo->unmap_region(MetaspaceShared::bm);
1400     mapinfo->set_is_mapped(false);
1401   }
1402 }
1403 
1404 // For -XX:PrintSharedArchiveAndExit
1405 class CountSharedSymbols : public SymbolClosure {
1406  private:
1407    int _count;
1408  public:
1409    CountSharedSymbols() : _count(0) {}
1410   void do_symbol(Symbol** sym) {
1411     _count++;
1412   }
1413   int total() { return _count; }
1414 
1415 };
1416 
1417 // Read the miscellaneous data from the shared file, and
1418 // serialize it out to its various destinations.
1419 
1420 void MetaspaceShared::initialize_shared_spaces() {
1421   FileMapInfo *static_mapinfo = FileMapInfo::current_info();
1422 
1423   // Verify various attributes of the archive, plus initialize the
1424   // shared string/symbol tables.
1425   char* buffer = static_mapinfo->serialized_data();
1426   intptr_t* array = (intptr_t*)buffer;
1427   ReadClosure rc(&array);
1428   serialize(&rc);
1429 
1430   // Initialize the run-time symbol table.
1431   SymbolTable::create_table();
1432 
1433   // Finish up archived heap initialization. These must be
1434   // done after ReadClosure.
1435   static_mapinfo->patch_heap_embedded_pointers();
1436   HeapShared::finish_initialization();
1437 
1438   // Close the mapinfo file
1439   static_mapinfo->close();
1440 
1441   static_mapinfo->unmap_region(MetaspaceShared::bm);
1442 
1443   FileMapInfo *dynamic_mapinfo = FileMapInfo::dynamic_info();
1444   if (dynamic_mapinfo != NULL) {
1445     intptr_t* buffer = (intptr_t*)dynamic_mapinfo->serialized_data();
1446     ReadClosure rc(&buffer);
1447     SymbolTable::serialize_shared_table_header(&rc, false);
1448     SystemDictionaryShared::serialize_dictionary_headers(&rc, false);
1449     dynamic_mapinfo->close();
1450     dynamic_mapinfo->unmap_region(MetaspaceShared::bm);
1451   }
1452 
1453   // Set up LambdaFormInvokers::_lambdaform_lines for dynamic dump
1454   if (DynamicDumpSharedSpaces) {
1455     // Read stored LF format lines stored in static archive
1456     LambdaFormInvokers::read_static_archive_invokers();
1457   }
1458 
1459   if (PrintSharedArchiveAndExit) {
1460     // Print archive names
1461     if (dynamic_mapinfo != nullptr) {
1462       tty->print_cr("\n\nBase archive name: %s", Arguments::GetSharedArchivePath());
1463       tty->print_cr("Base archive version %d", static_mapinfo->version());
1464     } else {
1465       tty->print_cr("Static archive name: %s", static_mapinfo->full_path());
1466       tty->print_cr("Static archive version %d", static_mapinfo->version());
1467     }
1468 
1469     SystemDictionaryShared::print_shared_archive(tty);
1470     if (dynamic_mapinfo != nullptr) {
1471       tty->print_cr("\n\nDynamic archive name: %s", dynamic_mapinfo->full_path());
1472       tty->print_cr("Dynamic archive version %d", dynamic_mapinfo->version());
1473       SystemDictionaryShared::print_shared_archive(tty, false/*dynamic*/);
1474     }
1475 
1476     // collect shared symbols and strings
1477     CountSharedSymbols cl;
1478     SymbolTable::shared_symbols_do(&cl);
1479     tty->print_cr("Number of shared symbols: %d", cl.total());
1480     tty->print_cr("Number of shared strings: %zu", StringTable::shared_entry_count());
1481     tty->print_cr("VM version: %s\r\n", static_mapinfo->vm_version());
1482     if (FileMapInfo::current_info() == NULL || _archive_loading_failed) {
1483       tty->print_cr("archive is invalid");
1484       vm_exit(1);
1485     } else {
1486       tty->print_cr("archive is valid");
1487       vm_exit(0);
1488     }
1489   }
1490 }
1491 
1492 // JVM/TI RedefineClasses() support:
1493 bool MetaspaceShared::remap_shared_readonly_as_readwrite() {
1494   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1495 
1496   if (UseSharedSpaces) {
1497     // remap the shared readonly space to shared readwrite, private
1498     FileMapInfo* mapinfo = FileMapInfo::current_info();
1499     if (!mapinfo->remap_shared_readonly_as_readwrite()) {
1500       return false;
1501     }
1502     if (FileMapInfo::dynamic_info() != NULL) {
1503       mapinfo = FileMapInfo::dynamic_info();
1504       if (!mapinfo->remap_shared_readonly_as_readwrite()) {
1505         return false;
1506       }
1507     }
1508     _remapped_readwrite = true;
1509   }
1510   return true;
1511 }
1512 
1513 bool MetaspaceShared::use_full_module_graph() {
1514 #if INCLUDE_CDS_JAVA_HEAP
1515   if (ClassLoaderDataShared::is_full_module_graph_loaded()) {
1516     return true;
1517   }
1518 #endif
1519   bool result = _use_optimized_module_handling && _use_full_module_graph;
1520   if (DumpSharedSpaces) {
1521     result &= HeapShared::can_write();
1522   } else if (UseSharedSpaces) {
1523     result &= HeapShared::can_use();
1524   } else {
1525     result = false;
1526   }
1527 
1528   if (result && UseSharedSpaces) {
1529     // Classes used by the archived full module graph are loaded in JVMTI early phase.
1530     assert(!(JvmtiExport::should_post_class_file_load_hook() && JvmtiExport::has_early_class_hook_env()),
1531            "CDS should be disabled if early class hooks are enabled");
1532   }
1533   return result;
1534 }
1535 
1536 void MetaspaceShared::print_on(outputStream* st) {
1537   if (UseSharedSpaces) {
1538     st->print("CDS archive(s) mapped at: ");
1539     address base = (address)MetaspaceObj::shared_metaspace_base();
1540     address static_top = (address)_shared_metaspace_static_top;
1541     address top = (address)MetaspaceObj::shared_metaspace_top();
1542     st->print("[" PTR_FORMAT "-" PTR_FORMAT "-" PTR_FORMAT "), ", p2i(base), p2i(static_top), p2i(top));
1543     st->print("size " SIZE_FORMAT ", ", top - base);
1544     st->print("SharedBaseAddress: " PTR_FORMAT ", ArchiveRelocationMode: %d.", SharedBaseAddress, (int)ArchiveRelocationMode);
1545   } else {
1546     st->print("CDS archive(s) not mapped");
1547   }
1548   st->cr();
1549 }
--- EOF ---