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