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