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