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