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