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