1 /*
   2  * Copyright (c) 2018, 2024, 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/classPreinitializer.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 DumpedInternedStrings *HeapShared::_dumped_interned_strings = nullptr;
 110 
 111 size_t HeapShared::_alloc_count[HeapShared::ALLOC_STAT_SLOTS];
 112 size_t HeapShared::_alloc_size[HeapShared::ALLOC_STAT_SLOTS];
 113 size_t HeapShared::_total_obj_count;
 114 size_t HeapShared::_total_obj_size;
 115 
 116 #ifndef PRODUCT
 117 #define ARCHIVE_TEST_FIELD_NAME "archivedObjects"
 118 static Array<char>* _archived_ArchiveHeapTestClass = nullptr;
 119 static const char* _test_class_name = nullptr;
 120 static const Klass* _test_class = nullptr;
 121 static const ArchivedKlassSubGraphInfoRecord* _test_class_record = nullptr;
 122 #endif
 123 
 124 
 125 //
 126 // If you add new entries to the following tables, you should know what you're doing!
 127 //
 128 
 129 static ArchivableStaticFieldInfo archive_subgraph_entry_fields[] = {
 130   {"java/lang/Boolean",                           "archivedCache"},
 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"},  // FIXME -- requires PreloadSharedClasses
 144   {"java/lang/invoke/MethodType",                 "archivedObjects"},  // FIXME -- requires PreloadSharedClasses
 145   {"java/lang/invoke/LambdaForm$NamedFunction",   "archivedObjects"},  // FIXME -- requires PreloadSharedClasses
 146   {"java/lang/reflect/Proxy$ProxyBuilder",        "archivedData"},     // FIXME -- requires PreloadSharedClasses
 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 MetaspaceObjToOopHandleTable* HeapShared::_scratch_java_mirror_table = nullptr;
 169 MetaspaceObjToOopHandleTable* HeapShared::_scratch_references_table = nullptr;
 170 int HeapShared::_permobj_segments = 0;
 171 
 172 static bool is_subgraph_root_class_of(ArchivableStaticFieldInfo fields[], InstanceKlass* ik) {
 173   for (int i = 0; fields[i].valid(); i++) {
 174     if (fields[i].klass == ik) {
 175       return true;
 176     }
 177   }
 178   return false;
 179 }
 180 
 181 bool HeapShared::is_subgraph_root_class(InstanceKlass* ik) {
 182   return is_subgraph_root_class_of(archive_subgraph_entry_fields, ik) ||
 183          is_subgraph_root_class_of(fmg_archive_subgraph_entry_fields, ik);
 184 }
 185 
 186 unsigned HeapShared::oop_hash(oop const& p) {
 187   // Do not call p->identity_hash() as that will update the
 188   // object header.
 189   return primitive_hash(cast_from_oop<intptr_t>(p));
 190 }
 191 
 192 static void reset_states(oop obj, TRAPS) {
 193   Handle h_obj(THREAD, obj);
 194   InstanceKlass* klass = InstanceKlass::cast(obj->klass());
 195   TempNewSymbol method_name = SymbolTable::new_symbol("resetArchivedStates");
 196   Symbol* method_sig = vmSymbols::void_method_signature();
 197 
 198   while (klass != nullptr) {
 199     Method* method = klass->find_method(method_name, method_sig);
 200     if (method != nullptr) {
 201       assert(method->is_private(), "must be");
 202       if (log_is_enabled(Debug, cds)) {
 203         ResourceMark rm(THREAD);
 204         log_debug(cds)("  calling %s", method->name_and_sig_as_C_string());
 205       }
 206       JavaValue result(T_VOID);
 207       JavaCalls::call_special(&result, h_obj, klass,
 208                               method_name, method_sig, CHECK);
 209     }
 210     klass = klass->java_super();
 211   }
 212 }
 213 
 214 void HeapShared::reset_archived_object_states(TRAPS) {
 215   assert(CDSConfig::is_dumping_heap(), "dump-time only");
 216   log_debug(cds)("Resetting platform loader");
 217   reset_states(SystemDictionary::java_platform_loader(), CHECK);
 218   log_debug(cds)("Resetting system loader");
 219   reset_states(SystemDictionary::java_system_loader(), CHECK);
 220 
 221   // Clean up jdk.internal.loader.ClassLoaders::bootLoader(), which is not
 222   // directly used for class loading, but rather is used by the core library
 223   // to keep track of resources, etc, loaded by the null class loader.
 224   //
 225   // Note, this object is non-null, and is not the same as
 226   // ClassLoaderData::the_null_class_loader_data()->class_loader(),
 227   // which is null.
 228   log_debug(cds)("Resetting boot loader");
 229   JavaValue result(T_OBJECT);
 230   JavaCalls::call_static(&result,
 231                          vmClasses::jdk_internal_loader_ClassLoaders_klass(),
 232                          vmSymbols::bootLoader_name(),
 233                          vmSymbols::void_BuiltinClassLoader_signature(),
 234                          CHECK);
 235   Handle boot_loader(THREAD, result.get_oop());
 236   reset_states(boot_loader(), CHECK);
 237 }
 238 
 239 HeapShared::ArchivedObjectCache* HeapShared::_archived_object_cache = nullptr;
 240 
 241 bool HeapShared::has_been_archived(oop obj) {
 242   assert(CDSConfig::is_dumping_heap(), "dump-time only");
 243   return archived_object_cache()->get(obj) != nullptr;
 244 }
 245 
 246 int HeapShared::append_root(oop obj) {
 247   assert(CDSConfig::is_dumping_heap(), "dump-time only");
 248 
 249   // No GC should happen since we aren't scanning _pending_roots.
 250   assert(Thread::current() == (Thread*)VMThread::vm_thread(), "should be in vm thread");
 251 
 252   if (_pending_roots == nullptr) {
 253     _pending_roots = new GrowableArrayCHeap<oop, mtClassShared>(500);
 254   }
 255 
 256   return _pending_roots->append(obj);
 257 }
 258 
 259 objArrayOop HeapShared::roots() {
 260   if (CDSConfig::is_dumping_heap() && !CDSConfig::is_dumping_final_static_archive()) {
 261     assert(Thread::current() == (Thread*)VMThread::vm_thread(), "should be in vm thread");
 262     if (!HeapShared::can_write()) {
 263       return nullptr;
 264     }
 265   } else {
 266     assert(UseSharedSpaces, "must be");
 267   }
 268 
 269   objArrayOop roots = (objArrayOop)_roots.resolve();
 270   assert(roots != nullptr, "should have been initialized");
 271   return roots;
 272 }
 273 
 274 static unsigned int oop_handle_hash(const OopHandle& oh) {
 275   oop o = oh.resolve();
 276   if (o == nullptr) {
 277     return 0;
 278   } else {
 279     return o->identity_hash();
 280   }
 281 }
 282 
 283 static bool oop_handle_equals(const OopHandle& a, const OopHandle& b) {
 284   return a.resolve() == b.resolve();
 285 }
 286 
 287 class OrigToScratchObjectTable: public ResourceHashtable<OopHandle, OopHandle,
 288     36137, // prime number
 289     AnyObj::C_HEAP,
 290     mtClassShared,
 291     oop_handle_hash,
 292     oop_handle_equals> {};
 293 
 294 static OrigToScratchObjectTable* _orig_to_scratch_object_table = nullptr;
 295 
 296 void HeapShared::track_scratch_object(oop orig_obj, oop scratch_obj) {
 297   MutexLocker ml(ArchivedObjectTables_lock, Mutex::_no_safepoint_check_flag);
 298   if (_orig_to_scratch_object_table == nullptr) {
 299     _orig_to_scratch_object_table = new (mtClass)OrigToScratchObjectTable();
 300   }
 301 
 302   OopHandle orig_h(Universe::vm_global(), orig_obj);
 303   OopHandle scratch_h(Universe::vm_global(), scratch_obj);
 304   _orig_to_scratch_object_table->put_when_absent(orig_h, scratch_h);
 305 }
 306 
 307 oop HeapShared::orig_to_scratch_object(oop orig_obj) {
 308   MutexLocker ml(ArchivedObjectTables_lock, Mutex::_no_safepoint_check_flag);
 309   if (_orig_to_scratch_object_table != nullptr) {
 310     OopHandle orig(&orig_obj);
 311     OopHandle* v = _orig_to_scratch_object_table->get(orig);
 312     if (v != nullptr) {
 313       return v->resolve();
 314     }
 315   }
 316   return nullptr;
 317 }
 318 
 319 class ArchivedObjectPermanentIndexTable: public ResourceHashtable<OopHandle, int,
 320     36137, // prime number
 321     AnyObj::C_HEAP,
 322     mtClassShared,
 323     oop_handle_hash,
 324     oop_handle_equals> {};
 325 
 326 static ArchivedObjectPermanentIndexTable* _permanent_index_table = nullptr;
 327 
 328 void HeapShared::add_to_permanent_index_table(oop obj, int index) {
 329   assert_locked_or_safepoint(ArchivedObjectTables_lock);
 330 
 331   if (_permanent_index_table == nullptr) {
 332     _permanent_index_table = new (mtClass)ArchivedObjectPermanentIndexTable();
 333   }
 334   OopHandle oh(Universe::vm_global(), obj);
 335   _permanent_index_table->put(oh, index);
 336 }
 337 
 338 int HeapShared::get_archived_object_permanent_index(oop obj) {
 339   if (!UsePermanentHeapObjects) {
 340     return -1;
 341   }
 342   if (!CDSConfig::is_dumping_heap() && _permobj_segments <= 0) {
 343     return -1;
 344   }
 345 
 346   MutexLocker ml(ArchivedObjectTables_lock, Mutex::_no_safepoint_check_flag);
 347 
 348   if (!CDSConfig::is_dumping_heap() && _permanent_index_table == nullptr) {
 349     int first_permobj_segment = roots()->length() - _permobj_segments;
 350     for (int i = 0; i < _permobj_segments; i++) {
 351       objArrayOop a = (objArrayOop)roots()->obj_at(i + first_permobj_segment);
 352       for (int j = 0; j < a->length(); j++) {
 353         int index = (i << ArchiveHeapWriter::PERMOBJ_SEGMENT_MAX_SHIFT) + j;
 354         add_to_permanent_index_table(a->obj_at(j), index);
 355       }
 356     }
 357   }
 358 
 359   if (_permanent_index_table != nullptr) {
 360     if (_orig_to_scratch_object_table != nullptr) {
 361       OopHandle orig(&obj);
 362       OopHandle* v = _orig_to_scratch_object_table->get(orig);
 363       if (v != nullptr) {
 364         obj = v->resolve();
 365       }
 366     }
 367     OopHandle tmp(&obj);
 368     int* v = _permanent_index_table->get(tmp);
 369     if (v != nullptr) {
 370       int n = *v;
 371       return n;
 372     }
 373   }
 374 
 375   return -1;
 376 }
 377 
 378 oop HeapShared::get_archived_object(int permanent_index) {
 379   if (ArchiveHeapLoader::is_in_use()) {
 380     assert(_permobj_segments > 0, "must be");
 381 
 382     int first_permobj_segment = roots()->length() - _permobj_segments;
 383     int upper = permanent_index >> ArchiveHeapWriter::PERMOBJ_SEGMENT_MAX_SHIFT;
 384     int lower = permanent_index &  ArchiveHeapWriter::PERMOBJ_SEGMENT_MAX_MASK;
 385     objArrayOop a = (objArrayOop)roots()->obj_at(upper + first_permobj_segment);
 386     return a->obj_at(lower);
 387   } else {
 388     assert(CDSConfig::is_dumping_heap(), "must be");
 389     return ArchiveHeapWriter::get_perm_object_by_index(permanent_index);
 390   }
 391 }
 392 
 393 // Returns an objArray that contains all the roots of the archived objects
 394 oop HeapShared::get_root(int index, bool clear) {
 395   assert(index >= 0, "sanity");
 396   assert(!CDSConfig::is_dumping_heap() && UseSharedSpaces, "runtime only");
 397   assert(!_roots.is_empty(), "must have loaded shared heap");
 398   oop result = roots()->obj_at(index);
 399   if (clear) {
 400     clear_root(index);
 401   }
 402   return result;
 403 }
 404 
 405 void HeapShared::clear_root(int index) {
 406   assert(index >= 0, "sanity");
 407   assert(UseSharedSpaces, "must be");
 408   if (ArchiveHeapLoader::is_in_use()) {
 409     if (log_is_enabled(Debug, cds, heap)) {
 410       oop old = roots()->obj_at(index);
 411       log_debug(cds, heap)("Clearing root %d: was " PTR_FORMAT, index, p2i(old));
 412     }
 413     roots()->obj_at_put(index, nullptr);
 414   }
 415 }
 416 
 417 bool HeapShared::archive_object(oop obj) {
 418   assert(CDSConfig::is_dumping_heap(), "dump-time only");
 419 
 420   assert(!obj->is_stackChunk(), "do not archive stack chunks");
 421   if (has_been_archived(obj)) {
 422     return true;
 423   }
 424 
 425   if (ArchiveHeapWriter::is_too_large_to_archive(obj->size())) {
 426     log_debug(cds, heap)("Cannot archive, object (" PTR_FORMAT ") is too large: " SIZE_FORMAT,
 427                          p2i(obj), obj->size());
 428     return false;
 429   } else {
 430     count_allocation(obj->size());
 431     ArchiveHeapWriter::add_source_obj(obj);
 432 
 433     // The archived objects are discovered in a predictable order. Compute
 434     // their identity_hash() as soon as we see them. This ensures that the
 435     // the identity_hash in the object header will have a predictable value,
 436     // making the archive reproducible.
 437     obj->identity_hash();
 438     CachedOopInfo info = make_cached_oop_info(obj);
 439     archived_object_cache()->put_when_absent(obj, info);
 440     archived_object_cache()->maybe_grow();
 441     mark_native_pointers(obj);
 442 
 443     if (log_is_enabled(Debug, cds, heap)) {
 444       ResourceMark rm;
 445       log_debug(cds, heap)("Archived heap object " PTR_FORMAT " : %s",
 446                            p2i(obj), obj->klass()->external_name());
 447     }
 448 
 449     if (java_lang_Module::is_instance(obj) && Modules::check_archived_module_oop(obj)) {
 450       Modules::update_oops_in_archived_module(obj, append_root(obj));
 451     }
 452 
 453     return true;
 454   }
 455 }
 456 
 457 class MetaspaceObjToOopHandleTable: public ResourceHashtable<MetaspaceObj*, OopHandle,
 458     36137, // prime number
 459     AnyObj::C_HEAP,
 460     mtClassShared> {
 461 public:
 462   oop get_oop(MetaspaceObj* ptr) {
 463     MutexLocker ml(ScratchObjects_lock, Mutex::_no_safepoint_check_flag);
 464     OopHandle* handle = get(ptr);
 465     if (handle != nullptr) {
 466       return handle->resolve();
 467     } else {
 468       return nullptr;
 469     }
 470   }
 471   void set_oop(MetaspaceObj* ptr, oop o) {
 472     MutexLocker ml(ScratchObjects_lock, Mutex::_no_safepoint_check_flag);
 473     OopHandle handle(Universe::vm_global(), o);
 474     bool is_new = put(ptr, handle);
 475     assert(is_new, "cannot set twice");
 476   }
 477   void remove_oop(MetaspaceObj* ptr) {
 478     MutexLocker ml(ScratchObjects_lock, Mutex::_no_safepoint_check_flag);
 479     OopHandle* handle = get(ptr);
 480     if (handle != nullptr) {
 481       handle->release(Universe::vm_global());
 482       remove(ptr);
 483     }
 484   }
 485 };
 486 
 487 void HeapShared::add_scratch_resolved_references(ConstantPool* src, objArrayOop dest) {
 488   if (_scratch_references_table == nullptr) {
 489     _scratch_references_table = new (mtClass)MetaspaceObjToOopHandleTable();
 490   }
 491   _scratch_references_table->set_oop(src, dest);
 492 }
 493 
 494 objArrayOop HeapShared::scratch_resolved_references(ConstantPool* src) {
 495   return (objArrayOop)_scratch_references_table->get_oop(src);
 496 }
 497 
 498 void HeapShared::init_scratch_objects(TRAPS) {
 499   for (int i = T_BOOLEAN; i < T_VOID+1; i++) {
 500     BasicType bt = (BasicType)i;
 501     if (!is_reference_type(bt)) {
 502       oop m = java_lang_Class::create_basic_type_mirror(type2name(bt), bt, CHECK);
 503       _scratch_basic_type_mirrors[i] = OopHandle(Universe::vm_global(), m);
 504       track_scratch_object(Universe::java_mirror(bt), m);
 505     }
 506   }
 507   _scratch_java_mirror_table = new (mtClass)MetaspaceObjToOopHandleTable();
 508   if (_scratch_references_table == nullptr) {
 509     _scratch_references_table = new (mtClass)MetaspaceObjToOopHandleTable();
 510   }
 511 }
 512 
 513 // Given java_mirror that represents a (primitive or reference) type T,
 514 // return the "scratch" version that represents the same type T.
 515 // Note that if java_mirror will be returned if it's already a
 516 // scratch mirror.
 517 //
 518 // See java_lang_Class::create_scratch_mirror() for more info.
 519 oop HeapShared::scratch_java_mirror(oop java_mirror) {
 520   assert(java_lang_Class::is_instance(java_mirror), "must be");
 521 
 522   for (int i = T_BOOLEAN; i < T_VOID+1; i++) {
 523     BasicType bt = (BasicType)i;
 524     if (!is_reference_type(bt)) {
 525       if (_scratch_basic_type_mirrors[i].resolve() == java_mirror) {
 526         return java_mirror;
 527       }
 528     }
 529   }
 530 
 531   if (java_lang_Class::is_primitive(java_mirror)) {
 532     return scratch_java_mirror(java_lang_Class::as_BasicType(java_mirror));
 533   } else {
 534     return scratch_java_mirror(java_lang_Class::as_Klass(java_mirror));
 535   }
 536 }
 537 
 538 oop HeapShared::scratch_java_mirror(BasicType t) {
 539   assert((uint)t < T_VOID+1, "range check");
 540   assert(!is_reference_type(t), "sanity");
 541   return _scratch_basic_type_mirrors[t].resolve();
 542 }
 543 
 544 oop HeapShared::scratch_java_mirror(Klass* k) {
 545   return _scratch_java_mirror_table->get_oop(k);
 546 }
 547 
 548 void HeapShared::set_scratch_java_mirror(Klass* k, oop mirror) {
 549   track_scratch_object(k->java_mirror(), mirror);
 550   _scratch_java_mirror_table->set_oop(k, mirror);
 551 }
 552 
 553 void HeapShared::remove_scratch_objects(Klass* k) {
 554   _scratch_java_mirror_table->remove_oop(k);
 555   if (k->is_instance_klass()) {
 556     _scratch_references_table->remove(InstanceKlass::cast(k)->constants());
 557   }
 558 }
 559 
 560 bool HeapShared::is_lambda_form_klass(InstanceKlass* ik) {
 561   return ik->is_hidden() &&
 562     (ik->name()->starts_with("java/lang/invoke/LambdaForm$MH+") ||
 563      ik->name()->starts_with("java/lang/invoke/LambdaForm$DMH+") ||
 564      ik->name()->starts_with("java/lang/invoke/LambdaForm$BMH+"));
 565      
 566 }
 567 
 568 bool HeapShared::is_lambda_proxy_klass(InstanceKlass* ik) {
 569   return ik->is_hidden() && (ik->name()->index_of_at(0, "$$Lambda+", 9) > 0);
 570 }
 571 
 572 bool HeapShared::is_archivable_hidden_klass(InstanceKlass* ik) {
 573   return is_lambda_form_klass(ik) || is_lambda_proxy_klass(ik);
 574 }
 575 
 576 void HeapShared::copy_preinitialized_mirror(Klass* orig_k, oop orig_mirror, oop m) {
 577   if (!orig_k->is_instance_klass()) {
 578     return;
 579   }
 580   InstanceKlass* ik = InstanceKlass::cast(orig_k);
 581 
 582   if (HeapShared::is_archivable_hidden_klass(ik)) {
 583     // We can't rerun the <clinit> method of hidden classes as we don't save
 584     // the classData, so we must archive its mirror in initialized state.
 585     assert(ik->is_initialized(), "must be");
 586   }
 587 
 588   if (!ik->is_initialized() || !ClassPreinitializer::can_archive_preinitialized_mirror(ik)) {
 589     return;
 590   }
 591 
 592   int nfields = 0;
 593   for (JavaFieldStream fs(ik); !fs.done(); fs.next()) {
 594     if (fs.access_flags().is_static()) {
 595       fieldDescriptor& fd = fs.field_descriptor();
 596       int offset = fd.offset();
 597       switch (fd.field_type()) {
 598       case T_OBJECT:
 599       case T_ARRAY:
 600         m->obj_field_put(offset, orig_mirror->obj_field(offset));
 601         break;
 602       case T_BOOLEAN:
 603         m->bool_field_put(offset, orig_mirror->bool_field(offset));
 604         break;
 605       case T_BYTE:
 606         m->byte_field_put(offset, orig_mirror->byte_field(offset));
 607         break;
 608       case T_SHORT:
 609         m->short_field_put(offset, orig_mirror->short_field(offset));
 610         break;
 611       case T_CHAR:
 612         m->char_field_put(offset, orig_mirror->char_field(offset));
 613         break;
 614       case T_INT:
 615         m->int_field_put(offset, orig_mirror->int_field(offset));
 616         break;
 617       case T_LONG:
 618         m->long_field_put(offset, orig_mirror->long_field(offset));
 619         break;
 620       case T_FLOAT:
 621         m->float_field_put(offset, orig_mirror->float_field(offset));
 622         break;
 623       case T_DOUBLE:
 624         m->double_field_put(offset, orig_mirror->double_field(offset));
 625         break;
 626       default:
 627         ShouldNotReachHere();
 628       }
 629       nfields ++;
 630     }
 631   }
 632   if (log_is_enabled(Info, cds, init)) {
 633     ResourceMark rm;
 634     log_debug(cds, init)("copied %3d field(s) in preinitialized mirror %s%s", nfields, ik->external_name(),
 635                          ik->is_hidden() ? " (hidden)" : "");
 636   }
 637 
 638   InstanceKlass* buffered_ik = ArchiveBuilder::current()->get_buffered_addr(ik);
 639   buffered_ik->set_has_preinitialized_mirror();
 640 }
 641 
 642 static void copy_java_mirror_hashcode(oop orig_mirror, oop scratch_m) {
 643   int src_hash = orig_mirror->identity_hash();
 644   scratch_m->set_mark(markWord::prototype().copy_set_hash(src_hash));
 645   assert(scratch_m->mark().is_unlocked(), "sanity");
 646 
 647   DEBUG_ONLY(int archived_hash = scratch_m->identity_hash());
 648   assert(src_hash == archived_hash, "Java mirror wrong hash: original %x, scratch %x", src_hash, archived_hash);
 649 }
 650 
 651 void HeapShared::archive_java_mirrors() {
 652   ClassPreinitializer::reset_preinit_check();
 653 
 654   for (int i = T_BOOLEAN; i < T_VOID+1; i++) {
 655     BasicType bt = (BasicType)i;
 656     if (!is_reference_type(bt)) {
 657       oop orig_mirror = Universe::java_mirror(bt);
 658       oop m = _scratch_basic_type_mirrors[i].resolve();
 659       assert(m != nullptr, "sanity");
 660       copy_java_mirror_hashcode(orig_mirror, m);
 661       bool success = archive_reachable_objects_from(1, _default_subgraph_info, orig_mirror);
 662       assert(success, "sanity");
 663 
 664       log_trace(cds, heap, mirror)(
 665         "Archived %s mirror object from " PTR_FORMAT,
 666         type2name(bt), p2i(m));
 667 
 668       Universe::set_archived_basic_type_mirror_index(bt, append_root(m));
 669     }
 670   }
 671 
 672   GrowableArray<Klass*>* klasses = ArchiveBuilder::current()->klasses();
 673   assert(klasses != nullptr, "sanity");
 674   for (int i = 0; i < klasses->length(); i++) {
 675     Klass* orig_k = klasses->at(i);
 676     oop orig_mirror = orig_k->java_mirror();
 677     oop m = scratch_java_mirror(orig_k);
 678     if (m != nullptr) {
 679       copy_java_mirror_hashcode(orig_mirror, m);
 680       copy_preinitialized_mirror(orig_k, orig_mirror, m);
 681       if (ArchiveReflectionData && java_lang_Class::has_reflection_data(orig_mirror)) {
 682         oop reflection_data = java_lang_Class::reflection_data(orig_mirror);
 683         bool success = archive_reachable_objects_from(1, _default_subgraph_info, reflection_data);
 684         guarantee(success, "");
 685         java_lang_Class::set_reflection_data(m, reflection_data);
 686       }
 687       Klass* buffered_k = ArchiveBuilder::get_buffered_klass(orig_k);
 688       bool success = archive_reachable_objects_from(1, _default_subgraph_info, orig_mirror);
 689       guarantee(success, "scratch mirrors must point to only archivable objects");
 690       buffered_k->set_archived_java_mirror(append_root(m));
 691       ResourceMark rm;
 692       log_trace(cds, heap, mirror)(
 693         "Archived %s mirror object from " PTR_FORMAT,
 694         buffered_k->external_name(), p2i(m));
 695 
 696       // archive the resolved_referenes array
 697       if (buffered_k->is_instance_klass()) {
 698         InstanceKlass* ik = InstanceKlass::cast(buffered_k);
 699         oop rr = ik->constants()->prepare_resolved_references_for_archiving();
 700         if (rr != nullptr && !ArchiveHeapWriter::is_too_large_to_archive(rr)) {
 701           bool success = HeapShared::archive_reachable_objects_from(1, _default_subgraph_info, rr);
 702           assert(success, "must be");
 703           int root_index = append_root(rr);
 704           ik->constants()->cache()->set_archived_references(root_index);
 705         }
 706       }
 707     }
 708   }
 709 }
 710 
 711 void HeapShared::archive_strings() {
 712   oop shared_strings_array = StringTable::init_shared_table(_dumped_interned_strings);
 713   bool success = archive_reachable_objects_from(1, _default_subgraph_info, shared_strings_array);
 714   // We must succeed because:
 715   // - _dumped_interned_strings do not contain any large strings.
 716   // - StringTable::init_shared_table() doesn't create any large arrays.
 717   assert(success, "shared strings array must not point to arrays or strings that are too large to archive");
 718   StringTable::set_shared_strings_array_index(append_root(shared_strings_array));
 719 }
 720 
 721 int HeapShared::archive_exception_instance(oop exception) {
 722   bool success = archive_reachable_objects_from(1, _default_subgraph_info, exception);
 723   assert(success, "sanity");
 724   return append_root(exception);
 725 }
 726 
 727 void HeapShared::mark_native_pointers(oop orig_obj) {
 728   if (java_lang_Class::is_instance(orig_obj)) {
 729     ArchiveHeapWriter::mark_native_pointer(orig_obj, java_lang_Class::klass_offset());
 730     ArchiveHeapWriter::mark_native_pointer(orig_obj, java_lang_Class::array_klass_offset());
 731   } else if (java_lang_invoke_ResolvedMethodName::is_instance(orig_obj)) {
 732     ArchiveHeapWriter::mark_native_pointer(orig_obj, java_lang_invoke_ResolvedMethodName::vmtarget_offset());
 733   }
 734 }
 735 
 736 void HeapShared::get_pointer_info(oop src_obj, bool& has_oop_pointers, bool& has_native_pointers) {
 737   CachedOopInfo* info = archived_object_cache()->get(src_obj);
 738   assert(info != nullptr, "must be");
 739   has_oop_pointers = info->has_oop_pointers();
 740   has_native_pointers = info->has_native_pointers();
 741 }
 742 
 743 void HeapShared::set_has_native_pointers(oop src_obj) {
 744   CachedOopInfo* info = archived_object_cache()->get(src_obj);
 745   assert(info != nullptr, "must be");
 746   info->set_has_native_pointers();
 747 }
 748 

























































































 749 void HeapShared::archive_objects(ArchiveHeapInfo *heap_info) {
 750   {
 751     NoSafepointVerifier nsv;
 752 
 753     _default_subgraph_info = init_subgraph_info(vmClasses::Object_klass(), false);
 754     _trace = new GrowableArrayCHeap<oop, mtClassShared>(250);
 755     _context = new GrowableArrayCHeap<const char*, mtClassShared>(250);
 756 
 757     // Cache for recording where the archived objects are copied to
 758     create_archived_object_cache();
 759 
 760     log_info(cds)("Heap range = [" PTR_FORMAT " - "  PTR_FORMAT "]",
 761                    UseCompressedOops ? p2i(CompressedOops::begin()) :
 762                                        p2i((address)G1CollectedHeap::heap()->reserved().start()),
 763                    UseCompressedOops ? p2i(CompressedOops::end()) :
 764                                        p2i((address)G1CollectedHeap::heap()->reserved().end()));
 765     copy_objects();
 766 
 767     CDSHeapVerifier::verify();
 768     check_default_subgraph_classes();
 769   }
 770 
 771   ArchiveHeapWriter::write(_pending_roots, heap_info);
 772 }
 773 
 774 void HeapShared::copy_interned_strings() {
 775   init_seen_objects_table();
 776 
 777   auto copier = [&] (oop s, bool value_ignored) {
 778     assert(s != nullptr, "sanity");
 779     assert(!ArchiveHeapWriter::is_string_too_large_to_archive(s), "large strings must have been filtered");
 780     bool success = archive_reachable_objects_from(1, _default_subgraph_info, s);
 781     assert(success, "must be");
 782     // Prevent string deduplication from changing the value field to
 783     // something not in the archive.
 784     java_lang_String::set_deduplication_forbidden(s);
 785   };
 786   _dumped_interned_strings->iterate_all(copier);
 787 
 788   delete_seen_objects_table();
 789 }
 790 
 791 void HeapShared::copy_special_objects() {
 792   // Archive special objects that do not belong to any subgraphs
 793   init_seen_objects_table();
 794   archive_java_mirrors();
 795   archive_strings();
 796   Universe::archive_exception_instances();
 797   delete_seen_objects_table();
 798 }
 799 
 800 void HeapShared::copy_objects() {
 801   assert(HeapShared::can_write(), "must be");
 802 
 803   copy_interned_strings();
 804   copy_special_objects();
 805 
 806   archive_object_subgraphs(archive_subgraph_entry_fields,
 807                            false /* is_full_module_graph */);
 808 
 809   if (CDSConfig::is_dumping_full_module_graph()) {
 810     archive_object_subgraphs(fmg_archive_subgraph_entry_fields,
 811                              true /* is_full_module_graph */);
 812     Modules::verify_archived_modules();
 813   }
 814 }
 815 
 816 //
 817 // Subgraph archiving support
 818 //
 819 HeapShared::DumpTimeKlassSubGraphInfoTable* HeapShared::_dump_time_subgraph_info_table = nullptr;
 820 HeapShared::RunTimeKlassSubGraphInfoTable   HeapShared::_run_time_subgraph_info_table;
 821 
 822 // Get the subgraph_info for Klass k. A new subgraph_info is created if
 823 // there is no existing one for k. The subgraph_info records the "buffered"
 824 // address of the class.
 825 KlassSubGraphInfo* HeapShared::init_subgraph_info(Klass* k, bool is_full_module_graph) {
 826   assert(CDSConfig::is_dumping_heap(), "dump time only");
 827   bool created;
 828   Klass* buffered_k = ArchiveBuilder::get_buffered_klass(k);
 829   KlassSubGraphInfo* info =
 830     _dump_time_subgraph_info_table->put_if_absent(k, KlassSubGraphInfo(buffered_k, is_full_module_graph),
 831                                                   &created);
 832   assert(created, "must not initialize twice");
 833   return info;
 834 }
 835 
 836 KlassSubGraphInfo* HeapShared::get_subgraph_info(Klass* k) {
 837   assert(CDSConfig::is_dumping_heap(), "dump time only");
 838   KlassSubGraphInfo* info = _dump_time_subgraph_info_table->get(k);
 839   assert(info != nullptr, "must have been initialized");
 840   return info;
 841 }
 842 
 843 // Add an entry field to the current KlassSubGraphInfo.
 844 void KlassSubGraphInfo::add_subgraph_entry_field(int static_field_offset, oop v) {
 845   assert(CDSConfig::is_dumping_heap(), "dump time only");
 846   if (_subgraph_entry_fields == nullptr) {
 847     _subgraph_entry_fields =
 848       new (mtClass) GrowableArray<int>(10, mtClass);
 849   }
 850   _subgraph_entry_fields->append(static_field_offset);
 851   _subgraph_entry_fields->append(HeapShared::append_root(v));
 852 }
 853 
 854 // Add the Klass* for an object in the current KlassSubGraphInfo's subgraphs.
 855 // Only objects of boot classes can be included in sub-graph.
 856 void KlassSubGraphInfo::add_subgraph_object_klass(Klass* orig_k) {
 857   assert(CDSConfig::is_dumping_heap(), "dump time only");
 858   Klass* buffered_k = ArchiveBuilder::get_buffered_klass(orig_k);
 859 
 860   if (_subgraph_object_klasses == nullptr) {
 861     _subgraph_object_klasses =
 862       new (mtClass) GrowableArray<Klass*>(50, mtClass);
 863   }
 864 
 865   assert(ArchiveBuilder::current()->is_in_buffer_space(buffered_k), "must be a shared class");
 866 
 867   if (_k == buffered_k) {
 868     // Don't add the Klass containing the sub-graph to it's own klass
 869     // initialization list.
 870     return;
 871   }
 872 
 873   if (buffered_k->is_instance_klass()) {
 874     if (!ArchiveInvokeDynamic) {
 875       // FIXME: this supports Lambda Proxy classes
 876       assert(InstanceKlass::cast(buffered_k)->is_shared_boot_class(),
 877              "must be boot class");
 878     }
 879     // vmClasses::xxx_klass() are not updated, need to check
 880     // the original Klass*
 881     if (orig_k == vmClasses::String_klass() ||
 882         orig_k == vmClasses::Object_klass()) {
 883       // Initialized early during VM initialization. No need to be added
 884       // to the sub-graph object class list.
 885       return;
 886     }
 887     check_allowed_klass(InstanceKlass::cast(orig_k));
 888   } else if (buffered_k->is_objArray_klass()) {
 889     Klass* abk = ObjArrayKlass::cast(buffered_k)->bottom_klass();
 890     if (abk->is_instance_klass()) {
 891       assert(InstanceKlass::cast(abk)->is_shared_boot_class(),
 892             "must be boot class");
 893       check_allowed_klass(InstanceKlass::cast(ObjArrayKlass::cast(orig_k)->bottom_klass()));
 894     }
 895     if (buffered_k == Universe::objectArrayKlass()) {
 896       // Initialized early during Universe::genesis. No need to be added
 897       // to the list.
 898       return;
 899     }
 900   } else {
 901     assert(buffered_k->is_typeArray_klass(), "must be");
 902     // Primitive type arrays are created early during Universe::genesis.
 903     return;
 904   }
 905 
 906   if (log_is_enabled(Debug, cds, heap)) {
 907     if (!_subgraph_object_klasses->contains(buffered_k)) {
 908       ResourceMark rm;
 909       log_debug(cds, heap)("Adding klass %s", orig_k->external_name());
 910     }
 911   }
 912 
 913   _subgraph_object_klasses->append_if_missing(buffered_k);
 914   _has_non_early_klasses |= is_non_early_klass(orig_k);
 915 }
 916 
 917 void KlassSubGraphInfo::check_allowed_klass(InstanceKlass* ik) {
 918   if (ArchiveInvokeDynamic) {
 919     // FIXME -- this allows LambdaProxy classes
 920     return;
 921   }
 922   if (ik->module()->name() == vmSymbols::java_base()) {
 923     assert(ik->package() != nullptr, "classes in java.base cannot be in unnamed package");
 924     return;
 925   }
 926 
 927 #ifndef PRODUCT
 928   if (!ik->module()->is_named() && ik->package() == nullptr) {
 929     // This class is loaded by ArchiveHeapTestClass
 930     return;
 931   }
 932   const char* extra_msg = ", or in an unnamed package of an unnamed module";
 933 #else
 934   const char* extra_msg = "";
 935 #endif
 936 
 937   ResourceMark rm;
 938   log_error(cds, heap)("Class %s not allowed in archive heap. Must be in java.base%s",
 939                        ik->external_name(), extra_msg);
 940   MetaspaceShared::unrecoverable_writing_error();
 941 }
 942 
 943 bool KlassSubGraphInfo::is_non_early_klass(Klass* k) {
 944   if (k->is_objArray_klass()) {
 945     k = ObjArrayKlass::cast(k)->bottom_klass();
 946   }
 947   if (k->is_instance_klass()) {
 948     if (!SystemDictionaryShared::is_early_klass(InstanceKlass::cast(k))) {
 949       ResourceMark rm;
 950       log_info(cds, heap)("non-early: %s", k->external_name());
 951       return true;
 952     } else {
 953       return false;
 954     }
 955   } else {
 956     return false;
 957   }
 958 }
 959 
 960 // Initialize an archived subgraph_info_record from the given KlassSubGraphInfo.
 961 void ArchivedKlassSubGraphInfoRecord::init(KlassSubGraphInfo* info) {
 962   _k = info->klass();
 963   _entry_field_records = nullptr;
 964   _subgraph_object_klasses = nullptr;
 965   _is_full_module_graph = info->is_full_module_graph();
 966 
 967   if (_is_full_module_graph) {
 968     // Consider all classes referenced by the full module graph as early -- we will be
 969     // allocating objects of these classes during JVMTI early phase, so they cannot
 970     // be processed by (non-early) JVMTI ClassFileLoadHook
 971     _has_non_early_klasses = false;
 972   } else {
 973     _has_non_early_klasses = info->has_non_early_klasses();
 974   }
 975 
 976   if (_has_non_early_klasses) {
 977     ResourceMark rm;
 978     log_info(cds, heap)(
 979           "Subgraph of klass %s has non-early klasses and cannot be used when JVMTI ClassFileLoadHook is enabled",
 980           _k->external_name());
 981   }
 982 
 983   // populate the entry fields
 984   GrowableArray<int>* entry_fields = info->subgraph_entry_fields();
 985   if (entry_fields != nullptr) {
 986     int num_entry_fields = entry_fields->length();
 987     assert(num_entry_fields % 2 == 0, "sanity");
 988     _entry_field_records =
 989       ArchiveBuilder::new_ro_array<int>(num_entry_fields);
 990     for (int i = 0 ; i < num_entry_fields; i++) {
 991       _entry_field_records->at_put(i, entry_fields->at(i));
 992     }
 993   }
 994 
 995   // the Klasses of the objects in the sub-graphs
 996   GrowableArray<Klass*>* subgraph_object_klasses = info->subgraph_object_klasses();
 997   if (subgraph_object_klasses != nullptr) {
 998     int num_subgraphs_klasses = subgraph_object_klasses->length();
 999     _subgraph_object_klasses =
1000       ArchiveBuilder::new_ro_array<Klass*>(num_subgraphs_klasses);
1001     for (int i = 0; i < num_subgraphs_klasses; i++) {
1002       Klass* subgraph_k = subgraph_object_klasses->at(i);
1003       if (log_is_enabled(Info, cds, heap)) {
1004         ResourceMark rm;
1005         log_info(cds, heap)(
1006           "Archived object klass %s (%2d) => %s",
1007           _k->external_name(), i, subgraph_k->external_name());
1008       }
1009       _subgraph_object_klasses->at_put(i, subgraph_k);
1010       ArchivePtrMarker::mark_pointer(_subgraph_object_klasses->adr_at(i));
1011     }
1012   }
1013 
1014   ArchivePtrMarker::mark_pointer(&_k);
1015   ArchivePtrMarker::mark_pointer(&_entry_field_records);
1016   ArchivePtrMarker::mark_pointer(&_subgraph_object_klasses);
1017 }
1018 
1019 class HeapShared::CopyKlassSubGraphInfoToArchive : StackObj {
1020 public:
1021   CompactHashtableWriter* _writer;
1022   CopyKlassSubGraphInfoToArchive(CompactHashtableWriter* writer) : _writer(writer) {}
1023 
1024   bool do_entry(Klass* klass, KlassSubGraphInfo& info) {
1025     if (info.subgraph_object_klasses() != nullptr || info.subgraph_entry_fields() != nullptr) {
1026       ArchivedKlassSubGraphInfoRecord* record = HeapShared::archive_subgraph_info(&info);



1027       Klass* buffered_k = ArchiveBuilder::get_buffered_klass(klass);
1028       unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary((address)buffered_k);
1029       u4 delta = ArchiveBuilder::current()->any_to_offset_u4(record);
1030       _writer->add(hash, delta);
1031     }
1032     return true; // keep on iterating
1033   }
1034 };
1035 
1036 ArchivedKlassSubGraphInfoRecord* HeapShared::archive_subgraph_info(KlassSubGraphInfo* info) {
1037   ArchivedKlassSubGraphInfoRecord* record =
1038       (ArchivedKlassSubGraphInfoRecord*)ArchiveBuilder::ro_region_alloc(sizeof(ArchivedKlassSubGraphInfoRecord));
1039   record->init(info);
1040   return record;
1041 }
1042 
1043 // Build the records of archived subgraph infos, which include:
1044 // - Entry points to all subgraphs from the containing class mirror. The entry
1045 //   points are static fields in the mirror. For each entry point, the field
1046 //   offset, and value are recorded in the sub-graph
1047 //   info. The value is stored back to the corresponding field at runtime.
1048 // - A list of klasses that need to be loaded/initialized before archived
1049 //   java object sub-graph can be accessed at runtime.
1050 void HeapShared::write_subgraph_info_table() {
1051   // Allocate the contents of the hashtable(s) inside the RO region of the CDS archive.
1052   DumpTimeKlassSubGraphInfoTable* d_table = _dump_time_subgraph_info_table;
1053   CompactHashtableStats stats;
1054 
1055   _run_time_subgraph_info_table.reset();
1056 
1057   CompactHashtableWriter writer(d_table->_count, &stats);
1058   CopyKlassSubGraphInfoToArchive copy(&writer);
1059   d_table->iterate(&copy);
1060   writer.dump(&_run_time_subgraph_info_table, "subgraphs");
1061 
1062   _runtime_default_subgraph_info = archive_subgraph_info(_default_subgraph_info);
1063 
1064 #ifndef PRODUCT
1065   if (ArchiveHeapTestClass != nullptr) {
1066     size_t len = strlen(ArchiveHeapTestClass) + 1;
1067     Array<char>* array = ArchiveBuilder::new_ro_array<char>((int)len);
1068     strncpy(array->adr_at(0), ArchiveHeapTestClass, len);
1069     _archived_ArchiveHeapTestClass = array;
1070   }
1071 #endif
1072   if (log_is_enabled(Info, cds, heap)) {
1073     print_stats();
1074   }
1075 }
1076 
1077 void HeapShared::serialize_misc_info(SerializeClosure* soc) {
1078   soc->do_int(&_permobj_segments);
1079 }
1080 
1081 void HeapShared::init_roots(oop roots_oop) {
1082   if (roots_oop != nullptr) {
1083     assert(ArchiveHeapLoader::is_in_use(), "must be");
1084     _roots = OopHandle(Universe::vm_global(), roots_oop);
1085   }
1086 }
1087 
1088 void HeapShared::serialize_tables(SerializeClosure* soc) {
1089 
1090 #ifndef PRODUCT
1091   soc->do_ptr(&_archived_ArchiveHeapTestClass);
1092   if (soc->reading() && _archived_ArchiveHeapTestClass != nullptr) {
1093     _test_class_name = _archived_ArchiveHeapTestClass->adr_at(0);
1094     setup_test_class(_test_class_name);
1095   }
1096 #endif
1097 
1098   _run_time_subgraph_info_table.serialize_header(soc);
1099   soc->do_ptr(&_runtime_default_subgraph_info);
1100 
1101 }
1102 
1103 static void verify_the_heap(Klass* k, const char* which) {
1104   if (VerifyArchivedFields > 0) {
1105     ResourceMark rm;
1106     log_info(cds, heap)("Verify heap %s initializing static field(s) in %s",
1107                         which, k->external_name());
1108 
1109     VM_Verify verify_op;
1110     VMThread::execute(&verify_op);
1111 
1112     if (VerifyArchivedFields > 1 && is_init_completed()) {
1113       // At this time, the oop->klass() of some archived objects in the heap may not
1114       // have been loaded into the system dictionary yet. Nevertheless, oop->klass() should
1115       // have enough information (object size, oop maps, etc) so that a GC can be safely
1116       // performed.
1117       //
1118       // -XX:VerifyArchivedFields=2 force a GC to happen in such an early stage
1119       // to check for GC safety.
1120       log_info(cds, heap)("Trigger GC %s initializing static field(s) in %s",
1121                           which, k->external_name());
1122       FlagSetting fs1(VerifyBeforeGC, true);
1123       FlagSetting fs2(VerifyDuringGC, true);
1124       FlagSetting fs3(VerifyAfterGC,  true);
1125       Universe::heap()->collect(GCCause::_java_lang_system_gc);
1126     }
1127   }
1128 }
1129 
1130 // Before GC can execute, we must ensure that all oops reachable from HeapShared::roots()
1131 // have a valid klass. I.e., oopDesc::klass() must have already been resolved.
1132 //
1133 // Note: if a ArchivedKlassSubGraphInfoRecord contains non-early classes, and JVMTI
1134 // ClassFileLoadHook is enabled, it's possible for this class to be dynamically replaced. In
1135 // this case, we will not load the ArchivedKlassSubGraphInfoRecord and will clear its roots.
1136 void HeapShared::resolve_classes(JavaThread* current) {
1137   assert(UseSharedSpaces, "runtime only!");
1138   if (!ArchiveHeapLoader::is_in_use()) {
1139     return; // nothing to do
1140   }
1141 
1142   if (!CDSConfig::has_preloaded_classes()) {
1143     assert( _runtime_default_subgraph_info != nullptr, "must be");
1144     Array<Klass*>* klasses = _runtime_default_subgraph_info->subgraph_object_klasses();
1145     if (klasses != nullptr) {
1146       for (int i = 0; i < klasses->length(); i++) {
1147         Klass* k = klasses->at(i);
1148         ExceptionMark em(current); // no exception can happen here
1149         resolve_or_init(k, /*do_init*/false, current);
1150       }
1151     }
1152   }
1153 
1154   resolve_classes_for_subgraphs(current, archive_subgraph_entry_fields);
1155   resolve_classes_for_subgraphs(current, fmg_archive_subgraph_entry_fields);
1156 }
1157 
1158 void HeapShared::resolve_classes_for_subgraphs(JavaThread* current, ArchivableStaticFieldInfo fields[]) {
1159   for (int i = 0; fields[i].valid(); i++) {
1160     ArchivableStaticFieldInfo* info = &fields[i];
1161     TempNewSymbol klass_name = SymbolTable::new_symbol(info->klass_name);
1162     InstanceKlass* k = SystemDictionaryShared::find_builtin_class(klass_name);
1163     assert(k != nullptr && k->is_shared_boot_class(), "sanity");
1164     resolve_classes_for_subgraph_of(current, k);
1165   }
1166 }
1167 
1168 void HeapShared::resolve_classes_for_subgraph_of(JavaThread* current, Klass* k) {
1169   JavaThread* THREAD = current;
1170   ExceptionMark em(THREAD);
1171   const ArchivedKlassSubGraphInfoRecord* record =
1172    resolve_or_init_classes_for_subgraph_of(k, /*do_init=*/false, THREAD);
1173   if (HAS_PENDING_EXCEPTION) {
1174    CLEAR_PENDING_EXCEPTION;
1175   }
1176   if (record == nullptr) {
1177    clear_archived_roots_of(k);
1178   }
1179 }
1180 
1181 void HeapShared::initialize_java_lang_invoke(TRAPS) {
1182   if (CDSConfig::is_loading_invokedynamic() || ArchiveInvokeDynamic) {
1183     resolve_or_init("java/lang/invoke/Invokers$Holder", true, CHECK);
1184     resolve_or_init("java/lang/invoke/MethodHandle", true, CHECK);
1185     resolve_or_init("java/lang/invoke/MethodHandleNatives", true, CHECK);
1186     resolve_or_init("java/lang/invoke/DirectMethodHandle$Holder", true, CHECK);
1187     resolve_or_init("java/lang/invoke/DelegatingMethodHandle$Holder", true, CHECK);
1188     resolve_or_init("java/lang/invoke/LambdaForm$Holder", true, CHECK);
1189     resolve_or_init("java/lang/invoke/BoundMethodHandle$Species_L", true, CHECK);
1190   }
1191 }
1192 
1193 void HeapShared::initialize_default_subgraph_classes(Handle loader, TRAPS) {
1194   if (!ArchiveHeapLoader::is_in_use()) {
1195     return;
1196   }
1197 
1198   assert( _runtime_default_subgraph_info != nullptr, "must be");
1199   Array<Klass*>* klasses = _runtime_default_subgraph_info->subgraph_object_klasses();
1200   if (klasses != nullptr) {
1201     for (int pass = 0; pass < 2; pass ++) {
1202       for (int i = 0; i < klasses->length(); i++) {
1203         Klass* k = klasses->at(i);
1204         if (k->class_loader_data() == nullptr) {
1205           // This class is not yet loaded. We will initialize it in a later phase.
1206           continue;
1207         }
1208         if (k->class_loader() == loader()) {
1209           if (pass == 0) {
1210             if (k->is_instance_klass()) {
1211               InstanceKlass::cast(k)->link_class(CHECK);
1212             }
1213           } else {
1214             resolve_or_init(k, /*do_init*/true, CHECK);
1215           }
1216         }
1217       }
1218     }
1219   }
1220 }
1221 
1222 void HeapShared::initialize_from_archived_subgraph(JavaThread* current, Klass* k) {
1223   JavaThread* THREAD = current;
1224   if (!ArchiveHeapLoader::is_in_use()) {
1225     return; // nothing to do
1226   }
1227 
1228   ExceptionMark em(THREAD);
1229   const ArchivedKlassSubGraphInfoRecord* record =
1230     resolve_or_init_classes_for_subgraph_of(k, /*do_init=*/true, THREAD);
1231 
1232   if (HAS_PENDING_EXCEPTION) {
1233     CLEAR_PENDING_EXCEPTION;
1234     // None of the field value will be set if there was an exception when initializing the classes.
1235     // The java code will not see any of the archived objects in the
1236     // subgraphs referenced from k in this case.
1237     return;
1238   }
1239 
1240   if (record != nullptr) {
1241     init_archived_fields_for(k, record);
1242   }
1243 }
1244 
1245 const ArchivedKlassSubGraphInfoRecord*
1246 HeapShared::resolve_or_init_classes_for_subgraph_of(Klass* k, bool do_init, TRAPS) {
1247   assert(!CDSConfig::is_dumping_heap(), "Should not be called when dumping heap");
1248 
1249   if (!k->is_shared()) {
1250     return nullptr;
1251   }
1252   unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary_quick(k);
1253   const ArchivedKlassSubGraphInfoRecord* record = _run_time_subgraph_info_table.lookup(k, hash, 0);
1254 
1255 #ifndef PRODUCT
1256   if (_test_class_name != nullptr && k->name()->equals(_test_class_name) && record != nullptr) {
1257     _test_class = k;
1258     _test_class_record = record;
1259   }
1260 #endif
1261 
1262   // Initialize from archived data. Currently this is done only
1263   // during VM initialization time. No lock is needed.
1264   if (record == nullptr) {
1265     if (log_is_enabled(Info, cds, heap)) {
1266       ResourceMark rm(THREAD);
1267       log_info(cds, heap)("subgraph %s is not recorded",
1268                           k->external_name());
1269     }
1270     return nullptr;
1271   } else {
1272     if (record->is_full_module_graph() && !CDSConfig::is_using_full_module_graph()) {
1273       if (log_is_enabled(Info, cds, heap)) {
1274         ResourceMark rm(THREAD);
1275         log_info(cds, heap)("subgraph %s cannot be used because full module graph is disabled",
1276                             k->external_name());
1277       }
1278       return nullptr;
1279     }
1280 
1281     if (record->has_non_early_klasses() && JvmtiExport::should_post_class_file_load_hook()) {
1282       if (log_is_enabled(Info, cds, heap)) {
1283         ResourceMark rm(THREAD);
1284         log_info(cds, heap)("subgraph %s cannot be used because JVMTI ClassFileLoadHook is enabled",
1285                             k->external_name());
1286       }
1287       return nullptr;
1288     }
1289 
1290     if (log_is_enabled(Info, cds, heap)) {
1291       ResourceMark rm;
1292       log_info(cds, heap)("%s subgraph %s ", do_init ? "init" : "resolve", k->external_name());
1293     }
1294 
1295     if (do_init && k->name() == vmSymbols::java_lang_invoke_MethodType()) {
1296       // FIXME - hack.
1297       //
1298       // (The real fix would be to archive the MethodType class in its already initialized state. That
1299       //  way we don't need to re-execute the <clinit> methods)
1300       //
1301       // We need to do this to break a cycle in the way the archived subgraphs are restored. Without this block, we
1302       // have the following sequence
1303       //
1304       // MethodType.<clinit>()
1305       //  -> CDS.initializeFromArchive(MethodType.class);
1306       //   -> (this "if" block)
1307       //   -> resolve_or_init("MethodType", ...); // this does nothing because MethodType.<clinit> is already executing
1308       //   -> resolve_or_init("DirectMethodHandle", ...); // this class is in record->subgraph_object_klasses();
1309       //      -> DirectMethodHandle.<clinit>()
1310       //          -> MethodType.methodType()
1311       //             -> MethodType.genericMethodType()
1312       //               -> aaload MethodType.objectOnlyTypes[n]; <<<< here
1313       //
1314       // We need to restore MethodType.objectOnlyTypes here, or else the above aaload will
1315       // get an NPE.
1316       Array<int>* entry_field_records = record->entry_field_records();
1317       assert(entry_field_records != nullptr, "must be");
1318       int efr_len = entry_field_records->length();
1319       assert(efr_len == 2, "must be");
1320       int root_index = entry_field_records->at(1);
1321       oop obj = get_root(root_index, /*clear=*/false);
1322       if (obj != nullptr) {
1323         objArrayOop archivedObjects = objArrayOop(obj);
1324         InstanceKlass* ik = InstanceKlass::cast(k);
1325         oop m = ik->java_mirror();
1326 
1327         {
1328           fieldDescriptor fd;
1329           TempNewSymbol name = SymbolTable::new_symbol("archivedMethodTypes");
1330           TempNewSymbol sig  = SymbolTable::new_symbol("Ljava/util/HashMap;");
1331           Klass* result = ik->find_field(name, sig, true, &fd);
1332           assert(result != nullptr, "must be");
1333           m->obj_field_put(fd.offset(), archivedObjects->obj_at(0));
1334         }
1335 
1336         {
1337           fieldDescriptor fd;
1338           TempNewSymbol name = SymbolTable::new_symbol("objectOnlyTypes");
1339           TempNewSymbol sig  = SymbolTable::new_symbol("[Ljava/lang/invoke/MethodType;");
1340           Klass* result = ik->find_field(name, sig, true, &fd);
1341           assert(result != nullptr, "must be");
1342           m->obj_field_put(fd.offset(), archivedObjects->obj_at(1));
1343         }
1344       }
1345     }
1346 
1347     resolve_or_init(k, do_init, CHECK_NULL);
1348 
1349     // Load/link/initialize the klasses of the objects in the subgraph.
1350     // nullptr class loader is used.
1351     Array<Klass*>* klasses = record->subgraph_object_klasses();
1352     if (klasses != nullptr) {
1353       for (int i = 0; i < klasses->length(); i++) {
1354         Klass* klass = klasses->at(i);
1355         if (!klass->is_shared()) {
1356           return nullptr;
1357         }
1358         resolve_or_init(klass, do_init, CHECK_NULL);
1359       }
1360     }
1361   }
1362 
1363   return record;
1364 }
1365 
1366 void HeapShared::resolve_or_init(const char* klass_name, bool do_init, TRAPS) {
1367   TempNewSymbol klass_name_sym =  SymbolTable::new_symbol(klass_name);
1368   InstanceKlass* k = SystemDictionaryShared::find_builtin_class(klass_name_sym);
1369   if (k == nullptr) {
1370     return;
1371   }
1372   assert(k->is_shared_boot_class(), "sanity");
1373   resolve_or_init(k, false, CHECK);
1374   if (do_init) {
1375     resolve_or_init(k, true, CHECK);
1376   }
1377 }
1378 
1379 void HeapShared::resolve_or_init(Klass* k, bool do_init, TRAPS) {
1380   if (!do_init) {
1381     if (k->class_loader_data() == nullptr) {
1382       Klass* resolved_k = SystemDictionary::resolve_or_null(k->name(), CHECK);
1383       assert(resolved_k == k, "classes used by archived heap must not be replaced by JVMTI ClassFileLoadHook");
1384     }
1385   } else {
1386     assert(k->class_loader_data() != nullptr, "must have been resolved by HeapShared::resolve_classes");
1387     if (k->is_instance_klass()) {
1388       InstanceKlass* ik = InstanceKlass::cast(k);
1389       ik->initialize(CHECK);
1390     } else if (k->is_objArray_klass()) {
1391       ObjArrayKlass* oak = ObjArrayKlass::cast(k);
1392       oak->initialize(CHECK);
1393     }
1394   }
1395 }
1396 
1397 void HeapShared::init_archived_fields_for(Klass* k, const ArchivedKlassSubGraphInfoRecord* record) {
1398   verify_the_heap(k, "before");
1399 
1400   // Load the subgraph entry fields from the record and store them back to
1401   // the corresponding fields within the mirror.
1402   oop m = k->java_mirror();
1403   Array<int>* entry_field_records = record->entry_field_records();
1404   if (entry_field_records != nullptr) {
1405     int efr_len = entry_field_records->length();
1406     assert(efr_len % 2 == 0, "sanity");
1407     for (int i = 0; i < efr_len; i += 2) {
1408       int field_offset = entry_field_records->at(i);
1409       int root_index = entry_field_records->at(i+1);
1410       oop v = get_root(root_index, /*clear=*/true);
1411       m->obj_field_put(field_offset, v);
1412       log_debug(cds, heap)("  " PTR_FORMAT " init field @ %2d = " PTR_FORMAT, p2i(k), field_offset, p2i(v));
1413     }
1414 
1415     // Done. Java code can see the archived sub-graphs referenced from k's
1416     // mirror after this point.
1417     if (log_is_enabled(Info, cds, heap)) {
1418       ResourceMark rm;
1419       log_info(cds, heap)("initialize_from_archived_subgraph %s " PTR_FORMAT "%s",
1420                           k->external_name(), p2i(k), JvmtiExport::is_early_phase() ? " (early)" : "");
1421     }
1422   }
1423 
1424   verify_the_heap(k, "after ");
1425 }
1426 
1427 void HeapShared::clear_archived_roots_of(Klass* k) {
1428   unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary_quick(k);
1429   const ArchivedKlassSubGraphInfoRecord* record = _run_time_subgraph_info_table.lookup(k, hash, 0);
1430   if (record != nullptr) {
1431     Array<int>* entry_field_records = record->entry_field_records();
1432     if (entry_field_records != nullptr) {
1433       int efr_len = entry_field_records->length();
1434       assert(efr_len % 2 == 0, "sanity");
1435       for (int i = 0; i < efr_len; i += 2) {
1436         int root_index = entry_field_records->at(i+1);
1437         clear_root(root_index);
1438       }
1439     }
1440   }
1441 }
1442 
1443 class WalkOopAndArchiveClosure: public BasicOopIterateClosure {
1444   int _level;
1445   bool _record_klasses_only;
1446   KlassSubGraphInfo* _subgraph_info;
1447   oop _referencing_obj;

1448   // The following are for maintaining a stack for determining
1449   // CachedOopInfo::_referrer
1450   static WalkOopAndArchiveClosure* _current;
1451   WalkOopAndArchiveClosure* _last;
1452  public:
1453   WalkOopAndArchiveClosure(int level,
1454                            bool record_klasses_only,
1455                            KlassSubGraphInfo* subgraph_info,
1456                            oop orig) :
1457     _level(level),
1458     _record_klasses_only(record_klasses_only),
1459     _subgraph_info(subgraph_info),
1460     _referencing_obj(orig) {
1461     _last = _current;
1462     _current = this;
1463   }
1464   ~WalkOopAndArchiveClosure() {
1465     _current = _last;
1466   }
1467   void do_oop(narrowOop *p) { WalkOopAndArchiveClosure::do_oop_work(p); }
1468   void do_oop(      oop *p) { WalkOopAndArchiveClosure::do_oop_work(p); }
1469 
1470  protected:
1471   template <class T> void do_oop_work(T *p) {
1472     oop obj = RawAccess<>::oop_load(p);
1473     if (!CompressedOops::is_null(obj)) {
1474       size_t field_delta = pointer_delta(p, _referencing_obj, sizeof(char));

1475       if (!_record_klasses_only && log_is_enabled(Debug, cds, heap)) {
1476         ResourceMark rm;
1477         log_debug(cds, heap)("(%d) %s[" SIZE_FORMAT "] ==> " PTR_FORMAT " size " SIZE_FORMAT " %s", _level,
1478                              _referencing_obj->klass()->external_name(), field_delta,
1479                              p2i(obj), obj->size() * HeapWordSize, obj->klass()->external_name());
1480         if (log_is_enabled(Trace, cds, heap)) {
1481           LogTarget(Trace, cds, heap) log;
1482           LogStream out(log);
1483           obj->print_on(&out);
1484         }
1485       }
1486 
1487       bool success = HeapShared::archive_reachable_objects_from(
1488           _level + 1, _subgraph_info, obj);
1489       assert(success, "VM should have exited with unarchivable objects for _level > 1");
1490     }
1491   }
1492 
1493  public:
1494   static WalkOopAndArchiveClosure* current()  { return _current;              }
1495   oop referencing_obj()                       { return _referencing_obj;      }
1496   KlassSubGraphInfo* subgraph_info()          { return _subgraph_info;        }
1497 };
1498 
1499 WalkOopAndArchiveClosure* WalkOopAndArchiveClosure::_current = nullptr;
1500 
1501 // Checks if an oop has any non-null oop fields
1502 class PointsToOopsChecker : public BasicOopIterateClosure {
1503   bool _result;
1504 
1505   template <class T> void check(T *p) {
1506     _result |= (HeapAccess<>::oop_load(p) != nullptr);
1507   }
1508 
1509 public:
1510   PointsToOopsChecker() : _result(false) {}
1511   void do_oop(narrowOop *p) { check(p); }
1512   void do_oop(      oop *p) { check(p); }
1513   bool result() { return _result; }
1514 };
1515 
1516 HeapShared::CachedOopInfo HeapShared::make_cached_oop_info(oop obj) {
1517   WalkOopAndArchiveClosure* walker = WalkOopAndArchiveClosure::current();
1518   oop referrer = (walker == nullptr) ? nullptr : walker->referencing_obj();
1519   PointsToOopsChecker points_to_oops_checker;
1520   obj->oop_iterate(&points_to_oops_checker);
1521   return CachedOopInfo(referrer, points_to_oops_checker.result());
1522 }
1523 
1524 // We currently allow only the box classes, which are initialized very early by
1525 // HeapShared::init_box_classes().
1526 bool HeapShared::can_mirror_be_used_in_subgraph(oop orig_java_mirror) {
1527   return java_lang_Class::is_primitive(orig_java_mirror)
1528     || orig_java_mirror == vmClasses::Boolean_klass()->java_mirror()
1529     || orig_java_mirror == vmClasses::Character_klass()->java_mirror()
1530     || orig_java_mirror == vmClasses::Float_klass()->java_mirror()
1531     || orig_java_mirror == vmClasses::Double_klass()->java_mirror()
1532     || orig_java_mirror == vmClasses::Byte_klass()->java_mirror()
1533     || orig_java_mirror == vmClasses::Short_klass()->java_mirror()
1534     || orig_java_mirror == vmClasses::Integer_klass()->java_mirror()
1535     || orig_java_mirror == vmClasses::Long_klass()->java_mirror()
1536     || orig_java_mirror == vmClasses::Void_klass()->java_mirror()
1537     || orig_java_mirror == vmClasses::Object_klass()->java_mirror();
1538 }
1539 
1540 void HeapShared::init_box_classes(TRAPS) {
1541   if (ArchiveHeapLoader::is_in_use()) {
1542     vmClasses::Boolean_klass()->initialize(CHECK);
1543     vmClasses::Character_klass()->initialize(CHECK);
1544     vmClasses::Float_klass()->initialize(CHECK);
1545     vmClasses::Double_klass()->initialize(CHECK);
1546     vmClasses::Byte_klass()->initialize(CHECK);
1547     vmClasses::Short_klass()->initialize(CHECK);
1548     vmClasses::Integer_klass()->initialize(CHECK);
1549     vmClasses::Long_klass()->initialize(CHECK);
1550     vmClasses::Void_klass()->initialize(CHECK);
1551   }
1552 }
1553 
1554 void HeapShared::exit_on_error() {
1555   if (_context != nullptr) {
1556     ResourceMark rm;
1557     LogStream ls(Log(cds, heap)::error());
1558     ls.print_cr("Context");
1559     for (int i = 0; i < _context->length(); i++) {
1560       const char* s = _context->at(i);
1561       ls.print_cr("- %s", s);
1562     }
1563   }
1564   if (_trace != nullptr) {
1565     ResourceMark rm;
1566     LogStream ls(Log(cds, heap)::error());
1567     ls.print_cr("Reference trace");
1568     for (int i = 0; i < _trace->length(); i++) {
1569       oop orig_obj = _trace->at(i);
1570       ls.print_cr("[%d] ========================================", i);
1571       orig_obj->print_on(&ls);
1572       ls.cr();
1573     }
1574   }
1575   MetaspaceShared::unrecoverable_writing_error();
1576 }
1577 
1578 // (1) If orig_obj has not been archived yet, archive it.
1579 // (2) If orig_obj has not been seen yet (since start_recording_subgraph() was called),
1580 //     trace all  objects that are reachable from it, and make sure these objects are archived.
1581 // (3) Record the klasses of all orig_obj and all reachable objects.
1582 bool HeapShared::archive_reachable_objects_from(int level,
1583                                                 KlassSubGraphInfo* subgraph_info,
1584                                                 oop orig_obj) {
1585   ArchivingObjectMark mark(orig_obj);
1586   assert(orig_obj != nullptr, "must be");
1587 
1588   if (!JavaClasses::is_supported_for_archiving(orig_obj)) {
1589     // This object has injected fields that cannot be supported easily, so we disallow them for now.
1590     // If you get an error here, you probably made a change in the JDK library that has added
1591     // these objects that are referenced (directly or indirectly) by static fields.
1592     ResourceMark rm;
1593     log_error(cds, heap)("Cannot archive object of class %s", orig_obj->klass()->external_name());
1594     exit_on_error();
1595   }
1596 
1597 #if 0




1598   if (java_lang_Class::is_instance(orig_obj) && subgraph_info != _default_subgraph_info) {
1599     if (can_mirror_be_used_in_subgraph(orig_obj)) {
1600       orig_obj = scratch_java_mirror(orig_obj);
1601       assert(orig_obj != nullptr, "must be archived");
1602     } else {
1603       // Don't follow the fields -- they will be nulled out when the mirror was copied
1604 
1605       // FIXME - we should preserve the static fields of LambdaForm classes (and other hidden classes?)
1606       // so we need to walk the oop fields.
1607       orig_obj = scratch_java_mirror(orig_obj);
1608       assert(orig_obj != nullptr, "must be archived");
1609     }
1610   }
1611 #else
1612   if (java_lang_Class::is_instance(orig_obj)) {
1613     orig_obj = scratch_java_mirror(orig_obj);
1614     assert(orig_obj != nullptr, "must be archived");
1615   }
1616 #endif
1617 
1618   if (has_been_seen_during_subgraph_recording(orig_obj)) {
1619     // orig_obj has already been archived and traced. Nothing more to do.
1620     return true;
1621   } else {
1622     set_has_been_seen_during_subgraph_recording(orig_obj);
1623   }
1624 
1625   bool already_archived = has_been_archived(orig_obj);
1626   bool record_klasses_only = already_archived;
1627   if (!already_archived) {
1628     ++_num_new_archived_objs;
1629     if (!archive_object(orig_obj)) {
1630       // Skip archiving the sub-graph referenced from the current entry field.
1631       ResourceMark rm;
1632       log_error(cds, heap)(
1633         "Cannot archive the sub-graph referenced from %s object ("
1634         PTR_FORMAT ") size " SIZE_FORMAT ", skipped.",
1635         orig_obj->klass()->external_name(), p2i(orig_obj), orig_obj->size() * HeapWordSize);
1636       if (level == 1) {
1637         // Don't archive a subgraph root that's too big. For archives static fields, that's OK
1638         // as the Java code will take care of initializing this field dynamically.
1639         return false;
1640       } else {
1641         // We don't know how to handle an object that has been archived, but some of its reachable
1642         // objects cannot be archived. Bail out for now. We might need to fix this in the future if
1643         // we have a real use case.
1644         exit_on_error();
1645       }
1646     }
1647   }
1648 
1649   Klass *orig_k = orig_obj->klass();
1650   subgraph_info->add_subgraph_object_klass(orig_k);
1651 
1652   WalkOopAndArchiveClosure walker(level, record_klasses_only, subgraph_info, orig_obj);
1653   orig_obj->oop_iterate(&walker);
1654 
1655   if (CDSEnumKlass::is_enum_obj(orig_obj)) {
1656     CDSEnumKlass::handle_enum_obj(level + 1, subgraph_info, orig_obj);
1657   }
1658   return true;
1659 }
1660 
1661 //
1662 // Start from the given static field in a java mirror and archive the
1663 // complete sub-graph of java heap objects that are reached directly
1664 // or indirectly from the starting object by following references.
1665 // Sub-graph archiving restrictions (current):
1666 //
1667 // - All classes of objects in the archived sub-graph (including the
1668 //   entry class) must be boot class only.
1669 // - No java.lang.Class instance (java mirror) can be included inside
1670 //   an archived sub-graph. Mirror can only be the sub-graph entry object.
1671 //
1672 // The Java heap object sub-graph archiving process (see
1673 // WalkOopAndArchiveClosure):
1674 //
1675 // 1) Java object sub-graph archiving starts from a given static field
1676 // within a Class instance (java mirror). If the static field is a
1677 // reference field and points to a non-null java object, proceed to
1678 // the next step.
1679 //
1680 // 2) Archives the referenced java object. If an archived copy of the
1681 // current object already exists, updates the pointer in the archived
1682 // copy of the referencing object to point to the current archived object.
1683 // Otherwise, proceed to the next step.
1684 //
1685 // 3) Follows all references within the current java object and recursively
1686 // archive the sub-graph of objects starting from each reference.
1687 //
1688 // 4) Updates the pointer in the archived copy of referencing object to
1689 // point to the current archived object.
1690 //
1691 // 5) The Klass of the current java object is added to the list of Klasses
1692 // for loading and initializing before any object in the archived graph can
1693 // be accessed at runtime.
1694 //
1695 void HeapShared::archive_reachable_objects_from_static_field(InstanceKlass *k,
1696                                                              const char* klass_name,
1697                                                              int field_offset,
1698                                                              const char* field_name) {
1699   assert(CDSConfig::is_dumping_heap(), "dump time only");
1700   assert(k->is_shared_boot_class(), "must be boot class");
1701 
1702   oop m = k->java_mirror();
1703 
1704   KlassSubGraphInfo* subgraph_info = get_subgraph_info(k);
1705   oop f = m->obj_field(field_offset);
1706 
1707   log_debug(cds, heap)("Start archiving from: %s::%s (" PTR_FORMAT ")", klass_name, field_name, p2i(f));
1708 
1709   if (!CompressedOops::is_null(f)) {
1710     if (log_is_enabled(Trace, cds, heap)) {
1711       LogTarget(Trace, cds, heap) log;
1712       LogStream out(log);
1713       f->print_on(&out);
1714     }
1715 
1716     bool success = archive_reachable_objects_from(1, subgraph_info, f);
1717     if (!success) {
1718       log_error(cds, heap)("Archiving failed %s::%s (some reachable objects cannot be archived)",
1719                            klass_name, field_name);
1720     } else {
1721       // Note: the field value is not preserved in the archived mirror.
1722       // Record the field as a new subGraph entry point. The recorded
1723       // information is restored from the archive at runtime.
1724       subgraph_info->add_subgraph_entry_field(field_offset, f);
1725       log_info(cds, heap)("Archived field %s::%s => " PTR_FORMAT, klass_name, field_name, p2i(f));
1726     }
1727   } else {
1728     // The field contains null, we still need to record the entry point,
1729     // so it can be restored at runtime.
1730     subgraph_info->add_subgraph_entry_field(field_offset, nullptr);
1731   }
1732 }
1733 
1734 #ifndef PRODUCT
1735 class VerifySharedOopClosure: public BasicOopIterateClosure {
1736  public:
1737   void do_oop(narrowOop *p) { VerifySharedOopClosure::do_oop_work(p); }
1738   void do_oop(      oop *p) { VerifySharedOopClosure::do_oop_work(p); }
1739 
1740  protected:
1741   template <class T> void do_oop_work(T *p) {
1742     oop obj = RawAccess<>::oop_load(p);
1743     if (!CompressedOops::is_null(obj)) {
1744       HeapShared::verify_reachable_objects_from(obj);
1745     }
1746   }
1747 };
1748 
1749 void HeapShared::verify_subgraph_from_static_field(InstanceKlass* k, int field_offset) {
1750   assert(CDSConfig::is_dumping_heap(), "dump time only");
1751   assert(k->is_shared_boot_class(), "must be boot class");
1752 
1753   oop m = k->java_mirror();
1754   oop f = m->obj_field(field_offset);
1755   if (!CompressedOops::is_null(f)) {
1756     verify_subgraph_from(f);
1757   }
1758 }
1759 
1760 void HeapShared::verify_subgraph_from(oop orig_obj) {
1761   if (!has_been_archived(orig_obj)) {
1762     // It's OK for the root of a subgraph to be not archived. See comments in
1763     // archive_reachable_objects_from().
1764     return;
1765   }
1766 
1767   // Verify that all objects reachable from orig_obj are archived.
1768   init_seen_objects_table();
1769   verify_reachable_objects_from(orig_obj);
1770   delete_seen_objects_table();
1771 }
1772 
1773 void HeapShared::verify_reachable_objects_from(oop obj) {
1774   _num_total_verifications ++;
1775   if (java_lang_Class::is_instance(obj)) {
1776     obj = scratch_java_mirror(obj);
1777     assert(obj != nullptr, "must be");
1778   }
1779   if (!has_been_seen_during_subgraph_recording(obj)) {
1780     set_has_been_seen_during_subgraph_recording(obj);
1781     assert(has_been_archived(obj), "must be");
1782     VerifySharedOopClosure walker;
1783     obj->oop_iterate(&walker);
1784   }
1785 }
1786 #endif
1787 
1788 // The "default subgraph" contains special objects (see heapShared.hpp) that
1789 // can be accessed before we load any Java classes (including java/lang/Class).
1790 // Make sure that these are only instances of the very few specific types
1791 // that we can handle.
1792 void HeapShared::check_default_subgraph_classes() {
1793   GrowableArray<Klass*>* klasses = _default_subgraph_info->subgraph_object_klasses();
1794   int num = klasses->length();
1795   int warned = 0;
1796   for (int i = 0; i < num; i++) {
1797     Klass* subgraph_k = klasses->at(i);
1798     if (log_is_enabled(Info, cds, heap)) {
1799       ResourceMark rm;
1800       log_info(cds, heap)(
1801           "Archived object klass (default subgraph %d) => %s",
1802           i, subgraph_k->external_name());
1803     }
1804 
1805     if (subgraph_k->is_instance_klass()) {
1806       InstanceKlass* ik = InstanceKlass::cast(subgraph_k);
1807       Symbol* name = ArchiveBuilder::current()->get_source_addr(ik->name());
1808       if (name != vmSymbols::java_lang_Class() &&
1809           name != vmSymbols::java_lang_String() &&
1810           name != vmSymbols::java_lang_ArithmeticException() &&
1811           name != vmSymbols::java_lang_ArrayIndexOutOfBoundsException() &&
1812           name != vmSymbols::java_lang_ArrayStoreException() &&
1813           name != vmSymbols::java_lang_ClassCastException() &&
1814           name != vmSymbols::java_lang_NullPointerException() &&
1815           name != vmSymbols::java_lang_VirtualMachineError() &&
1816           !is_archivable_hidden_klass(ik)) {
1817         ResourceMark rm;
1818         const char* category = ArchiveUtils::class_category(ik);
1819         log_info(cds)("TODO: Archived unusual klass (default subgraph %2d) => %-5s %s",
1820                       ++warned, category, ik->external_name());
1821       }
1822     }
1823   }
1824 }
1825 
1826 HeapShared::SeenObjectsTable* HeapShared::_seen_objects_table = nullptr;
1827 int HeapShared::_num_new_walked_objs;
1828 int HeapShared::_num_new_archived_objs;
1829 int HeapShared::_num_old_recorded_klasses;
1830 
1831 int HeapShared::_num_total_subgraph_recordings = 0;
1832 int HeapShared::_num_total_walked_objs = 0;
1833 int HeapShared::_num_total_archived_objs = 0;
1834 int HeapShared::_num_total_recorded_klasses = 0;
1835 int HeapShared::_num_total_verifications = 0;
1836 
1837 bool HeapShared::has_been_seen_during_subgraph_recording(oop obj) {
1838   return _seen_objects_table->get(obj) != nullptr;
1839 }
1840 
1841 void HeapShared::set_has_been_seen_during_subgraph_recording(oop obj) {
1842   assert(!has_been_seen_during_subgraph_recording(obj), "sanity");
1843   _seen_objects_table->put_when_absent(obj, true);
1844   _seen_objects_table->maybe_grow();
1845   ++ _num_new_walked_objs;
1846 }
1847 
1848 void HeapShared::start_recording_subgraph(InstanceKlass *k, const char* class_name, bool is_full_module_graph) {
1849   log_info(cds, heap)("Start recording subgraph(s) for archived fields in %s", class_name);
1850   init_subgraph_info(k, is_full_module_graph);
1851   init_seen_objects_table();
1852   _num_new_walked_objs = 0;
1853   _num_new_archived_objs = 0;
1854   _num_old_recorded_klasses = get_subgraph_info(k)->num_subgraph_object_klasses();
1855 }
1856 
1857 void HeapShared::done_recording_subgraph(InstanceKlass *k, const char* class_name) {
1858   int num_new_recorded_klasses = get_subgraph_info(k)->num_subgraph_object_klasses() -
1859     _num_old_recorded_klasses;
1860   log_info(cds, heap)("Done recording subgraph(s) for archived fields in %s: "
1861                       "walked %d objs, archived %d new objs, recorded %d classes",
1862                       class_name, _num_new_walked_objs, _num_new_archived_objs,
1863                       num_new_recorded_klasses);
1864 
1865   delete_seen_objects_table();
1866 
1867   _num_total_subgraph_recordings ++;
1868   _num_total_walked_objs      += _num_new_walked_objs;
1869   _num_total_archived_objs    += _num_new_archived_objs;
1870   _num_total_recorded_klasses +=  num_new_recorded_klasses;
1871 }
1872 
1873 class ArchivableStaticFieldFinder: public FieldClosure {
1874   InstanceKlass* _ik;
1875   Symbol* _field_name;
1876   bool _found;
1877   int _offset;
1878 public:
1879   ArchivableStaticFieldFinder(InstanceKlass* ik, Symbol* field_name) :
1880     _ik(ik), _field_name(field_name), _found(false), _offset(-1) {}
1881 
1882   virtual void do_field(fieldDescriptor* fd) {
1883     if (fd->name() == _field_name) {
1884       assert(!_found, "fields can never be overloaded");
1885       if (is_reference_type(fd->field_type())) {
1886         _found = true;
1887         _offset = fd->offset();
1888       }
1889     }
1890   }
1891   bool found()     { return _found;  }
1892   int offset()     { return _offset; }
1893 };
1894 
1895 void HeapShared::init_subgraph_entry_fields(ArchivableStaticFieldInfo fields[],
1896                                             TRAPS) {
1897   for (int i = 0; fields[i].valid(); i++) {
1898     ArchivableStaticFieldInfo* info = &fields[i];
1899     TempNewSymbol klass_name =  SymbolTable::new_symbol(info->klass_name);
1900     TempNewSymbol field_name =  SymbolTable::new_symbol(info->field_name);
1901     ResourceMark rm; // for stringStream::as_string() etc.
1902 
1903 #ifndef PRODUCT
1904     bool is_test_class = (ArchiveHeapTestClass != nullptr) && (strcmp(info->klass_name, ArchiveHeapTestClass) == 0);
1905     const char* test_class_name = ArchiveHeapTestClass;
1906 #else
1907     bool is_test_class = false;
1908     const char* test_class_name = "";
1909 #endif
1910 
1911     if (is_test_class) {
1912       log_warning(cds)("Loading ArchiveHeapTestClass %s ...", test_class_name);
1913     }
1914 
1915     Klass* k = SystemDictionary::resolve_or_fail(klass_name, true, THREAD);
1916     if (HAS_PENDING_EXCEPTION) {
1917       CLEAR_PENDING_EXCEPTION;
1918       stringStream st;
1919       st.print("Fail to initialize archive heap: %s cannot be loaded by the boot loader", info->klass_name);
1920       THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), st.as_string());
1921     }
1922 
1923     if (!k->is_instance_klass()) {
1924       stringStream st;
1925       st.print("Fail to initialize archive heap: %s is not an instance class", info->klass_name);
1926       THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), st.as_string());
1927     }
1928 
1929     InstanceKlass* ik = InstanceKlass::cast(k);
1930     assert(InstanceKlass::cast(ik)->is_shared_boot_class(),
1931            "Only support boot classes");
1932 
1933     if (is_test_class) {
1934       if (ik->module()->is_named()) {
1935         // We don't want ArchiveHeapTestClass to be abused to easily load/initialize arbitrary
1936         // core-lib classes. You need to at least append to the bootclasspath.
1937         stringStream st;
1938         st.print("ArchiveHeapTestClass %s is not in unnamed module", test_class_name);
1939         THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), st.as_string());
1940       }
1941 
1942       if (ik->package() != nullptr) {
1943         // This restriction makes HeapShared::is_a_test_class_in_unnamed_module() easy.
1944         stringStream st;
1945         st.print("ArchiveHeapTestClass %s is not in unnamed package", test_class_name);
1946         THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), st.as_string());
1947       }
1948     } else {
1949       if (ik->module()->name() != vmSymbols::java_base()) {
1950         // We don't want to deal with cases when a module is unavailable at runtime.
1951         // FUTURE -- load from archived heap only when module graph has not changed
1952         //           between dump and runtime.
1953         stringStream st;
1954         st.print("%s is not in java.base module", info->klass_name);
1955         THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), st.as_string());
1956       }
1957     }
1958 
1959     if (is_test_class) {
1960       log_warning(cds)("Initializing ArchiveHeapTestClass %s ...", test_class_name);
1961     }
1962     ik->initialize(CHECK);
1963 
1964     ArchivableStaticFieldFinder finder(ik, field_name);
1965     ik->do_local_static_fields(&finder);
1966     if (!finder.found()) {
1967       stringStream st;
1968       st.print("Unable to find the static T_OBJECT field %s::%s", info->klass_name, info->field_name);
1969       THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), st.as_string());
1970     }
1971 
1972     info->klass = ik;
1973     info->offset = finder.offset();
1974   }
1975 }
1976 
1977 void HeapShared::init_subgraph_entry_fields(TRAPS) {
1978   assert(HeapShared::can_write(), "must be");
1979   _dump_time_subgraph_info_table = new (mtClass)DumpTimeKlassSubGraphInfoTable();
1980   init_subgraph_entry_fields(archive_subgraph_entry_fields, CHECK);
1981   if (CDSConfig::is_dumping_full_module_graph()) {
1982     init_subgraph_entry_fields(fmg_archive_subgraph_entry_fields, CHECK);
1983   }
1984 }
1985 
1986 #ifndef PRODUCT
1987 void HeapShared::setup_test_class(const char* test_class_name) {
1988   ArchivableStaticFieldInfo* p = archive_subgraph_entry_fields;
1989   int num_slots = sizeof(archive_subgraph_entry_fields) / sizeof(ArchivableStaticFieldInfo);
1990   assert(p[num_slots - 2].klass_name == nullptr, "must have empty slot that's patched below");
1991   assert(p[num_slots - 1].klass_name == nullptr, "must have empty slot that marks the end of the list");
1992 
1993   if (test_class_name != nullptr) {
1994     p[num_slots - 2].klass_name = test_class_name;
1995     p[num_slots - 2].field_name = ARCHIVE_TEST_FIELD_NAME;
1996   }
1997 }
1998 
1999 // See if ik is one of the test classes that are pulled in by -XX:ArchiveHeapTestClass
2000 // during runtime. This may be called before the module system is initialized so
2001 // we cannot rely on InstanceKlass::module(), etc.
2002 bool HeapShared::is_a_test_class_in_unnamed_module(Klass* ik) {
2003   if (_test_class != nullptr) {
2004     if (ik == _test_class) {
2005       return true;
2006     }
2007     Array<Klass*>* klasses = _test_class_record->subgraph_object_klasses();
2008     if (klasses == nullptr) {
2009       return false;
2010     }
2011 
2012     for (int i = 0; i < klasses->length(); i++) {
2013       Klass* k = klasses->at(i);
2014       if (k == ik) {
2015         Symbol* name;
2016         if (k->is_instance_klass()) {
2017           name = InstanceKlass::cast(k)->name();
2018         } else if (k->is_objArray_klass()) {
2019           Klass* bk = ObjArrayKlass::cast(k)->bottom_klass();
2020           if (!bk->is_instance_klass()) {
2021             return false;
2022           }
2023           name = bk->name();
2024         } else {
2025           return false;
2026         }
2027 
2028         // See KlassSubGraphInfo::check_allowed_klass() - only two types of
2029         // classes are allowed:
2030         //   (A) java.base classes (which must not be in the unnamed module)
2031         //   (B) test classes which must be in the unnamed package of the unnamed module.
2032         // So if we see a '/' character in the class name, it must be in (A);
2033         // otherwise it must be in (B).
2034         if (name->index_of_at(0, "/", 1)  >= 0) {
2035           return false; // (A)
2036         }
2037 
2038         return true; // (B)
2039       }
2040     }
2041   }
2042 
2043   return false;
2044 }
2045 #endif
2046 
2047 void HeapShared::init_for_dumping(TRAPS) {
2048   if (HeapShared::can_write()) {
2049     setup_test_class(ArchiveHeapTestClass);
2050     _dumped_interned_strings = new (mtClass)DumpedInternedStrings(INITIAL_TABLE_SIZE, MAX_TABLE_SIZE);
2051     init_subgraph_entry_fields(CHECK);
2052   }
2053 }
2054 
2055 void HeapShared::archive_object_subgraphs(ArchivableStaticFieldInfo fields[],
2056                                           bool is_full_module_graph) {
2057   _num_total_subgraph_recordings = 0;
2058   _num_total_walked_objs = 0;
2059   _num_total_archived_objs = 0;
2060   _num_total_recorded_klasses = 0;
2061   _num_total_verifications = 0;
2062 
2063   // For each class X that has one or more archived fields:
2064   // [1] Dump the subgraph of each archived field
2065   // [2] Create a list of all the class of the objects that can be reached
2066   //     by any of these static fields.
2067   //     At runtime, these classes are initialized before X's archived fields
2068   //     are restored by HeapShared::initialize_from_archived_subgraph().
2069   int i;
2070   for (int i = 0; fields[i].valid(); ) {
2071     ArchivableStaticFieldInfo* info = &fields[i];
2072     const char* klass_name = info->klass_name;
2073     start_recording_subgraph(info->klass, klass_name, is_full_module_graph);
2074 
2075     ContextMark cm(klass_name);
2076     // If you have specified consecutive fields of the same klass in
2077     // fields[], these will be archived in the same
2078     // {start_recording_subgraph ... done_recording_subgraph} pass to
2079     // save time.
2080     for (; fields[i].valid(); i++) {
2081       ArchivableStaticFieldInfo* f = &fields[i];
2082       if (f->klass_name != klass_name) {
2083         break;
2084       }
2085 
2086       ContextMark cm(f->field_name);
2087       archive_reachable_objects_from_static_field(f->klass, f->klass_name,
2088                                                   f->offset, f->field_name);
2089     }
2090     done_recording_subgraph(info->klass, klass_name);
2091   }
2092 
2093   log_info(cds, heap)("Archived subgraph records = %d",
2094                       _num_total_subgraph_recordings);
2095   log_info(cds, heap)("  Walked %d objects", _num_total_walked_objs);
2096   log_info(cds, heap)("  Archived %d objects", _num_total_archived_objs);
2097   log_info(cds, heap)("  Recorded %d klasses", _num_total_recorded_klasses);
2098 
2099 #ifndef PRODUCT
2100   for (int i = 0; fields[i].valid(); i++) {
2101     ArchivableStaticFieldInfo* f = &fields[i];
2102     verify_subgraph_from_static_field(f->klass, f->offset);
2103   }
2104   log_info(cds, heap)("  Verified %d references", _num_total_verifications);
2105 #endif
2106 }
2107 
2108 // Not all the strings in the global StringTable are dumped into the archive, because
2109 // some of those strings may be only referenced by classes that are excluded from
2110 // the archive. We need to explicitly mark the strings that are:
2111 //   [1] used by classes that WILL be archived;
2112 //   [2] included in the SharedArchiveConfigFile.
2113 void HeapShared::add_to_dumped_interned_strings(oop string) {
2114   assert_at_safepoint(); // DumpedInternedStrings uses raw oops
2115   assert(!ArchiveHeapWriter::is_string_too_large_to_archive(string), "must be");
2116   bool created;
2117   _dumped_interned_strings->put_if_absent(string, true, &created);
2118   if (created) {
2119     _dumped_interned_strings->maybe_grow();
2120   }
2121 }
2122 
2123 #ifndef PRODUCT
2124 // At dump-time, find the location of all the non-null oop pointers in an archived heap
2125 // region. This way we can quickly relocate all the pointers without using
2126 // BasicOopIterateClosure at runtime.
2127 class FindEmbeddedNonNullPointers: public BasicOopIterateClosure {
2128   void* _start;
2129   BitMap *_oopmap;
2130   int _num_total_oops;
2131   int _num_null_oops;
2132  public:
2133   FindEmbeddedNonNullPointers(void* start, BitMap* oopmap)
2134     : _start(start), _oopmap(oopmap), _num_total_oops(0),  _num_null_oops(0) {}
2135 
2136   virtual void do_oop(narrowOop* p) {
2137     assert(UseCompressedOops, "sanity");
2138     _num_total_oops ++;
2139     narrowOop v = *p;
2140     if (!CompressedOops::is_null(v)) {
2141       size_t idx = p - (narrowOop*)_start;
2142       _oopmap->set_bit(idx);
2143     } else {
2144       _num_null_oops ++;
2145     }
2146   }
2147   virtual void do_oop(oop* p) {
2148     assert(!UseCompressedOops, "sanity");
2149     _num_total_oops ++;
2150     if ((*p) != nullptr) {
2151       size_t idx = p - (oop*)_start;
2152       _oopmap->set_bit(idx);
2153     } else {
2154       _num_null_oops ++;
2155     }
2156   }
2157   int num_total_oops() const { return _num_total_oops; }
2158   int num_null_oops()  const { return _num_null_oops; }
2159 };
2160 #endif
2161 
2162 #ifndef PRODUCT
2163 ResourceBitMap HeapShared::calculate_oopmap(MemRegion region) {
2164   size_t num_bits = region.byte_size() / (UseCompressedOops ? sizeof(narrowOop) : sizeof(oop));
2165   ResourceBitMap oopmap(num_bits);
2166 
2167   HeapWord* p   = region.start();
2168   HeapWord* end = region.end();
2169   FindEmbeddedNonNullPointers finder((void*)p, &oopmap);
2170 
2171   int num_objs = 0;
2172   while (p < end) {
2173     oop o = cast_to_oop(p);
2174     o->oop_iterate(&finder);
2175     p += o->size();
2176     ++ num_objs;
2177   }
2178 
2179   log_info(cds, heap)("calculate_oopmap: objects = %6d, oop fields = %7d (nulls = %7d)",
2180                       num_objs, finder.num_total_oops(), finder.num_null_oops());
2181   return oopmap;
2182 }
2183 
2184 #endif // !PRODUCT
2185 
2186 void HeapShared::count_allocation(size_t size) {
2187   _total_obj_count ++;
2188   _total_obj_size += size;
2189   for (int i = 0; i < ALLOC_STAT_SLOTS; i++) {
2190     if (size <= (size_t(1) << i)) {
2191       _alloc_count[i] ++;
2192       _alloc_size[i] += size;
2193       return;
2194     }
2195   }
2196 }
2197 
2198 static double avg_size(size_t size, size_t count) {
2199   double avg = 0;
2200   if (count > 0) {
2201     avg = double(size * HeapWordSize) / double(count);
2202   }
2203   return avg;
2204 }
2205 
2206 void HeapShared::print_stats() {
2207   size_t huge_count = _total_obj_count;
2208   size_t huge_size = _total_obj_size;
2209 
2210   for (int i = 0; i < ALLOC_STAT_SLOTS; i++) {
2211     size_t byte_size_limit = (size_t(1) << i) * HeapWordSize;
2212     size_t count = _alloc_count[i];
2213     size_t size = _alloc_size[i];
2214     log_info(cds, heap)(SIZE_FORMAT_W(8) " objects are <= " SIZE_FORMAT_W(-6)
2215                         " bytes (total " SIZE_FORMAT_W(8) " bytes, avg %8.1f bytes)",
2216                         count, byte_size_limit, size * HeapWordSize, avg_size(size, count));
2217     huge_count -= count;
2218     huge_size -= size;
2219   }
2220 
2221   log_info(cds, heap)(SIZE_FORMAT_W(8) " huge  objects               (total "  SIZE_FORMAT_W(8) " bytes"
2222                       ", avg %8.1f bytes)",
2223                       huge_count, huge_size * HeapWordSize,
2224                       avg_size(huge_size, huge_count));
2225   log_info(cds, heap)(SIZE_FORMAT_W(8) " total objects               (total "  SIZE_FORMAT_W(8) " bytes"
2226                       ", avg %8.1f bytes)",
2227                       _total_obj_count, _total_obj_size * HeapWordSize,
2228                       avg_size(_total_obj_size, _total_obj_count));
2229 }
2230 
2231 bool HeapShared::is_archived_boot_layer_available(JavaThread* current) {
2232   TempNewSymbol klass_name = SymbolTable::new_symbol(ARCHIVED_BOOT_LAYER_CLASS);
2233   InstanceKlass* k = SystemDictionary::find_instance_klass(current, klass_name, Handle(), Handle());
2234   if (k == nullptr) {
2235     return false;
2236   } else {
2237     TempNewSymbol field_name = SymbolTable::new_symbol(ARCHIVED_BOOT_LAYER_FIELD);
2238     TempNewSymbol field_signature = SymbolTable::new_symbol("Ljdk/internal/module/ArchivedBootLayer;");
2239     fieldDescriptor fd;
2240     if (k->find_field(field_name, field_signature, true, &fd) != nullptr) {
2241       oop m = k->java_mirror();
2242       oop f = m->obj_field(fd.offset());
2243       if (CompressedOops::is_null(f)) {
2244         return false;
2245       }
2246     } else {
2247       return false;
2248     }
2249   }
2250   return true;
2251 }
2252 
2253 #endif // INCLUDE_CDS_JAVA_HEAP
--- EOF ---