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