1 /*
   2  * Copyright (c) 2018, 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 "cds/archiveBuilder.hpp"
  27 #include "cds/archiveUtils.hpp"
  28 #include "cds/filemap.hpp"
  29 #include "cds/heapShared.inline.hpp"
  30 #include "cds/metaspaceShared.hpp"
  31 #include "classfile/classLoaderData.hpp"
  32 #include "classfile/classLoaderDataShared.hpp"
  33 #include "classfile/javaClasses.inline.hpp"
  34 #include "classfile/moduleEntry.hpp"
  35 #include "classfile/stringTable.hpp"
  36 #include "classfile/symbolTable.hpp"
  37 #include "classfile/systemDictionary.hpp"
  38 #include "classfile/systemDictionaryShared.hpp"
  39 #include "classfile/vmClasses.hpp"
  40 #include "classfile/vmSymbols.hpp"
  41 #include "gc/shared/collectedHeap.hpp"
  42 #include "gc/shared/gcLocker.hpp"
  43 #include "gc/shared/gcVMOperations.hpp"
  44 #include "logging/log.hpp"
  45 #include "logging/logMessage.hpp"
  46 #include "logging/logStream.hpp"
  47 #include "memory/iterator.inline.hpp"
  48 #include "memory/metadataFactory.hpp"
  49 #include "memory/metaspaceClosure.hpp"
  50 #include "memory/resourceArea.hpp"
  51 #include "memory/universe.hpp"
  52 #include "oops/compressedOops.inline.hpp"
  53 #include "oops/fieldStreams.inline.hpp"
  54 #include "oops/objArrayOop.hpp"
  55 #include "oops/oop.inline.hpp"
  56 #include "prims/jvmtiExport.hpp"
  57 #include "runtime/fieldDescriptor.inline.hpp"
  58 #include "runtime/globals_extension.hpp"
  59 #include "runtime/init.hpp"
  60 #include "runtime/java.hpp"
  61 #include "runtime/javaCalls.hpp"
  62 #include "runtime/safepointVerifiers.hpp"
  63 #include "utilities/bitMap.inline.hpp"
  64 #include "utilities/copy.hpp"
  65 #if INCLUDE_G1GC
  66 #include "gc/g1/g1CollectedHeap.hpp"
  67 #endif
  68 
  69 #if INCLUDE_CDS_JAVA_HEAP
  70 
  71 bool HeapShared::_closed_regions_mapped = false;
  72 bool HeapShared::_open_regions_mapped = false;
  73 bool HeapShared::_is_loaded = false;
  74 address   HeapShared::_narrow_oop_base;
  75 int       HeapShared::_narrow_oop_shift;
  76 DumpedInternedStrings *HeapShared::_dumped_interned_strings = NULL;
  77 
  78 uintptr_t HeapShared::_loaded_heap_bottom = 0;
  79 uintptr_t HeapShared::_loaded_heap_top = 0;
  80 uintptr_t HeapShared::_dumptime_base_0 = UINTPTR_MAX;
  81 uintptr_t HeapShared::_dumptime_base_1 = UINTPTR_MAX;
  82 uintptr_t HeapShared::_dumptime_base_2 = UINTPTR_MAX;
  83 uintptr_t HeapShared::_dumptime_base_3 = UINTPTR_MAX;
  84 uintptr_t HeapShared::_dumptime_top    = 0;
  85 intx HeapShared::_runtime_offset_0 = 0;
  86 intx HeapShared::_runtime_offset_1 = 0;
  87 intx HeapShared::_runtime_offset_2 = 0;
  88 intx HeapShared::_runtime_offset_3 = 0;
  89 bool HeapShared::_loading_failed = false;
  90 //
  91 // If you add new entries to the following tables, you should know what you're doing!
  92 //
  93 
  94 // Entry fields for shareable subgraphs archived in the closed archive heap
  95 // region. Warning: Objects in the subgraphs should not have reference fields
  96 // assigned at runtime.
  97 static ArchivableStaticFieldInfo closed_archive_subgraph_entry_fields[] = {
  98   {"java/lang/Integer$IntegerCache",              "archivedCache"},
  99   {"java/lang/Long$LongCache",                    "archivedCache"},
 100   {"java/lang/Byte$ByteCache",                    "archivedCache"},
 101   {"java/lang/Short$ShortCache",                  "archivedCache"},
 102   {"java/lang/Character$CharacterCache",          "archivedCache"},
 103   {"java/util/jar/Attributes$Name",               "KNOWN_NAMES"},
 104   {"sun/util/locale/BaseLocale",                  "constantBaseLocales"},
 105 };
 106 // Entry fields for subgraphs archived in the open archive heap region.
 107 static ArchivableStaticFieldInfo open_archive_subgraph_entry_fields[] = {
 108   {"jdk/internal/module/ArchivedModuleGraph",     "archivedModuleGraph"},
 109   {"java/util/ImmutableCollections",              "archivedObjects"},
 110   {"java/lang/ModuleLayer",                       "EMPTY_LAYER"},
 111   {"java/lang/module/Configuration",              "EMPTY_CONFIGURATION"},
 112   {"jdk/internal/math/FDBigInteger",              "archivedCaches"},
 113 };
 114 
 115 // Entry fields for subgraphs archived in the open archive heap region (full module graph).
 116 static ArchivableStaticFieldInfo fmg_open_archive_subgraph_entry_fields[] = {
 117   {"jdk/internal/loader/ArchivedClassLoaders",    "archivedClassLoaders"},
 118   {"jdk/internal/module/ArchivedBootLayer",       "archivedBootLayer"},
 119   {"java/lang/Module$ArchivedData",               "archivedData"},
 120 };
 121 
 122 const static int num_closed_archive_subgraph_entry_fields =
 123   sizeof(closed_archive_subgraph_entry_fields) / sizeof(ArchivableStaticFieldInfo);
 124 const static int num_open_archive_subgraph_entry_fields =
 125   sizeof(open_archive_subgraph_entry_fields) / sizeof(ArchivableStaticFieldInfo);
 126 const static int num_fmg_open_archive_subgraph_entry_fields =
 127   sizeof(fmg_open_archive_subgraph_entry_fields) / sizeof(ArchivableStaticFieldInfo);
 128 
 129 GrowableArrayCHeap<oop, mtClassShared>* HeapShared::_pending_roots = NULL;
 130 narrowOop HeapShared::_roots_narrow;
 131 OopHandle HeapShared::_roots;
 132 
 133 #ifdef ASSERT
 134 bool HeapShared::is_archived_object_during_dumptime(oop p) {
 135   assert(HeapShared::can_write(), "must be");
 136   assert(DumpSharedSpaces, "this function is only used with -Xshare:dump");
 137   return Universe::heap()->is_archived_object(p);
 138 }
 139 #endif
 140 
 141 ////////////////////////////////////////////////////////////////
 142 //
 143 // Java heap object archiving support
 144 //
 145 ////////////////////////////////////////////////////////////////
 146 void HeapShared::fixup_regions() {
 147   FileMapInfo* mapinfo = FileMapInfo::current_info();
 148   if (is_mapped()) {
 149     mapinfo->fixup_mapped_heap_regions();
 150   } else if (_loading_failed) {
 151     fill_failed_loaded_region();
 152   }
 153   if (is_fully_available()) {
 154     _roots = OopHandle(Universe::vm_global(), decode_from_archive(_roots_narrow));
 155     if (!MetaspaceShared::use_full_module_graph()) {
 156       // Need to remove all the archived java.lang.Module objects from HeapShared::roots().
 157       ClassLoaderDataShared::clear_archived_oops();
 158     }
 159   }
 160   SystemDictionaryShared::update_archived_mirror_native_pointers();
 161 }
 162 
 163 unsigned HeapShared::oop_hash(oop const& p) {
 164   // We are at a safepoint, so the object won't move. It's OK to use its
 165   // address as the hashcode.
 166   // We can't use p->identity_hash() as it's not available for primitive oops.
 167   assert_at_safepoint();
 168   return (unsigned)(p2i(p) >> LogBytesPerWord);
 169 }
 170 
 171 static void reset_states(oop obj, TRAPS) {
 172   Handle h_obj(THREAD, obj);
 173   InstanceKlass* klass = InstanceKlass::cast(obj->klass());
 174   TempNewSymbol method_name = SymbolTable::new_symbol("resetArchivedStates");
 175   Symbol* method_sig = vmSymbols::void_method_signature();
 176 
 177   while (klass != NULL) {
 178     Method* method = klass->find_method(method_name, method_sig);
 179     if (method != NULL) {
 180       assert(method->is_private(), "must be");
 181       if (log_is_enabled(Debug, cds)) {
 182         ResourceMark rm(THREAD);
 183         log_debug(cds)("  calling %s", method->name_and_sig_as_C_string());
 184       }
 185       JavaValue result(T_VOID);
 186       JavaCalls::call_special(&result, h_obj, klass,
 187                               method_name, method_sig, CHECK);
 188     }
 189     klass = klass->java_super();
 190   }
 191 }
 192 
 193 void HeapShared::reset_archived_object_states(TRAPS) {
 194   assert(DumpSharedSpaces, "dump-time only");
 195   log_debug(cds)("Resetting platform loader");
 196   reset_states(SystemDictionary::java_platform_loader(), CHECK);
 197   log_debug(cds)("Resetting system loader");
 198   reset_states(SystemDictionary::java_system_loader(), CHECK);
 199 }
 200 
 201 HeapShared::ArchivedObjectCache* HeapShared::_archived_object_cache = NULL;
 202 oop HeapShared::find_archived_heap_object(oop obj) {
 203   assert(DumpSharedSpaces, "dump-time only");
 204   ArchivedObjectCache* cache = archived_object_cache();
 205   oop* p = cache->get(obj);
 206   if (p != NULL) {
 207     return *p;
 208   } else {
 209     return NULL;
 210   }
 211 }
 212 
 213 int HeapShared::append_root(oop obj) {
 214   assert(DumpSharedSpaces, "dump-time only");
 215 
 216   // No GC should happen since we aren't scanning _pending_roots.
 217   assert(Thread::current() == (Thread*)VMThread::vm_thread(), "should be in vm thread");
 218 
 219   if (_pending_roots == NULL) {
 220     _pending_roots = new GrowableArrayCHeap<oop, mtClassShared>(500);
 221   }
 222 
 223   return _pending_roots->append(obj);
 224 }
 225 
 226 objArrayOop HeapShared::roots() {
 227   if (DumpSharedSpaces) {
 228     assert(Thread::current() == (Thread*)VMThread::vm_thread(), "should be in vm thread");
 229     if (!HeapShared::can_write()) {
 230       return NULL;
 231     }
 232   } else {
 233     assert(UseSharedSpaces, "must be");
 234   }
 235 
 236   objArrayOop roots = (objArrayOop)_roots.resolve();
 237   assert(roots != NULL, "should have been initialized");
 238   return roots;
 239 }
 240 
 241 void HeapShared::set_roots(narrowOop roots) {
 242   assert(UseSharedSpaces, "runtime only");
 243   assert(is_fully_available(), "must be");
 244   _roots_narrow = roots;
 245 }
 246 
 247 // Returns an objArray that contains all the roots of the archived objects
 248 oop HeapShared::get_root(int index, bool clear) {
 249   assert(index >= 0, "sanity");
 250   if (DumpSharedSpaces) {
 251     assert(Thread::current() == (Thread*)VMThread::vm_thread(), "should be in vm thread");
 252     assert(_pending_roots != NULL, "sanity");
 253     return _pending_roots->at(index);
 254   } else {
 255     assert(UseSharedSpaces, "must be");
 256     assert(!_roots.is_empty(), "must have loaded shared heap");
 257     oop result = roots()->obj_at(index);
 258     if (clear) {
 259       clear_root(index);
 260     }
 261     return result;
 262   }
 263 }
 264 
 265 void HeapShared::clear_root(int index) {
 266   assert(index >= 0, "sanity");
 267   assert(UseSharedSpaces, "must be");
 268   if (is_fully_available()) {
 269     if (log_is_enabled(Debug, cds, heap)) {
 270       oop old = roots()->obj_at(index);
 271       log_debug(cds, heap)("Clearing root %d: was " PTR_FORMAT, index, p2i(old));
 272     }
 273     roots()->obj_at_put(index, NULL);
 274   }
 275 }
 276 
 277 oop HeapShared::archive_object(oop obj) {
 278   assert(DumpSharedSpaces, "dump-time only");
 279 
 280   oop ao = find_archived_heap_object(obj);
 281   if (ao != NULL) {
 282     // already archived
 283     return ao;
 284   }
 285 
 286   int len = obj->size();
 287   if (G1CollectedHeap::heap()->is_archive_alloc_too_large(len)) {
 288     log_debug(cds, heap)("Cannot archive, object (" PTR_FORMAT ") is too large: " SIZE_FORMAT,
 289                          p2i(obj), (size_t)obj->size());
 290     return NULL;
 291   }
 292 
 293   oop archived_oop = cast_to_oop(G1CollectedHeap::heap()->archive_mem_allocate(len));
 294   if (archived_oop != NULL) {
 295     Copy::aligned_disjoint_words(cast_from_oop<HeapWord*>(obj), cast_from_oop<HeapWord*>(archived_oop), len);
 296     // Reinitialize markword to remove age/marking/locking/etc.
 297     //
 298     // We need to retain the identity_hash, because it may have been used by some hashtables
 299     // in the shared heap. This also has the side effect of pre-initializing the
 300     // identity_hash for all shared objects, so they are less likely to be written
 301     // into during run time, increasing the potential of memory sharing.
 302     if (!(EnableValhalla && obj->mark().is_inline_type())) {
 303       int hash_original = obj->identity_hash();
 304       archived_oop->set_mark(archived_oop->klass()->prototype_header().copy_set_hash(hash_original));
 305       assert(archived_oop->mark().is_unlocked(), "sanity");
 306 
 307       DEBUG_ONLY(int hash_archived = archived_oop->identity_hash());
 308       assert(hash_original == hash_archived, "Different hash codes: original %x, archived %x", hash_original, hash_archived);
 309     }
 310 
 311     ArchivedObjectCache* cache = archived_object_cache();
 312     cache->put(obj, archived_oop);
 313     if (log_is_enabled(Debug, cds, heap)) {
 314       ResourceMark rm;
 315       log_debug(cds, heap)("Archived heap object " PTR_FORMAT " ==> " PTR_FORMAT " : %s",
 316                            p2i(obj), p2i(archived_oop), obj->klass()->external_name());
 317     }
 318   } else {
 319     log_error(cds, heap)(
 320       "Cannot allocate space for object " PTR_FORMAT " in archived heap region",
 321       p2i(obj));
 322     vm_direct_exit(-1,
 323       err_msg("Out of memory. Please run with a larger Java heap, current MaxHeapSize = "
 324               SIZE_FORMAT "M", MaxHeapSize/M));
 325   }
 326   return archived_oop;
 327 }
 328 
 329 void HeapShared::archive_klass_objects() {
 330   GrowableArray<Klass*>* klasses = ArchiveBuilder::current()->klasses();
 331   assert(klasses != NULL, "sanity");
 332   for (int i = 0; i < klasses->length(); i++) {
 333     Klass* k = ArchiveBuilder::get_relocated_klass(klasses->at(i));
 334 
 335     // archive mirror object
 336     java_lang_Class::archive_mirror(k);
 337 
 338     // archive the resolved_referenes array
 339     if (k->is_instance_klass()) {
 340       InstanceKlass* ik = InstanceKlass::cast(k);
 341       ik->constants()->archive_resolved_references();
 342     }
 343   }
 344 }
 345 
 346 void HeapShared::run_full_gc_in_vm_thread() {
 347   if (HeapShared::can_write()) {
 348     // Avoid fragmentation while archiving heap objects.
 349     // We do this inside a safepoint, so that no further allocation can happen after GC
 350     // has finished.
 351     if (GCLocker::is_active()) {
 352       // Just checking for safety ...
 353       // This should not happen during -Xshare:dump. If you see this, probably the Java core lib
 354       // has been modified such that JNI code is executed in some clean up threads after
 355       // we have finished class loading.
 356       log_warning(cds)("GC locker is held, unable to start extra compacting GC. This may produce suboptimal results.");
 357     } else {
 358       log_info(cds)("Run GC ...");
 359       Universe::heap()->collect_as_vm_thread(GCCause::_archive_time_gc);
 360       log_info(cds)("Run GC done");
 361     }
 362   }
 363 }
 364 
 365 void HeapShared::archive_objects(GrowableArray<MemRegion>* closed_regions,
 366                                  GrowableArray<MemRegion>* open_regions) {
 367 
 368   G1HeapVerifier::verify_ready_for_archiving();
 369 
 370   {
 371     NoSafepointVerifier nsv;
 372 
 373     // Cache for recording where the archived objects are copied to
 374     create_archived_object_cache();
 375 
 376     log_info(cds)("Heap range = [" PTR_FORMAT " - "  PTR_FORMAT "]",
 377                   p2i(CompressedOops::begin()), p2i(CompressedOops::end()));
 378     log_info(cds)("Dumping objects to closed archive heap region ...");
 379     copy_closed_objects(closed_regions);
 380 
 381     log_info(cds)("Dumping objects to open archive heap region ...");
 382     copy_open_objects(open_regions);
 383 
 384     destroy_archived_object_cache();
 385   }
 386 
 387   G1HeapVerifier::verify_archive_regions();
 388 }
 389 
 390 void HeapShared::copy_closed_objects(GrowableArray<MemRegion>* closed_regions) {
 391   assert(HeapShared::can_write(), "must be");
 392 
 393   G1CollectedHeap::heap()->begin_archive_alloc_range();
 394 
 395   // Archive interned string objects
 396   StringTable::write_to_archive(_dumped_interned_strings);
 397 
 398   archive_object_subgraphs(closed_archive_subgraph_entry_fields,
 399                            num_closed_archive_subgraph_entry_fields,
 400                            true /* is_closed_archive */,
 401                            false /* is_full_module_graph */);
 402 
 403   G1CollectedHeap::heap()->end_archive_alloc_range(closed_regions,
 404                                                    os::vm_allocation_granularity());
 405 }
 406 
 407 void HeapShared::copy_open_objects(GrowableArray<MemRegion>* open_regions) {
 408   assert(HeapShared::can_write(), "must be");
 409 
 410   G1CollectedHeap::heap()->begin_archive_alloc_range(true /* open */);
 411 
 412   java_lang_Class::archive_basic_type_mirrors();
 413 
 414   archive_klass_objects();
 415 
 416   archive_object_subgraphs(open_archive_subgraph_entry_fields,
 417                            num_open_archive_subgraph_entry_fields,
 418                            false /* is_closed_archive */,
 419                            false /* is_full_module_graph */);
 420   if (MetaspaceShared::use_full_module_graph()) {
 421     archive_object_subgraphs(fmg_open_archive_subgraph_entry_fields,
 422                              num_fmg_open_archive_subgraph_entry_fields,
 423                              false /* is_closed_archive */,
 424                              true /* is_full_module_graph */);
 425     ClassLoaderDataShared::init_archived_oops();
 426   }
 427 
 428   copy_roots();
 429 
 430   G1CollectedHeap::heap()->end_archive_alloc_range(open_regions,
 431                                                    os::vm_allocation_granularity());
 432 }
 433 
 434 // Copy _pending_archive_roots into an objArray
 435 void HeapShared::copy_roots() {
 436   int length = _pending_roots != NULL ? _pending_roots->length() : 0;
 437   int size = objArrayOopDesc::object_size(length);
 438   Klass* k = Universe::objectArrayKlassObj(); // already relocated to point to archived klass
 439   HeapWord* mem = G1CollectedHeap::heap()->archive_mem_allocate(size);
 440 
 441   memset(mem, 0, size * BytesPerWord);
 442   {
 443     // This is copied from MemAllocator::finish
 444     oopDesc::set_mark(mem, k->prototype_header());
 445     oopDesc::release_set_klass(mem, k);
 446   }
 447   {
 448     // This is copied from ObjArrayAllocator::initialize
 449     arrayOopDesc::set_length(mem, length);
 450   }
 451 
 452   _roots = OopHandle(Universe::vm_global(), cast_to_oop(mem));
 453   for (int i = 0; i < length; i++) {
 454     roots()->obj_at_put(i, _pending_roots->at(i));
 455   }
 456   log_info(cds)("archived obj roots[%d] = %d words, klass = %p, obj = %p", length, size, k, mem);
 457 }
 458 
 459 void HeapShared::init_narrow_oop_decoding(address base, int shift) {
 460   _narrow_oop_base = base;
 461   _narrow_oop_shift = shift;
 462 }
 463 
 464 //
 465 // Subgraph archiving support
 466 //
 467 HeapShared::DumpTimeKlassSubGraphInfoTable* HeapShared::_dump_time_subgraph_info_table = NULL;
 468 HeapShared::RunTimeKlassSubGraphInfoTable   HeapShared::_run_time_subgraph_info_table;
 469 
 470 // Get the subgraph_info for Klass k. A new subgraph_info is created if
 471 // there is no existing one for k. The subgraph_info records the relocated
 472 // Klass* of the original k.
 473 KlassSubGraphInfo* HeapShared::init_subgraph_info(Klass* k, bool is_full_module_graph) {
 474   assert(DumpSharedSpaces, "dump time only");
 475   bool created;
 476   Klass* relocated_k = ArchiveBuilder::get_relocated_klass(k);
 477   KlassSubGraphInfo* info =
 478     _dump_time_subgraph_info_table->put_if_absent(relocated_k, KlassSubGraphInfo(relocated_k, is_full_module_graph),
 479                                                   &created);
 480   assert(created, "must not initialize twice");
 481   return info;
 482 }
 483 
 484 KlassSubGraphInfo* HeapShared::get_subgraph_info(Klass* k) {
 485   assert(DumpSharedSpaces, "dump time only");
 486   Klass* relocated_k = ArchiveBuilder::get_relocated_klass(k);
 487   KlassSubGraphInfo* info = _dump_time_subgraph_info_table->get(relocated_k);
 488   assert(info != NULL, "must have been initialized");
 489   return info;
 490 }
 491 
 492 // Add an entry field to the current KlassSubGraphInfo.
 493 void KlassSubGraphInfo::add_subgraph_entry_field(
 494       int static_field_offset, oop v, bool is_closed_archive) {
 495   assert(DumpSharedSpaces, "dump time only");
 496   if (_subgraph_entry_fields == NULL) {
 497     _subgraph_entry_fields =
 498       new(ResourceObj::C_HEAP, mtClass) GrowableArray<int>(10, mtClass);
 499   }
 500   _subgraph_entry_fields->append(static_field_offset);
 501   _subgraph_entry_fields->append(HeapShared::append_root(v));
 502 }
 503 
 504 // Add the Klass* for an object in the current KlassSubGraphInfo's subgraphs.
 505 // Only objects of boot classes can be included in sub-graph.
 506 void KlassSubGraphInfo::add_subgraph_object_klass(Klass* orig_k) {
 507   assert(DumpSharedSpaces, "dump time only");
 508   Klass* relocated_k = ArchiveBuilder::get_relocated_klass(orig_k);
 509 
 510   if (_subgraph_object_klasses == NULL) {
 511     _subgraph_object_klasses =
 512       new(ResourceObj::C_HEAP, mtClass) GrowableArray<Klass*>(50, mtClass);
 513   }
 514 
 515   assert(ArchiveBuilder::current()->is_in_buffer_space(relocated_k), "must be a shared class");
 516 
 517   if (_k == relocated_k) {
 518     // Don't add the Klass containing the sub-graph to it's own klass
 519     // initialization list.
 520     return;
 521   }
 522 
 523   if (relocated_k->is_instance_klass()) {
 524     assert(InstanceKlass::cast(relocated_k)->is_shared_boot_class(),
 525           "must be boot class");
 526     // vmClasses::xxx_klass() are not updated, need to check
 527     // the original Klass*
 528     if (orig_k == vmClasses::String_klass() ||
 529         orig_k == vmClasses::Object_klass()) {
 530       // Initialized early during VM initialization. No need to be added
 531       // to the sub-graph object class list.
 532       return;
 533     }
 534   } else if (relocated_k->is_objArray_klass()) {
 535     Klass* abk = ObjArrayKlass::cast(relocated_k)->bottom_klass();
 536     if (abk->is_instance_klass()) {
 537       assert(InstanceKlass::cast(abk)->is_shared_boot_class(),
 538             "must be boot class");
 539     }
 540     if (relocated_k == Universe::objectArrayKlassObj()) {
 541       // Initialized early during Universe::genesis. No need to be added
 542       // to the list.
 543       return;
 544     }
 545   } else {
 546     assert(relocated_k->is_typeArray_klass(), "must be");
 547     // Primitive type arrays are created early during Universe::genesis.
 548     return;
 549   }
 550 
 551   if (log_is_enabled(Debug, cds, heap)) {
 552     if (!_subgraph_object_klasses->contains(relocated_k)) {
 553       ResourceMark rm;
 554       log_debug(cds, heap)("Adding klass %s", orig_k->external_name());
 555     }
 556   }
 557 
 558   _subgraph_object_klasses->append_if_missing(relocated_k);
 559   _has_non_early_klasses |= is_non_early_klass(orig_k);
 560 }
 561 
 562 bool KlassSubGraphInfo::is_non_early_klass(Klass* k) {
 563   if (k->is_objArray_klass()) {
 564     k = ObjArrayKlass::cast(k)->bottom_klass();
 565   }
 566   if (k->is_instance_klass()) {
 567     if (!SystemDictionaryShared::is_early_klass(InstanceKlass::cast(k))) {
 568       ResourceMark rm;
 569       log_info(cds, heap)("non-early: %s", k->external_name());
 570       return true;
 571     } else {
 572       return false;
 573     }
 574   } else {
 575     return false;
 576   }
 577 }
 578 
 579 // Initialize an archived subgraph_info_record from the given KlassSubGraphInfo.
 580 void ArchivedKlassSubGraphInfoRecord::init(KlassSubGraphInfo* info) {
 581   _k = info->klass();
 582   _entry_field_records = NULL;
 583   _subgraph_object_klasses = NULL;
 584   _is_full_module_graph = info->is_full_module_graph();
 585 
 586   if (_is_full_module_graph) {
 587     // Consider all classes referenced by the full module graph as early -- we will be
 588     // allocating objects of these classes during JVMTI early phase, so they cannot
 589     // be processed by (non-early) JVMTI ClassFileLoadHook
 590     _has_non_early_klasses = false;
 591   } else {
 592     _has_non_early_klasses = info->has_non_early_klasses();
 593   }
 594 
 595   if (_has_non_early_klasses) {
 596     ResourceMark rm;
 597     log_info(cds, heap)(
 598           "Subgraph of klass %s has non-early klasses and cannot be used when JVMTI ClassFileLoadHook is enabled",
 599           _k->external_name());
 600   }
 601 
 602   // populate the entry fields
 603   GrowableArray<int>* entry_fields = info->subgraph_entry_fields();
 604   if (entry_fields != NULL) {
 605     int num_entry_fields = entry_fields->length();
 606     assert(num_entry_fields % 2 == 0, "sanity");
 607     _entry_field_records =
 608       ArchiveBuilder::new_ro_array<int>(num_entry_fields);
 609     for (int i = 0 ; i < num_entry_fields; i++) {
 610       _entry_field_records->at_put(i, entry_fields->at(i));
 611     }
 612   }
 613 
 614   // the Klasses of the objects in the sub-graphs
 615   GrowableArray<Klass*>* subgraph_object_klasses = info->subgraph_object_klasses();
 616   if (subgraph_object_klasses != NULL) {
 617     int num_subgraphs_klasses = subgraph_object_klasses->length();
 618     _subgraph_object_klasses =
 619       ArchiveBuilder::new_ro_array<Klass*>(num_subgraphs_klasses);
 620     for (int i = 0; i < num_subgraphs_klasses; i++) {
 621       Klass* subgraph_k = subgraph_object_klasses->at(i);
 622       if (log_is_enabled(Info, cds, heap)) {
 623         ResourceMark rm;
 624         log_info(cds, heap)(
 625           "Archived object klass %s (%2d) => %s",
 626           _k->external_name(), i, subgraph_k->external_name());
 627       }
 628       _subgraph_object_klasses->at_put(i, subgraph_k);
 629       ArchivePtrMarker::mark_pointer(_subgraph_object_klasses->adr_at(i));
 630     }
 631   }
 632 
 633   ArchivePtrMarker::mark_pointer(&_k);
 634   ArchivePtrMarker::mark_pointer(&_entry_field_records);
 635   ArchivePtrMarker::mark_pointer(&_subgraph_object_klasses);
 636 }
 637 
 638 struct CopyKlassSubGraphInfoToArchive : StackObj {
 639   CompactHashtableWriter* _writer;
 640   CopyKlassSubGraphInfoToArchive(CompactHashtableWriter* writer) : _writer(writer) {}
 641 
 642   bool do_entry(Klass* klass, KlassSubGraphInfo& info) {
 643     if (info.subgraph_object_klasses() != NULL || info.subgraph_entry_fields() != NULL) {
 644       ArchivedKlassSubGraphInfoRecord* record =
 645         (ArchivedKlassSubGraphInfoRecord*)ArchiveBuilder::ro_region_alloc(sizeof(ArchivedKlassSubGraphInfoRecord));
 646       record->init(&info);
 647 
 648       unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary((address)klass);
 649       u4 delta = ArchiveBuilder::current()->any_to_offset_u4(record);
 650       _writer->add(hash, delta);
 651     }
 652     return true; // keep on iterating
 653   }
 654 };
 655 
 656 // Build the records of archived subgraph infos, which include:
 657 // - Entry points to all subgraphs from the containing class mirror. The entry
 658 //   points are static fields in the mirror. For each entry point, the field
 659 //   offset, value and is_closed_archive flag are recorded in the sub-graph
 660 //   info. The value is stored back to the corresponding field at runtime.
 661 // - A list of klasses that need to be loaded/initialized before archived
 662 //   java object sub-graph can be accessed at runtime.
 663 void HeapShared::write_subgraph_info_table() {
 664   // Allocate the contents of the hashtable(s) inside the RO region of the CDS archive.
 665   DumpTimeKlassSubGraphInfoTable* d_table = _dump_time_subgraph_info_table;
 666   CompactHashtableStats stats;
 667 
 668   _run_time_subgraph_info_table.reset();
 669 
 670   CompactHashtableWriter writer(d_table->_count, &stats);
 671   CopyKlassSubGraphInfoToArchive copy(&writer);
 672   d_table->iterate(&copy);
 673 
 674   writer.dump(&_run_time_subgraph_info_table, "subgraphs");
 675 }
 676 
 677 void HeapShared::serialize_subgraph_info_table_header(SerializeClosure* soc) {
 678   _run_time_subgraph_info_table.serialize_header(soc);
 679 }
 680 
 681 static void verify_the_heap(Klass* k, const char* which) {
 682   if (VerifyArchivedFields > 0) {
 683     ResourceMark rm;
 684     log_info(cds, heap)("Verify heap %s initializing static field(s) in %s",
 685                         which, k->external_name());
 686 
 687     VM_Verify verify_op;
 688     VMThread::execute(&verify_op);
 689 
 690     if (VerifyArchivedFields > 1 && is_init_completed()) {
 691       // At this time, the oop->klass() of some archived objects in the heap may not
 692       // have been loaded into the system dictionary yet. Nevertheless, oop->klass() should
 693       // have enough information (object size, oop maps, etc) so that a GC can be safely
 694       // performed.
 695       //
 696       // -XX:VerifyArchivedFields=2 force a GC to happen in such an early stage
 697       // to check for GC safety.
 698       log_info(cds, heap)("Trigger GC %s initializing static field(s) in %s",
 699                           which, k->external_name());
 700       FlagSetting fs1(VerifyBeforeGC, true);
 701       FlagSetting fs2(VerifyDuringGC, true);
 702       FlagSetting fs3(VerifyAfterGC,  true);
 703       Universe::heap()->collect(GCCause::_java_lang_system_gc);
 704     }
 705   }
 706 }
 707 
 708 // Before GC can execute, we must ensure that all oops reachable from HeapShared::roots()
 709 // have a valid klass. I.e., oopDesc::klass() must have already been resolved.
 710 //
 711 // Note: if a ArchivedKlassSubGraphInfoRecord contains non-early classes, and JVMTI
 712 // ClassFileLoadHook is enabled, it's possible for this class to be dynamically replaced. In
 713 // this case, we will not load the ArchivedKlassSubGraphInfoRecord and will clear its roots.
 714 void HeapShared::resolve_classes(JavaThread* THREAD) {
 715   if (!is_fully_available()) {
 716     return; // nothing to do
 717   }
 718   resolve_classes_for_subgraphs(closed_archive_subgraph_entry_fields,
 719                                 num_closed_archive_subgraph_entry_fields,
 720                                 THREAD);
 721   resolve_classes_for_subgraphs(open_archive_subgraph_entry_fields,
 722                                 num_open_archive_subgraph_entry_fields,
 723                                 THREAD);
 724   resolve_classes_for_subgraphs(fmg_open_archive_subgraph_entry_fields,
 725                                 num_fmg_open_archive_subgraph_entry_fields,
 726                                 THREAD);
 727 }
 728 
 729 void HeapShared::resolve_classes_for_subgraphs(ArchivableStaticFieldInfo fields[],
 730                                                int num, JavaThread* THREAD) {
 731   for (int i = 0; i < num; i++) {
 732     ArchivableStaticFieldInfo* info = &fields[i];
 733     TempNewSymbol klass_name = SymbolTable::new_symbol(info->klass_name);
 734     InstanceKlass* k = SystemDictionaryShared::find_builtin_class(klass_name);
 735     assert(k != NULL && k->is_shared_boot_class(), "sanity");
 736     resolve_classes_for_subgraph_of(k, THREAD);
 737   }
 738 }
 739 
 740 void HeapShared::resolve_classes_for_subgraph_of(Klass* k, JavaThread* THREAD) {
 741   ExceptionMark em(THREAD);
 742   const ArchivedKlassSubGraphInfoRecord* record =
 743    resolve_or_init_classes_for_subgraph_of(k, /*do_init=*/false, THREAD);
 744   if (HAS_PENDING_EXCEPTION) {
 745    CLEAR_PENDING_EXCEPTION;
 746   }
 747   if (record == NULL) {
 748    clear_archived_roots_of(k);
 749   }
 750 }
 751 
 752 void HeapShared::initialize_from_archived_subgraph(Klass* k, JavaThread* THREAD) {
 753   if (!is_fully_available()) {
 754     return; // nothing to do
 755   }
 756 
 757   ExceptionMark em(THREAD);
 758   const ArchivedKlassSubGraphInfoRecord* record =
 759     resolve_or_init_classes_for_subgraph_of(k, /*do_init=*/true, THREAD);
 760 
 761   if (HAS_PENDING_EXCEPTION) {
 762     CLEAR_PENDING_EXCEPTION;
 763     // None of the field value will be set if there was an exception when initializing the classes.
 764     // The java code will not see any of the archived objects in the
 765     // subgraphs referenced from k in this case.
 766     return;
 767   }
 768 
 769   if (record != NULL) {
 770     init_archived_fields_for(k, record);
 771   }
 772 }
 773 
 774 const ArchivedKlassSubGraphInfoRecord*
 775 HeapShared::resolve_or_init_classes_for_subgraph_of(Klass* k, bool do_init, TRAPS) {
 776   assert(!DumpSharedSpaces, "Should not be called with DumpSharedSpaces");
 777 
 778   if (!k->is_shared()) {
 779     return NULL;
 780   }
 781   unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary_quick(k);
 782   const ArchivedKlassSubGraphInfoRecord* record = _run_time_subgraph_info_table.lookup(k, hash, 0);
 783 
 784   // Initialize from archived data. Currently this is done only
 785   // during VM initialization time. No lock is needed.
 786   if (record != NULL) {
 787     if (record->is_full_module_graph() && !MetaspaceShared::use_full_module_graph()) {
 788       if (log_is_enabled(Info, cds, heap)) {
 789         ResourceMark rm(THREAD);
 790         log_info(cds, heap)("subgraph %s cannot be used because full module graph is disabled",
 791                             k->external_name());
 792       }
 793       return NULL;
 794     }
 795 
 796     if (record->has_non_early_klasses() && JvmtiExport::should_post_class_file_load_hook()) {
 797       if (log_is_enabled(Info, cds, heap)) {
 798         ResourceMark rm(THREAD);
 799         log_info(cds, heap)("subgraph %s cannot be used because JVMTI ClassFileLoadHook is enabled",
 800                             k->external_name());
 801       }
 802       return NULL;
 803     }
 804 
 805     resolve_or_init(k, do_init, CHECK_NULL);
 806 
 807     // Load/link/initialize the klasses of the objects in the subgraph.
 808     // NULL class loader is used.
 809     Array<Klass*>* klasses = record->subgraph_object_klasses();
 810     if (klasses != NULL) {
 811       for (int i = 0; i < klasses->length(); i++) {
 812         Klass* klass = klasses->at(i);
 813         if (!klass->is_shared()) {
 814           return NULL;
 815         }
 816         resolve_or_init(klass, do_init, CHECK_NULL);
 817       }
 818     }
 819   }
 820 
 821   return record;
 822 }
 823 
 824 void HeapShared::resolve_or_init(Klass* k, bool do_init, TRAPS) {
 825   if (!do_init) {
 826     if (k->class_loader_data() == NULL) {
 827       Klass* resolved_k = SystemDictionary::resolve_or_null(k->name(), CHECK);
 828       assert(resolved_k == k, "classes used by archived heap must not be replaced by JVMTI ClassFileLoadHook");
 829     }
 830   } else {
 831     assert(k->class_loader_data() != NULL, "must have been resolved by HeapShared::resolve_classes");
 832     if (k->is_instance_klass()) {
 833       InstanceKlass* ik = InstanceKlass::cast(k);
 834       ik->initialize(CHECK);
 835     } else if (k->is_objArray_klass()) {
 836       ObjArrayKlass* oak = ObjArrayKlass::cast(k);
 837       oak->initialize(CHECK);
 838     }
 839   }
 840 }
 841 
 842 void HeapShared::init_archived_fields_for(Klass* k, const ArchivedKlassSubGraphInfoRecord* record) {
 843   verify_the_heap(k, "before");
 844 
 845   // Load the subgraph entry fields from the record and store them back to
 846   // the corresponding fields within the mirror.
 847   oop m = k->java_mirror();
 848   Array<int>* entry_field_records = record->entry_field_records();
 849   if (entry_field_records != NULL) {
 850     int efr_len = entry_field_records->length();
 851     assert(efr_len % 2 == 0, "sanity");
 852     for (int i = 0; i < efr_len; i += 2) {
 853       int field_offset = entry_field_records->at(i);
 854       int root_index = entry_field_records->at(i+1);
 855       oop v = get_root(root_index, /*clear=*/true);
 856       m->obj_field_put(field_offset, v);
 857       log_debug(cds, heap)("  " PTR_FORMAT " init field @ %2d = " PTR_FORMAT, p2i(k), field_offset, p2i(v));
 858     }
 859 
 860     // Done. Java code can see the archived sub-graphs referenced from k's
 861     // mirror after this point.
 862     if (log_is_enabled(Info, cds, heap)) {
 863       ResourceMark rm;
 864       log_info(cds, heap)("initialize_from_archived_subgraph %s " PTR_FORMAT "%s",
 865                           k->external_name(), p2i(k), JvmtiExport::is_early_phase() ? " (early)" : "");
 866     }
 867   }
 868 
 869   verify_the_heap(k, "after ");
 870 }
 871 
 872 void HeapShared::clear_archived_roots_of(Klass* k) {
 873   unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary_quick(k);
 874   const ArchivedKlassSubGraphInfoRecord* record = _run_time_subgraph_info_table.lookup(k, hash, 0);
 875   if (record != NULL) {
 876     Array<int>* entry_field_records = record->entry_field_records();
 877     if (entry_field_records != NULL) {
 878       int efr_len = entry_field_records->length();
 879       assert(efr_len % 2 == 0, "sanity");
 880       for (int i = 0; i < efr_len; i += 2) {
 881         int root_index = entry_field_records->at(i+1);
 882         clear_root(root_index);
 883       }
 884     }
 885   }
 886 }
 887 
 888 class WalkOopAndArchiveClosure: public BasicOopIterateClosure {
 889   int _level;
 890   bool _is_closed_archive;
 891   bool _record_klasses_only;
 892   KlassSubGraphInfo* _subgraph_info;
 893   oop _orig_referencing_obj;
 894   oop _archived_referencing_obj;
 895  public:
 896   WalkOopAndArchiveClosure(int level,
 897                            bool is_closed_archive,
 898                            bool record_klasses_only,
 899                            KlassSubGraphInfo* subgraph_info,
 900                            oop orig, oop archived) :
 901     _level(level), _is_closed_archive(is_closed_archive),
 902     _record_klasses_only(record_klasses_only),
 903     _subgraph_info(subgraph_info),
 904     _orig_referencing_obj(orig), _archived_referencing_obj(archived) {}
 905   void do_oop(narrowOop *p) { WalkOopAndArchiveClosure::do_oop_work(p); }
 906   void do_oop(      oop *p) { WalkOopAndArchiveClosure::do_oop_work(p); }
 907 
 908  protected:
 909   template <class T> void do_oop_work(T *p) {
 910     oop obj = RawAccess<>::oop_load(p);
 911     if (!CompressedOops::is_null(obj)) {
 912       assert(!HeapShared::is_archived_object_during_dumptime(obj),
 913              "original objects must not point to archived objects");
 914 
 915       size_t field_delta = pointer_delta(p, _orig_referencing_obj, sizeof(char));
 916       T* new_p = (T*)(cast_from_oop<address>(_archived_referencing_obj) + field_delta);
 917 
 918       if (!_record_klasses_only && log_is_enabled(Debug, cds, heap)) {
 919         ResourceMark rm;
 920         log_debug(cds, heap)("(%d) %s[" SIZE_FORMAT "] ==> " PTR_FORMAT " size %d %s", _level,
 921                              _orig_referencing_obj->klass()->external_name(), field_delta,
 922                              p2i(obj), obj->size() * HeapWordSize, obj->klass()->external_name());
 923         LogTarget(Trace, cds, heap) log;
 924         LogStream out(log);
 925         obj->print_on(&out);
 926       }
 927 
 928       oop archived = HeapShared::archive_reachable_objects_from(
 929           _level + 1, _subgraph_info, obj, _is_closed_archive);
 930       assert(archived != NULL, "VM should have exited with unarchivable objects for _level > 1");
 931       assert(HeapShared::is_archived_object_during_dumptime(archived), "must be");
 932 
 933       if (!_record_klasses_only) {
 934         // Update the reference in the archived copy of the referencing object.
 935         log_debug(cds, heap)("(%d) updating oop @[" PTR_FORMAT "] " PTR_FORMAT " ==> " PTR_FORMAT,
 936                              _level, p2i(new_p), p2i(obj), p2i(archived));
 937         RawAccess<IS_NOT_NULL>::oop_store(new_p, archived);
 938       }
 939     }
 940   }
 941 };
 942 
 943 void HeapShared::check_closed_region_object(InstanceKlass* k) {
 944   // Check fields in the object
 945   for (JavaFieldStream fs(k); !fs.done(); fs.next()) {
 946     if (!fs.access_flags().is_static()) {
 947       BasicType ft = fs.field_descriptor().field_type();
 948       if (!fs.access_flags().is_final() && is_reference_type(ft)) {
 949         ResourceMark rm;
 950         log_warning(cds, heap)(
 951           "Please check reference field in %s instance in closed archive heap region: %s %s",
 952           k->external_name(), (fs.name())->as_C_string(),
 953           (fs.signature())->as_C_string());
 954       }
 955     }
 956   }
 957 }
 958 
 959 void HeapShared::check_module_oop(oop orig_module_obj) {
 960   assert(DumpSharedSpaces, "must be");
 961   assert(java_lang_Module::is_instance(orig_module_obj), "must be");
 962   ModuleEntry* orig_module_ent = java_lang_Module::module_entry_raw(orig_module_obj);
 963   if (orig_module_ent == NULL) {
 964     // These special Module objects are created in Java code. They are not
 965     // defined via Modules::define_module(), so they don't have a ModuleEntry:
 966     //     java.lang.Module::ALL_UNNAMED_MODULE
 967     //     java.lang.Module::EVERYONE_MODULE
 968     //     jdk.internal.loader.ClassLoaders$BootClassLoader::unnamedModule
 969     assert(java_lang_Module::name(orig_module_obj) == NULL, "must be unnamed");
 970     log_info(cds, heap)("Module oop with No ModuleEntry* @[" PTR_FORMAT "]", p2i(orig_module_obj));
 971   } else {
 972     ClassLoaderData* loader_data = orig_module_ent->loader_data();
 973     assert(loader_data->is_builtin_class_loader_data(), "must be");
 974   }
 975 }
 976 
 977 
 978 // (1) If orig_obj has not been archived yet, archive it.
 979 // (2) If orig_obj has not been seen yet (since start_recording_subgraph() was called),
 980 //     trace all  objects that are reachable from it, and make sure these objects are archived.
 981 // (3) Record the klasses of all orig_obj and all reachable objects.
 982 oop HeapShared::archive_reachable_objects_from(int level,
 983                                                KlassSubGraphInfo* subgraph_info,
 984                                                oop orig_obj,
 985                                                bool is_closed_archive) {
 986   assert(orig_obj != NULL, "must be");
 987   assert(!is_archived_object_during_dumptime(orig_obj), "sanity");
 988 
 989   if (!JavaClasses::is_supported_for_archiving(orig_obj)) {
 990     // This object has injected fields that cannot be supported easily, so we disallow them for now.
 991     // If you get an error here, you probably made a change in the JDK library that has added
 992     // these objects that are referenced (directly or indirectly) by static fields.
 993     ResourceMark rm;
 994     log_error(cds, heap)("Cannot archive object of class %s", orig_obj->klass()->external_name());
 995     vm_direct_exit(1);
 996   }
 997 
 998   // java.lang.Class instances cannot be included in an archived object sub-graph. We only support
 999   // them as Klass::_archived_mirror because they need to be specially restored at run time.
1000   //
1001   // If you get an error here, you probably made a change in the JDK library that has added a Class
1002   // object that is referenced (directly or indirectly) by static fields.
1003   if (java_lang_Class::is_instance(orig_obj)) {
1004     log_error(cds, heap)("(%d) Unknown java.lang.Class object is in the archived sub-graph", level);
1005     vm_direct_exit(1);
1006   }
1007 
1008   oop archived_obj = find_archived_heap_object(orig_obj);
1009   if (java_lang_String::is_instance(orig_obj) && archived_obj != NULL) {
1010     // To save time, don't walk strings that are already archived. They just contain
1011     // pointers to a type array, whose klass doesn't need to be recorded.
1012     return archived_obj;
1013   }
1014 
1015   if (has_been_seen_during_subgraph_recording(orig_obj)) {
1016     // orig_obj has already been archived and traced. Nothing more to do.
1017     return archived_obj;
1018   } else {
1019     set_has_been_seen_during_subgraph_recording(orig_obj);
1020   }
1021 
1022   bool record_klasses_only = (archived_obj != NULL);
1023   if (archived_obj == NULL) {
1024     ++_num_new_archived_objs;
1025     archived_obj = archive_object(orig_obj);
1026     if (archived_obj == NULL) {
1027       // Skip archiving the sub-graph referenced from the current entry field.
1028       ResourceMark rm;
1029       log_error(cds, heap)(
1030         "Cannot archive the sub-graph referenced from %s object ("
1031         PTR_FORMAT ") size %d, skipped.",
1032         orig_obj->klass()->external_name(), p2i(orig_obj), orig_obj->size() * HeapWordSize);
1033       if (level == 1) {
1034         // Don't archive a subgraph root that's too big. For archives static fields, that's OK
1035         // as the Java code will take care of initializing this field dynamically.
1036         return NULL;
1037       } else {
1038         // We don't know how to handle an object that has been archived, but some of its reachable
1039         // objects cannot be archived. Bail out for now. We might need to fix this in the future if
1040         // we have a real use case.
1041         vm_direct_exit(1);
1042       }
1043     }
1044 
1045     if (java_lang_Module::is_instance(orig_obj)) {
1046       check_module_oop(orig_obj);
1047       java_lang_Module::set_module_entry(archived_obj, NULL);
1048       java_lang_Module::set_loader(archived_obj, NULL);
1049     } else if (java_lang_ClassLoader::is_instance(orig_obj)) {
1050       // class_data will be restored explicitly at run time.
1051       guarantee(orig_obj == SystemDictionary::java_platform_loader() ||
1052                 orig_obj == SystemDictionary::java_system_loader() ||
1053                 java_lang_ClassLoader::loader_data(orig_obj) == NULL, "must be");
1054       java_lang_ClassLoader::release_set_loader_data(archived_obj, NULL);
1055     }
1056   }
1057 
1058   assert(archived_obj != NULL, "must be");
1059   Klass *orig_k = orig_obj->klass();
1060   subgraph_info->add_subgraph_object_klass(orig_k);
1061 
1062   WalkOopAndArchiveClosure walker(level, is_closed_archive, record_klasses_only,
1063                                   subgraph_info, orig_obj, archived_obj);
1064   orig_obj->oop_iterate(&walker);
1065   if (is_closed_archive && orig_k->is_instance_klass()) {
1066     check_closed_region_object(InstanceKlass::cast(orig_k));
1067   }
1068   return archived_obj;
1069 }
1070 
1071 //
1072 // Start from the given static field in a java mirror and archive the
1073 // complete sub-graph of java heap objects that are reached directly
1074 // or indirectly from the starting object by following references.
1075 // Sub-graph archiving restrictions (current):
1076 //
1077 // - All classes of objects in the archived sub-graph (including the
1078 //   entry class) must be boot class only.
1079 // - No java.lang.Class instance (java mirror) can be included inside
1080 //   an archived sub-graph. Mirror can only be the sub-graph entry object.
1081 //
1082 // The Java heap object sub-graph archiving process (see
1083 // WalkOopAndArchiveClosure):
1084 //
1085 // 1) Java object sub-graph archiving starts from a given static field
1086 // within a Class instance (java mirror). If the static field is a
1087 // refererence field and points to a non-null java object, proceed to
1088 // the next step.
1089 //
1090 // 2) Archives the referenced java object. If an archived copy of the
1091 // current object already exists, updates the pointer in the archived
1092 // copy of the referencing object to point to the current archived object.
1093 // Otherwise, proceed to the next step.
1094 //
1095 // 3) Follows all references within the current java object and recursively
1096 // archive the sub-graph of objects starting from each reference.
1097 //
1098 // 4) Updates the pointer in the archived copy of referencing object to
1099 // point to the current archived object.
1100 //
1101 // 5) The Klass of the current java object is added to the list of Klasses
1102 // for loading and initialzing before any object in the archived graph can
1103 // be accessed at runtime.
1104 //
1105 void HeapShared::archive_reachable_objects_from_static_field(InstanceKlass *k,
1106                                                              const char* klass_name,
1107                                                              int field_offset,
1108                                                              const char* field_name,
1109                                                              bool is_closed_archive) {
1110   assert(DumpSharedSpaces, "dump time only");
1111   assert(k->is_shared_boot_class(), "must be boot class");
1112 
1113   oop m = k->java_mirror();
1114 
1115   KlassSubGraphInfo* subgraph_info = get_subgraph_info(k);
1116   oop f = m->obj_field(field_offset);
1117 
1118   log_debug(cds, heap)("Start archiving from: %s::%s (" PTR_FORMAT ")", klass_name, field_name, p2i(f));
1119 
1120   if (!CompressedOops::is_null(f)) {
1121     if (log_is_enabled(Trace, cds, heap)) {
1122       LogTarget(Trace, cds, heap) log;
1123       LogStream out(log);
1124       f->print_on(&out);
1125     }
1126 
1127     oop af = archive_reachable_objects_from(1, subgraph_info, f, is_closed_archive);
1128 
1129     if (af == NULL) {
1130       log_error(cds, heap)("Archiving failed %s::%s (some reachable objects cannot be archived)",
1131                            klass_name, field_name);
1132     } else {
1133       // Note: the field value is not preserved in the archived mirror.
1134       // Record the field as a new subGraph entry point. The recorded
1135       // information is restored from the archive at runtime.
1136       subgraph_info->add_subgraph_entry_field(field_offset, af, is_closed_archive);
1137       log_info(cds, heap)("Archived field %s::%s => " PTR_FORMAT, klass_name, field_name, p2i(af));
1138     }
1139   } else {
1140     // The field contains null, we still need to record the entry point,
1141     // so it can be restored at runtime.
1142     subgraph_info->add_subgraph_entry_field(field_offset, NULL, false);
1143   }
1144 }
1145 
1146 #ifndef PRODUCT
1147 class VerifySharedOopClosure: public BasicOopIterateClosure {
1148  private:
1149   bool _is_archived;
1150 
1151  public:
1152   VerifySharedOopClosure(bool is_archived) : _is_archived(is_archived) {}
1153 
1154   void do_oop(narrowOop *p) { VerifySharedOopClosure::do_oop_work(p); }
1155   void do_oop(      oop *p) { VerifySharedOopClosure::do_oop_work(p); }
1156 
1157  protected:
1158   template <class T> void do_oop_work(T *p) {
1159     oop obj = RawAccess<>::oop_load(p);
1160     if (!CompressedOops::is_null(obj)) {
1161       HeapShared::verify_reachable_objects_from(obj, _is_archived);
1162     }
1163   }
1164 };
1165 
1166 void HeapShared::verify_subgraph_from_static_field(InstanceKlass* k, int field_offset) {
1167   assert(DumpSharedSpaces, "dump time only");
1168   assert(k->is_shared_boot_class(), "must be boot class");
1169 
1170   oop m = k->java_mirror();
1171   oop f = m->obj_field(field_offset);
1172   if (!CompressedOops::is_null(f)) {
1173     verify_subgraph_from(f);
1174   }
1175 }
1176 
1177 void HeapShared::verify_subgraph_from(oop orig_obj) {
1178   oop archived_obj = find_archived_heap_object(orig_obj);
1179   if (archived_obj == NULL) {
1180     // It's OK for the root of a subgraph to be not archived. See comments in
1181     // archive_reachable_objects_from().
1182     return;
1183   }
1184 
1185   // Verify that all objects reachable from orig_obj are archived.
1186   init_seen_objects_table();
1187   verify_reachable_objects_from(orig_obj, false);
1188   delete_seen_objects_table();
1189 
1190   // Note: we could also verify that all objects reachable from the archived
1191   // copy of orig_obj can only point to archived objects, with:
1192   //      init_seen_objects_table();
1193   //      verify_reachable_objects_from(archived_obj, true);
1194   //      init_seen_objects_table();
1195   // but that's already done in G1HeapVerifier::verify_archive_regions so we
1196   // won't do it here.
1197 }
1198 
1199 void HeapShared::verify_reachable_objects_from(oop obj, bool is_archived) {
1200   _num_total_verifications ++;
1201   if (!has_been_seen_during_subgraph_recording(obj)) {
1202     set_has_been_seen_during_subgraph_recording(obj);
1203 
1204     if (is_archived) {
1205       assert(is_archived_object_during_dumptime(obj), "must be");
1206       assert(find_archived_heap_object(obj) == NULL, "must be");
1207     } else {
1208       assert(!is_archived_object_during_dumptime(obj), "must be");
1209       assert(find_archived_heap_object(obj) != NULL, "must be");
1210     }
1211 
1212     VerifySharedOopClosure walker(is_archived);
1213     obj->oop_iterate(&walker);
1214   }
1215 }
1216 #endif
1217 
1218 HeapShared::SeenObjectsTable* HeapShared::_seen_objects_table = NULL;
1219 int HeapShared::_num_new_walked_objs;
1220 int HeapShared::_num_new_archived_objs;
1221 int HeapShared::_num_old_recorded_klasses;
1222 
1223 int HeapShared::_num_total_subgraph_recordings = 0;
1224 int HeapShared::_num_total_walked_objs = 0;
1225 int HeapShared::_num_total_archived_objs = 0;
1226 int HeapShared::_num_total_recorded_klasses = 0;
1227 int HeapShared::_num_total_verifications = 0;
1228 
1229 bool HeapShared::has_been_seen_during_subgraph_recording(oop obj) {
1230   return _seen_objects_table->get(obj) != NULL;
1231 }
1232 
1233 void HeapShared::set_has_been_seen_during_subgraph_recording(oop obj) {
1234   assert(!has_been_seen_during_subgraph_recording(obj), "sanity");
1235   _seen_objects_table->put(obj, true);
1236   ++ _num_new_walked_objs;
1237 }
1238 
1239 void HeapShared::start_recording_subgraph(InstanceKlass *k, const char* class_name, bool is_full_module_graph) {
1240   log_info(cds, heap)("Start recording subgraph(s) for archived fields in %s", class_name);
1241   init_subgraph_info(k, is_full_module_graph);
1242   init_seen_objects_table();
1243   _num_new_walked_objs = 0;
1244   _num_new_archived_objs = 0;
1245   _num_old_recorded_klasses = get_subgraph_info(k)->num_subgraph_object_klasses();
1246 }
1247 
1248 void HeapShared::done_recording_subgraph(InstanceKlass *k, const char* class_name) {
1249   int num_new_recorded_klasses = get_subgraph_info(k)->num_subgraph_object_klasses() -
1250     _num_old_recorded_klasses;
1251   log_info(cds, heap)("Done recording subgraph(s) for archived fields in %s: "
1252                       "walked %d objs, archived %d new objs, recorded %d classes",
1253                       class_name, _num_new_walked_objs, _num_new_archived_objs,
1254                       num_new_recorded_klasses);
1255 
1256   delete_seen_objects_table();
1257 
1258   _num_total_subgraph_recordings ++;
1259   _num_total_walked_objs      += _num_new_walked_objs;
1260   _num_total_archived_objs    += _num_new_archived_objs;
1261   _num_total_recorded_klasses +=  num_new_recorded_klasses;
1262 }
1263 
1264 class ArchivableStaticFieldFinder: public FieldClosure {
1265   InstanceKlass* _ik;
1266   Symbol* _field_name;
1267   bool _found;
1268   int _offset;
1269 public:
1270   ArchivableStaticFieldFinder(InstanceKlass* ik, Symbol* field_name) :
1271     _ik(ik), _field_name(field_name), _found(false), _offset(-1) {}
1272 
1273   virtual void do_field(fieldDescriptor* fd) {
1274     if (fd->name() == _field_name) {
1275       assert(!_found, "fields cannot be overloaded");
1276       assert(is_reference_type(fd->field_type()), "can archive only fields that are references");
1277       _found = true;
1278       _offset = fd->offset();
1279     }
1280   }
1281   bool found()     { return _found;  }
1282   int offset()     { return _offset; }
1283 };
1284 
1285 void HeapShared::init_subgraph_entry_fields(ArchivableStaticFieldInfo fields[],
1286                                             int num, TRAPS) {
1287   for (int i = 0; i < num; i++) {
1288     ArchivableStaticFieldInfo* info = &fields[i];
1289     TempNewSymbol klass_name =  SymbolTable::new_symbol(info->klass_name);
1290     TempNewSymbol field_name =  SymbolTable::new_symbol(info->field_name);
1291 
1292     Klass* k = SystemDictionary::resolve_or_fail(klass_name, true, CHECK);
1293     InstanceKlass* ik = InstanceKlass::cast(k);
1294     assert(InstanceKlass::cast(ik)->is_shared_boot_class(),
1295            "Only support boot classes");
1296     ik->initialize(CHECK);
1297 
1298     ArchivableStaticFieldFinder finder(ik, field_name);
1299     ik->do_local_static_fields(&finder);
1300     assert(finder.found(), "field must exist");
1301 
1302     info->klass = ik;
1303     info->offset = finder.offset();
1304   }
1305 }
1306 
1307 void HeapShared::init_subgraph_entry_fields(TRAPS) {
1308   assert(HeapShared::can_write(), "must be");
1309   _dump_time_subgraph_info_table = new (ResourceObj::C_HEAP, mtClass)DumpTimeKlassSubGraphInfoTable();
1310   init_subgraph_entry_fields(closed_archive_subgraph_entry_fields,
1311                              num_closed_archive_subgraph_entry_fields,
1312                              CHECK);
1313   init_subgraph_entry_fields(open_archive_subgraph_entry_fields,
1314                              num_open_archive_subgraph_entry_fields,
1315                              CHECK);
1316   if (MetaspaceShared::use_full_module_graph()) {
1317     init_subgraph_entry_fields(fmg_open_archive_subgraph_entry_fields,
1318                                num_fmg_open_archive_subgraph_entry_fields,
1319                                CHECK);
1320   }
1321 }
1322 
1323 void HeapShared::init_for_dumping(TRAPS) {
1324   if (HeapShared::can_write()) {
1325     _dumped_interned_strings = new (ResourceObj::C_HEAP, mtClass)DumpedInternedStrings();
1326     init_subgraph_entry_fields(CHECK);
1327   }
1328 }
1329 
1330 void HeapShared::archive_object_subgraphs(ArchivableStaticFieldInfo fields[],
1331                                           int num, bool is_closed_archive,
1332                                           bool is_full_module_graph) {
1333   _num_total_subgraph_recordings = 0;
1334   _num_total_walked_objs = 0;
1335   _num_total_archived_objs = 0;
1336   _num_total_recorded_klasses = 0;
1337   _num_total_verifications = 0;
1338 
1339   // For each class X that has one or more archived fields:
1340   // [1] Dump the subgraph of each archived field
1341   // [2] Create a list of all the class of the objects that can be reached
1342   //     by any of these static fields.
1343   //     At runtime, these classes are initialized before X's archived fields
1344   //     are restored by HeapShared::initialize_from_archived_subgraph().
1345   int i;
1346   for (i = 0; i < num; ) {
1347     ArchivableStaticFieldInfo* info = &fields[i];
1348     const char* klass_name = info->klass_name;
1349     start_recording_subgraph(info->klass, klass_name, is_full_module_graph);
1350 
1351     // If you have specified consecutive fields of the same klass in
1352     // fields[], these will be archived in the same
1353     // {start_recording_subgraph ... done_recording_subgraph} pass to
1354     // save time.
1355     for (; i < num; i++) {
1356       ArchivableStaticFieldInfo* f = &fields[i];
1357       if (f->klass_name != klass_name) {
1358         break;
1359       }
1360 
1361       archive_reachable_objects_from_static_field(f->klass, f->klass_name,
1362                                                   f->offset, f->field_name,
1363                                                   is_closed_archive);
1364     }
1365     done_recording_subgraph(info->klass, klass_name);
1366   }
1367 
1368   log_info(cds, heap)("Archived subgraph records in %s archive heap region = %d",
1369                       is_closed_archive ? "closed" : "open",
1370                       _num_total_subgraph_recordings);
1371   log_info(cds, heap)("  Walked %d objects", _num_total_walked_objs);
1372   log_info(cds, heap)("  Archived %d objects", _num_total_archived_objs);
1373   log_info(cds, heap)("  Recorded %d klasses", _num_total_recorded_klasses);
1374 
1375 #ifndef PRODUCT
1376   for (int i = 0; i < num; i++) {
1377     ArchivableStaticFieldInfo* f = &fields[i];
1378     verify_subgraph_from_static_field(f->klass, f->offset);
1379   }
1380   log_info(cds, heap)("  Verified %d references", _num_total_verifications);
1381 #endif
1382 }
1383 
1384 // Not all the strings in the global StringTable are dumped into the archive, because
1385 // some of those strings may be only referenced by classes that are excluded from
1386 // the archive. We need to explicitly mark the strings that are:
1387 //   [1] used by classes that WILL be archived;
1388 //   [2] included in the SharedArchiveConfigFile.
1389 void HeapShared::add_to_dumped_interned_strings(oop string) {
1390   assert_at_safepoint(); // DumpedInternedStrings uses raw oops
1391   bool created;
1392   _dumped_interned_strings->put_if_absent(string, true, &created);
1393 }
1394 
1395 // At dump-time, find the location of all the non-null oop pointers in an archived heap
1396 // region. This way we can quickly relocate all the pointers without using
1397 // BasicOopIterateClosure at runtime.
1398 class FindEmbeddedNonNullPointers: public BasicOopIterateClosure {
1399   narrowOop* _start;
1400   BitMap *_oopmap;
1401   int _num_total_oops;
1402   int _num_null_oops;
1403  public:
1404   FindEmbeddedNonNullPointers(narrowOop* start, BitMap* oopmap)
1405     : _start(start), _oopmap(oopmap), _num_total_oops(0),  _num_null_oops(0) {}
1406 
1407   virtual void do_oop(narrowOop* p) {
1408     _num_total_oops ++;
1409     narrowOop v = *p;
1410     if (!CompressedOops::is_null(v)) {
1411       size_t idx = p - _start;
1412       _oopmap->set_bit(idx);
1413     } else {
1414       _num_null_oops ++;
1415     }
1416   }
1417   virtual void do_oop(oop *p) {
1418     ShouldNotReachHere();
1419   }
1420   int num_total_oops() const { return _num_total_oops; }
1421   int num_null_oops()  const { return _num_null_oops; }
1422 };
1423 
1424 ResourceBitMap HeapShared::calculate_oopmap(MemRegion region) {
1425   assert(UseCompressedOops, "must be");
1426   size_t num_bits = region.byte_size() / sizeof(narrowOop);
1427   ResourceBitMap oopmap(num_bits);
1428 
1429   HeapWord* p   = region.start();
1430   HeapWord* end = region.end();
1431   FindEmbeddedNonNullPointers finder((narrowOop*)p, &oopmap);
1432   ArchiveBuilder* builder = DumpSharedSpaces ? ArchiveBuilder::current() : NULL;
1433 
1434   int num_objs = 0;
1435   while (p < end) {
1436     oop o = cast_to_oop(p);
1437     o->oop_iterate(&finder);
1438     p += o->size();
1439     if (DumpSharedSpaces) {
1440       builder->relocate_klass_ptr(o);
1441     }
1442     ++ num_objs;
1443   }
1444 
1445   log_info(cds, heap)("calculate_oopmap: objects = %6d, embedded oops = %7d, nulls = %7d",
1446                       num_objs, finder.num_total_oops(), finder.num_null_oops());
1447   return oopmap;
1448 }
1449 
1450 // Patch all the embedded oop pointers inside an archived heap region,
1451 // to be consistent with the runtime oop encoding.
1452 class PatchEmbeddedPointers: public BitMapClosure {
1453   narrowOop* _start;
1454 
1455  public:
1456   PatchEmbeddedPointers(narrowOop* start) : _start(start) {}
1457 
1458   bool do_bit(size_t offset) {
1459     narrowOop* p = _start + offset;
1460     narrowOop v = *p;
1461     assert(!CompressedOops::is_null(v), "null oops should have been filtered out at dump time");
1462     oop o = HeapShared::decode_from_archive(v);
1463     RawAccess<IS_NOT_NULL>::oop_store(p, o);
1464     return true;
1465   }
1466 };
1467 
1468 // Patch all the non-null pointers that are embedded in the archived heap objects
1469 // in this region
1470 void HeapShared::patch_embedded_pointers(MemRegion region, address oopmap,
1471                                          size_t oopmap_size_in_bits) {
1472   BitMapView bm((BitMap::bm_word_t*)oopmap, oopmap_size_in_bits);
1473 
1474 #ifndef PRODUCT
1475   ResourceMark rm;
1476   ResourceBitMap checkBm = calculate_oopmap(region);
1477   assert(bm.is_same(checkBm), "sanity");
1478 #endif
1479 
1480   PatchEmbeddedPointers patcher((narrowOop*)region.start());
1481   bm.iterate(&patcher);
1482 }
1483 
1484 // The CDS archive remembers each heap object by its address at dump time, but
1485 // the heap object may be loaded at a different address at run time. This structure is used
1486 // to translate the dump time addresses for all objects in FileMapInfo::space_at(region_index)
1487 // to their runtime addresses.
1488 struct LoadedArchiveHeapRegion {
1489   int       _region_index;   // index for FileMapInfo::space_at(index)
1490   size_t    _region_size;    // number of bytes in this region
1491   uintptr_t _dumptime_base;  // The dump-time (decoded) address of the first object in this region
1492   intx      _runtime_offset; // If an object's dump time address P is within in this region, its
1493                              // runtime address is P + _runtime_offset
1494 
1495   static int comparator(const void* a, const void* b) {
1496     LoadedArchiveHeapRegion* reg_a = (LoadedArchiveHeapRegion*)a;
1497     LoadedArchiveHeapRegion* reg_b = (LoadedArchiveHeapRegion*)b;
1498     if (reg_a->_dumptime_base < reg_b->_dumptime_base) {
1499       return -1;
1500     } else if (reg_a->_dumptime_base == reg_b->_dumptime_base) {
1501       return 0;
1502     } else {
1503       return 1;
1504     }
1505   }
1506 
1507   uintptr_t top() {
1508     return _dumptime_base + _region_size;
1509   }
1510 };
1511 
1512 void HeapShared::init_loaded_heap_relocation(LoadedArchiveHeapRegion* loaded_regions,
1513                                              int num_loaded_regions) {
1514   _dumptime_base_0 = loaded_regions[0]._dumptime_base;
1515   _dumptime_base_1 = loaded_regions[1]._dumptime_base;
1516   _dumptime_base_2 = loaded_regions[2]._dumptime_base;
1517   _dumptime_base_3 = loaded_regions[3]._dumptime_base;
1518   _dumptime_top = loaded_regions[num_loaded_regions-1].top();
1519 
1520   _runtime_offset_0 = loaded_regions[0]._runtime_offset;
1521   _runtime_offset_1 = loaded_regions[1]._runtime_offset;
1522   _runtime_offset_2 = loaded_regions[2]._runtime_offset;
1523   _runtime_offset_3 = loaded_regions[3]._runtime_offset;
1524 
1525   assert(2 <= num_loaded_regions && num_loaded_regions <= 4, "must be");
1526   if (num_loaded_regions < 4) {
1527     _dumptime_base_3 = UINTPTR_MAX;
1528   }
1529   if (num_loaded_regions < 3) {
1530     _dumptime_base_2 = UINTPTR_MAX;
1531   }
1532 }
1533 
1534 bool HeapShared::can_load() {
1535   return Universe::heap()->can_load_archived_objects();
1536 }
1537 
1538 template <int NUM_LOADED_REGIONS>
1539 class PatchLoadedRegionPointers: public BitMapClosure {
1540   narrowOop* _start;
1541   intx _offset_0;
1542   intx _offset_1;
1543   intx _offset_2;
1544   intx _offset_3;
1545   uintptr_t _base_0;
1546   uintptr_t _base_1;
1547   uintptr_t _base_2;
1548   uintptr_t _base_3;
1549   uintptr_t _top;
1550 
1551   static_assert(MetaspaceShared::max_num_heap_regions == 4, "can't handle more than 4 regions");
1552   static_assert(NUM_LOADED_REGIONS >= 2, "we have at least 2 loaded regions");
1553   static_assert(NUM_LOADED_REGIONS <= 4, "we have at most 4 loaded regions");
1554 
1555  public:
1556   PatchLoadedRegionPointers(narrowOop* start, LoadedArchiveHeapRegion* loaded_regions)
1557     : _start(start),
1558       _offset_0(loaded_regions[0]._runtime_offset),
1559       _offset_1(loaded_regions[1]._runtime_offset),
1560       _offset_2(loaded_regions[2]._runtime_offset),
1561       _offset_3(loaded_regions[3]._runtime_offset),
1562       _base_0(loaded_regions[0]._dumptime_base),
1563       _base_1(loaded_regions[1]._dumptime_base),
1564       _base_2(loaded_regions[2]._dumptime_base),
1565       _base_3(loaded_regions[3]._dumptime_base) {
1566     _top = loaded_regions[NUM_LOADED_REGIONS-1].top();
1567   }
1568 
1569   bool do_bit(size_t offset) {
1570     narrowOop* p = _start + offset;
1571     narrowOop v = *p;
1572     assert(!CompressedOops::is_null(v), "null oops should have been filtered out at dump time");
1573     uintptr_t o = cast_from_oop<uintptr_t>(HeapShared::decode_from_archive(v));
1574     assert(_base_0 <= o && o < _top, "must be");
1575 
1576 
1577     // We usually have only 2 regions for the default archive. Use template to avoid unnecessary comparisons.
1578     if (NUM_LOADED_REGIONS > 3 && o >= _base_3) {
1579       o += _offset_3;
1580     } else if (NUM_LOADED_REGIONS > 2 && o >= _base_2) {
1581       o += _offset_2;
1582     } else if (o >= _base_1) {
1583       o += _offset_1;
1584     } else {
1585       o += _offset_0;
1586     }
1587     HeapShared::assert_in_loaded_heap(o);
1588     RawAccess<IS_NOT_NULL>::oop_store(p, cast_to_oop(o));
1589     return true;
1590   }
1591 };
1592 
1593 int HeapShared::init_loaded_regions(FileMapInfo* mapinfo, LoadedArchiveHeapRegion* loaded_regions,
1594                                     MemRegion& archive_space) {
1595   size_t total_bytes = 0;
1596   int num_loaded_regions = 0;
1597   for (int i = MetaspaceShared::first_archive_heap_region;
1598        i <= MetaspaceShared::last_archive_heap_region; i++) {
1599     FileMapRegion* r = mapinfo->space_at(i);
1600     r->assert_is_heap_region();
1601     if (r->used() > 0) {
1602       assert(is_aligned(r->used(), HeapWordSize), "must be");
1603       total_bytes += r->used();
1604       LoadedArchiveHeapRegion* ri = &loaded_regions[num_loaded_regions++];
1605       ri->_region_index = i;
1606       ri->_region_size = r->used();
1607       ri->_dumptime_base = (uintptr_t)mapinfo->start_address_as_decoded_from_archive(r);
1608     }
1609   }
1610 
1611   assert(is_aligned(total_bytes, HeapWordSize), "must be");
1612   size_t word_size = total_bytes / HeapWordSize;
1613   HeapWord* buffer = Universe::heap()->allocate_loaded_archive_space(word_size);
1614   if (buffer == nullptr) {
1615     return 0;
1616   }
1617 
1618   archive_space = MemRegion(buffer, word_size);
1619   _loaded_heap_bottom = (uintptr_t)archive_space.start();
1620   _loaded_heap_top    = _loaded_heap_bottom + total_bytes;
1621 
1622   return num_loaded_regions;
1623 }
1624 
1625 void HeapShared::sort_loaded_regions(LoadedArchiveHeapRegion* loaded_regions, int num_loaded_regions,
1626                                      uintptr_t buffer) {
1627   // Find the relocation offset of the pointers in each region
1628   qsort(loaded_regions, num_loaded_regions, sizeof(LoadedArchiveHeapRegion),
1629         LoadedArchiveHeapRegion::comparator);
1630 
1631   uintptr_t p = buffer;
1632   for (int i = 0; i < num_loaded_regions; i++) {
1633     // This region will be loaded at p, so all objects inside this
1634     // region will be shifted by ri->offset
1635     LoadedArchiveHeapRegion* ri = &loaded_regions[i];
1636     ri->_runtime_offset = p - ri->_dumptime_base;
1637     p += ri->_region_size;
1638   }
1639   assert(p == _loaded_heap_top, "must be");
1640 }
1641 
1642 bool HeapShared::load_regions(FileMapInfo* mapinfo, LoadedArchiveHeapRegion* loaded_regions,
1643                               int num_loaded_regions, uintptr_t buffer) {
1644   uintptr_t bitmap_base = (uintptr_t)mapinfo->map_bitmap_region();
1645   uintptr_t load_address = buffer;
1646   for (int i = 0; i < num_loaded_regions; i++) {
1647     LoadedArchiveHeapRegion* ri = &loaded_regions[i];
1648     FileMapRegion* r = mapinfo->space_at(ri->_region_index);
1649 
1650     if (!mapinfo->read_region(ri->_region_index, (char*)load_address, r->used(), /* do_commit = */ false)) {
1651       // There's no easy way to free the buffer, so we will fill it with zero later
1652       // in fill_failed_loaded_region(), and it will eventually be GC'ed.
1653       log_warning(cds)("Loading of heap region %d has failed. Archived objects are disabled", i);
1654       _loading_failed = true;
1655       return false;
1656     }
1657     log_info(cds)("Loaded heap    region #%d at base " INTPTR_FORMAT " top " INTPTR_FORMAT
1658                   " size " SIZE_FORMAT_W(6) " delta " INTX_FORMAT,
1659                   ri->_region_index, load_address, load_address + ri->_region_size,
1660                   ri->_region_size, ri->_runtime_offset);
1661 
1662     uintptr_t oopmap = bitmap_base + r->oopmap_offset();
1663     BitMapView bm((BitMap::bm_word_t*)oopmap, r->oopmap_size_in_bits());
1664 
1665     if (num_loaded_regions == 4) {
1666       PatchLoadedRegionPointers<4> patcher((narrowOop*)load_address, loaded_regions);
1667       bm.iterate(&patcher);
1668     } else if (num_loaded_regions == 3) {
1669       PatchLoadedRegionPointers<3> patcher((narrowOop*)load_address, loaded_regions);
1670       bm.iterate(&patcher);
1671     } else {
1672       assert(num_loaded_regions == 2, "must be");
1673       PatchLoadedRegionPointers<2> patcher((narrowOop*)load_address, loaded_regions);
1674       bm.iterate(&patcher);
1675     }
1676 
1677     load_address += r->used();
1678   }
1679 
1680   return true;
1681 }
1682 
1683 bool HeapShared::load_heap_regions(FileMapInfo* mapinfo) {
1684   init_narrow_oop_decoding(mapinfo->narrow_oop_base(), mapinfo->narrow_oop_shift());
1685 
1686   LoadedArchiveHeapRegion loaded_regions[MetaspaceShared::max_num_heap_regions];
1687   memset(loaded_regions, 0, sizeof(loaded_regions));
1688 
1689   MemRegion archive_space;
1690   int num_loaded_regions = init_loaded_regions(mapinfo, loaded_regions, archive_space);
1691   if (num_loaded_regions <= 0) {
1692     return false;
1693   }
1694   sort_loaded_regions(loaded_regions, num_loaded_regions, (uintptr_t)archive_space.start());
1695   if (!load_regions(mapinfo, loaded_regions, num_loaded_regions, (uintptr_t)archive_space.start())) {
1696     assert(_loading_failed, "must be");
1697     return false;
1698   }
1699 
1700   init_loaded_heap_relocation(loaded_regions, num_loaded_regions);
1701   _is_loaded = true;
1702   set_roots(mapinfo->heap_obj_roots());
1703 
1704   return true;
1705 }
1706 
1707 class VerifyLoadedHeapEmbeddedPointers: public BasicOopIterateClosure {
1708   ResourceHashtable<uintptr_t, bool>* _table;
1709 
1710  public:
1711   VerifyLoadedHeapEmbeddedPointers(ResourceHashtable<uintptr_t, bool>* table) : _table(table) {}
1712 
1713   virtual void do_oop(narrowOop* p) {
1714     // This should be called before the loaded regions are modified, so all the embedded pointers
1715     // must be NULL, or must point to a valid object in the loaded regions.
1716     narrowOop v = *p;
1717     if (!CompressedOops::is_null(v)) {
1718       oop o = CompressedOops::decode_not_null(v);
1719       uintptr_t u = cast_from_oop<uintptr_t>(o);
1720       HeapShared::assert_in_loaded_heap(u);
1721       guarantee(_table->contains(u), "must point to beginning of object in loaded archived regions");
1722     }
1723   }
1724   virtual void do_oop(oop* p) {
1725     ShouldNotReachHere();
1726   }
1727 };
1728 
1729 void HeapShared::finish_initialization() {
1730   if (is_loaded()) {
1731     HeapWord* bottom = (HeapWord*)_loaded_heap_bottom;
1732     HeapWord* top    = (HeapWord*)_loaded_heap_top;
1733 
1734     MemRegion archive_space = MemRegion(bottom, top);
1735     Universe::heap()->complete_loaded_archive_space(archive_space);
1736   }
1737 
1738   if (VerifyArchivedFields <= 0 || !is_loaded()) {
1739     return;
1740   }
1741 
1742   log_info(cds, heap)("Verify all oops and pointers in loaded heap");
1743 
1744   ResourceMark rm;
1745   ResourceHashtable<uintptr_t, bool> table;
1746   VerifyLoadedHeapEmbeddedPointers verifier(&table);
1747   HeapWord* bottom = (HeapWord*)_loaded_heap_bottom;
1748   HeapWord* top    = (HeapWord*)_loaded_heap_top;
1749 
1750   for (HeapWord* p = bottom; p < top; ) {
1751     oop o = cast_to_oop(p);
1752     table.put(cast_from_oop<uintptr_t>(o), true);
1753     p += o->size();
1754   }
1755 
1756   for (HeapWord* p = bottom; p < top; ) {
1757     oop o = cast_to_oop(p);
1758     o->oop_iterate(&verifier);
1759     p += o->size();
1760   }
1761 }
1762 
1763 void HeapShared::fill_failed_loaded_region() {
1764   assert(_loading_failed, "must be");
1765   if (_loaded_heap_bottom != 0) {
1766     assert(_loaded_heap_top != 0, "must be");
1767     HeapWord* bottom = (HeapWord*)_loaded_heap_bottom;
1768     HeapWord* top = (HeapWord*)_loaded_heap_top;
1769     Universe::heap()->fill_with_objects(bottom, top - bottom);
1770   }
1771 }
1772 
1773 #endif // INCLUDE_CDS_JAVA_HEAP