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