1 /*
   2  * Copyright (c) 2018, 2026, 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 "cds/aotArtifactFinder.hpp"
  26 #include "cds/aotClassInitializer.hpp"
  27 #include "cds/aotClassLocation.hpp"
  28 #include "cds/aotCompressedPointers.hpp"
  29 #include "cds/aotLogging.hpp"
  30 #include "cds/aotMappedHeapLoader.hpp"
  31 #include "cds/aotMappedHeapWriter.hpp"
  32 #include "cds/aotMetaspace.hpp"
  33 #include "cds/aotOopChecker.hpp"
  34 #include "cds/aotReferenceObjSupport.hpp"
  35 #include "cds/aotStreamedHeapLoader.hpp"
  36 #include "cds/aotStreamedHeapWriter.hpp"
  37 #include "cds/archiveBuilder.hpp"
  38 #include "cds/archiveUtils.hpp"
  39 #include "cds/cds_globals.hpp"
  40 #include "cds/cdsConfig.hpp"
  41 #include "cds/cdsEnumKlass.hpp"
  42 #include "cds/cdsHeapVerifier.hpp"
  43 #include "cds/heapShared.inline.hpp"
  44 #include "cds/regeneratedClasses.hpp"
  45 #include "classfile/classLoaderData.hpp"
  46 #include "classfile/javaClasses.inline.hpp"
  47 #include "classfile/modules.hpp"
  48 #include "classfile/stringTable.hpp"
  49 #include "classfile/symbolTable.hpp"
  50 #include "classfile/systemDictionary.hpp"
  51 #include "classfile/systemDictionaryShared.hpp"
  52 #include "classfile/vmClasses.hpp"
  53 #include "classfile/vmSymbols.hpp"
  54 #include "gc/shared/collectedHeap.hpp"
  55 #include "gc/shared/gcLocker.hpp"
  56 #include "gc/shared/gcVMOperations.hpp"
  57 #include "logging/log.hpp"
  58 #include "logging/logStream.hpp"
  59 #include "memory/iterator.inline.hpp"
  60 #include "memory/resourceArea.hpp"
  61 #include "memory/universe.hpp"
  62 #include "oops/compressedOops.inline.hpp"
  63 #include "oops/fieldStreams.inline.hpp"
  64 #include "oops/objArrayOop.inline.hpp"
  65 #include "oops/oop.inline.hpp"
  66 #include "oops/oopHandle.inline.hpp"
  67 #include "oops/typeArrayOop.inline.hpp"
  68 #include "prims/jvmtiExport.hpp"
  69 #include "runtime/arguments.hpp"
  70 #include "runtime/fieldDescriptor.inline.hpp"
  71 #include "runtime/globals_extension.hpp"
  72 #include "runtime/init.hpp"
  73 #include "runtime/javaCalls.hpp"
  74 #include "runtime/mutexLocker.hpp"
  75 #include "runtime/safepointVerifiers.hpp"
  76 #include "utilities/bitMap.inline.hpp"
  77 #include "utilities/copy.hpp"
  78 #if INCLUDE_G1GC
  79 #include "gc/g1/g1CollectedHeap.hpp"
  80 #endif
  81 
  82 #if INCLUDE_CDS_JAVA_HEAP
  83 
  84 struct ArchivableStaticFieldInfo {
  85   const char* klass_name;
  86   const char* field_name;
  87   InstanceKlass* klass;
  88   int offset;
  89   BasicType type;
  90 
  91   ArchivableStaticFieldInfo(const char* k, const char* f)
  92   : klass_name(k), field_name(f), klass(nullptr), offset(0), type(T_ILLEGAL) {}
  93 
  94   bool valid() {
  95     return klass_name != nullptr;
  96   }
  97 };
  98 
  99 HeapArchiveMode HeapShared::_heap_load_mode = HeapArchiveMode::_uninitialized;
 100 HeapArchiveMode HeapShared::_heap_write_mode = HeapArchiveMode::_uninitialized;
 101 
 102 size_t HeapShared::_alloc_count[HeapShared::ALLOC_STAT_SLOTS];
 103 size_t HeapShared::_alloc_size[HeapShared::ALLOC_STAT_SLOTS];
 104 size_t HeapShared::_total_obj_count;
 105 size_t HeapShared::_total_obj_size;
 106 
 107 #ifndef PRODUCT
 108 #define ARCHIVE_TEST_FIELD_NAME "archivedObjects"
 109 static Array<char>* _archived_ArchiveHeapTestClass = nullptr;
 110 static const char* _test_class_name = nullptr;
 111 static Klass* _test_class = nullptr;
 112 static const ArchivedKlassSubGraphInfoRecord* _test_class_record = nullptr;
 113 #endif
 114 
 115 
 116 //
 117 // If you add new entries to the following tables, you should know what you're doing!
 118 //
 119 
 120 static ArchivableStaticFieldInfo archive_subgraph_entry_fields[] = {
 121   {"java/lang/Integer$IntegerCache",              "archivedCache"},
 122   {"java/lang/Long$LongCache",                    "archivedCache"},
 123   {"java/lang/Byte$ByteCache",                    "archivedCache"},
 124   {"java/lang/Short$ShortCache",                  "archivedCache"},
 125   {"java/lang/Character$CharacterCache",          "archivedCache"},
 126   {"java/util/jar/Attributes$Name",               "KNOWN_NAMES"},
 127   {"sun/util/locale/BaseLocale",                  "constantBaseLocales"},
 128   {"jdk/internal/module/ArchivedModuleGraph",     "archivedModuleGraph"},
 129   {"java/util/ImmutableCollections",              "archivedObjects"},
 130   {"java/lang/ModuleLayer",                       "EMPTY_LAYER"},
 131   {"java/lang/module/Configuration",              "EMPTY_CONFIGURATION"},
 132   {"jdk/internal/math/FDBigInteger",              "archivedCaches"},
 133 
 134 #ifndef PRODUCT
 135   {nullptr, nullptr}, // Extra slot for -XX:ArchiveHeapTestClass
 136 #endif
 137   {nullptr, nullptr},
 138 };
 139 
 140 // full module graph
 141 static ArchivableStaticFieldInfo fmg_archive_subgraph_entry_fields[] = {
 142   {"jdk/internal/loader/ArchivedClassLoaders",    "archivedClassLoaders"},
 143   {ARCHIVED_BOOT_LAYER_CLASS,                     ARCHIVED_BOOT_LAYER_FIELD},
 144   {"java/lang/Module$ArchivedData",               "archivedData"},
 145   {nullptr, nullptr},
 146 };
 147 
 148 KlassSubGraphInfo* HeapShared::_dump_time_special_subgraph;
 149 ArchivedKlassSubGraphInfoRecord* HeapShared::_run_time_special_subgraph;
 150 GrowableArrayCHeap<oop, mtClassShared>* HeapShared::_pending_roots = nullptr;
 151 OopHandle HeapShared::_scratch_basic_type_mirrors[T_VOID+1];
 152 MetaspaceObjToOopHandleTable* HeapShared::_scratch_objects_table = nullptr;
 153 
 154 static bool is_subgraph_root_class_of(ArchivableStaticFieldInfo fields[], InstanceKlass* ik) {
 155   for (int i = 0; fields[i].valid(); i++) {
 156     if (fields[i].klass == ik) {
 157       return true;
 158     }
 159   }
 160   return false;
 161 }
 162 
 163 bool HeapShared::is_subgraph_root_class(InstanceKlass* ik) {
 164   assert(CDSConfig::is_dumping_heap(), "dump-time only");
 165   if (CDSConfig::is_dumping_klass_subgraphs()) {
 166     // Legacy CDS archive support (to be deprecated)
 167     return is_subgraph_root_class_of(archive_subgraph_entry_fields, ik) ||
 168            is_subgraph_root_class_of(fmg_archive_subgraph_entry_fields, ik);
 169   } else {
 170     return false;
 171   }
 172 }
 173 
 174 oop HeapShared::CachedOopInfo::orig_referrer() const {
 175   return _orig_referrer.resolve();
 176 }
 177 
 178 unsigned HeapShared::oop_hash(oop const& p) {
 179   assert(SafepointSynchronize::is_at_safepoint() ||
 180          JavaThread::current()->is_in_no_safepoint_scope(), "sanity");
 181   // Do not call p->identity_hash() as that will update the
 182   // object header.
 183   return primitive_hash(cast_from_oop<intptr_t>(p));
 184 }
 185 
 186 unsigned int HeapShared::oop_handle_hash_raw(const OopHandle& oh) {
 187   return oop_hash(oh.resolve());
 188 }
 189 
 190 unsigned int HeapShared::oop_handle_hash(const OopHandle& oh) {
 191   oop o = oh.resolve();
 192   if (o == nullptr) {
 193     return 0;
 194   } else {
 195     return o->identity_hash();
 196   }
 197 }
 198 
 199 bool HeapShared::oop_handle_equals(const OopHandle& a, const OopHandle& b) {
 200   return a.resolve() == b.resolve();
 201 }
 202 
 203 static void reset_states(oop obj, TRAPS) {
 204   Handle h_obj(THREAD, obj);
 205   InstanceKlass* klass = InstanceKlass::cast(obj->klass());
 206   TempNewSymbol method_name = SymbolTable::new_symbol("resetArchivedStates");
 207   Symbol* method_sig = vmSymbols::void_method_signature();
 208 
 209   while (klass != nullptr) {
 210     Method* method = klass->find_method(method_name, method_sig);
 211     if (method != nullptr) {
 212       assert(method->is_private(), "must be");
 213       if (log_is_enabled(Debug, aot)) {
 214         ResourceMark rm(THREAD);
 215         log_debug(aot)("  calling %s", method->name_and_sig_as_C_string());
 216       }
 217       JavaValue result(T_VOID);
 218       JavaCalls::call_special(&result, h_obj, klass,
 219                               method_name, method_sig, CHECK);
 220     }
 221     klass = klass->super();
 222   }
 223 }
 224 
 225 void HeapShared::reset_archived_object_states(TRAPS) {
 226   assert(CDSConfig::is_dumping_heap(), "dump-time only");
 227   log_debug(aot)("Resetting platform loader");
 228   reset_states(SystemDictionary::java_platform_loader(), CHECK);
 229   log_debug(aot)("Resetting system loader");
 230   reset_states(SystemDictionary::java_system_loader(), CHECK);
 231 
 232   // Clean up jdk.internal.loader.ClassLoaders::bootLoader(), which is not
 233   // directly used for class loading, but rather is used by the core library
 234   // to keep track of resources, etc, loaded by the null class loader.
 235   //
 236   // Note, this object is non-null, and is not the same as
 237   // ClassLoaderData::the_null_class_loader_data()->class_loader(),
 238   // which is null.
 239   log_debug(aot)("Resetting boot loader");
 240   JavaValue result(T_OBJECT);
 241   JavaCalls::call_static(&result,
 242                          vmClasses::jdk_internal_loader_ClassLoaders_klass(),
 243                          vmSymbols::bootLoader_name(),
 244                          vmSymbols::void_BuiltinClassLoader_signature(),
 245                          CHECK);
 246   Handle boot_loader(THREAD, result.get_oop());
 247   reset_states(boot_loader(), CHECK);
 248 }
 249 
 250 void HeapShared::ensure_determinism(TRAPS) {
 251   TempNewSymbol class_name = SymbolTable::new_symbol("jdk/internal/util/WeakReferenceKey");
 252   TempNewSymbol method_name = SymbolTable::new_symbol("ensureDeterministicAOTCache");
 253 
 254   Klass* weak_ref_key_class = SystemDictionary::resolve_or_fail(class_name, true, CHECK);
 255   precond(weak_ref_key_class != nullptr);
 256 
 257   log_debug(aot)("Calling WeakReferenceKey::ensureDeterministicAOTCache(Object.class)");
 258   JavaValue result(T_BOOLEAN);
 259   JavaCalls::call_static(&result,
 260                          weak_ref_key_class,
 261                          method_name,
 262                          vmSymbols::void_boolean_signature(),
 263                          CHECK);
 264   assert(result.get_jboolean() == false, "sanity");
 265 }
 266 
 267 void HeapShared::prepare_for_archiving(TRAPS) {
 268   reset_archived_object_states(CHECK);
 269   ensure_determinism(CHECK);
 270 }
 271 
 272 HeapShared::ArchivedObjectCache* HeapShared::_archived_object_cache = nullptr;
 273 
 274 bool HeapShared::is_archived_heap_in_use() {
 275   if (HeapShared::is_loading()) {
 276     if (HeapShared::is_loading_streaming_mode()) {
 277       return AOTStreamedHeapLoader::is_in_use();
 278     } else {
 279       return AOTMappedHeapLoader::is_in_use();
 280     }
 281   }
 282 
 283   return false;
 284 }
 285 
 286 bool HeapShared::can_use_archived_heap() {
 287   FileMapInfo* static_mapinfo = FileMapInfo::current_info();
 288   if (static_mapinfo == nullptr) {
 289     return false;
 290   }
 291   if (!static_mapinfo->has_heap_region()) {
 292     return false;
 293   }
 294   if (!static_mapinfo->object_streaming_mode() &&
 295       !Universe::heap()->can_load_archived_objects() &&
 296       !UseG1GC) {
 297     // Incompatible object format
 298     return false;
 299   }
 300 
 301   return true;
 302 }
 303 
 304 bool HeapShared::is_too_large_to_archive(size_t size) {
 305   if (HeapShared::is_writing_streaming_mode()) {
 306     return false;
 307   } else {
 308     return AOTMappedHeapWriter::is_too_large_to_archive(size);
 309   }
 310 }
 311 
 312 bool HeapShared::is_too_large_to_archive(oop obj) {
 313   if (HeapShared::is_writing_streaming_mode()) {
 314     return false;
 315   } else {
 316     return AOTMappedHeapWriter::is_too_large_to_archive(obj);
 317   }
 318 }
 319 
 320 bool HeapShared::is_string_too_large_to_archive(oop string) {
 321   typeArrayOop value = java_lang_String::value_no_keepalive(string);
 322   return is_too_large_to_archive(value);
 323 }
 324 
 325 void HeapShared::initialize_loading_mode(HeapArchiveMode mode) {
 326   assert(_heap_load_mode == HeapArchiveMode::_uninitialized, "already set?");
 327   assert(mode != HeapArchiveMode::_uninitialized, "sanity");
 328   _heap_load_mode = mode;
 329 };
 330 
 331 void HeapShared::initialize_writing_mode() {
 332   assert(!FLAG_IS_ERGO(AOTStreamableObjects), "Should not have been ergonomically set yet");
 333 
 334   if (!CDSConfig::is_dumping_archive()) {
 335     // We use FLAG_IS_CMDLINE below because we are specifically looking to warn
 336     // a user that explicitly sets the flag on the command line for a JVM that is
 337     // not dumping an archive.
 338     if (FLAG_IS_CMDLINE(AOTStreamableObjects)) {
 339       log_warning(cds)("-XX:%cAOTStreamableObjects was specified, "
 340                        "AOTStreamableObjects is only used for writing "
 341                        "the AOT cache.",
 342                        AOTStreamableObjects ? '+' : '-');
 343     }
 344   }
 345 
 346   // The below checks use !FLAG_IS_DEFAULT instead of FLAG_IS_CMDLINE
 347   // because the one step AOT cache creation transfers the AOTStreamableObjects
 348   // flag value from the training JVM to the assembly JVM using an environment
 349   // variable that sets the flag as ERGO in the assembly JVM.
 350   if (FLAG_IS_DEFAULT(AOTStreamableObjects)) {
 351     // By default, the value of AOTStreamableObjects should match !UseCompressedOops.
 352     FLAG_SET_DEFAULT(AOTStreamableObjects, !UseCompressedOops);
 353   } else if (!AOTStreamableObjects && UseZGC) {
 354     // Never write mapped heap with ZGC
 355     if (CDSConfig::is_dumping_archive()) {
 356       log_warning(cds)("Heap archiving without streaming not supported for -XX:+UseZGC");
 357     }
 358     FLAG_SET_ERGO(AOTStreamableObjects, true);
 359   }
 360 
 361   if (CDSConfig::is_dumping_archive()) {
 362     // Select default mode
 363     assert(_heap_write_mode == HeapArchiveMode::_uninitialized, "already initialized?");
 364     _heap_write_mode = AOTStreamableObjects ? HeapArchiveMode::_streaming : HeapArchiveMode::_mapping;
 365   }
 366 }
 367 
 368 void HeapShared::initialize_streaming() {
 369   assert(is_loading_streaming_mode(), "shouldn't call this");
 370   if (can_use_archived_heap()) {
 371     AOTStreamedHeapLoader::initialize();
 372   }
 373 }
 374 
 375 void HeapShared::enable_gc() {
 376   if (AOTStreamedHeapLoader::is_in_use()) {
 377     AOTStreamedHeapLoader::enable_gc();
 378   }
 379 }
 380 
 381 void HeapShared::materialize_thread_object() {
 382   if (AOTStreamedHeapLoader::is_in_use()) {
 383     AOTStreamedHeapLoader::materialize_thread_object();
 384   }
 385 }
 386 
 387 void HeapShared::add_to_dumped_interned_strings(oop string) {
 388   assert(HeapShared::is_writing_mapping_mode(), "Only used by this mode");
 389   AOTMappedHeapWriter::add_to_dumped_interned_strings(string);
 390   bool success = archive_reachable_objects_from(1, _dump_time_special_subgraph, string);
 391   assert(success, "shared strings array must not point to arrays or strings that are too large to archive");
 392 }
 393 
 394 void HeapShared::finalize_initialization(FileMapInfo* static_mapinfo) {
 395   if (HeapShared::is_loading()) {
 396     if (HeapShared::is_loading_streaming_mode()) {
 397       // Heap initialization can be done only after vtables are initialized by ReadClosure.
 398       AOTStreamedHeapLoader::finish_initialization(static_mapinfo);
 399     } else {
 400       // Finish up archived heap initialization. These must be
 401       // done after ReadClosure.
 402       AOTMappedHeapLoader::finish_initialization(static_mapinfo);
 403     }
 404   }
 405 }
 406 
 407 HeapShared::CachedOopInfo* HeapShared::get_cached_oop_info(oop obj) {
 408   OopHandle oh(Universe::vm_global(), obj);
 409   CachedOopInfo* result = _archived_object_cache->get(oh);
 410   oh.release(Universe::vm_global());
 411   return result;
 412 }
 413 
 414 bool HeapShared::has_been_archived(oop obj) {
 415   assert(CDSConfig::is_dumping_heap(), "dump-time only");
 416   return get_cached_oop_info(obj) != nullptr;
 417 }
 418 
 419 int HeapShared::append_root(oop obj) {
 420   assert(CDSConfig::is_dumping_heap(), "dump-time only");
 421   if (obj != nullptr) {
 422     assert(has_been_archived(obj), "must be");
 423   }
 424   // No GC should happen since we aren't scanning _pending_roots.
 425   assert(Thread::current() == (Thread*)VMThread::vm_thread(), "should be in vm thread");
 426 
 427   return _pending_roots->append(obj);
 428 }
 429 
 430 oop HeapShared::get_root(int index, bool clear) {
 431   assert(index >= 0, "sanity");
 432   assert(is_archived_heap_in_use(), "getting roots into heap that is not used");
 433 
 434   oop result;
 435   if (HeapShared::is_loading_streaming_mode()) {
 436     result = AOTStreamedHeapLoader::get_root(index);
 437   } else {
 438     assert(HeapShared::is_loading_mapping_mode(), "must be");
 439     result = AOTMappedHeapLoader::get_root(index);
 440   }
 441 
 442   if (clear) {
 443     clear_root(index);
 444   }
 445 
 446   return result;
 447 }
 448 
 449 void HeapShared::finish_materialize_objects() {
 450   if (AOTStreamedHeapLoader::is_in_use()) {
 451     AOTStreamedHeapLoader::finish_materialize_objects();
 452   }
 453 }
 454 
 455 void HeapShared::clear_root(int index) {
 456   assert(index >= 0, "sanity");
 457   assert(CDSConfig::is_using_archive(), "must be");
 458   if (is_archived_heap_in_use()) {
 459     if (log_is_enabled(Debug, aot, heap)) {
 460       log_debug(aot, heap)("Clearing root %d: was %zu", index, p2i(get_root(index, false /* clear */)));
 461     }
 462     if (HeapShared::is_loading_streaming_mode()) {
 463       AOTStreamedHeapLoader::clear_root(index);
 464     } else {
 465       assert(HeapShared::is_loading_mapping_mode(), "must be");
 466       AOTMappedHeapLoader::clear_root(index);
 467     }
 468   }
 469 }
 470 
 471 bool HeapShared::archive_object(oop obj, oop referrer, KlassSubGraphInfo* subgraph_info) {
 472   assert(CDSConfig::is_dumping_heap(), "dump-time only");
 473 
 474   assert(!obj->is_stackChunk(), "do not archive stack chunks");
 475   if (has_been_archived(obj)) {
 476     return true;
 477   }
 478 
 479   if (is_too_large_to_archive(obj)) {
 480     log_debug(aot, heap)("Cannot archive, object (" PTR_FORMAT ") is too large: %zu",
 481                          p2i(obj), obj->size());
 482     debug_trace();
 483     return false;
 484   }
 485 
 486   AOTOopChecker::check(obj); // Make sure contents of this oop are safe.
 487   count_allocation(obj->size());
 488 
 489   if (HeapShared::is_writing_streaming_mode()) {
 490     AOTStreamedHeapWriter::add_source_obj(obj);
 491   } else {
 492     AOTMappedHeapWriter::add_source_obj(obj);
 493   }
 494 
 495   OopHandle oh(Universe::vm_global(), obj);
 496   CachedOopInfo info = make_cached_oop_info(obj, referrer);
 497   archived_object_cache()->put_when_absent(oh, info);
 498   archived_object_cache()->maybe_grow();
 499 
 500   Klass* k = obj->klass();
 501   if (k->is_instance_klass()) {
 502     // Whenever we see a non-array Java object of type X, we mark X to be aot-initialized.
 503     // This ensures that during the production run, whenever Java code sees a cached object
 504     // of type X, we know that X is already initialized. (see TODO comment below ...)
 505 
 506     if (InstanceKlass::cast(k)->is_enum_subclass()
 507         // We can't rerun <clinit> of enum classes (see cdsEnumKlass.cpp) so
 508         // we must store them as AOT-initialized.
 509         || (subgraph_info == _dump_time_special_subgraph))
 510         // TODO: we do this only for the special subgraph for now. Extending this to
 511         // other subgraphs would require more refactoring of the core library (such as
 512         // move some initialization logic into runtimeSetup()).
 513         //
 514         // For the other subgraphs, we have a weaker mechanism to ensure that
 515         // all classes in a subgraph are initialized before the subgraph is programmatically
 516         // returned from jdk.internal.misc.CDS::initializeFromArchive().
 517         // See HeapShared::initialize_from_archived_subgraph().
 518     {
 519       AOTArtifactFinder::add_aot_inited_class(InstanceKlass::cast(k));
 520     }
 521 
 522     if (java_lang_Class::is_instance(obj)) {
 523       Klass* mirror_k = java_lang_Class::as_Klass(obj);
 524       if (mirror_k != nullptr) {
 525         AOTArtifactFinder::add_cached_class(mirror_k);
 526       }
 527     } else if (java_lang_invoke_ResolvedMethodName::is_instance(obj)) {
 528       Method* m = java_lang_invoke_ResolvedMethodName::vmtarget(obj);
 529       if (m != nullptr) {
 530         if (RegeneratedClasses::has_been_regenerated(m)) {
 531           m = RegeneratedClasses::get_regenerated_object(m);
 532         }
 533         InstanceKlass* method_holder = m->method_holder();
 534         AOTArtifactFinder::add_cached_class(method_holder);
 535       }
 536     }
 537   }
 538 
 539   if (log_is_enabled(Debug, aot, heap)) {
 540     ResourceMark rm;
 541     LogTarget(Debug, aot, heap) log;
 542     LogStream out(log);
 543     out.print("Archived heap object " PTR_FORMAT " : %s ",
 544               p2i(obj), obj->klass()->external_name());
 545     if (java_lang_Class::is_instance(obj)) {
 546       Klass* k = java_lang_Class::as_Klass(obj);
 547       if (k != nullptr) {
 548         out.print("%s", k->external_name());
 549       } else {
 550         out.print("primitive");
 551       }
 552     }
 553     out.cr();
 554   }
 555 
 556   return true;
 557 }
 558 
 559 class MetaspaceObjToOopHandleTable: public HashTable<MetaspaceObj*, OopHandle,
 560     36137, // prime number
 561     AnyObj::C_HEAP,
 562     mtClassShared> {
 563 public:
 564   oop get_oop(MetaspaceObj* ptr) {
 565     MutexLocker ml(ScratchObjects_lock, Mutex::_no_safepoint_check_flag);
 566     OopHandle* handle = get(ptr);
 567     if (handle != nullptr) {
 568       return handle->resolve();
 569     } else {
 570       return nullptr;
 571     }
 572   }
 573   void set_oop(MetaspaceObj* ptr, oop o) {
 574     MutexLocker ml(ScratchObjects_lock, Mutex::_no_safepoint_check_flag);
 575     OopHandle handle(Universe::vm_global(), o);
 576     put_when_absent(ptr, handle);
 577   }
 578   void remove_oop(MetaspaceObj* ptr) {
 579     MutexLocker ml(ScratchObjects_lock, Mutex::_no_safepoint_check_flag);
 580     OopHandle* handle = get(ptr);
 581     if (handle != nullptr) {
 582       handle->release(Universe::vm_global());
 583       remove(ptr);
 584     }
 585   }
 586 };
 587 
 588 void HeapShared::add_scratch_resolved_references(ConstantPool* src, objArrayOop dest) {
 589   if (CDSConfig::is_dumping_preimage_static_archive() && scratch_resolved_references(src) != nullptr) {
 590     // We are in AOT training run. The class has been redefined and we are giving it a new resolved_reference.
 591     // Ignore it, as this class will be excluded from the AOT config.
 592     return;
 593   }
 594   if (SystemDictionaryShared::is_builtin_loader(src->pool_holder()->class_loader_data())) {
 595     _scratch_objects_table->set_oop(src, dest);
 596   }
 597 }
 598 
 599 objArrayOop HeapShared::scratch_resolved_references(ConstantPool* src) {
 600   return (objArrayOop)_scratch_objects_table->get_oop(src);
 601 }
 602 
 603  void HeapShared::init_dumping() {
 604    _scratch_objects_table = new (mtClass)MetaspaceObjToOopHandleTable();
 605    _pending_roots = new GrowableArrayCHeap<oop, mtClassShared>(500);
 606 }
 607 
 608 void HeapShared::init_scratch_objects_for_basic_type_mirrors(TRAPS) {
 609   for (int i = T_BOOLEAN; i < T_VOID+1; i++) {
 610     BasicType bt = (BasicType)i;
 611     if (!is_reference_type(bt)) {
 612       oop m = java_lang_Class::create_basic_type_mirror(type2name(bt), bt, CHECK);
 613       _scratch_basic_type_mirrors[i] = OopHandle(Universe::vm_global(), m);
 614     }
 615   }
 616 }
 617 
 618 // Given java_mirror that represents a (primitive or reference) type T,
 619 // return the "scratch" version that represents the same type T. Note
 620 // that java_mirror will be returned if the mirror is already a scratch mirror.
 621 //
 622 // See java_lang_Class::create_scratch_mirror() for more info.
 623 oop HeapShared::scratch_java_mirror(oop java_mirror) {
 624   assert(java_lang_Class::is_instance(java_mirror), "must be");
 625 
 626   for (int i = T_BOOLEAN; i < T_VOID+1; i++) {
 627     BasicType bt = (BasicType)i;
 628     if (!is_reference_type(bt)) {
 629       if (_scratch_basic_type_mirrors[i].resolve() == java_mirror) {
 630         return java_mirror;
 631       }
 632     }
 633   }
 634 
 635   if (java_lang_Class::is_primitive(java_mirror)) {
 636     return scratch_java_mirror(java_lang_Class::as_BasicType(java_mirror));
 637   } else {
 638     return scratch_java_mirror(java_lang_Class::as_Klass(java_mirror));
 639   }
 640 }
 641 
 642 oop HeapShared::scratch_java_mirror(BasicType t) {
 643   assert((uint)t < T_VOID+1, "range check");
 644   assert(!is_reference_type(t), "sanity");
 645   return _scratch_basic_type_mirrors[t].resolve();
 646 }
 647 
 648 oop HeapShared::scratch_java_mirror(Klass* k) {
 649   return _scratch_objects_table->get_oop(k);
 650 }
 651 
 652 void HeapShared::set_scratch_java_mirror(Klass* k, oop mirror) {
 653   _scratch_objects_table->set_oop(k, mirror);
 654 }
 655 
 656 void HeapShared::remove_scratch_objects(Klass* k) {
 657   // Klass is being deallocated. Java mirror can still be alive, and it should not
 658   // point to dead klass. We need to break the link from mirror to the Klass.
 659   // See how InstanceKlass::deallocate_contents does it for normal mirrors.
 660   oop mirror = _scratch_objects_table->get_oop(k);
 661   if (mirror != nullptr) {
 662     java_lang_Class::set_klass(mirror, nullptr);
 663   }
 664   _scratch_objects_table->remove_oop(k);
 665   if (k->is_instance_klass()) {
 666     _scratch_objects_table->remove(InstanceKlass::cast(k)->constants());
 667   }
 668 }
 669 
 670 //TODO: we eventually want a more direct test for these kinds of things.
 671 //For example the JVM could record some bit of context from the creation
 672 //of the klass, such as who called the hidden class factory.  Using
 673 //string compares on names is fragile and will break as soon as somebody
 674 //changes the names in the JDK code.  See discussion in JDK-8342481 for
 675 //related ideas about marking AOT-related classes.
 676 bool HeapShared::is_lambda_form_klass(InstanceKlass* ik) {
 677   return ik->is_hidden() &&
 678     (ik->name()->starts_with("java/lang/invoke/LambdaForm$MH+") ||
 679      ik->name()->starts_with("java/lang/invoke/LambdaForm$DMH+") ||
 680      ik->name()->starts_with("java/lang/invoke/LambdaForm$BMH+") ||
 681      ik->name()->starts_with("java/lang/invoke/LambdaForm$VH+"));
 682 }
 683 
 684 bool HeapShared::is_lambda_proxy_klass(InstanceKlass* ik) {
 685   return ik->is_hidden() && (ik->name()->index_of_at(0, "$$Lambda+", 9) > 0);
 686 }
 687 
 688 bool HeapShared::is_string_concat_klass(InstanceKlass* ik) {
 689   return ik->is_hidden() && ik->name()->starts_with("java/lang/String$$StringConcat");
 690 }
 691 
 692 bool HeapShared::is_archivable_hidden_klass(InstanceKlass* ik) {
 693   return CDSConfig::is_dumping_method_handles() &&
 694     (is_lambda_form_klass(ik) || is_lambda_proxy_klass(ik) || is_string_concat_klass(ik));
 695 }
 696 
 697 
 698 void HeapShared::copy_and_rescan_aot_inited_mirror(InstanceKlass* ik) {
 699   ik->set_has_aot_initialized_mirror();
 700 
 701   oop orig_mirror;
 702   if (RegeneratedClasses::is_regenerated_object(ik)) {
 703     InstanceKlass* orig_ik = RegeneratedClasses::get_original_object(ik);
 704     precond(orig_ik->is_initialized());
 705     orig_mirror = orig_ik->java_mirror();
 706   } else {
 707     precond(ik->is_initialized());
 708     orig_mirror = ik->java_mirror();
 709   }
 710 
 711   oop m = scratch_java_mirror(ik);
 712   int nfields = 0;
 713   for (JavaFieldStream fs(ik); !fs.done(); fs.next()) {
 714     if (fs.access_flags().is_static()) {
 715       fieldDescriptor& fd = fs.field_descriptor();
 716       int offset = fd.offset();
 717       switch (fd.field_type()) {
 718       case T_OBJECT:
 719       case T_ARRAY:
 720         {
 721           oop field_obj = orig_mirror->obj_field(offset);
 722           if (offset == java_lang_Class::reflection_data_offset()) {
 723             // Class::reflectData use SoftReference, which cannot be archived. Set it
 724             // to null and it will be recreated at runtime.
 725             field_obj = nullptr;
 726           }
 727           m->obj_field_put(offset, field_obj);
 728           if (field_obj != nullptr) {
 729             bool success = archive_reachable_objects_from(1, _dump_time_special_subgraph, field_obj);
 730             assert(success, "sanity");
 731           }
 732         }
 733         break;
 734       case T_BOOLEAN:
 735         m->bool_field_put(offset, orig_mirror->bool_field(offset));
 736         break;
 737       case T_BYTE:
 738         m->byte_field_put(offset, orig_mirror->byte_field(offset));
 739         break;
 740       case T_SHORT:
 741         m->short_field_put(offset, orig_mirror->short_field(offset));
 742         break;
 743       case T_CHAR:
 744         m->char_field_put(offset, orig_mirror->char_field(offset));
 745         break;
 746       case T_INT:
 747         m->int_field_put(offset, orig_mirror->int_field(offset));
 748         break;
 749       case T_LONG:
 750         m->long_field_put(offset, orig_mirror->long_field(offset));
 751         break;
 752       case T_FLOAT:
 753         m->float_field_put(offset, orig_mirror->float_field(offset));
 754         break;
 755       case T_DOUBLE:
 756         m->double_field_put(offset, orig_mirror->double_field(offset));
 757         break;
 758       default:
 759         ShouldNotReachHere();
 760       }
 761       nfields ++;
 762     }
 763   }
 764 
 765   oop class_data = java_lang_Class::class_data(orig_mirror);
 766   java_lang_Class::set_class_data(m, class_data);
 767   if (class_data != nullptr) {
 768     bool success = archive_reachable_objects_from(1, _dump_time_special_subgraph, class_data);
 769     assert(success, "sanity");
 770   }
 771 
 772   if (log_is_enabled(Debug, aot, init)) {
 773     ResourceMark rm;
 774     log_debug(aot, init)("copied %3d field(s) in aot-initialized mirror %s%s%s", nfields, ik->external_name(),
 775                          ik->is_hidden() ? " (hidden)" : "",
 776                          ik->is_enum_subclass() ? " (enum)" : "");
 777   }
 778 }
 779 
 780 void HeapShared::copy_java_mirror(oop orig_mirror, oop scratch_m) {
 781   // We need to retain the identity_hash, because it may have been used by some hashtables
 782   // in the shared heap.
 783   if (!orig_mirror->fast_no_hash_check()) {
 784     intptr_t src_hash = orig_mirror->identity_hash();
 785     if (UseCompactObjectHeaders) {
 786       narrowKlass nk = CompressedKlassPointers::encode(orig_mirror->klass());
 787       scratch_m->set_mark(markWord::prototype().set_narrow_klass(nk).copy_set_hash(src_hash));
 788     } else {
 789       scratch_m->set_mark(markWord::prototype().copy_set_hash(src_hash));
 790     }
 791     assert(scratch_m->mark().is_unlocked(), "sanity");
 792 
 793     DEBUG_ONLY(intptr_t archived_hash = scratch_m->identity_hash());
 794     assert(src_hash == archived_hash, "Different hash codes: original " INTPTR_FORMAT ", archived " INTPTR_FORMAT, src_hash, archived_hash);
 795   }
 796 
 797   if (CDSConfig::is_dumping_aot_linked_classes()) {
 798     java_lang_Class::set_module(scratch_m, java_lang_Class::module(orig_mirror));
 799     java_lang_Class::set_protection_domain(scratch_m, java_lang_Class::protection_domain(orig_mirror));
 800   }
 801 }
 802 
 803 static objArrayOop get_archived_resolved_references(InstanceKlass* src_ik) {
 804   if (SystemDictionaryShared::is_builtin_loader(src_ik->class_loader_data())) {
 805     objArrayOop rr = src_ik->constants()->resolved_references_or_null();
 806     if (rr != nullptr && !HeapShared::is_too_large_to_archive(rr)) {
 807       return HeapShared::scratch_resolved_references(src_ik->constants());
 808     }
 809   }
 810   return nullptr;
 811 }
 812 
 813 int HeapShared::archive_exception_instance(oop exception) {
 814   bool success = archive_reachable_objects_from(1, _dump_time_special_subgraph, exception);
 815   assert(success, "sanity");
 816   return append_root(exception);
 817 }
 818 
 819 void HeapShared::get_pointer_info(oop src_obj, bool& has_oop_pointers, bool& has_native_pointers) {
 820   OopHandle oh(&src_obj);
 821   CachedOopInfo* info = archived_object_cache()->get(oh);
 822   assert(info != nullptr, "must be");
 823   has_oop_pointers = info->has_oop_pointers();
 824   has_native_pointers = info->has_native_pointers();
 825 }
 826 
 827 void HeapShared::set_has_native_pointers(oop src_obj) {
 828   OopHandle oh(&src_obj);
 829   CachedOopInfo* info = archived_object_cache()->get(oh);
 830   assert(info != nullptr, "must be");
 831   info->set_has_native_pointers();
 832 }
 833 
 834 // Between start_scanning_for_oops() and end_scanning_for_oops(), we discover all Java heap objects that
 835 // should be stored in the AOT cache. The scanning is coordinated by AOTArtifactFinder.
 836 void HeapShared::start_scanning_for_oops() {
 837   {
 838     NoSafepointVerifier nsv;
 839 
 840     // The special subgraph doesn't belong to any class. We use Object_klass() here just
 841     // for convenience.
 842     _dump_time_special_subgraph = init_subgraph_info(vmClasses::Object_klass(), false);
 843 
 844     // Cache for recording where the archived objects are copied to
 845     create_archived_object_cache();
 846 
 847     if (HeapShared::is_writing_mapping_mode() && (UseG1GC || UseCompressedOops)) {
 848       aot_log_info(aot)("Heap range = [" PTR_FORMAT " - "  PTR_FORMAT "]",
 849                     UseCompressedOops ? p2i(CompressedOops::begin()) :
 850                                         p2i((address)G1CollectedHeap::heap()->reserved().start()),
 851                     UseCompressedOops ? p2i(CompressedOops::end()) :
 852                                         p2i((address)G1CollectedHeap::heap()->reserved().end()));
 853     }
 854 
 855     archive_subgraphs();
 856   }
 857 
 858   init_seen_objects_table();
 859   Universe::archive_exception_instances();
 860 }
 861 
 862 void HeapShared::end_scanning_for_oops() {
 863   if (is_writing_mapping_mode()) {
 864     StringTable::init_shared_table();
 865   }
 866   delete_seen_objects_table();
 867 }
 868 
 869 void HeapShared::write_heap(AOTMappedHeapInfo* mapped_heap_info, AOTStreamedHeapInfo* streamed_heap_info) {
 870   {
 871     NoSafepointVerifier nsv;
 872     CDSHeapVerifier::verify();
 873     check_special_subgraph_classes();
 874   }
 875 
 876   if (HeapShared::is_writing_mapping_mode()) {
 877     StringTable::write_shared_table();
 878     AOTMappedHeapWriter::write(_pending_roots, mapped_heap_info);
 879   } else {
 880     assert(HeapShared::is_writing_streaming_mode(), "are there more modes?");
 881     AOTStreamedHeapWriter::write(_pending_roots, streamed_heap_info);
 882   }
 883 
 884   ArchiveBuilder::OtherROAllocMark mark;
 885   write_subgraph_info_table();
 886 }
 887 
 888 void HeapShared::scan_java_mirror(oop orig_mirror) {
 889   oop m = scratch_java_mirror(orig_mirror);
 890   if (m != nullptr) { // nullptr if for custom class loader
 891     copy_java_mirror(orig_mirror, m);
 892     bool success = archive_reachable_objects_from(1, _dump_time_special_subgraph, m);
 893     assert(success, "sanity");
 894   }
 895 }
 896 
 897 void HeapShared::scan_java_class(Klass* orig_k) {
 898   scan_java_mirror(orig_k->java_mirror());
 899 
 900   if (orig_k->is_instance_klass()) {
 901     InstanceKlass* orig_ik = InstanceKlass::cast(orig_k);
 902     orig_ik->constants()->prepare_resolved_references_for_archiving();
 903     objArrayOop rr = get_archived_resolved_references(orig_ik);
 904     if (rr != nullptr) {
 905       bool success = HeapShared::archive_reachable_objects_from(1, _dump_time_special_subgraph, rr);
 906       assert(success, "must be");
 907     }
 908   }
 909 }
 910 
 911 void HeapShared::archive_subgraphs() {
 912   assert(CDSConfig::is_dumping_heap(), "must be");
 913 
 914   if (CDSConfig::is_dumping_klass_subgraphs()) {
 915     archive_object_subgraphs(archive_subgraph_entry_fields,
 916                              false /* is_full_module_graph */);
 917     if (CDSConfig::is_dumping_full_module_graph()) {
 918       archive_object_subgraphs(fmg_archive_subgraph_entry_fields,
 919                                true /* is_full_module_graph */);
 920     }
 921   }
 922 }
 923 
 924 //
 925 // Subgraph archiving support
 926 //
 927 HeapShared::DumpTimeKlassSubGraphInfoTable* HeapShared::_dump_time_subgraph_info_table = nullptr;
 928 HeapShared::RunTimeKlassSubGraphInfoTable   HeapShared::_run_time_subgraph_info_table;
 929 
 930 // Get the subgraph_info for Klass k. A new subgraph_info is created if
 931 // there is no existing one for k. The subgraph_info records the "buffered"
 932 // address of the class.
 933 KlassSubGraphInfo* HeapShared::init_subgraph_info(Klass* k, bool is_full_module_graph) {
 934   assert(CDSConfig::is_dumping_heap(), "dump time only");
 935   bool created;
 936   KlassSubGraphInfo* info =
 937     _dump_time_subgraph_info_table->put_if_absent(k, KlassSubGraphInfo(k, is_full_module_graph),
 938                                                   &created);
 939   assert(created, "must not initialize twice");
 940   return info;
 941 }
 942 
 943 KlassSubGraphInfo* HeapShared::get_subgraph_info(Klass* k) {
 944   assert(CDSConfig::is_dumping_heap(), "dump time only");
 945   KlassSubGraphInfo* info = _dump_time_subgraph_info_table->get(k);
 946   assert(info != nullptr, "must have been initialized");
 947   return info;
 948 }
 949 
 950 // Add an entry field to the current KlassSubGraphInfo.
 951 void KlassSubGraphInfo::add_subgraph_entry_field(int static_field_offset, oop v) {
 952   assert(CDSConfig::is_dumping_heap(), "dump time only");
 953   if (_subgraph_entry_fields == nullptr) {
 954     _subgraph_entry_fields =
 955       new (mtClass) GrowableArray<int>(10, mtClass);
 956   }
 957   _subgraph_entry_fields->append(static_field_offset);
 958   _subgraph_entry_fields->append(HeapShared::append_root(v));
 959 }
 960 
 961 // Add the Klass* for an object in the current KlassSubGraphInfo's subgraphs.
 962 // Only objects of boot classes can be included in sub-graph.
 963 void KlassSubGraphInfo::add_subgraph_object_klass(Klass* orig_k) {
 964   assert(CDSConfig::is_dumping_heap(), "dump time only");
 965 
 966   if (_subgraph_object_klasses == nullptr) {
 967     _subgraph_object_klasses =
 968       new (mtClass) GrowableArray<Klass*>(50, mtClass);
 969   }
 970 
 971   if (_k == orig_k) {
 972     // Don't add the Klass containing the sub-graph to it's own klass
 973     // initialization list.
 974     return;
 975   }
 976 
 977   if (orig_k->is_instance_klass()) {
 978 #ifdef ASSERT
 979     InstanceKlass* ik = InstanceKlass::cast(orig_k);
 980     if (CDSConfig::is_dumping_method_handles()) {
 981       // -XX:AOTInitTestClass must be used carefully in regression tests to
 982       // include only classes that are safe to aot-initialize.
 983       assert(ik->class_loader() == nullptr ||
 984              HeapShared::is_lambda_proxy_klass(ik) ||
 985              AOTClassInitializer::has_test_class(),
 986             "we can archive only instances of boot classes or lambda proxy classes");
 987     } else {
 988       assert(ik->class_loader() == nullptr, "must be boot class");
 989     }
 990 #endif
 991     // vmClasses::xxx_klass() are not updated, need to check
 992     // the original Klass*
 993     if (orig_k == vmClasses::String_klass() ||
 994         orig_k == vmClasses::Object_klass()) {
 995       // Initialized early during VM initialization. No need to be added
 996       // to the sub-graph object class list.
 997       return;
 998     }
 999     check_allowed_klass(InstanceKlass::cast(orig_k));
1000   } else if (orig_k->is_objArray_klass()) {
1001     Klass* abk = ObjArrayKlass::cast(orig_k)->bottom_klass();
1002     if (abk->is_instance_klass()) {
1003       assert(InstanceKlass::cast(abk)->defined_by_boot_loader(),
1004             "must be boot class");
1005       check_allowed_klass(InstanceKlass::cast(ObjArrayKlass::cast(orig_k)->bottom_klass()));
1006     }
1007     if (orig_k == Universe::objectArrayKlass()) {
1008       // Initialized early during Universe::genesis. No need to be added
1009       // to the list.
1010       return;
1011     }
1012   } else {
1013     assert(orig_k->is_typeArray_klass(), "must be");
1014     // Primitive type arrays are created early during Universe::genesis.
1015     return;
1016   }
1017 
1018   if (log_is_enabled(Debug, aot, heap)) {
1019     if (!_subgraph_object_klasses->contains(orig_k)) {
1020       ResourceMark rm;
1021       log_debug(aot, heap)("Adding klass %s", orig_k->external_name());
1022     }
1023   }
1024 
1025   _subgraph_object_klasses->append_if_missing(orig_k);
1026   _has_non_early_klasses |= is_non_early_klass(orig_k);
1027 }
1028 
1029 void KlassSubGraphInfo::check_allowed_klass(InstanceKlass* ik) {
1030 #ifndef PRODUCT
1031   if (AOTClassInitializer::has_test_class()) {
1032     // The tests can cache arbitrary types of objects.
1033     return;
1034   }
1035 #endif
1036 
1037   if (ik->module()->name() == vmSymbols::java_base()) {
1038     assert(ik->package() != nullptr, "classes in java.base cannot be in unnamed package");
1039     return;
1040   }
1041 
1042   const char* lambda_msg = "";
1043   if (CDSConfig::is_dumping_method_handles()) {
1044     lambda_msg = ", or a lambda proxy class";
1045     if (HeapShared::is_lambda_proxy_klass(ik) &&
1046         (ik->class_loader() == nullptr ||
1047          ik->class_loader() == SystemDictionary::java_platform_loader() ||
1048          ik->class_loader() == SystemDictionary::java_system_loader())) {
1049       return;
1050     }
1051   }
1052 
1053 #ifndef PRODUCT
1054   if (!ik->module()->is_named() && ik->package() == nullptr && ArchiveHeapTestClass != nullptr) {
1055     // This class is loaded by ArchiveHeapTestClass
1056     return;
1057   }
1058   const char* testcls_msg = ", or a test class in an unnamed package of an unnamed module";
1059 #else
1060   const char* testcls_msg = "";
1061 #endif
1062 
1063   ResourceMark rm;
1064   log_error(aot, heap)("Class %s not allowed in archive heap. Must be in java.base%s%s",
1065                        ik->external_name(), lambda_msg, testcls_msg);
1066   AOTMetaspace::unrecoverable_writing_error();
1067 }
1068 
1069 bool KlassSubGraphInfo::is_non_early_klass(Klass* k) {
1070   if (k->is_objArray_klass()) {
1071     k = ObjArrayKlass::cast(k)->bottom_klass();
1072   }
1073   if (k->is_instance_klass()) {
1074     if (!SystemDictionaryShared::is_early_klass(InstanceKlass::cast(k))) {
1075       ResourceMark rm;
1076       log_info(aot, heap)("non-early: %s", k->external_name());
1077       return true;
1078     } else {
1079       return false;
1080     }
1081   } else {
1082     return false;
1083   }
1084 }
1085 
1086 // Initialize an archived subgraph_info_record from the given KlassSubGraphInfo.
1087 void ArchivedKlassSubGraphInfoRecord::init(KlassSubGraphInfo* info) {
1088   _k = ArchiveBuilder::get_buffered_klass(info->klass());
1089   _entry_field_records = nullptr;
1090   _subgraph_object_klasses = nullptr;
1091   _is_full_module_graph = info->is_full_module_graph();
1092 
1093   if (_is_full_module_graph) {
1094     // Consider all classes referenced by the full module graph as early -- we will be
1095     // allocating objects of these classes during JVMTI early phase, so they cannot
1096     // be processed by (non-early) JVMTI ClassFileLoadHook
1097     _has_non_early_klasses = false;
1098   } else {
1099     _has_non_early_klasses = info->has_non_early_klasses();
1100   }
1101 
1102   if (_has_non_early_klasses) {
1103     ResourceMark rm;
1104     log_info(aot, heap)(
1105           "Subgraph of klass %s has non-early klasses and cannot be used when JVMTI ClassFileLoadHook is enabled",
1106           _k->external_name());
1107   }
1108 
1109   // populate the entry fields
1110   GrowableArray<int>* entry_fields = info->subgraph_entry_fields();
1111   if (entry_fields != nullptr) {
1112     int num_entry_fields = entry_fields->length();
1113     assert(num_entry_fields % 2 == 0, "sanity");
1114     _entry_field_records =
1115       ArchiveBuilder::new_ro_array<int>(num_entry_fields);
1116     for (int i = 0 ; i < num_entry_fields; i++) {
1117       _entry_field_records->at_put(i, entry_fields->at(i));
1118     }
1119   }
1120 
1121   // <recorded_klasses> has the Klasses of all the objects that are referenced by this subgraph.
1122   // Copy those that need to be explicitly initialized into <_subgraph_object_klasses>.
1123   GrowableArray<Klass*>* recorded_klasses = info->subgraph_object_klasses();
1124   if (recorded_klasses != nullptr) {
1125     // AOT-inited classes are automatically marked as "initialized" during bootstrap. When
1126     // programmatically loading a subgraph, we only need to explicitly initialize the classes
1127     // that are not aot-inited.
1128     int num_to_copy = 0;
1129     for (int i = 0; i < recorded_klasses->length(); i++) {
1130       Klass* subgraph_k = ArchiveBuilder::get_buffered_klass(recorded_klasses->at(i));
1131       if (!subgraph_k->has_aot_initialized_mirror()) {
1132         num_to_copy ++;
1133       }
1134     }
1135 
1136     _subgraph_object_klasses = ArchiveBuilder::new_ro_array<Klass*>(num_to_copy);
1137     bool is_special = (_k == ArchiveBuilder::get_buffered_klass(vmClasses::Object_klass()));
1138     for (int i = 0, n = 0; i < recorded_klasses->length(); i++) {
1139       Klass* subgraph_k = ArchiveBuilder::get_buffered_klass(recorded_klasses->at(i));
1140       if (subgraph_k->has_aot_initialized_mirror()) {
1141         continue;
1142       }
1143       if (log_is_enabled(Info, aot, heap)) {
1144         ResourceMark rm;
1145         const char* owner_name =  is_special ? "<special>" : _k->external_name();
1146         if (subgraph_k->is_instance_klass()) {
1147           InstanceKlass* src_ik = InstanceKlass::cast(ArchiveBuilder::current()->get_source_addr(subgraph_k));
1148         }
1149         log_info(aot, heap)(
1150           "Archived object klass %s (%2d) => %s",
1151           owner_name, n, subgraph_k->external_name());
1152       }
1153       _subgraph_object_klasses->at_put(n, subgraph_k);
1154       ArchivePtrMarker::mark_pointer(_subgraph_object_klasses->adr_at(n));
1155       n++;
1156     }
1157   }
1158 
1159   ArchivePtrMarker::mark_pointer(&_k);
1160   ArchivePtrMarker::mark_pointer(&_entry_field_records);
1161   ArchivePtrMarker::mark_pointer(&_subgraph_object_klasses);
1162 }
1163 
1164 class HeapShared::CopyKlassSubGraphInfoToArchive : StackObj {
1165   CompactHashtableWriter* _writer;
1166 public:
1167   CopyKlassSubGraphInfoToArchive(CompactHashtableWriter* writer) : _writer(writer) {}
1168 
1169   bool do_entry(Klass* klass, KlassSubGraphInfo& info) {
1170     if (info.subgraph_object_klasses() != nullptr || info.subgraph_entry_fields() != nullptr) {
1171       ArchivedKlassSubGraphInfoRecord* record = HeapShared::archive_subgraph_info(&info);
1172       Klass* buffered_k = ArchiveBuilder::get_buffered_klass(klass);
1173       unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary((address)buffered_k);
1174       _writer->add(hash, AOTCompressedPointers::encode_not_null(record));
1175     }
1176     return true; // keep on iterating
1177   }
1178 };
1179 
1180 ArchivedKlassSubGraphInfoRecord* HeapShared::archive_subgraph_info(KlassSubGraphInfo* info) {
1181   ArchivedKlassSubGraphInfoRecord* record =
1182       (ArchivedKlassSubGraphInfoRecord*)ArchiveBuilder::ro_region_alloc(sizeof(ArchivedKlassSubGraphInfoRecord));
1183   record->init(info);
1184   if (info ==  _dump_time_special_subgraph) {
1185     _run_time_special_subgraph = record;
1186   }
1187   return record;
1188 }
1189 
1190 // Build the records of archived subgraph infos, which include:
1191 // - Entry points to all subgraphs from the containing class mirror. The entry
1192 //   points are static fields in the mirror. For each entry point, the field
1193 //   offset, and value are recorded in the sub-graph
1194 //   info. The value is stored back to the corresponding field at runtime.
1195 // - A list of klasses that need to be loaded/initialized before archived
1196 //   java object sub-graph can be accessed at runtime.
1197 void HeapShared::write_subgraph_info_table() {
1198   // Allocate the contents of the hashtable(s) inside the RO region of the CDS archive.
1199   DumpTimeKlassSubGraphInfoTable* d_table = _dump_time_subgraph_info_table;
1200   CompactHashtableStats stats;
1201 
1202   _run_time_subgraph_info_table.reset();
1203 
1204   CompactHashtableWriter writer(d_table->number_of_entries(), &stats);
1205   CopyKlassSubGraphInfoToArchive copy(&writer);
1206   d_table->iterate(&copy);
1207   writer.dump(&_run_time_subgraph_info_table, "subgraphs");
1208 
1209 #ifndef PRODUCT
1210   if (ArchiveHeapTestClass != nullptr) {
1211     size_t len = strlen(ArchiveHeapTestClass) + 1;
1212     Array<char>* array = ArchiveBuilder::new_ro_array<char>((int)len);
1213     strncpy(array->adr_at(0), ArchiveHeapTestClass, len);
1214     _archived_ArchiveHeapTestClass = array;
1215   }
1216 #endif
1217   if (log_is_enabled(Info, aot, heap)) {
1218     print_stats();
1219   }
1220 }
1221 
1222 void HeapShared::serialize_tables(SerializeClosure* soc) {
1223 
1224 #ifndef PRODUCT
1225   soc->do_ptr(&_archived_ArchiveHeapTestClass);
1226   if (soc->reading() && _archived_ArchiveHeapTestClass != nullptr) {
1227     _test_class_name = _archived_ArchiveHeapTestClass->adr_at(0);
1228     setup_test_class(_test_class_name);
1229   }
1230 #endif
1231 
1232   _run_time_subgraph_info_table.serialize_header(soc);
1233   soc->do_ptr(&_run_time_special_subgraph);
1234 }
1235 
1236 static void verify_the_heap(Klass* k, const char* which) {
1237   if (VerifyArchivedFields > 0) {
1238     ResourceMark rm;
1239     log_info(aot, heap)("Verify heap %s initializing static field(s) in %s",
1240                         which, k->external_name());
1241 
1242     if (VerifyArchivedFields == 1) {
1243       VM_Verify verify_op;
1244       VMThread::execute(&verify_op);
1245     } else if (VerifyArchivedFields == 2 && is_init_completed()) {
1246       // At this time, the oop->klass() of some archived objects in the heap may not
1247       // have been loaded into the system dictionary yet. Nevertheless, oop->klass() should
1248       // have enough information (object size, oop maps, etc) so that a GC can be safely
1249       // performed.
1250       //
1251       // -XX:VerifyArchivedFields=2 force a GC to happen in such an early stage
1252       // to check for GC safety.
1253       log_info(aot, heap)("Trigger GC %s initializing static field(s) in %s",
1254                           which, k->external_name());
1255       FlagSetting fs1(VerifyBeforeGC, true);
1256       FlagSetting fs2(VerifyDuringGC, true);
1257       FlagSetting fs3(VerifyAfterGC,  true);
1258       Universe::heap()->collect(GCCause::_java_lang_system_gc);
1259     }
1260   }
1261 }
1262 
1263 // Before GC can execute, we must ensure that all oops reachable from HeapShared::roots()
1264 // have a valid klass. I.e., oopDesc::klass() must have already been resolved.
1265 //
1266 // Note: if a ArchivedKlassSubGraphInfoRecord contains non-early classes, and JVMTI
1267 // ClassFileLoadHook is enabled, it's possible for this class to be dynamically replaced. In
1268 // this case, we will not load the ArchivedKlassSubGraphInfoRecord and will clear its roots.
1269 void HeapShared::resolve_classes(JavaThread* current) {
1270   assert(CDSConfig::is_using_archive(), "runtime only!");
1271   if (CDSConfig::is_using_klass_subgraphs()) {
1272     resolve_classes_for_subgraphs(current, archive_subgraph_entry_fields);
1273     resolve_classes_for_subgraphs(current, fmg_archive_subgraph_entry_fields);
1274   }
1275 }
1276 
1277 void HeapShared::resolve_classes_for_subgraphs(JavaThread* current, ArchivableStaticFieldInfo fields[]) {
1278   for (int i = 0; fields[i].valid(); i++) {
1279     ArchivableStaticFieldInfo* info = &fields[i];
1280     TempNewSymbol klass_name = SymbolTable::new_symbol(info->klass_name);
1281     InstanceKlass* k = SystemDictionaryShared::find_builtin_class(klass_name);
1282     assert(k != nullptr && k->defined_by_boot_loader(), "sanity");
1283     resolve_classes_for_subgraph_of(current, k);
1284   }
1285 }
1286 
1287 void HeapShared::resolve_classes_for_subgraph_of(JavaThread* current, Klass* k) {
1288   JavaThread* THREAD = current;
1289   ExceptionMark em(THREAD);
1290   const ArchivedKlassSubGraphInfoRecord* record =
1291    resolve_or_init_classes_for_subgraph_of(k, /*do_init=*/false, THREAD);
1292   if (HAS_PENDING_EXCEPTION) {
1293    CLEAR_PENDING_EXCEPTION;
1294   }
1295   if (record == nullptr) {
1296    clear_archived_roots_of(k);
1297   }
1298 }
1299 
1300 void HeapShared::initialize_java_lang_invoke(TRAPS) {
1301   if (CDSConfig::is_using_aot_linked_classes() || CDSConfig::is_dumping_method_handles()) {
1302     resolve_or_init("java/lang/invoke/Invokers$Holder", true, CHECK);
1303     resolve_or_init("java/lang/invoke/MethodHandle", true, CHECK);
1304     resolve_or_init("java/lang/invoke/MethodHandleNatives", true, CHECK);
1305     resolve_or_init("java/lang/invoke/DirectMethodHandle$Holder", true, CHECK);
1306     resolve_or_init("java/lang/invoke/DelegatingMethodHandle$Holder", true, CHECK);
1307     resolve_or_init("java/lang/invoke/LambdaForm$Holder", true, CHECK);
1308     resolve_or_init("java/lang/invoke/BoundMethodHandle$Species_L", true, CHECK);
1309   }
1310 }
1311 
1312 // Initialize the InstanceKlasses of objects that are reachable from the following roots:
1313 //   - interned strings
1314 //   - Klass::java_mirror() -- including aot-initialized mirrors such as those of Enum klasses.
1315 //   - ConstantPool::resolved_references()
1316 //   - Universe::<xxx>_exception_instance()
1317 //
1318 // For example, if this enum class is initialized at AOT cache assembly time:
1319 //
1320 //    enum Fruit {
1321 //       APPLE, ORANGE, BANANA;
1322 //       static final Set<Fruit> HAVE_SEEDS = new HashSet<>(Arrays.asList(APPLE, ORANGE));
1323 //   }
1324 //
1325 // the aot-initialized mirror of Fruit has a static field that references HashSet, which
1326 // should be initialized before any Java code can access the Fruit class. Note that
1327 // HashSet itself doesn't necessary need to be an aot-initialized class.
1328 void HeapShared::init_classes_for_special_subgraph(Handle class_loader, TRAPS) {
1329   if (!is_archived_heap_in_use()) {
1330     return;
1331   }
1332 
1333   assert( _run_time_special_subgraph != nullptr, "must be");
1334   Array<Klass*>* klasses = _run_time_special_subgraph->subgraph_object_klasses();
1335   if (klasses != nullptr) {
1336     for (int pass = 0; pass < 2; pass ++) {
1337       for (int i = 0; i < klasses->length(); i++) {
1338         Klass* k = klasses->at(i);
1339         if (k->class_loader_data() == nullptr) {
1340           // This class is not yet loaded. We will initialize it in a later phase.
1341           // For example, we have loaded only AOTLinkedClassCategory::BOOT1 classes
1342           // but k is part of AOTLinkedClassCategory::BOOT2.
1343           continue;
1344         }
1345         if (k->class_loader() == class_loader()) {
1346           if (pass == 0) {
1347             if (k->is_instance_klass()) {
1348               InstanceKlass::cast(k)->link_class(CHECK);
1349             }
1350           } else {
1351             resolve_or_init(k, /*do_init*/true, CHECK);
1352           }
1353         }
1354       }
1355     }
1356   }
1357 }
1358 
1359 void HeapShared::initialize_from_archived_subgraph(JavaThread* current, Klass* k) {
1360   JavaThread* THREAD = current;
1361   if (!CDSConfig::is_using_klass_subgraphs()) {
1362     return; // nothing to do
1363   }
1364 
1365   if (k->name()->equals("jdk/internal/module/ArchivedModuleGraph") &&
1366       !CDSConfig::is_using_optimized_module_handling() &&
1367       // archive was created with --module-path
1368       AOTClassLocationConfig::runtime()->num_module_paths() > 0) {
1369     // ArchivedModuleGraph was created with a --module-path that's different than the runtime --module-path.
1370     // Thus, it might contain references to modules that do not exist at runtime. We cannot use it.
1371     log_info(aot, heap)("Skip initializing ArchivedModuleGraph subgraph: is_using_optimized_module_handling=%s num_module_paths=%d",
1372                         BOOL_TO_STR(CDSConfig::is_using_optimized_module_handling()),
1373                         AOTClassLocationConfig::runtime()->num_module_paths());
1374     return;
1375   }
1376 
1377   ExceptionMark em(THREAD);
1378   const ArchivedKlassSubGraphInfoRecord* record =
1379     resolve_or_init_classes_for_subgraph_of(k, /*do_init=*/true, THREAD);
1380 
1381   if (HAS_PENDING_EXCEPTION) {
1382     CLEAR_PENDING_EXCEPTION;
1383     // None of the field value will be set if there was an exception when initializing the classes.
1384     // The java code will not see any of the archived objects in the
1385     // subgraphs referenced from k in this case.
1386     return;
1387   }
1388 
1389   if (record != nullptr) {
1390     init_archived_fields_for(k, record);
1391   }
1392 }
1393 
1394 const ArchivedKlassSubGraphInfoRecord*
1395 HeapShared::resolve_or_init_classes_for_subgraph_of(Klass* k, bool do_init, TRAPS) {
1396   assert(!CDSConfig::is_dumping_heap(), "Should not be called when dumping heap");
1397 
1398   if (!k->in_aot_cache()) {
1399     return nullptr;
1400   }
1401   unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary_quick(k);
1402   const ArchivedKlassSubGraphInfoRecord* record = _run_time_subgraph_info_table.lookup(k, hash, 0);
1403 
1404 #ifndef PRODUCT
1405   if (_test_class_name != nullptr && k->name()->equals(_test_class_name) && record != nullptr) {
1406     _test_class = k;
1407     _test_class_record = record;
1408   }
1409 #endif
1410 
1411   // Initialize from archived data. Currently this is done only
1412   // during VM initialization time. No lock is needed.
1413   if (record == nullptr) {
1414     if (log_is_enabled(Info, aot, heap)) {
1415       ResourceMark rm(THREAD);
1416       log_info(aot, heap)("subgraph %s is not recorded",
1417                           k->external_name());
1418     }
1419     return nullptr;
1420   } else {
1421     if (record->is_full_module_graph() && !CDSConfig::is_using_full_module_graph()) {
1422       if (log_is_enabled(Info, aot, heap)) {
1423         ResourceMark rm(THREAD);
1424         log_info(aot, heap)("subgraph %s cannot be used because full module graph is disabled",
1425                             k->external_name());
1426       }
1427       return nullptr;
1428     }
1429 
1430     if (record->has_non_early_klasses() && JvmtiExport::should_post_class_file_load_hook()) {
1431       if (log_is_enabled(Info, aot, heap)) {
1432         ResourceMark rm(THREAD);
1433         log_info(aot, heap)("subgraph %s cannot be used because JVMTI ClassFileLoadHook is enabled",
1434                             k->external_name());
1435       }
1436       return nullptr;
1437     }
1438 
1439     if (log_is_enabled(Info, aot, heap)) {
1440       ResourceMark rm;
1441       log_info(aot, heap)("%s subgraph %s ", do_init ? "init" : "resolve", k->external_name());
1442     }
1443 
1444     resolve_or_init(k, do_init, CHECK_NULL);
1445 
1446     // Load/link/initialize the klasses of the objects in the subgraph.
1447     // nullptr class loader is used.
1448     Array<Klass*>* klasses = record->subgraph_object_klasses();
1449     if (klasses != nullptr) {
1450       for (int i = 0; i < klasses->length(); i++) {
1451         Klass* klass = klasses->at(i);
1452         if (!klass->in_aot_cache()) {
1453           return nullptr;
1454         }
1455         resolve_or_init(klass, do_init, CHECK_NULL);
1456       }
1457     }
1458   }
1459 
1460   return record;
1461 }
1462 
1463 void HeapShared::resolve_or_init(const char* klass_name, bool do_init, TRAPS) {
1464   TempNewSymbol klass_name_sym =  SymbolTable::new_symbol(klass_name);
1465   InstanceKlass* k = SystemDictionaryShared::find_builtin_class(klass_name_sym);
1466   if (k == nullptr) {
1467     return;
1468   }
1469   assert(k->defined_by_boot_loader(), "sanity");
1470   resolve_or_init(k, false, CHECK);
1471   if (do_init) {
1472     resolve_or_init(k, true, CHECK);
1473   }
1474 }
1475 
1476 void HeapShared::resolve_or_init(Klass* k, bool do_init, TRAPS) {
1477   if (!do_init) {
1478     if (k->class_loader_data() == nullptr) {
1479       Klass* resolved_k = SystemDictionary::resolve_or_null(k->name(), CHECK);
1480       assert(resolved_k == k, "classes used by archived heap must not be replaced by JVMTI ClassFileLoadHook");
1481     }
1482   } else {
1483     assert(k->class_loader_data() != nullptr, "must have been resolved by HeapShared::resolve_classes");
1484     if (k->is_instance_klass()) {
1485       InstanceKlass* ik = InstanceKlass::cast(k);
1486       ik->initialize(CHECK);
1487     } else if (k->is_objArray_klass()) {
1488       ObjArrayKlass* oak = ObjArrayKlass::cast(k);
1489       oak->initialize(CHECK);
1490     }
1491   }
1492 }
1493 
1494 void HeapShared::init_archived_fields_for(Klass* k, const ArchivedKlassSubGraphInfoRecord* record) {
1495   verify_the_heap(k, "before");
1496 
1497   Array<int>* entry_field_records = record->entry_field_records();
1498   if (entry_field_records != nullptr) {
1499     int efr_len = entry_field_records->length();
1500     assert(efr_len % 2 == 0, "sanity");
1501     for (int i = 0; i < efr_len; i += 2) {
1502       int field_offset = entry_field_records->at(i);
1503       int root_index = entry_field_records->at(i+1);
1504       // Load the subgraph entry fields from the record and store them back to
1505       // the corresponding fields within the mirror.
1506       oop v = get_root(root_index, /*clear=*/true);
1507       oop m = k->java_mirror();
1508       if (k->has_aot_initialized_mirror()) {
1509         assert(v == m->obj_field(field_offset), "must be aot-initialized");
1510       } else {
1511         m->obj_field_put(field_offset, v);
1512       }
1513       log_debug(aot, heap)("  " PTR_FORMAT " init field @ %2d = " PTR_FORMAT, p2i(k), field_offset, p2i(v));
1514     }
1515 
1516     // Done. Java code can see the archived sub-graphs referenced from k's
1517     // mirror after this point.
1518     if (log_is_enabled(Info, aot, heap)) {
1519       ResourceMark rm;
1520       log_info(aot, heap)("initialize_from_archived_subgraph %s " PTR_FORMAT "%s%s",
1521                           k->external_name(), p2i(k), JvmtiExport::is_early_phase() ? " (early)" : "",
1522                           k->has_aot_initialized_mirror() ? " (aot-inited)" : "");
1523     }
1524   }
1525 
1526   verify_the_heap(k, "after ");
1527 }
1528 
1529 void HeapShared::clear_archived_roots_of(Klass* k) {
1530   unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary_quick(k);
1531   const ArchivedKlassSubGraphInfoRecord* record = _run_time_subgraph_info_table.lookup(k, hash, 0);
1532   if (record != nullptr) {
1533     Array<int>* entry_field_records = record->entry_field_records();
1534     if (entry_field_records != nullptr) {
1535       int efr_len = entry_field_records->length();
1536       assert(efr_len % 2 == 0, "sanity");
1537       for (int i = 0; i < efr_len; i += 2) {
1538         int root_index = entry_field_records->at(i+1);
1539         clear_root(root_index);
1540       }
1541     }
1542   }
1543 }
1544 
1545 // Push all oop fields (or oop array elemenets in case of an objArray) in
1546 // _referencing_obj onto the _stack.
1547 class HeapShared::OopFieldPusher: public BasicOopIterateClosure {
1548   PendingOopStack* _stack;
1549   GrowableArray<oop> _found_oop_fields;
1550   int _level;
1551   bool _record_klasses_only;
1552   KlassSubGraphInfo* _subgraph_info;
1553   oop _referencing_obj;
1554   bool _is_java_lang_ref;
1555  public:
1556   OopFieldPusher(PendingOopStack* stack,
1557                  int level,
1558                  bool record_klasses_only,
1559                  KlassSubGraphInfo* subgraph_info,
1560                  oop orig) :
1561     _stack(stack),
1562     _found_oop_fields(),
1563     _level(level),
1564     _record_klasses_only(record_klasses_only),
1565     _subgraph_info(subgraph_info),
1566     _referencing_obj(orig) {
1567     _is_java_lang_ref = AOTReferenceObjSupport::check_if_ref_obj(orig);
1568   }
1569   void do_oop(narrowOop *p) { OopFieldPusher::do_oop_work(p); }
1570   void do_oop(      oop *p) { OopFieldPusher::do_oop_work(p); }
1571 
1572   ~OopFieldPusher() {
1573     while (_found_oop_fields.length() > 0) {
1574       // This produces the exact same traversal order as the previous version
1575       // of OopFieldPusher that recurses on the C stack -- a depth-first search,
1576       // walking the oop fields in _referencing_obj by ascending field offsets.
1577       oop obj = _found_oop_fields.pop();
1578       _stack->push(PendingOop(obj, _referencing_obj, _level + 1));
1579     }
1580   }
1581 
1582  protected:
1583   template <class T> void do_oop_work(T *p) {
1584     int field_offset = pointer_delta_as_int((char*)p, cast_from_oop<char*>(_referencing_obj));
1585     oop obj = HeapAccess<ON_UNKNOWN_OOP_REF>::oop_load_at(_referencing_obj, field_offset);
1586     if (obj != nullptr) {
1587       if (_is_java_lang_ref && AOTReferenceObjSupport::skip_field(field_offset)) {
1588         // Do not follow these fields. They will be cleared to null.
1589         return;
1590       }
1591 
1592       if (!_record_klasses_only && log_is_enabled(Debug, aot, heap)) {
1593         ResourceMark rm;
1594         log_debug(aot, heap)("(%d) %s[%d] ==> " PTR_FORMAT " size %zu %s", _level,
1595                              _referencing_obj->klass()->external_name(), field_offset,
1596                              p2i(obj), obj->size() * HeapWordSize, obj->klass()->external_name());
1597         if (log_is_enabled(Trace, aot, heap)) {
1598           LogTarget(Trace, aot, heap) log;
1599           LogStream out(log);
1600           obj->print_on(&out);
1601         }
1602       }
1603 
1604       _found_oop_fields.push(obj);
1605     }
1606   }
1607 
1608  public:
1609   oop referencing_obj()                       { return _referencing_obj;      }
1610   KlassSubGraphInfo* subgraph_info()          { return _subgraph_info;        }
1611 };
1612 
1613 // Checks if an oop has any non-null oop fields
1614 class PointsToOopsChecker : public BasicOopIterateClosure {
1615   bool _result;
1616 
1617   template <class T> void check(T *p) {
1618     _result |= (HeapAccess<>::oop_load(p) != nullptr);
1619   }
1620 
1621 public:
1622   PointsToOopsChecker() : _result(false) {}
1623   void do_oop(narrowOop *p) { check(p); }
1624   void do_oop(      oop *p) { check(p); }
1625   bool result() { return _result; }
1626 };
1627 
1628 HeapShared::CachedOopInfo HeapShared::make_cached_oop_info(oop obj, oop referrer) {
1629   PointsToOopsChecker points_to_oops_checker;
1630   obj->oop_iterate(&points_to_oops_checker);
1631   return CachedOopInfo(OopHandle(Universe::vm_global(), referrer), points_to_oops_checker.result());
1632 }
1633 
1634 void HeapShared::init_box_classes(TRAPS) {
1635   if (is_archived_heap_in_use()) {
1636     vmClasses::Boolean_klass()->initialize(CHECK);
1637     vmClasses::Character_klass()->initialize(CHECK);
1638     vmClasses::Float_klass()->initialize(CHECK);
1639     vmClasses::Double_klass()->initialize(CHECK);
1640     vmClasses::Byte_klass()->initialize(CHECK);
1641     vmClasses::Short_klass()->initialize(CHECK);
1642     vmClasses::Integer_klass()->initialize(CHECK);
1643     vmClasses::Long_klass()->initialize(CHECK);
1644     vmClasses::Void_klass()->initialize(CHECK);
1645   }
1646 }
1647 
1648 // (1) If orig_obj has not been archived yet, archive it.
1649 // (2) If orig_obj has not been seen yet (since start_recording_subgraph() was called),
1650 //     trace all  objects that are reachable from it, and make sure these objects are archived.
1651 // (3) Record the klasses of all objects that are reachable from orig_obj (including those that
1652 //     were already archived when this function is called)
1653 bool HeapShared::archive_reachable_objects_from(int level,
1654                                                 KlassSubGraphInfo* subgraph_info,
1655                                                 oop orig_obj) {
1656   assert(orig_obj != nullptr, "must be");
1657   PendingOopStack stack;
1658   stack.push(PendingOop(orig_obj, nullptr, level));
1659 
1660   while (stack.length() > 0) {
1661     PendingOop po = stack.pop();
1662     _object_being_archived = po;
1663     bool status = walk_one_object(&stack, po.level(), subgraph_info, po.obj(), po.referrer());
1664     _object_being_archived = PendingOop();
1665 
1666     if (!status) {
1667       // Don't archive a subgraph root that's too big. For archives static fields, that's OK
1668       // as the Java code will take care of initializing this field dynamically.
1669       assert(level == 1, "VM should have exited with unarchivable objects for _level > 1");
1670       return false;
1671     }
1672   }
1673 
1674   return true;
1675 }
1676 
1677 bool HeapShared::walk_one_object(PendingOopStack* stack, int level, KlassSubGraphInfo* subgraph_info,
1678                                  oop orig_obj, oop referrer) {
1679   assert(orig_obj != nullptr, "must be");
1680   if (!JavaClasses::is_supported_for_archiving(orig_obj)) {
1681     // This object has injected fields that cannot be supported easily, so we disallow them for now.
1682     // If you get an error here, you probably made a change in the JDK library that has added
1683     // these objects that are referenced (directly or indirectly) by static fields.
1684     ResourceMark rm;
1685     log_error(aot, heap)("Cannot archive object " PTR_FORMAT " of class %s", p2i(orig_obj), orig_obj->klass()->external_name());
1686     debug_trace();
1687     AOTMetaspace::unrecoverable_writing_error();
1688   }
1689 
1690   if (log_is_enabled(Debug, aot, heap) && java_lang_Class::is_instance(orig_obj)) {
1691     ResourceMark rm;
1692     LogTarget(Debug, aot, heap) log;
1693     LogStream out(log);
1694     out.print("Found java mirror " PTR_FORMAT " ", p2i(orig_obj));
1695     Klass* k = java_lang_Class::as_Klass(orig_obj);
1696     if (k != nullptr) {
1697       out.print("%s", k->external_name());
1698     } else {
1699       out.print("primitive");
1700     }
1701     out.print_cr("; scratch mirror = "  PTR_FORMAT,
1702                  p2i(scratch_java_mirror(orig_obj)));
1703   }
1704 
1705   if (java_lang_Class::is_instance(orig_obj)) {
1706     Klass* k = java_lang_Class::as_Klass(orig_obj);
1707     if (RegeneratedClasses::has_been_regenerated(k)) {
1708       orig_obj = RegeneratedClasses::get_regenerated_object(k)->java_mirror();
1709     }
1710   }
1711 
1712   if (CDSConfig::is_dumping_aot_linked_classes()) {
1713     if (java_lang_Class::is_instance(orig_obj)) {
1714       orig_obj = scratch_java_mirror(orig_obj);
1715       assert(orig_obj != nullptr, "must be archived");
1716     }
1717   } else if (java_lang_Class::is_instance(orig_obj) && subgraph_info != _dump_time_special_subgraph) {
1718     // Without CDSConfig::is_dumping_aot_linked_classes(), we only allow archived objects to
1719     // point to the mirrors of (1) j.l.Object, (2) primitive classes, and (3) box classes. These are initialized
1720     // very early by HeapShared::init_box_classes().
1721     if (orig_obj == vmClasses::Object_klass()->java_mirror()
1722         || java_lang_Class::is_primitive(orig_obj)
1723         || orig_obj == vmClasses::Boolean_klass()->java_mirror()
1724         || orig_obj == vmClasses::Character_klass()->java_mirror()
1725         || orig_obj == vmClasses::Float_klass()->java_mirror()
1726         || orig_obj == vmClasses::Double_klass()->java_mirror()
1727         || orig_obj == vmClasses::Byte_klass()->java_mirror()
1728         || orig_obj == vmClasses::Short_klass()->java_mirror()
1729         || orig_obj == vmClasses::Integer_klass()->java_mirror()
1730         || orig_obj == vmClasses::Long_klass()->java_mirror()
1731         || orig_obj == vmClasses::Void_klass()->java_mirror()) {
1732       orig_obj = scratch_java_mirror(orig_obj);
1733       assert(orig_obj != nullptr, "must be archived");
1734     } else {
1735       // If you get an error here, you probably made a change in the JDK library that has added a Class
1736       // object that is referenced (directly or indirectly) by an ArchivableStaticFieldInfo
1737       // defined at the top of this file.
1738       log_error(aot, heap)("(%d) Unknown java.lang.Class object is in the archived sub-graph", level);
1739       debug_trace();
1740       AOTMetaspace::unrecoverable_writing_error();
1741     }
1742   }
1743 
1744   if (has_been_seen_during_subgraph_recording(orig_obj)) {
1745     // orig_obj has already been archived and traced. Nothing more to do.
1746     return true;
1747   } else {
1748     set_has_been_seen_during_subgraph_recording(orig_obj);
1749   }
1750 
1751   bool already_archived = has_been_archived(orig_obj);
1752   bool record_klasses_only = already_archived;
1753   if (!already_archived) {
1754     ++_num_new_archived_objs;
1755     if (!archive_object(orig_obj, referrer, subgraph_info)) {
1756       // Skip archiving the sub-graph referenced from the current entry field.
1757       ResourceMark rm;
1758       log_error(aot, heap)(
1759         "Cannot archive the sub-graph referenced from %s object ("
1760         PTR_FORMAT ") size %zu, skipped.",
1761         orig_obj->klass()->external_name(), p2i(orig_obj), orig_obj->size() * HeapWordSize);
1762       if (level == 1) {
1763         // Don't archive a subgraph root that's too big. For archives static fields, that's OK
1764         // as the Java code will take care of initializing this field dynamically.
1765         return false;
1766       } else {
1767         // We don't know how to handle an object that has been archived, but some of its reachable
1768         // objects cannot be archived. Bail out for now. We might need to fix this in the future if
1769         // we have a real use case.
1770         AOTMetaspace::unrecoverable_writing_error();
1771       }
1772     }
1773   }
1774 
1775   Klass *orig_k = orig_obj->klass();
1776   subgraph_info->add_subgraph_object_klass(orig_k);
1777 
1778   {
1779     // Find all the oops that are referenced by orig_obj, push them onto the stack
1780     // so we can work on them next.
1781     ResourceMark rm;
1782     OopFieldPusher pusher(stack, level, record_klasses_only, subgraph_info, orig_obj);
1783     orig_obj->oop_iterate(&pusher);
1784   }
1785 
1786   if (CDSConfig::is_dumping_aot_linked_classes()) {
1787     // The enum klasses are archived with aot-initialized mirror.
1788     // See AOTClassInitializer::can_archive_initialized_mirror().
1789   } else {
1790     // This is legacy support for enum classes before JEP 483 -- we cannot rerun
1791     // the enum's <clinit> in the production run, so special handling is needed.
1792     if (CDSEnumKlass::is_enum_obj(orig_obj)) {
1793       CDSEnumKlass::handle_enum_obj(level + 1, subgraph_info, orig_obj);
1794     }
1795   }
1796 
1797   return true;
1798 }
1799 
1800 //
1801 // Start from the given static field in a java mirror and archive the
1802 // complete sub-graph of java heap objects that are reached directly
1803 // or indirectly from the starting object by following references.
1804 // Sub-graph archiving restrictions (current):
1805 //
1806 // - All classes of objects in the archived sub-graph (including the
1807 //   entry class) must be boot class only.
1808 // - No java.lang.Class instance (java mirror) can be included inside
1809 //   an archived sub-graph. Mirror can only be the sub-graph entry object.
1810 //
1811 // The Java heap object sub-graph archiving process (see OopFieldPusher):
1812 //
1813 // 1) Java object sub-graph archiving starts from a given static field
1814 // within a Class instance (java mirror). If the static field is a
1815 // reference field and points to a non-null java object, proceed to
1816 // the next step.
1817 //
1818 // 2) Archives the referenced java object. If an archived copy of the
1819 // current object already exists, updates the pointer in the archived
1820 // copy of the referencing object to point to the current archived object.
1821 // Otherwise, proceed to the next step.
1822 //
1823 // 3) Follows all references within the current java object and recursively
1824 // archive the sub-graph of objects starting from each reference.
1825 //
1826 // 4) Updates the pointer in the archived copy of referencing object to
1827 // point to the current archived object.
1828 //
1829 // 5) The Klass of the current java object is added to the list of Klasses
1830 // for loading and initializing before any object in the archived graph can
1831 // be accessed at runtime.
1832 //
1833 void HeapShared::archive_reachable_objects_from_static_field(InstanceKlass *k,
1834                                                              const char* klass_name,
1835                                                              int field_offset,
1836                                                              const char* field_name) {
1837   precond(CDSConfig::is_dumping_klass_subgraphs());
1838   assert(k->defined_by_boot_loader(), "must be boot class");
1839 
1840   oop m = k->java_mirror();
1841 
1842   KlassSubGraphInfo* subgraph_info = get_subgraph_info(k);
1843   oop f = m->obj_field(field_offset);
1844 
1845   log_debug(aot, heap)("Start archiving from: %s::%s (" PTR_FORMAT ")", klass_name, field_name, p2i(f));
1846 
1847   if (!CompressedOops::is_null(f)) {
1848     if (log_is_enabled(Trace, aot, heap)) {
1849       LogTarget(Trace, aot, heap) log;
1850       LogStream out(log);
1851       f->print_on(&out);
1852     }
1853 
1854     bool success = archive_reachable_objects_from(1, subgraph_info, f);
1855     if (!success) {
1856       log_error(aot, heap)("Archiving failed %s::%s (some reachable objects cannot be archived)",
1857                            klass_name, field_name);
1858     } else {
1859       // Note: the field value is not preserved in the archived mirror.
1860       // Record the field as a new subGraph entry point. The recorded
1861       // information is restored from the archive at runtime.
1862       subgraph_info->add_subgraph_entry_field(field_offset, f);
1863       log_info(aot, heap)("Archived field %s::%s => " PTR_FORMAT, klass_name, field_name, p2i(f));
1864     }
1865   } else {
1866     // The field contains null, we still need to record the entry point,
1867     // so it can be restored at runtime.
1868     subgraph_info->add_subgraph_entry_field(field_offset, nullptr);
1869   }
1870 }
1871 
1872 #ifndef PRODUCT
1873 class VerifySharedOopClosure: public BasicOopIterateClosure {
1874  public:
1875   void do_oop(narrowOop *p) { VerifySharedOopClosure::do_oop_work(p); }
1876   void do_oop(      oop *p) { VerifySharedOopClosure::do_oop_work(p); }
1877 
1878  protected:
1879   template <class T> void do_oop_work(T *p) {
1880     oop obj = HeapAccess<>::oop_load(p);
1881     if (obj != nullptr) {
1882       HeapShared::verify_reachable_objects_from(obj);
1883     }
1884   }
1885 };
1886 
1887 void HeapShared::verify_subgraph_from_static_field(InstanceKlass* k, int field_offset) {
1888   precond(CDSConfig::is_dumping_klass_subgraphs());
1889   assert(k->defined_by_boot_loader(), "must be boot class");
1890 
1891   oop m = k->java_mirror();
1892   oop f = m->obj_field(field_offset);
1893   if (!CompressedOops::is_null(f)) {
1894     verify_subgraph_from(f);
1895   }
1896 }
1897 
1898 void HeapShared::verify_subgraph_from(oop orig_obj) {
1899   if (!has_been_archived(orig_obj)) {
1900     // It's OK for the root of a subgraph to be not archived. See comments in
1901     // archive_reachable_objects_from().
1902     return;
1903   }
1904 
1905   // Verify that all objects reachable from orig_obj are archived.
1906   init_seen_objects_table();
1907   verify_reachable_objects_from(orig_obj);
1908   delete_seen_objects_table();
1909 }
1910 
1911 void HeapShared::verify_reachable_objects_from(oop obj) {
1912   _num_total_verifications ++;
1913   if (java_lang_Class::is_instance(obj)) {
1914     obj = scratch_java_mirror(obj);
1915     assert(obj != nullptr, "must be");
1916   }
1917   if (!has_been_seen_during_subgraph_recording(obj)) {
1918     set_has_been_seen_during_subgraph_recording(obj);
1919     assert(has_been_archived(obj), "must be");
1920     VerifySharedOopClosure walker;
1921     obj->oop_iterate(&walker);
1922   }
1923 }
1924 #endif
1925 
1926 void HeapShared::check_special_subgraph_classes() {
1927   if (CDSConfig::is_dumping_aot_linked_classes()) {
1928     // We can have aot-initialized classes (such as Enums) that can reference objects
1929     // of arbitrary types. Currently, we trust the JEP 483 implementation to only
1930     // aot-initialize classes that are "safe".
1931     //
1932     // TODO: we need an automatic tool that checks the safety of aot-initialized
1933     // classes (when we extend the set of aot-initialized classes beyond JEP 483)
1934     return;
1935   } else {
1936     // In this case, the special subgraph should contain a few specific types
1937     GrowableArray<Klass*>* klasses = _dump_time_special_subgraph->subgraph_object_klasses();
1938     int num = klasses->length();
1939     for (int i = 0; i < num; i++) {
1940       Klass* subgraph_k = klasses->at(i);
1941       Symbol* name = subgraph_k->name();
1942       if (subgraph_k->is_instance_klass() &&
1943           name != vmSymbols::java_lang_Class() &&
1944           name != vmSymbols::java_lang_String() &&
1945           name != vmSymbols::java_lang_ArithmeticException() &&
1946           name != vmSymbols::java_lang_ArrayIndexOutOfBoundsException() &&
1947           name != vmSymbols::java_lang_ArrayStoreException() &&
1948           name != vmSymbols::java_lang_ClassCastException() &&
1949           name != vmSymbols::java_lang_InternalError() &&
1950           name != vmSymbols::java_lang_NullPointerException() &&
1951           name != vmSymbols::jdk_internal_vm_PreemptedException()) {
1952         ResourceMark rm;
1953         fatal("special subgraph cannot have objects of type %s", subgraph_k->external_name());
1954       }
1955     }
1956   }
1957 }
1958 
1959 HeapShared::SeenObjectsTable* HeapShared::_seen_objects_table = nullptr;
1960 HeapShared::PendingOop HeapShared::_object_being_archived;
1961 size_t HeapShared::_num_new_walked_objs;
1962 size_t HeapShared::_num_new_archived_objs;
1963 size_t HeapShared::_num_old_recorded_klasses;
1964 
1965 size_t HeapShared::_num_total_subgraph_recordings = 0;
1966 size_t HeapShared::_num_total_walked_objs = 0;
1967 size_t HeapShared::_num_total_archived_objs = 0;
1968 size_t HeapShared::_num_total_recorded_klasses = 0;
1969 size_t HeapShared::_num_total_verifications = 0;
1970 
1971 bool HeapShared::has_been_seen_during_subgraph_recording(oop obj) {
1972   return _seen_objects_table->get(obj) != nullptr;
1973 }
1974 
1975 void HeapShared::set_has_been_seen_during_subgraph_recording(oop obj) {
1976   assert(!has_been_seen_during_subgraph_recording(obj), "sanity");
1977   _seen_objects_table->put_when_absent(obj, true);
1978   _seen_objects_table->maybe_grow();
1979   ++ _num_new_walked_objs;
1980 }
1981 
1982 void HeapShared::start_recording_subgraph(InstanceKlass *k, const char* class_name, bool is_full_module_graph) {
1983   log_info(aot, heap)("Start recording subgraph(s) for archived fields in %s", class_name);
1984   init_subgraph_info(k, is_full_module_graph);
1985   init_seen_objects_table();
1986   _num_new_walked_objs = 0;
1987   _num_new_archived_objs = 0;
1988   _num_old_recorded_klasses = get_subgraph_info(k)->num_subgraph_object_klasses();
1989 }
1990 
1991 void HeapShared::done_recording_subgraph(InstanceKlass *k, const char* class_name) {
1992   size_t num_new_recorded_klasses = get_subgraph_info(k)->num_subgraph_object_klasses() -
1993     _num_old_recorded_klasses;
1994   log_info(aot, heap)("Done recording subgraph(s) for archived fields in %s: "
1995                       "walked %zu objs, archived %zu new objs, recorded %zu classes",
1996                       class_name, _num_new_walked_objs, _num_new_archived_objs,
1997                       num_new_recorded_klasses);
1998 
1999   delete_seen_objects_table();
2000 
2001   _num_total_subgraph_recordings ++;
2002   _num_total_walked_objs      += _num_new_walked_objs;
2003   _num_total_archived_objs    += _num_new_archived_objs;
2004   _num_total_recorded_klasses +=  num_new_recorded_klasses;
2005 }
2006 
2007 class ArchivableStaticFieldFinder: public FieldClosure {
2008   InstanceKlass* _ik;
2009   Symbol* _field_name;
2010   bool _found;
2011   int _offset;
2012 public:
2013   ArchivableStaticFieldFinder(InstanceKlass* ik, Symbol* field_name) :
2014     _ik(ik), _field_name(field_name), _found(false), _offset(-1) {}
2015 
2016   virtual void do_field(fieldDescriptor* fd) {
2017     if (fd->name() == _field_name) {
2018       assert(!_found, "fields can never be overloaded");
2019       if (is_reference_type(fd->field_type())) {
2020         _found = true;
2021         _offset = fd->offset();
2022       }
2023     }
2024   }
2025   bool found()     { return _found;  }
2026   int offset()     { return _offset; }
2027 };
2028 
2029 void HeapShared::init_subgraph_entry_fields(ArchivableStaticFieldInfo fields[],
2030                                             TRAPS) {
2031   for (int i = 0; fields[i].valid(); i++) {
2032     ArchivableStaticFieldInfo* info = &fields[i];
2033     TempNewSymbol klass_name =  SymbolTable::new_symbol(info->klass_name);
2034     TempNewSymbol field_name =  SymbolTable::new_symbol(info->field_name);
2035     ResourceMark rm; // for stringStream::as_string() etc.
2036 
2037 #ifndef PRODUCT
2038     bool is_test_class = (ArchiveHeapTestClass != nullptr) && (strcmp(info->klass_name, ArchiveHeapTestClass) == 0);
2039     const char* test_class_name = ArchiveHeapTestClass;
2040 #else
2041     bool is_test_class = false;
2042     const char* test_class_name = ""; // avoid C++ printf checks warnings.
2043 #endif
2044 
2045     if (is_test_class) {
2046       log_warning(aot)("Loading ArchiveHeapTestClass %s ...", test_class_name);
2047     }
2048 
2049     Klass* k = SystemDictionary::resolve_or_fail(klass_name, true, THREAD);
2050     if (HAS_PENDING_EXCEPTION) {
2051       CLEAR_PENDING_EXCEPTION;
2052       stringStream st;
2053       st.print("Fail to initialize archive heap: %s cannot be loaded by the boot loader", info->klass_name);
2054       THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), st.as_string());
2055     }
2056 
2057     if (!k->is_instance_klass()) {
2058       stringStream st;
2059       st.print("Fail to initialize archive heap: %s is not an instance class", info->klass_name);
2060       THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), st.as_string());
2061     }
2062 
2063     InstanceKlass* ik = InstanceKlass::cast(k);
2064     assert(InstanceKlass::cast(ik)->defined_by_boot_loader(),
2065            "Only support boot classes");
2066 
2067     if (is_test_class) {
2068       if (ik->module()->is_named()) {
2069         // We don't want ArchiveHeapTestClass to be abused to easily load/initialize arbitrary
2070         // core-lib classes. You need to at least append to the bootclasspath.
2071         stringStream st;
2072         st.print("ArchiveHeapTestClass %s is not in unnamed module", test_class_name);
2073         THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), st.as_string());
2074       }
2075 
2076       if (ik->package() != nullptr) {
2077         // This restriction makes HeapShared::is_a_test_class_in_unnamed_module() easy.
2078         stringStream st;
2079         st.print("ArchiveHeapTestClass %s is not in unnamed package", test_class_name);
2080         THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), st.as_string());
2081       }
2082     } else {
2083       if (ik->module()->name() != vmSymbols::java_base()) {
2084         // We don't want to deal with cases when a module is unavailable at runtime.
2085         // FUTURE -- load from archived heap only when module graph has not changed
2086         //           between dump and runtime.
2087         stringStream st;
2088         st.print("%s is not in java.base module", info->klass_name);
2089         THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), st.as_string());
2090       }
2091     }
2092 
2093     if (is_test_class) {
2094       log_warning(aot)("Initializing ArchiveHeapTestClass %s ...", test_class_name);
2095     }
2096     ik->initialize(CHECK);
2097 
2098     ArchivableStaticFieldFinder finder(ik, field_name);
2099     ik->do_local_static_fields(&finder);
2100     if (!finder.found()) {
2101       stringStream st;
2102       st.print("Unable to find the static T_OBJECT field %s::%s", info->klass_name, info->field_name);
2103       THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), st.as_string());
2104     }
2105 
2106     info->klass = ik;
2107     info->offset = finder.offset();
2108   }
2109 }
2110 
2111 void HeapShared::init_subgraph_entry_fields(TRAPS) {
2112   assert(CDSConfig::is_dumping_heap(), "must be");
2113   _dump_time_subgraph_info_table = new (mtClass)DumpTimeKlassSubGraphInfoTable();
2114   if (CDSConfig::is_dumping_klass_subgraphs()) {
2115     init_subgraph_entry_fields(archive_subgraph_entry_fields, CHECK);
2116     if (CDSConfig::is_dumping_full_module_graph()) {
2117       init_subgraph_entry_fields(fmg_archive_subgraph_entry_fields, CHECK);
2118     }
2119   }
2120 }
2121 
2122 #ifndef PRODUCT
2123 void HeapShared::setup_test_class(const char* test_class_name) {
2124   ArchivableStaticFieldInfo* p = archive_subgraph_entry_fields;
2125   int num_slots = sizeof(archive_subgraph_entry_fields) / sizeof(ArchivableStaticFieldInfo);
2126   assert(p[num_slots - 2].klass_name == nullptr, "must have empty slot that's patched below");
2127   assert(p[num_slots - 1].klass_name == nullptr, "must have empty slot that marks the end of the list");
2128 
2129   if (test_class_name != nullptr) {
2130     p[num_slots - 2].klass_name = test_class_name;
2131     p[num_slots - 2].field_name = ARCHIVE_TEST_FIELD_NAME;
2132   }
2133 }
2134 
2135 // See if ik is one of the test classes that are pulled in by -XX:ArchiveHeapTestClass
2136 // during runtime. This may be called before the module system is initialized so
2137 // we cannot rely on InstanceKlass::module(), etc.
2138 bool HeapShared::is_a_test_class_in_unnamed_module(Klass* ik) {
2139   if (_test_class != nullptr) {
2140     if (ik == _test_class) {
2141       return true;
2142     }
2143     Array<Klass*>* klasses = _test_class_record->subgraph_object_klasses();
2144     if (klasses == nullptr) {
2145       return false;
2146     }
2147 
2148     for (int i = 0; i < klasses->length(); i++) {
2149       Klass* k = klasses->at(i);
2150       if (k == ik) {
2151         Symbol* name;
2152         if (k->is_instance_klass()) {
2153           name = InstanceKlass::cast(k)->name();
2154         } else if (k->is_objArray_klass()) {
2155           Klass* bk = ObjArrayKlass::cast(k)->bottom_klass();
2156           if (!bk->is_instance_klass()) {
2157             return false;
2158           }
2159           name = bk->name();
2160         } else {
2161           return false;
2162         }
2163 
2164         // See KlassSubGraphInfo::check_allowed_klass() - we only allow test classes
2165         // to be:
2166         //   (A) java.base classes (which must not be in the unnamed module)
2167         //   (B) test classes which must be in the unnamed package of the unnamed module.
2168         // So if we see a '/' character in the class name, it must be in (A);
2169         // otherwise it must be in (B).
2170         if (name->index_of_at(0, "/", 1)  >= 0) {
2171           return false; // (A)
2172         }
2173 
2174         return true; // (B)
2175       }
2176     }
2177   }
2178 
2179   return false;
2180 }
2181 
2182 void HeapShared::initialize_test_class_from_archive(JavaThread* current) {
2183   Klass* k = _test_class;
2184   if (k != nullptr && is_archived_heap_in_use()) {
2185     JavaThread* THREAD = current;
2186     ExceptionMark em(THREAD);
2187     const ArchivedKlassSubGraphInfoRecord* record =
2188       resolve_or_init_classes_for_subgraph_of(k, /*do_init=*/false, THREAD);
2189 
2190     // The _test_class is in the unnamed module, so it can't call CDS.initializeFromArchive()
2191     // from its <clinit> method. So we set up its "archivedObjects" field first, before
2192     // calling its <clinit>. This is not strictly clean, but it's a convenient way to write unit
2193     // test cases (see test/hotspot/jtreg/runtime/cds/appcds/cacheObject/ArchiveHeapTestClass.java).
2194     if (record != nullptr) {
2195       init_archived_fields_for(k, record);
2196     }
2197     resolve_or_init_classes_for_subgraph_of(k, /*do_init=*/true, THREAD);
2198   }
2199 }
2200 #endif
2201 
2202 void HeapShared::init_for_dumping(TRAPS) {
2203   if (CDSConfig::is_dumping_heap()) {
2204     setup_test_class(ArchiveHeapTestClass);
2205     init_subgraph_entry_fields(CHECK);
2206   }
2207 }
2208 
2209 void HeapShared::init_heap_writer() {
2210   if (HeapShared::is_writing_streaming_mode()) {
2211     AOTStreamedHeapWriter::init();
2212   } else {
2213     AOTMappedHeapWriter::init();
2214   }
2215 }
2216 
2217 void HeapShared::archive_object_subgraphs(ArchivableStaticFieldInfo fields[],
2218                                           bool is_full_module_graph) {
2219   _num_total_subgraph_recordings = 0;
2220   _num_total_walked_objs = 0;
2221   _num_total_archived_objs = 0;
2222   _num_total_recorded_klasses = 0;
2223   _num_total_verifications = 0;
2224 
2225   // For each class X that has one or more archived fields:
2226   // [1] Dump the subgraph of each archived field
2227   // [2] Create a list of all the class of the objects that can be reached
2228   //     by any of these static fields.
2229   //     At runtime, these classes are initialized before X's archived fields
2230   //     are restored by HeapShared::initialize_from_archived_subgraph().
2231   for (int i = 0; fields[i].valid(); ) {
2232     ArchivableStaticFieldInfo* info = &fields[i];
2233     const char* klass_name = info->klass_name;
2234     start_recording_subgraph(info->klass, klass_name, is_full_module_graph);
2235 
2236     // If you have specified consecutive fields of the same klass in
2237     // fields[], these will be archived in the same
2238     // {start_recording_subgraph ... done_recording_subgraph} pass to
2239     // save time.
2240     for (; fields[i].valid(); i++) {
2241       ArchivableStaticFieldInfo* f = &fields[i];
2242       if (f->klass_name != klass_name) {
2243         break;
2244       }
2245 
2246       archive_reachable_objects_from_static_field(f->klass, f->klass_name,
2247                                                   f->offset, f->field_name);
2248     }
2249     done_recording_subgraph(info->klass, klass_name);
2250   }
2251 
2252   log_info(aot, heap)("Archived subgraph records = %zu",
2253                       _num_total_subgraph_recordings);
2254   log_info(aot, heap)("  Walked %zu objects", _num_total_walked_objs);
2255   log_info(aot, heap)("  Archived %zu objects", _num_total_archived_objs);
2256   log_info(aot, heap)("  Recorded %zu klasses", _num_total_recorded_klasses);
2257 
2258 #ifndef PRODUCT
2259   for (int i = 0; fields[i].valid(); i++) {
2260     ArchivableStaticFieldInfo* f = &fields[i];
2261     verify_subgraph_from_static_field(f->klass, f->offset);
2262   }
2263   log_info(aot, heap)("  Verified %zu references", _num_total_verifications);
2264 #endif
2265 }
2266 
2267 bool HeapShared::is_dumped_interned_string(oop o) {
2268   if (is_writing_mapping_mode()) {
2269     return AOTMappedHeapWriter::is_dumped_interned_string(o);
2270   } else {
2271     return AOTStreamedHeapWriter::is_dumped_interned_string(o);
2272   }
2273 }
2274 
2275 // These tables should be used only within the CDS safepoint, so
2276 // delete them before we exit the safepoint. Otherwise the table will
2277 // contain bad oops after a GC.
2278 void HeapShared::delete_tables_with_raw_oops() {
2279   assert(_seen_objects_table == nullptr, "should have been deleted");
2280 
2281   if (is_writing_mapping_mode()) {
2282     AOTMappedHeapWriter::delete_tables_with_raw_oops();
2283   } else {
2284     assert(is_writing_streaming_mode(), "what other mode?");
2285     AOTStreamedHeapWriter::delete_tables_with_raw_oops();
2286   }
2287 }
2288 
2289 void HeapShared::debug_trace() {
2290   ResourceMark rm;
2291   oop referrer = _object_being_archived.referrer();
2292   if (referrer != nullptr) {
2293     LogStream ls(Log(aot, heap)::error());
2294     ls.print_cr("Reference trace");
2295     CDSHeapVerifier::trace_to_root(&ls, referrer);
2296   }
2297 }
2298 
2299 #ifndef PRODUCT
2300 // At dump-time, find the location of all the non-null oop pointers in an archived heap
2301 // region. This way we can quickly relocate all the pointers without using
2302 // BasicOopIterateClosure at runtime.
2303 class FindEmbeddedNonNullPointers: public BasicOopIterateClosure {
2304   void* _start;
2305   BitMap *_oopmap;
2306   size_t _num_total_oops;
2307   size_t _num_null_oops;
2308  public:
2309   FindEmbeddedNonNullPointers(void* start, BitMap* oopmap)
2310     : _start(start), _oopmap(oopmap), _num_total_oops(0),  _num_null_oops(0) {}
2311 
2312   virtual void do_oop(narrowOop* p) {
2313     assert(UseCompressedOops, "sanity");
2314     _num_total_oops ++;
2315     narrowOop v = *p;
2316     if (!CompressedOops::is_null(v)) {
2317       size_t idx = p - (narrowOop*)_start;
2318       _oopmap->set_bit(idx);
2319     } else {
2320       _num_null_oops ++;
2321     }
2322   }
2323   virtual void do_oop(oop* p) {
2324     assert(!UseCompressedOops, "sanity");
2325     _num_total_oops ++;
2326     if ((*p) != nullptr) {
2327       size_t idx = p - (oop*)_start;
2328       _oopmap->set_bit(idx);
2329     } else {
2330       _num_null_oops ++;
2331     }
2332   }
2333   size_t num_total_oops() const { return _num_total_oops; }
2334   size_t num_null_oops()  const { return _num_null_oops; }
2335 };
2336 #endif
2337 
2338 void HeapShared::count_allocation(size_t size) {
2339   _total_obj_count ++;
2340   _total_obj_size += size;
2341   for (int i = 0; i < ALLOC_STAT_SLOTS; i++) {
2342     if (size <= (size_t(1) << i)) {
2343       _alloc_count[i] ++;
2344       _alloc_size[i] += size;
2345       return;
2346     }
2347   }
2348 }
2349 
2350 static double avg_size(size_t size, size_t count) {
2351   double avg = 0;
2352   if (count > 0) {
2353     avg = double(size * HeapWordSize) / double(count);
2354   }
2355   return avg;
2356 }
2357 
2358 void HeapShared::print_stats() {
2359   size_t huge_count = _total_obj_count;
2360   size_t huge_size = _total_obj_size;
2361 
2362   for (int i = 0; i < ALLOC_STAT_SLOTS; i++) {
2363     size_t byte_size_limit = (size_t(1) << i) * HeapWordSize;
2364     size_t count = _alloc_count[i];
2365     size_t size = _alloc_size[i];
2366     log_info(aot, heap)("%8zu objects are <= %-6zu"
2367                         " bytes (total %8zu bytes, avg %8.1f bytes)",
2368                         count, byte_size_limit, size * HeapWordSize, avg_size(size, count));
2369     huge_count -= count;
2370     huge_size -= size;
2371   }
2372 
2373   log_info(aot, heap)("%8zu huge  objects               (total %8zu bytes"
2374                       ", avg %8.1f bytes)",
2375                       huge_count, huge_size * HeapWordSize,
2376                       avg_size(huge_size, huge_count));
2377   log_info(aot, heap)("%8zu total objects               (total %8zu bytes"
2378                       ", avg %8.1f bytes)",
2379                       _total_obj_count, _total_obj_size * HeapWordSize,
2380                       avg_size(_total_obj_size, _total_obj_count));
2381 }
2382 
2383 bool HeapShared::is_metadata_field(oop src_obj, int offset) {
2384   bool result = false;
2385   do_metadata_offsets(src_obj, [&](int metadata_offset) {
2386     if (metadata_offset == offset) {
2387       result = true;
2388     }
2389   });
2390   return result;
2391 }
2392 
2393 void HeapShared::remap_dumped_metadata(oop src_obj, address archived_object) {
2394   do_metadata_offsets(src_obj, [&](int offset) {
2395     Metadata** buffered_field_addr = (Metadata**)(archived_object + offset);
2396     Metadata* native_ptr = *buffered_field_addr;
2397 
2398     if (native_ptr == nullptr) {
2399       return;
2400     }
2401 
2402     if (RegeneratedClasses::has_been_regenerated(native_ptr)) {
2403       native_ptr = RegeneratedClasses::get_regenerated_object(native_ptr);
2404     }
2405 
2406     address buffered_native_ptr = ArchiveBuilder::current()->get_buffered_addr((address)native_ptr);
2407     address requested_native_ptr = ArchiveBuilder::current()->to_requested(buffered_native_ptr);
2408     *buffered_field_addr = (Metadata*)requested_native_ptr;
2409   });
2410 }
2411 
2412 bool HeapShared::is_archived_boot_layer_available(JavaThread* current) {
2413   TempNewSymbol klass_name = SymbolTable::new_symbol(ARCHIVED_BOOT_LAYER_CLASS);
2414   InstanceKlass* k = SystemDictionary::find_instance_klass(current, klass_name, Handle());
2415   if (k == nullptr) {
2416     return false;
2417   } else {
2418     TempNewSymbol field_name = SymbolTable::new_symbol(ARCHIVED_BOOT_LAYER_FIELD);
2419     TempNewSymbol field_signature = SymbolTable::new_symbol("Ljdk/internal/module/ArchivedBootLayer;");
2420     fieldDescriptor fd;
2421     if (k->find_field(field_name, field_signature, true, &fd) != nullptr) {
2422       oop m = k->java_mirror();
2423       oop f = m->obj_field(fd.offset());
2424       if (CompressedOops::is_null(f)) {
2425         return false;
2426       }
2427     } else {
2428       return false;
2429     }
2430   }
2431   return true;
2432 }
2433 
2434 #endif // INCLUDE_CDS_JAVA_HEAP