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