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