1 /*
   2  * Copyright (c) 2018, 2020, 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 "classfile/classLoaderData.hpp"
  27 #include "classfile/classLoaderDataShared.hpp"
  28 #include "classfile/javaClasses.inline.hpp"
  29 #include "classfile/moduleEntry.hpp"
  30 #include "classfile/stringTable.hpp"
  31 #include "classfile/symbolTable.hpp"
  32 #include "classfile/systemDictionary.hpp"
  33 #include "classfile/systemDictionaryShared.hpp"
  34 #include "classfile/vmSymbols.hpp"
  35 #include "gc/shared/gcLocker.hpp"
  36 #include "logging/log.hpp"
  37 #include "logging/logMessage.hpp"
  38 #include "logging/logStream.hpp"
  39 #include "memory/archiveUtils.hpp"
  40 #include "memory/filemap.hpp"
  41 #include "memory/heapShared.inline.hpp"
  42 #include "memory/iterator.inline.hpp"
  43 #include "memory/metadataFactory.hpp"
  44 #include "memory/metaspaceClosure.hpp"
  45 #include "memory/metaspaceShared.hpp"
  46 #include "memory/resourceArea.hpp"
  47 #include "memory/universe.hpp"
  48 #include "oops/compressedOops.inline.hpp"
  49 #include "oops/fieldStreams.inline.hpp"
  50 #include "oops/oop.inline.hpp"
  51 #include "runtime/fieldDescriptor.inline.hpp"
  52 #include "runtime/javaCalls.hpp"
  53 #include "runtime/safepointVerifiers.hpp"
  54 #include "utilities/bitMap.inline.hpp"
  55 #if INCLUDE_G1GC
  56 #include "gc/g1/g1CollectedHeap.hpp"
  57 #endif
  58 
  59 #if INCLUDE_CDS_JAVA_HEAP
  60 
  61 bool HeapShared::_closed_archive_heap_region_mapped = false;
  62 bool HeapShared::_open_archive_heap_region_mapped = false;
  63 bool HeapShared::_archive_heap_region_fixed = false;
  64 
  65 address   HeapShared::_narrow_oop_base;
  66 int       HeapShared::_narrow_oop_shift;
  67 
  68 //
  69 // If you add new entries to the following tables, you should know what you're doing!
  70 //
  71 
  72 // Entry fields for shareable subgraphs archived in the closed archive heap
  73 // region. Warning: Objects in the subgraphs should not have reference fields
  74 // assigned at runtime.
  75 static ArchivableStaticFieldInfo closed_archive_subgraph_entry_fields[] = {
  76   {"java/lang/Integer$IntegerCache",              0, "archivedCache"},
  77   {"java/lang/Long$LongCache",                    0, "archivedCache"},
  78   {"java/lang/Byte$ByteCache",                    0, "archivedCache"},
  79   {"java/lang/Short$ShortCache",                  0, "archivedCache"},
  80   {"java/lang/Character$CharacterCache",          0, "archivedCache"},
  81   {"java/util/jar/Attributes$Name",               0, "KNOWN_NAMES"},
  82   {"sun/util/locale/BaseLocale",                  0, "constantBaseLocales"},
  83 };
  84 // Entry fields for subgraphs archived in the open archive heap region.
  85 static ArchivableStaticFieldInfo open_archive_subgraph_entry_fields[] = {
  86   {"jdk/internal/loader/ArchivedClassLoaders",                    1, "archivedClassLoaders"},
  87   {"jdk/internal/module/ArchivedBootLayer",                       1, "archivedBootLayer"},
  88   {"jdk/internal/module/ArchivedModuleGraph",                     0, "archivedModuleGraph"},
  89   {"java/util/ImmutableCollections",                              0, "archivedObjects"},
  90   {"java/lang/Module$ArchivedData",                               1, "archivedData"},
  91   {"java/lang/module/Configuration",                              0, "EMPTY_CONFIGURATION"},
  92   {"jdk/internal/math/FDBigInteger",                              0, "archivedCaches"},
  93 };
  94 
  95 const static int num_closed_archive_subgraph_entry_fields =
  96   sizeof(closed_archive_subgraph_entry_fields) / sizeof(ArchivableStaticFieldInfo);
  97 const static int num_open_archive_subgraph_entry_fields =
  98   sizeof(open_archive_subgraph_entry_fields) / sizeof(ArchivableStaticFieldInfo);
  99 
 100 ////////////////////////////////////////////////////////////////
 101 //
 102 // Java heap object archiving support
 103 //
 104 ////////////////////////////////////////////////////////////////
 105 void HeapShared::fixup_mapped_heap_regions() {
 106   FileMapInfo *mapinfo = FileMapInfo::current_info();
 107   mapinfo->fixup_mapped_heap_regions();
 108   set_archive_heap_region_fixed();
 109   SystemDictionaryShared::update_archived_mirror_native_pointers();
 110 }
 111 
 112 unsigned HeapShared::oop_hash(oop const& p) {
 113   assert(!p->mark().has_bias_pattern(),
 114          "this object should never have been locked");  // so identity_hash won't safepoin
 115   unsigned hash = (unsigned)p->identity_hash();
 116   return hash;
 117 }
 118 
 119 static void reset_states(oop obj, TRAPS) {
 120   Handle h_obj(THREAD, obj);
 121   InstanceKlass* klass = InstanceKlass::cast(obj->klass());
 122   TempNewSymbol method_name = SymbolTable::new_symbol("resetArchivedStates");
 123   Symbol* method_sig = vmSymbols::void_method_signature();
 124 
 125   while (klass != NULL) {
 126     Method* method = klass->find_method(method_name, method_sig);
 127     if (method != NULL) {
 128       assert(method->is_private(), "must be");
 129       if (log_is_enabled(Debug, cds)) {
 130         ResourceMark rm(THREAD);
 131         log_debug(cds)("  calling %s", method->name_and_sig_as_C_string());
 132       }
 133       JavaValue result(T_VOID);
 134       JavaCalls::call_special(&result, h_obj, klass,
 135                               method_name, method_sig, CHECK);
 136     }
 137     klass = klass->java_super();
 138   }
 139 }
 140 
 141 void HeapShared::reset_archived_object_states(TRAPS) {
 142   assert(DumpSharedSpaces, "dump-time only");
 143   log_debug(cds)("Resetting platform loader");
 144   reset_states(SystemDictionary::java_platform_loader(), THREAD);
 145   log_debug(cds)("Resetting system loader");
 146   reset_states(SystemDictionary::java_system_loader(), THREAD);
 147 }
 148 
 149 HeapShared::ArchivedObjectCache* HeapShared::_archived_object_cache = NULL;
 150 oop HeapShared::find_archived_heap_object(oop obj) {
 151   assert(DumpSharedSpaces, "dump-time only");
 152   ArchivedObjectCache* cache = archived_object_cache();
 153   oop* p = cache->get(obj);
 154   if (p != NULL) {
 155     return *p;
 156   } else {
 157     return NULL;
 158   }
 159 }
 160 
 161 oop HeapShared::archive_heap_object(oop obj, Thread* THREAD) {
 162   assert(DumpSharedSpaces, "dump-time only");
 163 
 164   oop ao = find_archived_heap_object(obj);
 165   if (ao != NULL) {
 166     // already archived
 167     return ao;
 168   }
 169 
 170   int len = obj->size();
 171   if (G1CollectedHeap::heap()->is_archive_alloc_too_large(len)) {
 172     log_debug(cds, heap)("Cannot archive, object (" PTR_FORMAT ") is too large: " SIZE_FORMAT,
 173                          p2i(obj), (size_t)obj->size());
 174     return NULL;
 175   }
 176 
 177   // Pre-compute object identity hash at CDS dump time.
 178   obj->identity_hash();
 179 
 180   oop archived_oop = (oop)G1CollectedHeap::heap()->archive_mem_allocate(len);
 181   if (archived_oop != NULL) {
 182     Copy::aligned_disjoint_words(cast_from_oop<HeapWord*>(obj), cast_from_oop<HeapWord*>(archived_oop), len);
 183     MetaspaceShared::relocate_klass_ptr(archived_oop);
 184     // Clear age -- it might have been set if a GC happened during -Xshare:dump
 185     markWord mark = archived_oop->mark_raw();
 186     mark = mark.set_age(0);
 187     archived_oop->set_mark_raw(mark);
 188     ArchivedObjectCache* cache = archived_object_cache();
 189     cache->put(obj, archived_oop);
 190     log_debug(cds, heap)("Archived heap object " PTR_FORMAT " ==> " PTR_FORMAT,
 191                          p2i(obj), p2i(archived_oop));
 192   } else {
 193     log_error(cds, heap)(
 194       "Cannot allocate space for object " PTR_FORMAT " in archived heap region",
 195       p2i(obj));
 196     vm_exit(1);
 197   }
 198   return archived_oop;
 199 }
 200 
 201 oop HeapShared::materialize_archived_object(narrowOop v) {
 202   assert(archive_heap_region_fixed(),
 203          "must be called after archive heap regions are fixed");
 204   if (!CompressedOops::is_null(v)) {
 205     oop obj = HeapShared::decode_from_archive(v);
 206     return G1CollectedHeap::heap()->materialize_archived_object(obj);
 207   }
 208   return NULL;
 209 }
 210 
 211 void HeapShared::archive_klass_objects(Thread* THREAD) {
 212   GrowableArray<Klass*>* klasses = MetaspaceShared::collected_klasses();
 213   assert(klasses != NULL, "sanity");
 214   for (int i = 0; i < klasses->length(); i++) {
 215     Klass* k = klasses->at(i);
 216 
 217     // archive mirror object
 218     java_lang_Class::archive_mirror(k, CHECK);
 219 
 220     // archive the resolved_referenes array
 221     if (k->is_instance_klass()) {
 222       InstanceKlass* ik = InstanceKlass::cast(k);
 223       ik->constants()->archive_resolved_references(THREAD);
 224     }
 225   }
 226 }
 227 
 228 void HeapShared::run_full_gc_in_vm_thread() {
 229   if (is_heap_object_archiving_allowed()) {
 230     // Avoid fragmentation while archiving heap objects.
 231     // We do this inside a safepoint, so that no further allocation can happen after GC
 232     // has finished.
 233     if (GCLocker::is_active()) {
 234       // Just checking for safety ...
 235       // This should not happen during -Xshare:dump. If you see this, probably the Java core lib
 236       // has been modified such that JNI code is executed in some clean up threads after
 237       // we have finished class loading.
 238       log_warning(cds)("GC locker is held, unable to start extra compacting GC. This may produce suboptimal results.");
 239     } else {
 240       log_info(cds)("Run GC ...");
 241       Universe::heap()->collect_as_vm_thread(GCCause::_archive_time_gc);
 242       log_info(cds)("Run GC done");
 243     }
 244   }
 245 }
 246 
 247 void HeapShared::archive_java_heap_objects(GrowableArray<MemRegion> *closed,
 248                                            GrowableArray<MemRegion> *open) {
 249   if (!is_heap_object_archiving_allowed()) {
 250     log_info(cds)(
 251       "Archived java heap is not supported as UseG1GC, "
 252       "UseCompressedOops and UseCompressedClassPointers are required."
 253       "Current settings: UseG1GC=%s, UseCompressedOops=%s, UseCompressedClassPointers=%s.",
 254       BOOL_TO_STR(UseG1GC), BOOL_TO_STR(UseCompressedOops),
 255       BOOL_TO_STR(UseCompressedClassPointers));
 256     return;
 257   }
 258 
 259   G1HeapVerifier::verify_ready_for_archiving();
 260 
 261   {
 262     NoSafepointVerifier nsv;
 263 
 264     // Cache for recording where the archived objects are copied to
 265     create_archived_object_cache();
 266 
 267     log_info(cds)("Dumping objects to closed archive heap region ...");
 268     NOT_PRODUCT(StringTable::verify());
 269     copy_closed_archive_heap_objects(closed);
 270 
 271     log_info(cds)("Dumping objects to open archive heap region ...");
 272     copy_open_archive_heap_objects(open);
 273 
 274     ClassLoaderDataShared::init_archived_oops();
 275 
 276     destroy_archived_object_cache();
 277   }
 278 
 279   G1HeapVerifier::verify_archive_regions();
 280 }
 281 
 282 void HeapShared::copy_closed_archive_heap_objects(
 283                                     GrowableArray<MemRegion> * closed_archive) {
 284   assert(is_heap_object_archiving_allowed(), "Cannot archive java heap objects");
 285 
 286   Thread* THREAD = Thread::current();
 287   G1CollectedHeap::heap()->begin_archive_alloc_range();
 288 
 289   // Archive interned string objects
 290   StringTable::write_to_archive();
 291 
 292   archive_object_subgraphs(closed_archive_subgraph_entry_fields,
 293                            num_closed_archive_subgraph_entry_fields,
 294                            true /* is_closed_archive */, THREAD);
 295 
 296   G1CollectedHeap::heap()->end_archive_alloc_range(closed_archive,
 297                                                    os::vm_allocation_granularity());
 298 }
 299 
 300 void HeapShared::copy_open_archive_heap_objects(
 301                                     GrowableArray<MemRegion> * open_archive) {
 302   assert(is_heap_object_archiving_allowed(), "Cannot archive java heap objects");
 303 
 304   Thread* THREAD = Thread::current();
 305   G1CollectedHeap::heap()->begin_archive_alloc_range(true /* open */);
 306 
 307   java_lang_Class::archive_basic_type_mirrors(THREAD);
 308 
 309   archive_klass_objects(THREAD);
 310 
 311   archive_object_subgraphs(open_archive_subgraph_entry_fields,
 312                            num_open_archive_subgraph_entry_fields,
 313                            false /* is_closed_archive */,
 314                            THREAD);
 315 
 316   G1CollectedHeap::heap()->end_archive_alloc_range(open_archive,
 317                                                    os::vm_allocation_granularity());
 318 }
 319 
 320 void HeapShared::init_narrow_oop_decoding(address base, int shift) {
 321   _narrow_oop_base = base;
 322   _narrow_oop_shift = shift;
 323 }
 324 
 325 //
 326 // Subgraph archiving support
 327 //
 328 HeapShared::DumpTimeKlassSubGraphInfoTable* HeapShared::_dump_time_subgraph_info_table = NULL;
 329 HeapShared::RunTimeKlassSubGraphInfoTable   HeapShared::_run_time_subgraph_info_table;
 330 
 331 // Get the subgraph_info for Klass k. A new subgraph_info is created if
 332 // there is no existing one for k. The subgraph_info records the relocated
 333 // Klass* of the original k.
 334 KlassSubGraphInfo* HeapShared::get_subgraph_info(Klass* k) {
 335   assert(DumpSharedSpaces, "dump time only");
 336   Klass* relocated_k = MetaspaceShared::get_relocated_klass(k);
 337   KlassSubGraphInfo* info = _dump_time_subgraph_info_table->get(relocated_k);
 338   if (info == NULL) {
 339     _dump_time_subgraph_info_table->put(relocated_k, KlassSubGraphInfo(relocated_k));
 340     info = _dump_time_subgraph_info_table->get(relocated_k);
 341     ++ _dump_time_subgraph_info_table->_count;
 342   }
 343   return info;
 344 }
 345 
 346 // Add an entry field to the current KlassSubGraphInfo.
 347 void KlassSubGraphInfo::add_subgraph_entry_field(
 348       int static_field_offset, oop v, bool is_closed_archive) {
 349   assert(DumpSharedSpaces, "dump time only");
 350   if (_subgraph_entry_fields == NULL) {
 351     _subgraph_entry_fields =
 352       new(ResourceObj::C_HEAP, mtClass) GrowableArray<juint>(10, mtClass);
 353   }
 354   _subgraph_entry_fields->append((juint)static_field_offset);
 355   _subgraph_entry_fields->append(CompressedOops::encode(v));
 356   _subgraph_entry_fields->append(is_closed_archive ? 1 : 0);
 357 }
 358 
 359 // Add the Klass* for an object in the current KlassSubGraphInfo's subgraphs.
 360 // Only objects of boot classes can be included in sub-graph.
 361 void KlassSubGraphInfo::add_subgraph_object_klass(Klass* orig_k, Klass *relocated_k) {
 362   assert(DumpSharedSpaces, "dump time only");
 363   assert(relocated_k == MetaspaceShared::get_relocated_klass(orig_k),
 364          "must be the relocated Klass in the shared space");
 365 
 366   if (_subgraph_object_klasses == NULL) {
 367     _subgraph_object_klasses =
 368       new(ResourceObj::C_HEAP, mtClass) GrowableArray<Klass*>(50, mtClass);
 369   }
 370 
 371   assert(relocated_k->is_shared(), "must be a shared class");
 372 
 373   if (_k == relocated_k) {
 374     // Don't add the Klass containing the sub-graph to it's own klass
 375     // initialization list.
 376     return;
 377   }
 378 
 379   if (relocated_k->is_instance_klass()) {
 380     assert(InstanceKlass::cast(relocated_k)->is_shared_boot_class(),
 381           "must be boot class");
 382     // SystemDictionary::xxx_klass() are not updated, need to check
 383     // the original Klass*
 384     if (orig_k == SystemDictionary::String_klass() ||
 385         orig_k == SystemDictionary::Object_klass()) {
 386       // Initialized early during VM initialization. No need to be added
 387       // to the sub-graph object class list.
 388       return;
 389     }
 390   } else if (relocated_k->is_objArray_klass()) {
 391     Klass* abk = ObjArrayKlass::cast(relocated_k)->bottom_klass();
 392     if (abk->is_instance_klass()) {
 393       assert(InstanceKlass::cast(abk)->is_shared_boot_class(),
 394             "must be boot class");
 395     }
 396     if (relocated_k == Universe::objectArrayKlassObj()) {
 397       // Initialized early during Universe::genesis. No need to be added
 398       // to the list.
 399       return;
 400     }
 401   } else {
 402     assert(relocated_k->is_typeArray_klass(), "must be");
 403     // Primitive type arrays are created early during Universe::genesis.
 404     return;
 405   }
 406 
 407   if (log_is_enabled(Debug, cds, heap)) {
 408     if (!_subgraph_object_klasses->contains(relocated_k)) {
 409       ResourceMark rm;
 410       log_debug(cds, heap)("Adding klass %s", orig_k->external_name());
 411     }
 412   }
 413 
 414   _subgraph_object_klasses->append_if_missing(relocated_k);
 415 }
 416 
 417 // Initialize an archived subgraph_info_record from the given KlassSubGraphInfo.
 418 void ArchivedKlassSubGraphInfoRecord::init(KlassSubGraphInfo* info) {
 419   _k = info->klass();
 420   _entry_field_records = NULL;
 421   _subgraph_object_klasses = NULL;
 422 
 423   // populate the entry fields
 424   GrowableArray<juint>* entry_fields = info->subgraph_entry_fields();
 425   if (entry_fields != NULL) {
 426     int num_entry_fields = entry_fields->length();
 427     assert(num_entry_fields % 3 == 0, "sanity");
 428     _entry_field_records =
 429       MetaspaceShared::new_ro_array<juint>(num_entry_fields);
 430     for (int i = 0 ; i < num_entry_fields; i++) {
 431       _entry_field_records->at_put(i, entry_fields->at(i));
 432     }
 433   }
 434 
 435   // the Klasses of the objects in the sub-graphs
 436   GrowableArray<Klass*>* subgraph_object_klasses = info->subgraph_object_klasses();
 437   if (subgraph_object_klasses != NULL) {
 438     int num_subgraphs_klasses = subgraph_object_klasses->length();
 439     _subgraph_object_klasses =
 440       MetaspaceShared::new_ro_array<Klass*>(num_subgraphs_klasses);
 441     for (int i = 0; i < num_subgraphs_klasses; i++) {
 442       Klass* subgraph_k = subgraph_object_klasses->at(i);
 443       if (log_is_enabled(Info, cds, heap)) {
 444         ResourceMark rm;
 445         log_info(cds, heap)(
 446           "Archived object klass %s (%2d) => %s",
 447           _k->external_name(), i, subgraph_k->external_name());
 448       }
 449       _subgraph_object_klasses->at_put(i, subgraph_k);
 450       ArchivePtrMarker::mark_pointer(_subgraph_object_klasses->adr_at(i));
 451     }
 452   }
 453 
 454   ArchivePtrMarker::mark_pointer(&_k);
 455   ArchivePtrMarker::mark_pointer(&_entry_field_records);
 456   ArchivePtrMarker::mark_pointer(&_subgraph_object_klasses);
 457 }
 458 
 459 struct CopyKlassSubGraphInfoToArchive : StackObj {
 460   CompactHashtableWriter* _writer;
 461   CopyKlassSubGraphInfoToArchive(CompactHashtableWriter* writer) : _writer(writer) {}
 462 
 463   bool do_entry(Klass* klass, KlassSubGraphInfo& info) {
 464     if (info.subgraph_object_klasses() != NULL || info.subgraph_entry_fields() != NULL) {
 465       ArchivedKlassSubGraphInfoRecord* record =
 466         (ArchivedKlassSubGraphInfoRecord*)MetaspaceShared::read_only_space_alloc(sizeof(ArchivedKlassSubGraphInfoRecord));
 467       record->init(&info);
 468 
 469       unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary(klass);
 470       u4 delta = MetaspaceShared::object_delta_u4(record);
 471       _writer->add(hash, delta);
 472     }
 473     return true; // keep on iterating
 474   }
 475 };
 476 
 477 // Build the records of archived subgraph infos, which include:
 478 // - Entry points to all subgraphs from the containing class mirror. The entry
 479 //   points are static fields in the mirror. For each entry point, the field
 480 //   offset, value and is_closed_archive flag are recorded in the sub-graph
 481 //   info. The value is stored back to the corresponding field at runtime.
 482 // - A list of klasses that need to be loaded/initialized before archived
 483 //   java object sub-graph can be accessed at runtime.
 484 void HeapShared::write_subgraph_info_table() {
 485   // Allocate the contents of the hashtable(s) inside the RO region of the CDS archive.
 486   DumpTimeKlassSubGraphInfoTable* d_table = _dump_time_subgraph_info_table;
 487   CompactHashtableStats stats;
 488 
 489   _run_time_subgraph_info_table.reset();
 490 
 491   CompactHashtableWriter writer(d_table->_count, &stats);
 492   CopyKlassSubGraphInfoToArchive copy(&writer);
 493   d_table->iterate(&copy);
 494 
 495   writer.dump(&_run_time_subgraph_info_table, "subgraphs");
 496 }
 497 
 498 void HeapShared::serialize_subgraph_info_table_header(SerializeClosure* soc) {
 499   _run_time_subgraph_info_table.serialize_header(soc);
 500 }
 501 
 502 void HeapShared::initialize_from_archived_subgraph(Klass* k) {
 503   if (!open_archive_heap_region_mapped()) {
 504     return; // nothing to do
 505   }
 506   assert(!DumpSharedSpaces, "Should not be called with DumpSharedSpaces");
 507 
 508   if (!MetaspaceShared::use_full_module_graph()) {
 509     for (int i = 0; i < num_open_archive_subgraph_entry_fields; i++) {
 510       const ArchivableStaticFieldInfo* info = &open_archive_subgraph_entry_fields[i];
 511       if (info->full_module_graph_only && k->name()->equals(info->klass_name)) {
 512         return;
 513       }
 514     }
 515   }
 516 
 517   unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary(k);
 518   const ArchivedKlassSubGraphInfoRecord* record = _run_time_subgraph_info_table.lookup(k, hash, 0);
 519 
 520   // Initialize from archived data. Currently this is done only
 521   // during VM initialization time. No lock is needed.
 522   if (record != NULL) {
 523     Thread* THREAD = Thread::current();
 524 
 525     int i;
 526     // Load/link/initialize the klasses of the objects in the subgraph.
 527     // NULL class loader is used.
 528     Array<Klass*>* klasses = record->subgraph_object_klasses();
 529     if (klasses != NULL) {
 530       for (i = 0; i < klasses->length(); i++) {
 531         Klass* obj_k = klasses->at(i);
 532         Klass* resolved_k = SystemDictionary::resolve_or_null(
 533                                               (obj_k)->name(), THREAD);
 534         if (resolved_k != obj_k) {
 535           assert(!SystemDictionary::is_well_known_klass(resolved_k),
 536                  "shared well-known classes must not be replaced by JVMTI ClassFileLoadHook");
 537           ResourceMark rm(THREAD);
 538           log_info(cds, heap)("Failed to load subgraph because %s was not loaded from archive",
 539                               resolved_k->external_name());
 540           return;
 541         }
 542         if ((obj_k)->is_instance_klass()) {
 543           InstanceKlass* ik = InstanceKlass::cast(obj_k);
 544           ik->initialize(THREAD);
 545         } else if ((obj_k)->is_objArray_klass()) {
 546           ObjArrayKlass* oak = ObjArrayKlass::cast(obj_k);
 547           oak->initialize(THREAD);
 548         }
 549       }
 550     }
 551 
 552     if (HAS_PENDING_EXCEPTION) {
 553       CLEAR_PENDING_EXCEPTION;
 554       // None of the field value will be set if there was an exception.
 555       // The java code will not see any of the archived objects in the
 556       // subgraphs referenced from k in this case.
 557       return;
 558     }
 559 
 560     // Load the subgraph entry fields from the record and store them back to
 561     // the corresponding fields within the mirror.
 562     oop m = k->java_mirror();
 563     Array<juint>* entry_field_records = record->entry_field_records();
 564     if (entry_field_records != NULL) {
 565       int efr_len = entry_field_records->length();
 566       assert(efr_len % 3 == 0, "sanity");
 567       for (i = 0; i < efr_len;) {
 568         int field_offset = entry_field_records->at(i);
 569         narrowOop nv = entry_field_records->at(i+1);
 570         int is_closed_archive = entry_field_records->at(i+2);
 571         oop v;
 572         if (is_closed_archive == 0) {
 573           // It's an archived object in the open archive heap regions, not shared.
 574           // The object refereced by the field becomes 'known' by GC from this
 575           // point. All objects in the subgraph reachable from the object are
 576           // also 'known' by GC.
 577           v = materialize_archived_object(nv);
 578         } else {
 579           // Shared object in the closed archive heap regions. Decode directly.
 580           assert(!CompressedOops::is_null(nv), "shared object is null");
 581           v = HeapShared::decode_from_archive(nv);
 582         }
 583         m->obj_field_put(field_offset, v);
 584         i += 3;
 585 
 586         log_debug(cds, heap)("  " PTR_FORMAT " init field @ %2d = " PTR_FORMAT, p2i(k), field_offset, p2i(v));
 587       }
 588 
 589       // Done. Java code can see the archived sub-graphs referenced from k's
 590       // mirror after this point.
 591       if (log_is_enabled(Info, cds, heap)) {
 592         ResourceMark rm;
 593         log_info(cds, heap)("initialize_from_archived_subgraph %s " PTR_FORMAT,
 594                             k->external_name(), p2i(k));
 595       }
 596     }
 597   }
 598 }
 599 
 600 class WalkOopAndArchiveClosure: public BasicOopIterateClosure {
 601   int _level;
 602   bool _is_closed_archive;
 603   bool _record_klasses_only;
 604   KlassSubGraphInfo* _subgraph_info;
 605   oop _orig_referencing_obj;
 606   oop _archived_referencing_obj;
 607   Thread* _thread;
 608  public:
 609   WalkOopAndArchiveClosure(int level,
 610                            bool is_closed_archive,
 611                            bool record_klasses_only,
 612                            KlassSubGraphInfo* subgraph_info,
 613                            oop orig, oop archived, TRAPS) :
 614     _level(level), _is_closed_archive(is_closed_archive),
 615     _record_klasses_only(record_klasses_only),
 616     _subgraph_info(subgraph_info),
 617     _orig_referencing_obj(orig), _archived_referencing_obj(archived),
 618     _thread(THREAD) {}
 619   void do_oop(narrowOop *p) { WalkOopAndArchiveClosure::do_oop_work(p); }
 620   void do_oop(      oop *p) { WalkOopAndArchiveClosure::do_oop_work(p); }
 621 
 622  protected:
 623   template <class T> void do_oop_work(T *p) {
 624     oop obj = RawAccess<>::oop_load(p);
 625     if (!CompressedOops::is_null(obj)) {
 626       assert(!HeapShared::is_archived_object(obj),
 627              "original objects must not point to archived objects");
 628 
 629       size_t field_delta = pointer_delta(p, _orig_referencing_obj, sizeof(char));
 630       T* new_p = (T*)(cast_from_oop<address>(_archived_referencing_obj) + field_delta);
 631       Thread* THREAD = _thread;
 632 
 633       if (!_record_klasses_only && log_is_enabled(Debug, cds, heap)) {
 634         ResourceMark rm;
 635         log_debug(cds, heap)("(%d) %s[" SIZE_FORMAT "] ==> " PTR_FORMAT " size %d %s", _level,
 636                              _orig_referencing_obj->klass()->external_name(), field_delta,
 637                              p2i(obj), obj->size() * HeapWordSize, obj->klass()->external_name());
 638         LogTarget(Trace, cds, heap) log;
 639         LogStream out(log);
 640         obj->print_on(&out);
 641       }
 642 
 643       oop archived = HeapShared::archive_reachable_objects_from(
 644           _level + 1, _subgraph_info, obj, _is_closed_archive, THREAD);
 645       assert(archived != NULL, "VM should have exited with unarchivable objects for _level > 1");
 646       assert(HeapShared::is_archived_object(archived), "must be");
 647 
 648       if (!_record_klasses_only) {
 649         // Update the reference in the archived copy of the referencing object.
 650         log_debug(cds, heap)("(%d) updating oop @[" PTR_FORMAT "] " PTR_FORMAT " ==> " PTR_FORMAT,
 651                              _level, p2i(new_p), p2i(obj), p2i(archived));
 652         RawAccess<IS_NOT_NULL>::oop_store(new_p, archived);
 653       }
 654     }
 655   }
 656 };
 657 
 658 void HeapShared::check_closed_archive_heap_region_object(InstanceKlass* k,
 659                                                          Thread* THREAD) {
 660   // Check fields in the object
 661   for (JavaFieldStream fs(k); !fs.done(); fs.next()) {
 662     if (!fs.access_flags().is_static()) {
 663       BasicType ft = fs.field_descriptor().field_type();
 664       if (!fs.access_flags().is_final() && is_reference_type(ft)) {
 665         ResourceMark rm(THREAD);
 666         log_warning(cds, heap)(
 667           "Please check reference field in %s instance in closed archive heap region: %s %s",
 668           k->external_name(), (fs.name())->as_C_string(),
 669           (fs.signature())->as_C_string());
 670       }
 671     }
 672   }
 673 }
 674 
 675 void HeapShared::check_module_oop(oop orig_module_obj) {
 676   assert(DumpSharedSpaces, "must be");
 677   assert(java_lang_Module::is_instance(orig_module_obj), "must be");
 678   ModuleEntry* orig_module_ent = java_lang_Module::module_entry_raw(orig_module_obj);
 679   if (orig_module_ent == NULL) {
 680     // These special Module objects are created in Java code. They are not
 681     // defined via Modules::define_module(), so they don't have a ModuleEntry:
 682     //     java.lang.Module::ALL_UNNAMED_MODULE
 683     //     java.lang.Module::EVERYONE_MODULE
 684     //     jdk.internal.loader.ClassLoaders$BootClassLoader::unnamedModule
 685     assert(java_lang_Module::name(orig_module_obj) == NULL, "must be unnamed");
 686     log_info(cds, heap)("Module oop with No ModuleEntry* @[" PTR_FORMAT "]", p2i(orig_module_obj));
 687   } else {
 688     ClassLoaderData* loader_data = orig_module_ent->loader_data();
 689     assert(loader_data->is_builtin_class_loader_data(), "must be");
 690   }
 691 }
 692 
 693 
 694 // (1) If orig_obj has not been archived yet, archive it.
 695 // (2) If orig_obj has not been seen yet (since start_recording_subgraph() was called),
 696 //     trace all  objects that are reachable from it, and make sure these objects are archived.
 697 // (3) Record the klasses of all orig_obj and all reachable objects.
 698 oop HeapShared::archive_reachable_objects_from(int level,
 699                                                KlassSubGraphInfo* subgraph_info,
 700                                                oop orig_obj,
 701                                                bool is_closed_archive,
 702                                                TRAPS) {
 703   assert(orig_obj != NULL, "must be");
 704   assert(!is_archived_object(orig_obj), "sanity");
 705 
 706   if (!JavaClasses::is_supported_for_archiving(orig_obj)) {
 707     // This object has injected fields that cannot be supported easily, so we disallow them for now.
 708     // If you get an error here, you probably made a change in the JDK library that has added
 709     // these objects that are referenced (directly or indirectly) by static fields.
 710     ResourceMark rm;
 711     log_error(cds, heap)("Cannot archive object of class %s", orig_obj->klass()->external_name());
 712     vm_exit(1);
 713   }
 714 
 715   // java.lang.Class instances cannot be included in an archived object sub-graph. We only support
 716   // them as Klass::_archived_mirror because they need to be specially restored at run time.
 717   //
 718   // If you get an error here, you probably made a change in the JDK library that has added a Class
 719   // object that is referenced (directly or indirectly) by static fields.
 720   if (java_lang_Class::is_instance(orig_obj)) {
 721     log_error(cds, heap)("(%d) Unknown java.lang.Class object is in the archived sub-graph", level);
 722     vm_exit(1);
 723   }
 724 
 725   oop archived_obj = find_archived_heap_object(orig_obj);
 726   if (java_lang_String::is_instance(orig_obj) && archived_obj != NULL) {
 727     // To save time, don't walk strings that are already archived. They just contain
 728     // pointers to a type array, whose klass doesn't need to be recorded.
 729     return archived_obj;
 730   }
 731 
 732   if (has_been_seen_during_subgraph_recording(orig_obj)) {
 733     // orig_obj has already been archived and traced. Nothing more to do.
 734     return archived_obj;
 735   } else {
 736     set_has_been_seen_during_subgraph_recording(orig_obj);
 737   }
 738 
 739   bool record_klasses_only = (archived_obj != NULL);
 740   if (archived_obj == NULL) {
 741     ++_num_new_archived_objs;
 742     archived_obj = archive_heap_object(orig_obj, THREAD);
 743     if (archived_obj == NULL) {
 744       // Skip archiving the sub-graph referenced from the current entry field.
 745       ResourceMark rm;
 746       log_error(cds, heap)(
 747         "Cannot archive the sub-graph referenced from %s object ("
 748         PTR_FORMAT ") size %d, skipped.",
 749         orig_obj->klass()->external_name(), p2i(orig_obj), orig_obj->size() * HeapWordSize);
 750       if (level == 1) {
 751         // Don't archive a subgraph root that's too big. For archives static fields, that's OK
 752         // as the Java code will take care of initializing this field dynamically.
 753         return NULL;
 754       } else {
 755         // We don't know how to handle an object that has been archived, but some of its reachable
 756         // objects cannot be archived. Bail out for now. We might need to fix this in the future if
 757         // we have a real use case.
 758         vm_exit(1);
 759       }
 760     }
 761 
 762     if (java_lang_Module::is_instance(orig_obj)) {
 763       check_module_oop(orig_obj);
 764       java_lang_Module::set_module_entry(archived_obj, NULL);
 765       java_lang_Module::set_loader(archived_obj, NULL);
 766     } else if (java_lang_ClassLoader::is_instance(orig_obj)) {
 767       // class_data will be restored explicitly at run time. 
 768       guarantee(orig_obj == SystemDictionary::java_platform_loader() ||
 769                 orig_obj == SystemDictionary::java_system_loader() ||
 770                 java_lang_ClassLoader::loader_data_raw(orig_obj) == NULL, "must be");
 771       java_lang_ClassLoader::release_set_loader_data(archived_obj, NULL);
 772     }
 773   }
 774 
 775   assert(archived_obj != NULL, "must be");
 776   Klass *orig_k = orig_obj->klass();
 777   Klass *relocated_k = archived_obj->klass();
 778   subgraph_info->add_subgraph_object_klass(orig_k, relocated_k);
 779 
 780   WalkOopAndArchiveClosure walker(level, is_closed_archive, record_klasses_only,
 781                                   subgraph_info, orig_obj, archived_obj, THREAD);
 782   orig_obj->oop_iterate(&walker);
 783   if (is_closed_archive && orig_k->is_instance_klass()) {
 784     check_closed_archive_heap_region_object(InstanceKlass::cast(orig_k), THREAD);
 785   }
 786   return archived_obj;
 787 }
 788 
 789 //
 790 // Start from the given static field in a java mirror and archive the
 791 // complete sub-graph of java heap objects that are reached directly
 792 // or indirectly from the starting object by following references.
 793 // Sub-graph archiving restrictions (current):
 794 //
 795 // - All classes of objects in the archived sub-graph (including the
 796 //   entry class) must be boot class only.
 797 // - No java.lang.Class instance (java mirror) can be included inside
 798 //   an archived sub-graph. Mirror can only be the sub-graph entry object.
 799 //
 800 // The Java heap object sub-graph archiving process (see
 801 // WalkOopAndArchiveClosure):
 802 //
 803 // 1) Java object sub-graph archiving starts from a given static field
 804 // within a Class instance (java mirror). If the static field is a
 805 // refererence field and points to a non-null java object, proceed to
 806 // the next step.
 807 //
 808 // 2) Archives the referenced java object. If an archived copy of the
 809 // current object already exists, updates the pointer in the archived
 810 // copy of the referencing object to point to the current archived object.
 811 // Otherwise, proceed to the next step.
 812 //
 813 // 3) Follows all references within the current java object and recursively
 814 // archive the sub-graph of objects starting from each reference.
 815 //
 816 // 4) Updates the pointer in the archived copy of referencing object to
 817 // point to the current archived object.
 818 //
 819 // 5) The Klass of the current java object is added to the list of Klasses
 820 // for loading and initialzing before any object in the archived graph can
 821 // be accessed at runtime.
 822 //
 823 void HeapShared::archive_reachable_objects_from_static_field(InstanceKlass *k,
 824                                                              const char* klass_name,
 825                                                              int field_offset,
 826                                                              const char* field_name,
 827                                                              bool is_closed_archive,
 828                                                              TRAPS) {
 829   assert(DumpSharedSpaces, "dump time only");
 830   assert(k->is_shared_boot_class(), "must be boot class");
 831 
 832   oop m = k->java_mirror();
 833 
 834   KlassSubGraphInfo* subgraph_info = get_subgraph_info(k);
 835   oop f = m->obj_field(field_offset);
 836 
 837   log_debug(cds, heap)("Start archiving from: %s::%s (" PTR_FORMAT ")", klass_name, field_name, p2i(f));
 838 
 839   if (!CompressedOops::is_null(f)) {
 840     if (log_is_enabled(Trace, cds, heap)) {
 841       LogTarget(Trace, cds, heap) log;
 842       LogStream out(log);
 843       f->print_on(&out);
 844     }
 845 
 846     oop af = archive_reachable_objects_from(1, subgraph_info, f,
 847                                             is_closed_archive, CHECK);
 848 
 849     if (af == NULL) {
 850       log_error(cds, heap)("Archiving failed %s::%s (some reachable objects cannot be archived)",
 851                            klass_name, field_name);
 852     } else {
 853       // Note: the field value is not preserved in the archived mirror.
 854       // Record the field as a new subGraph entry point. The recorded
 855       // information is restored from the archive at runtime.
 856       subgraph_info->add_subgraph_entry_field(field_offset, af, is_closed_archive);
 857       log_info(cds, heap)("Archived field %s::%s => " PTR_FORMAT, klass_name, field_name, p2i(af));
 858     }
 859   } else {
 860     // The field contains null, we still need to record the entry point,
 861     // so it can be restored at runtime.
 862     subgraph_info->add_subgraph_entry_field(field_offset, NULL, false);
 863   }
 864 }
 865 
 866 #ifndef PRODUCT
 867 class VerifySharedOopClosure: public BasicOopIterateClosure {
 868  private:
 869   bool _is_archived;
 870 
 871  public:
 872   VerifySharedOopClosure(bool is_archived) : _is_archived(is_archived) {}
 873 
 874   void do_oop(narrowOop *p) { VerifySharedOopClosure::do_oop_work(p); }
 875   void do_oop(      oop *p) { VerifySharedOopClosure::do_oop_work(p); }
 876 
 877  protected:
 878   template <class T> void do_oop_work(T *p) {
 879     oop obj = RawAccess<>::oop_load(p);
 880     if (!CompressedOops::is_null(obj)) {
 881       HeapShared::verify_reachable_objects_from(obj, _is_archived);
 882     }
 883   }
 884 };
 885 
 886 void HeapShared::verify_subgraph_from_static_field(InstanceKlass* k, int field_offset) {
 887   assert(DumpSharedSpaces, "dump time only");
 888   assert(k->is_shared_boot_class(), "must be boot class");
 889 
 890   oop m = k->java_mirror();
 891   oop f = m->obj_field(field_offset);
 892   if (!CompressedOops::is_null(f)) {
 893     verify_subgraph_from(f);
 894   }
 895 }
 896 
 897 void HeapShared::verify_subgraph_from(oop orig_obj) {
 898   oop archived_obj = find_archived_heap_object(orig_obj);
 899   if (archived_obj == NULL) {
 900     // It's OK for the root of a subgraph to be not archived. See comments in
 901     // archive_reachable_objects_from().
 902     return;
 903   }
 904 
 905   // Verify that all objects reachable from orig_obj are archived.
 906   init_seen_objects_table();
 907   verify_reachable_objects_from(orig_obj, false);
 908   delete_seen_objects_table();
 909 
 910   // Note: we could also verify that all objects reachable from the archived
 911   // copy of orig_obj can only point to archived objects, with:
 912   //      init_seen_objects_table();
 913   //      verify_reachable_objects_from(archived_obj, true);
 914   //      init_seen_objects_table();
 915   // but that's already done in G1HeapVerifier::verify_archive_regions so we
 916   // won't do it here.
 917 }
 918 
 919 void HeapShared::verify_reachable_objects_from(oop obj, bool is_archived) {
 920   _num_total_verifications ++;
 921   if (!has_been_seen_during_subgraph_recording(obj)) {
 922     set_has_been_seen_during_subgraph_recording(obj);
 923 
 924     if (is_archived) {
 925       assert(is_archived_object(obj), "must be");
 926       assert(find_archived_heap_object(obj) == NULL, "must be");
 927     } else {
 928       assert(!is_archived_object(obj), "must be");
 929       assert(find_archived_heap_object(obj) != NULL, "must be");
 930     }
 931 
 932     VerifySharedOopClosure walker(is_archived);
 933     obj->oop_iterate(&walker);
 934   }
 935 }
 936 #endif
 937 
 938 HeapShared::SeenObjectsTable* HeapShared::_seen_objects_table = NULL;
 939 int HeapShared::_num_new_walked_objs;
 940 int HeapShared::_num_new_archived_objs;
 941 int HeapShared::_num_old_recorded_klasses;
 942 
 943 int HeapShared::_num_total_subgraph_recordings = 0;
 944 int HeapShared::_num_total_walked_objs = 0;
 945 int HeapShared::_num_total_archived_objs = 0;
 946 int HeapShared::_num_total_recorded_klasses = 0;
 947 int HeapShared::_num_total_verifications = 0;
 948 
 949 bool HeapShared::has_been_seen_during_subgraph_recording(oop obj) {
 950   return _seen_objects_table->get(obj) != NULL;
 951 }
 952 
 953 void HeapShared::set_has_been_seen_during_subgraph_recording(oop obj) {
 954   assert(!has_been_seen_during_subgraph_recording(obj), "sanity");
 955   _seen_objects_table->put(obj, true);
 956   ++ _num_new_walked_objs;
 957 }
 958 
 959 void HeapShared::start_recording_subgraph(InstanceKlass *k, const char* class_name) {
 960   log_info(cds, heap)("Start recording subgraph(s) for archived fields in %s", class_name);
 961   init_seen_objects_table();
 962   _num_new_walked_objs = 0;
 963   _num_new_archived_objs = 0;
 964   _num_old_recorded_klasses = get_subgraph_info(k)->num_subgraph_object_klasses();
 965 }
 966 
 967 void HeapShared::done_recording_subgraph(InstanceKlass *k, const char* class_name) {
 968   int num_new_recorded_klasses = get_subgraph_info(k)->num_subgraph_object_klasses() -
 969     _num_old_recorded_klasses;
 970   log_info(cds, heap)("Done recording subgraph(s) for archived fields in %s: "
 971                       "walked %d objs, archived %d new objs, recorded %d classes",
 972                       class_name, _num_new_walked_objs, _num_new_archived_objs,
 973                       num_new_recorded_klasses);
 974 
 975   delete_seen_objects_table();
 976 
 977   _num_total_subgraph_recordings ++;
 978   _num_total_walked_objs      += _num_new_walked_objs;
 979   _num_total_archived_objs    += _num_new_archived_objs;
 980   _num_total_recorded_klasses +=  num_new_recorded_klasses;
 981 }
 982 
 983 class ArchivableStaticFieldFinder: public FieldClosure {
 984   InstanceKlass* _ik;
 985   Symbol* _field_name;
 986   bool _found;
 987   int _offset;
 988 public:
 989   ArchivableStaticFieldFinder(InstanceKlass* ik, Symbol* field_name) :
 990     _ik(ik), _field_name(field_name), _found(false), _offset(-1) {}
 991 
 992   virtual void do_field(fieldDescriptor* fd) {
 993     if (fd->name() == _field_name) {
 994       assert(!_found, "fields cannot be overloaded");
 995       assert(is_reference_type(fd->field_type()), "can archive only fields that are references");
 996       _found = true;
 997       _offset = fd->offset();
 998     }
 999   }
1000   bool found()     { return _found;  }
1001   int offset()     { return _offset; }
1002 };
1003 
1004 void HeapShared::init_subgraph_entry_fields(ArchivableStaticFieldInfo fields[],
1005                                             int num, Thread* THREAD) {
1006   for (int i = 0; i < num; i++) {
1007     ArchivableStaticFieldInfo* info = &fields[i];
1008     TempNewSymbol klass_name =  SymbolTable::new_symbol(info->klass_name);
1009     TempNewSymbol field_name =  SymbolTable::new_symbol(info->field_name);
1010 
1011     Klass* k = SystemDictionary::resolve_or_null(klass_name, THREAD);
1012     assert(k != NULL && !HAS_PENDING_EXCEPTION, "class must exist");
1013     InstanceKlass* ik = InstanceKlass::cast(k);
1014     assert(InstanceKlass::cast(ik)->is_shared_boot_class(),
1015            "Only support boot classes");
1016     ik->initialize(THREAD);
1017     guarantee(!HAS_PENDING_EXCEPTION, "exception in initialize");
1018 
1019     ArchivableStaticFieldFinder finder(ik, field_name);
1020     ik->do_local_static_fields(&finder);
1021     assert(finder.found(), "field must exist");
1022 
1023     info->klass = ik;
1024     info->offset = finder.offset();
1025   }
1026 }
1027 
1028 void HeapShared::init_subgraph_entry_fields(Thread* THREAD) {
1029   _dump_time_subgraph_info_table = new (ResourceObj::C_HEAP, mtClass)DumpTimeKlassSubGraphInfoTable();
1030 
1031   init_subgraph_entry_fields(closed_archive_subgraph_entry_fields,
1032                              num_closed_archive_subgraph_entry_fields,
1033                              THREAD);
1034   init_subgraph_entry_fields(open_archive_subgraph_entry_fields,
1035                              num_open_archive_subgraph_entry_fields,
1036                              THREAD);
1037 }
1038 
1039 void HeapShared::archive_object_subgraphs(ArchivableStaticFieldInfo fields[],
1040                                           int num, bool is_closed_archive,
1041                                           Thread* THREAD) {
1042   _num_total_subgraph_recordings = 0;
1043   _num_total_walked_objs = 0;
1044   _num_total_archived_objs = 0;
1045   _num_total_recorded_klasses = 0;
1046   _num_total_verifications = 0;
1047 
1048   // For each class X that has one or more archived fields:
1049   // [1] Dump the subgraph of each archived field
1050   // [2] Create a list of all the class of the objects that can be reached
1051   //     by any of these static fields.
1052   //     At runtime, these classes are initialized before X's archived fields
1053   //     are restored by HeapShared::initialize_from_archived_subgraph().
1054   int i;
1055   for (i = 0; i < num; ) {
1056     ArchivableStaticFieldInfo* info = &fields[i];
1057     const char* klass_name = info->klass_name;
1058     start_recording_subgraph(info->klass, klass_name);
1059 
1060     // If you have specified consecutive fields of the same klass in
1061     // fields[], these will be archived in the same
1062     // {start_recording_subgraph ... done_recording_subgraph} pass to
1063     // save time.
1064     for (; i < num; i++) {
1065       ArchivableStaticFieldInfo* f = &fields[i];
1066       if (f->klass_name != klass_name) {
1067         break;
1068       }
1069 
1070       if (!info->full_module_graph_only || MetaspaceShared::use_full_module_graph()) {
1071         archive_reachable_objects_from_static_field(f->klass, f->klass_name,
1072                                                     f->offset, f->field_name,
1073                                                     is_closed_archive, CHECK);
1074       }
1075     }
1076     done_recording_subgraph(info->klass, klass_name);
1077   }
1078 
1079   log_info(cds, heap)("Archived subgraph records in %s archive heap region = %d",
1080                       is_closed_archive ? "closed" : "open",
1081                       _num_total_subgraph_recordings);
1082   log_info(cds, heap)("  Walked %d objects", _num_total_walked_objs);
1083   log_info(cds, heap)("  Archived %d objects", _num_total_archived_objs);
1084   log_info(cds, heap)("  Recorded %d klasses", _num_total_recorded_klasses);
1085 
1086 #ifndef PRODUCT
1087   for (int i = 0; i < num; i++) {
1088     ArchivableStaticFieldInfo* f = &fields[i];
1089     verify_subgraph_from_static_field(f->klass, f->offset);
1090   }
1091   log_info(cds, heap)("  Verified %d references", _num_total_verifications);
1092 #endif
1093 }
1094 
1095 // At dump-time, find the location of all the non-null oop pointers in an archived heap
1096 // region. This way we can quickly relocate all the pointers without using
1097 // BasicOopIterateClosure at runtime.
1098 class FindEmbeddedNonNullPointers: public BasicOopIterateClosure {
1099   narrowOop* _start;
1100   BitMap *_oopmap;
1101   int _num_total_oops;
1102   int _num_null_oops;
1103  public:
1104   FindEmbeddedNonNullPointers(narrowOop* start, BitMap* oopmap)
1105     : _start(start), _oopmap(oopmap), _num_total_oops(0),  _num_null_oops(0) {}
1106 
1107   virtual bool should_verify_oops(void) {
1108     return false;
1109   }
1110   virtual void do_oop(narrowOop* p) {
1111     _num_total_oops ++;
1112     narrowOop v = *p;
1113     if (!CompressedOops::is_null(v)) {
1114       size_t idx = p - _start;
1115       _oopmap->set_bit(idx);
1116     } else {
1117       _num_null_oops ++;
1118     }
1119   }
1120   virtual void do_oop(oop *p) {
1121     ShouldNotReachHere();
1122   }
1123   int num_total_oops() const { return _num_total_oops; }
1124   int num_null_oops()  const { return _num_null_oops; }
1125 };
1126 
1127 ResourceBitMap HeapShared::calculate_oopmap(MemRegion region) {
1128   assert(UseCompressedOops, "must be");
1129   size_t num_bits = region.byte_size() / sizeof(narrowOop);
1130   ResourceBitMap oopmap(num_bits);
1131 
1132   HeapWord* p   = region.start();
1133   HeapWord* end = region.end();
1134   FindEmbeddedNonNullPointers finder((narrowOop*)p, &oopmap);
1135 
1136   int num_objs = 0;
1137   while (p < end) {
1138     oop o = (oop)p;
1139     o->oop_iterate(&finder);
1140     p += o->size();
1141     ++ num_objs;
1142   }
1143 
1144   log_info(cds, heap)("calculate_oopmap: objects = %6d, embedded oops = %7d, nulls = %7d",
1145                       num_objs, finder.num_total_oops(), finder.num_null_oops());
1146   return oopmap;
1147 }
1148 
1149 // Patch all the embedded oop pointers inside an archived heap region,
1150 // to be consistent with the runtime oop encoding.
1151 class PatchEmbeddedPointers: public BitMapClosure {
1152   narrowOop* _start;
1153 
1154  public:
1155   PatchEmbeddedPointers(narrowOop* start) : _start(start) {}
1156 
1157   bool do_bit(size_t offset) {
1158     narrowOop* p = _start + offset;
1159     narrowOop v = *p;
1160     assert(!CompressedOops::is_null(v), "null oops should have been filtered out at dump time");
1161     oop o = HeapShared::decode_from_archive(v);
1162     RawAccess<IS_NOT_NULL>::oop_store(p, o);
1163     return true;
1164   }
1165 };
1166 
1167 void HeapShared::patch_archived_heap_embedded_pointers(MemRegion region, address oopmap,
1168                                                        size_t oopmap_size_in_bits) {
1169   BitMapView bm((BitMap::bm_word_t*)oopmap, oopmap_size_in_bits);
1170 
1171 #ifndef PRODUCT
1172   ResourceMark rm;
1173   ResourceBitMap checkBm = calculate_oopmap(region);
1174   assert(bm.is_same(checkBm), "sanity");
1175 #endif
1176 
1177   PatchEmbeddedPointers patcher((narrowOop*)region.start());
1178   bm.iterate(&patcher);
1179 }
1180 
1181 #endif // INCLUDE_CDS_JAVA_HEAP