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