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