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