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