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