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