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