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