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