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