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