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