1 /*
   2  * Copyright (c) 2018, 2023, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "cds/archiveBuilder.hpp"
  27 #include "cds/archiveHeapLoader.hpp"
  28 #include "cds/archiveHeapWriter.hpp"
  29 #include "cds/archiveUtils.hpp"
  30 #include "cds/cdsConfig.hpp"
  31 #include "cds/cdsHeapVerifier.hpp"
  32 #include "cds/heapShared.hpp"
  33 #include "cds/metaspaceShared.hpp"
  34 #include "classfile/classLoaderData.hpp"
  35 #include "classfile/javaClasses.inline.hpp"
  36 #include "classfile/modules.hpp"
  37 #include "classfile/stringTable.hpp"
  38 #include "classfile/symbolTable.hpp"
  39 #include "classfile/systemDictionary.hpp"
  40 #include "classfile/systemDictionaryShared.hpp"
  41 #include "classfile/vmClasses.hpp"
  42 #include "classfile/vmSymbols.hpp"
  43 #include "gc/shared/collectedHeap.hpp"
  44 #include "gc/shared/gcLocker.hpp"
  45 #include "gc/shared/gcVMOperations.hpp"
  46 #include "logging/log.hpp"
  47 #include "logging/logStream.hpp"
  48 #include "memory/iterator.inline.hpp"
  49 #include "memory/resourceArea.hpp"
  50 #include "memory/universe.hpp"
  51 #include "oops/compressedOops.inline.hpp"
  52 #include "oops/fieldStreams.inline.hpp"
  53 #include "oops/objArrayOop.inline.hpp"
  54 #include "oops/oop.inline.hpp"
  55 #include "oops/typeArrayOop.inline.hpp"
  56 #include "prims/jvmtiExport.hpp"
  57 #include "runtime/fieldDescriptor.inline.hpp"
  58 #include "runtime/init.hpp"
  59 #include "runtime/javaCalls.hpp"
  60 #include "runtime/mutexLocker.hpp"
  61 #include "runtime/safepointVerifiers.hpp"
  62 #include "utilities/bitMap.inline.hpp"
  63 #include "utilities/copy.hpp"
  64 #if INCLUDE_G1GC
  65 #include "gc/g1/g1CollectedHeap.hpp"
  66 #endif
  67 
  68 #if INCLUDE_CDS_JAVA_HEAP
  69 
  70 struct ArchivableStaticFieldInfo {
  71   const char* klass_name;
  72   const char* field_name;
  73   InstanceKlass* klass;
  74   int offset;
  75   BasicType type;
  76 
  77   ArchivableStaticFieldInfo(const char* k, const char* f)
  78   : klass_name(k), field_name(f), klass(nullptr), offset(0), type(T_ILLEGAL) {}
  79 
  80   bool valid() {
  81     return klass_name != nullptr;
  82   }
  83 };
  84 
  85 bool HeapShared::_disable_writing = false;
  86 DumpedInternedStrings *HeapShared::_dumped_interned_strings = nullptr;
  87 
  88 size_t HeapShared::_alloc_count[HeapShared::ALLOC_STAT_SLOTS];
  89 size_t HeapShared::_alloc_size[HeapShared::ALLOC_STAT_SLOTS];
  90 size_t HeapShared::_total_obj_count;
  91 size_t HeapShared::_total_obj_size;
  92 
  93 #ifndef PRODUCT
  94 #define ARCHIVE_TEST_FIELD_NAME "archivedObjects"
  95 static Array<char>* _archived_ArchiveHeapTestClass = nullptr;
  96 static const char* _test_class_name = nullptr;
  97 static const Klass* _test_class = nullptr;
  98 static const ArchivedKlassSubGraphInfoRecord* _test_class_record = nullptr;
  99 #endif
 100 
 101 
 102 //
 103 // If you add new entries to the following tables, you should know what you're doing!
 104 //
 105 
 106 static ArchivableStaticFieldInfo archive_subgraph_entry_fields[] = {
 107   {"java/lang/Integer$IntegerCache",              "archivedCache"},
 108   {"java/lang/Long$LongCache",                    "archivedCache"},
 109   {"java/lang/Byte$ByteCache",                    "archivedCache"},
 110   {"java/lang/Short$ShortCache",                  "archivedCache"},
 111   {"java/lang/Character$CharacterCache",          "archivedCache"},
 112   {"java/util/jar/Attributes$Name",               "KNOWN_NAMES"},
 113   {"sun/util/locale/BaseLocale",                  "constantBaseLocales"},
 114   {"jdk/internal/module/ArchivedModuleGraph",     "archivedModuleGraph"},
 115   {"java/util/ImmutableCollections",              "archivedObjects"},
 116   {"java/lang/ModuleLayer",                       "EMPTY_LAYER"},
 117   {"java/lang/module/Configuration",              "EMPTY_CONFIGURATION"},
 118   {"jdk/internal/math/FDBigInteger",              "archivedCaches"},
 119 #ifndef PRODUCT
 120   {nullptr, nullptr}, // Extra slot for -XX:ArchiveHeapTestClass
 121 #endif
 122   {nullptr, nullptr},
 123 };
 124 
 125 // full module graph
 126 static ArchivableStaticFieldInfo fmg_archive_subgraph_entry_fields[] = {
 127   {"jdk/internal/loader/ArchivedClassLoaders",    "archivedClassLoaders"},
 128   {ARCHIVED_BOOT_LAYER_CLASS,                     ARCHIVED_BOOT_LAYER_FIELD},
 129   {"java/lang/Module$ArchivedData",               "archivedData"},
 130   {nullptr, nullptr},
 131 };
 132 
 133 KlassSubGraphInfo* HeapShared::_default_subgraph_info;
 134 GrowableArrayCHeap<oop, mtClassShared>* HeapShared::_pending_roots = nullptr;
 135 OopHandle HeapShared::_roots;
 136 OopHandle HeapShared::_scratch_basic_type_mirrors[T_VOID+1];
 137 MetaspaceObjToOopHandleTable* HeapShared::_scratch_java_mirror_table = nullptr;
 138 MetaspaceObjToOopHandleTable* HeapShared::_scratch_references_table = nullptr;
 139 
 140 static bool is_subgraph_root_class_of(ArchivableStaticFieldInfo fields[], InstanceKlass* ik) {
 141   for (int i = 0; fields[i].valid(); i++) {
 142     if (fields[i].klass == ik) {
 143       return true;
 144     }
 145   }
 146   return false;
 147 }
 148 
 149 bool HeapShared::is_subgraph_root_class(InstanceKlass* ik) {
 150   return is_subgraph_root_class_of(archive_subgraph_entry_fields, ik) ||
 151          is_subgraph_root_class_of(fmg_archive_subgraph_entry_fields, ik);
 152 }
 153 
 154 unsigned HeapShared::oop_hash(oop const& p) {
 155   // Do not call p->identity_hash() as that will update the
 156   // object header.
 157   return primitive_hash(cast_from_oop<intptr_t>(p));
 158 }
 159 
 160 static void reset_states(oop obj, TRAPS) {
 161   Handle h_obj(THREAD, obj);
 162   InstanceKlass* klass = InstanceKlass::cast(obj->klass());
 163   TempNewSymbol method_name = SymbolTable::new_symbol("resetArchivedStates");
 164   Symbol* method_sig = vmSymbols::void_method_signature();
 165 
 166   while (klass != nullptr) {
 167     Method* method = klass->find_method(method_name, method_sig);
 168     if (method != nullptr) {
 169       assert(method->is_private(), "must be");
 170       if (log_is_enabled(Debug, cds)) {
 171         ResourceMark rm(THREAD);
 172         log_debug(cds)("  calling %s", method->name_and_sig_as_C_string());
 173       }
 174       JavaValue result(T_VOID);
 175       JavaCalls::call_special(&result, h_obj, klass,
 176                               method_name, method_sig, CHECK);
 177     }
 178     klass = klass->java_super();
 179   }
 180 }
 181 
 182 void HeapShared::reset_archived_object_states(TRAPS) {
 183   assert(CDSConfig::is_dumping_heap(), "dump-time only");
 184   log_debug(cds)("Resetting platform loader");
 185   reset_states(SystemDictionary::java_platform_loader(), CHECK);
 186   log_debug(cds)("Resetting system loader");
 187   reset_states(SystemDictionary::java_system_loader(), CHECK);
 188 
 189   // Clean up jdk.internal.loader.ClassLoaders::bootLoader(), which is not
 190   // directly used for class loading, but rather is used by the core library
 191   // to keep track of resources, etc, loaded by the null class loader.
 192   //
 193   // Note, this object is non-null, and is not the same as
 194   // ClassLoaderData::the_null_class_loader_data()->class_loader(),
 195   // which is null.
 196   log_debug(cds)("Resetting boot loader");
 197   JavaValue result(T_OBJECT);
 198   JavaCalls::call_static(&result,
 199                          vmClasses::jdk_internal_loader_ClassLoaders_klass(),
 200                          vmSymbols::bootLoader_name(),
 201                          vmSymbols::void_BuiltinClassLoader_signature(),
 202                          CHECK);
 203   Handle boot_loader(THREAD, result.get_oop());
 204   reset_states(boot_loader(), CHECK);
 205 }
 206 
 207 HeapShared::ArchivedObjectCache* HeapShared::_archived_object_cache = nullptr;
 208 
 209 bool HeapShared::has_been_archived(oop obj) {
 210   assert(CDSConfig::is_dumping_heap(), "dump-time only");
 211   return archived_object_cache()->get(obj) != nullptr;
 212 }
 213 
 214 int HeapShared::append_root(oop obj) {
 215   assert(CDSConfig::is_dumping_heap(), "dump-time only");
 216 
 217   // No GC should happen since we aren't scanning _pending_roots.
 218   assert(Thread::current() == (Thread*)VMThread::vm_thread(), "should be in vm thread");
 219 
 220   if (_pending_roots == nullptr) {
 221     _pending_roots = new GrowableArrayCHeap<oop, mtClassShared>(500);
 222   }
 223 
 224   return _pending_roots->append(obj);
 225 }
 226 
 227 objArrayOop HeapShared::roots() {
 228   if (CDSConfig::is_dumping_heap()) {
 229     assert(Thread::current() == (Thread*)VMThread::vm_thread(), "should be in vm thread");
 230     if (!HeapShared::can_write()) {
 231       return nullptr;
 232     }
 233   } else {
 234     assert(UseSharedSpaces, "must be");
 235   }
 236 
 237   objArrayOop roots = (objArrayOop)_roots.resolve();
 238   assert(roots != nullptr, "should have been initialized");
 239   return roots;
 240 }
 241 
 242 // Returns an objArray that contains all the roots of the archived objects
 243 oop HeapShared::get_root(int index, bool clear) {
 244   assert(index >= 0, "sanity");
 245   assert(!CDSConfig::is_dumping_heap() && UseSharedSpaces, "runtime only");
 246   assert(!_roots.is_empty(), "must have loaded shared heap");
 247   oop result = roots()->obj_at(index);
 248   if (clear) {
 249     clear_root(index);
 250   }
 251   return result;
 252 }
 253 
 254 void HeapShared::clear_root(int index) {
 255   assert(index >= 0, "sanity");
 256   assert(UseSharedSpaces, "must be");
 257   if (ArchiveHeapLoader::is_in_use()) {
 258     if (log_is_enabled(Debug, cds, heap)) {
 259       oop old = roots()->obj_at(index);
 260       log_debug(cds, heap)("Clearing root %d: was " PTR_FORMAT, index, p2i(old));
 261     }
 262     roots()->obj_at_put(index, nullptr);
 263   }
 264 }
 265 
 266 bool HeapShared::archive_object(oop obj) {
 267   assert(CDSConfig::is_dumping_heap(), "dump-time only");
 268 
 269   assert(!obj->is_stackChunk(), "do not archive stack chunks");
 270   if (has_been_archived(obj)) {
 271     return true;
 272   }
 273 
 274   if (ArchiveHeapWriter::is_too_large_to_archive(obj->size())) {
 275     log_debug(cds, heap)("Cannot archive, object (" PTR_FORMAT ") is too large: " SIZE_FORMAT,
 276                          p2i(obj), obj->size());
 277     return false;
 278   } else {
 279     count_allocation(obj->size());
 280     ArchiveHeapWriter::add_source_obj(obj);
 281 
 282     // The archived objects are discovered in a predictable order. Compute
 283     // their identity_hash() as soon as we see them. This ensures that the
 284     // the identity_hash in the object header will have a predictable value,
 285     // making the archive reproducible.
 286     obj->identity_hash();
 287     CachedOopInfo info = make_cached_oop_info();
 288     archived_object_cache()->put(obj, info);
 289     mark_native_pointers(obj);
 290 
 291     if (log_is_enabled(Debug, cds, heap)) {
 292       ResourceMark rm;
 293       log_debug(cds, heap)("Archived heap object " PTR_FORMAT " : %s",
 294                            p2i(obj), obj->klass()->external_name());
 295     }
 296 
 297     if (java_lang_Module::is_instance(obj) && Modules::check_archived_module_oop(obj)) {
 298       Modules::update_oops_in_archived_module(obj, append_root(obj));
 299     }
 300 
 301     return true;
 302   }
 303 }
 304 
 305 class MetaspaceObjToOopHandleTable: public ResourceHashtable<MetaspaceObj*, OopHandle,
 306     36137, // prime number
 307     AnyObj::C_HEAP,
 308     mtClassShared> {
 309 public:
 310   oop get_oop(MetaspaceObj* ptr) {
 311     MutexLocker ml(ScratchObjects_lock, Mutex::_no_safepoint_check_flag);
 312     OopHandle* handle = get(ptr);
 313     if (handle != nullptr) {
 314       return handle->resolve();
 315     } else {
 316       return nullptr;
 317     }
 318   }
 319   void set_oop(MetaspaceObj* ptr, oop o) {
 320     MutexLocker ml(ScratchObjects_lock, Mutex::_no_safepoint_check_flag);
 321     OopHandle handle(Universe::vm_global(), o);
 322     bool is_new = put(ptr, handle);
 323     assert(is_new, "cannot set twice");
 324   }
 325   void remove_oop(MetaspaceObj* ptr) {
 326     MutexLocker ml(ScratchObjects_lock, Mutex::_no_safepoint_check_flag);
 327     OopHandle* handle = get(ptr);
 328     if (handle != nullptr) {
 329       handle->release(Universe::vm_global());
 330       remove(ptr);
 331     }
 332   }
 333 };
 334 
 335 void HeapShared::add_scratch_resolved_references(ConstantPool* src, objArrayOop dest) {
 336   _scratch_references_table->set_oop(src, dest);
 337 }
 338 
 339 objArrayOop HeapShared::scratch_resolved_references(ConstantPool* src) {
 340   return (objArrayOop)_scratch_references_table->get_oop(src);
 341 }
 342 
 343 void HeapShared::init_scratch_objects(TRAPS) {
 344   for (int i = T_BOOLEAN; i < T_VOID+1; i++) {
 345     BasicType bt = (BasicType)i;
 346     if (!is_reference_type(bt)) {
 347       oop m = java_lang_Class::create_basic_type_mirror(type2name(bt), bt, CHECK);
 348       _scratch_basic_type_mirrors[i] = OopHandle(Universe::vm_global(), m);
 349     }
 350   }
 351   _scratch_java_mirror_table = new (mtClass)MetaspaceObjToOopHandleTable();
 352   _scratch_references_table = new (mtClass)MetaspaceObjToOopHandleTable();
 353 }
 354 
 355 oop HeapShared::scratch_java_mirror(BasicType t) {
 356   assert((uint)t < T_VOID+1, "range check");
 357   assert(!is_reference_type(t), "sanity");
 358   return _scratch_basic_type_mirrors[t].resolve();
 359 }
 360 
 361 oop HeapShared::scratch_java_mirror(Klass* k) {
 362   return _scratch_java_mirror_table->get_oop(k);
 363 }
 364 
 365 void HeapShared::set_scratch_java_mirror(Klass* k, oop mirror) {
 366   _scratch_java_mirror_table->set_oop(k, mirror);
 367 }
 368 
 369 void HeapShared::remove_scratch_objects(Klass* k) {
 370   _scratch_java_mirror_table->remove_oop(k);
 371   if (k->is_instance_klass()) {
 372     _scratch_references_table->remove(InstanceKlass::cast(k)->constants());
 373   }
 374 }
 375 
 376 void HeapShared::archive_java_mirrors() {
 377   for (int i = T_BOOLEAN; i < T_VOID+1; i++) {
 378     BasicType bt = (BasicType)i;
 379     if (!is_reference_type(bt)) {
 380       oop m = _scratch_basic_type_mirrors[i].resolve();
 381       assert(m != nullptr, "sanity");
 382       bool success = archive_reachable_objects_from(1, _default_subgraph_info, m);
 383       assert(success, "sanity");
 384 
 385       log_trace(cds, heap, mirror)(
 386         "Archived %s mirror object from " PTR_FORMAT,
 387         type2name(bt), p2i(m));
 388 
 389       Universe::set_archived_basic_type_mirror_index(bt, append_root(m));
 390     }
 391   }
 392 
 393   GrowableArray<Klass*>* klasses = ArchiveBuilder::current()->klasses();
 394   assert(klasses != nullptr, "sanity");
 395   for (int i = 0; i < klasses->length(); i++) {
 396     Klass* orig_k = klasses->at(i);
 397     oop m = scratch_java_mirror(orig_k);
 398     if (m != nullptr) {
 399       Klass* buffered_k = ArchiveBuilder::get_buffered_klass(orig_k);
 400       bool success = archive_reachable_objects_from(1, _default_subgraph_info, m);
 401       guarantee(success, "scratch mirrors must point to only archivable objects");
 402       buffered_k->set_archived_java_mirror(append_root(m));
 403       ResourceMark rm;
 404       log_trace(cds, heap, mirror)(
 405         "Archived %s mirror object from " PTR_FORMAT,
 406         buffered_k->external_name(), p2i(m));
 407 
 408       // archive the resolved_referenes array
 409       if (buffered_k->is_instance_klass()) {
 410         InstanceKlass* ik = InstanceKlass::cast(buffered_k);
 411         oop rr = ik->constants()->prepare_resolved_references_for_archiving();
 412         if (rr != nullptr && !ArchiveHeapWriter::is_too_large_to_archive(rr)) {
 413           bool success = HeapShared::archive_reachable_objects_from(1, _default_subgraph_info, rr);
 414           assert(success, "must be");
 415           int root_index = append_root(rr);
 416           ik->constants()->cache()->set_archived_references(root_index);
 417         }
 418       }
 419     }
 420   }
 421 }
 422 
 423 void HeapShared::archive_strings() {
 424   oop shared_strings_array = StringTable::init_shared_table(_dumped_interned_strings);
 425   bool success = archive_reachable_objects_from(1, _default_subgraph_info, shared_strings_array);
 426   // We must succeed because:
 427   // - _dumped_interned_strings do not contain any large strings.
 428   // - StringTable::init_shared_table() doesn't create any large arrays.
 429   assert(success, "shared strings array must not point to arrays or strings that are too large to archive");
 430   StringTable::set_shared_strings_array_index(append_root(shared_strings_array));
 431 }
 432 
 433 void HeapShared::mark_native_pointers(oop orig_obj) {
 434   if (java_lang_Class::is_instance(orig_obj)) {
 435     ArchiveHeapWriter::mark_native_pointer(orig_obj, java_lang_Class::klass_offset());
 436     ArchiveHeapWriter::mark_native_pointer(orig_obj, java_lang_Class::array_klass_offset());
 437   }
 438 }
 439 
 440 // -- Handling of Enum objects
 441 // Java Enum classes have synthetic <clinit> methods that look like this
 442 //     enum MyEnum {FOO, BAR}
 443 //     MyEnum::<clinint> {
 444 //        /*static final MyEnum*/ MyEnum::FOO = new MyEnum("FOO");
 445 //        /*static final MyEnum*/ MyEnum::BAR = new MyEnum("BAR");
 446 //     }
 447 //
 448 // If MyEnum::FOO object is referenced by any of the archived subgraphs, we must
 449 // ensure the archived value equals (in object address) to the runtime value of
 450 // MyEnum::FOO.
 451 //
 452 // However, since MyEnum::<clinint> is synthetically generated by javac, there's
 453 // no way of programmatically handling this inside the Java code (as you would handle
 454 // ModuleLayer::EMPTY_LAYER, for example).
 455 //
 456 // Instead, we archive all static field of such Enum classes. At runtime,
 457 // HeapShared::initialize_enum_klass() will skip the <clinit> method and pull
 458 // the static fields out of the archived heap.
 459 void HeapShared::check_enum_obj(int level,
 460                                 KlassSubGraphInfo* subgraph_info,
 461                                 oop orig_obj) {
 462   assert(level > 1, "must never be called at the first (outermost) level");
 463   Klass* k = orig_obj->klass();
 464   Klass* buffered_k = ArchiveBuilder::get_buffered_klass(k);
 465   if (!k->is_instance_klass()) {
 466     return;
 467   }
 468   InstanceKlass* ik = InstanceKlass::cast(k);
 469   if (ik->java_super() == vmClasses::Enum_klass() && !ik->has_archived_enum_objs()) {
 470     ResourceMark rm;
 471     ik->set_has_archived_enum_objs();
 472     buffered_k->set_has_archived_enum_objs();
 473     oop mirror = ik->java_mirror();
 474 
 475     for (JavaFieldStream fs(ik); !fs.done(); fs.next()) {
 476       if (fs.access_flags().is_static()) {
 477         fieldDescriptor& fd = fs.field_descriptor();
 478         if (fd.field_type() != T_OBJECT && fd.field_type() != T_ARRAY) {
 479           guarantee(false, "static field %s::%s must be T_OBJECT or T_ARRAY",
 480                     ik->external_name(), fd.name()->as_C_string());
 481         }
 482         oop oop_field = mirror->obj_field(fd.offset());
 483         if (oop_field == nullptr) {
 484           guarantee(false, "static field %s::%s must not be null",
 485                     ik->external_name(), fd.name()->as_C_string());
 486         } else if (oop_field->klass() != ik && oop_field->klass() != ik->array_klass_or_null()) {
 487           guarantee(false, "static field %s::%s is of the wrong type",
 488                     ik->external_name(), fd.name()->as_C_string());
 489         }
 490         bool success = archive_reachable_objects_from(level, subgraph_info, oop_field);
 491         assert(success, "VM should have exited with unarchivable objects for _level > 1");
 492         int root_index = append_root(oop_field);
 493         log_info(cds, heap)("Archived enum obj @%d %s::%s (" INTPTR_FORMAT ")",
 494                             root_index, ik->external_name(), fd.name()->as_C_string(),
 495                             p2i((oopDesc*)oop_field));
 496         SystemDictionaryShared::add_enum_klass_static_field(ik, root_index);
 497       }
 498     }
 499   }
 500 }
 501 
 502 // See comments in HeapShared::check_enum_obj()
 503 bool HeapShared::initialize_enum_klass(InstanceKlass* k, TRAPS) {
 504   if (!ArchiveHeapLoader::is_in_use()) {
 505     return false;
 506   }
 507 
 508   RunTimeClassInfo* info = RunTimeClassInfo::get_for(k);
 509   assert(info != nullptr, "sanity");
 510 
 511   if (log_is_enabled(Info, cds, heap)) {
 512     ResourceMark rm;
 513     log_info(cds, heap)("Initializing Enum class: %s", k->external_name());
 514   }
 515 
 516   oop mirror = k->java_mirror();
 517   int i = 0;
 518   for (JavaFieldStream fs(k); !fs.done(); fs.next()) {
 519     if (fs.access_flags().is_static()) {
 520       int root_index = info->enum_klass_static_field_root_index_at(i++);
 521       fieldDescriptor& fd = fs.field_descriptor();
 522       assert(fd.field_type() == T_OBJECT || fd.field_type() == T_ARRAY, "must be");
 523       mirror->obj_field_put(fd.offset(), get_root(root_index, /*clear=*/true));
 524     }
 525   }
 526   return true;
 527 }
 528 
 529 void HeapShared::archive_objects(ArchiveHeapInfo *heap_info) {
 530   {
 531     NoSafepointVerifier nsv;
 532 
 533     _default_subgraph_info = init_subgraph_info(vmClasses::Object_klass(), false);
 534 
 535     // Cache for recording where the archived objects are copied to
 536     create_archived_object_cache();
 537 
 538     log_info(cds)("Heap range = [" PTR_FORMAT " - "  PTR_FORMAT "]",
 539                    UseCompressedOops ? p2i(CompressedOops::begin()) :
 540                                        p2i((address)G1CollectedHeap::heap()->reserved().start()),
 541                    UseCompressedOops ? p2i(CompressedOops::end()) :
 542                                        p2i((address)G1CollectedHeap::heap()->reserved().end()));
 543     copy_objects();
 544 
 545     CDSHeapVerifier::verify();
 546     check_default_subgraph_classes();
 547   }
 548 
 549   ArchiveHeapWriter::write(_pending_roots, heap_info);
 550 }
 551 
 552 void HeapShared::copy_interned_strings() {
 553   init_seen_objects_table();
 554 
 555   auto copier = [&] (oop s, bool value_ignored) {
 556     assert(s != nullptr, "sanity");
 557     assert(!ArchiveHeapWriter::is_string_too_large_to_archive(s), "large strings must have been filtered");
 558     bool success = archive_reachable_objects_from(1, _default_subgraph_info, s);
 559     assert(success, "must be");
 560     // Prevent string deduplication from changing the value field to
 561     // something not in the archive.
 562     java_lang_String::set_deduplication_forbidden(s);
 563   };
 564   _dumped_interned_strings->iterate_all(copier);
 565 
 566   delete_seen_objects_table();
 567 }
 568 
 569 void HeapShared::copy_special_objects() {
 570   // Archive special objects that do not belong to any subgraphs
 571   init_seen_objects_table();
 572   archive_java_mirrors();
 573   archive_strings();
 574   delete_seen_objects_table();
 575 }
 576 
 577 void HeapShared::copy_objects() {
 578   assert(HeapShared::can_write(), "must be");
 579 
 580   copy_interned_strings();
 581   copy_special_objects();
 582 
 583   archive_object_subgraphs(archive_subgraph_entry_fields,
 584                            false /* is_full_module_graph */);
 585 
 586   if (CDSConfig::is_dumping_full_module_graph()) {
 587     archive_object_subgraphs(fmg_archive_subgraph_entry_fields,
 588                              true /* is_full_module_graph */);
 589     Modules::verify_archived_modules();
 590   }
 591 }
 592 
 593 //
 594 // Subgraph archiving support
 595 //
 596 HeapShared::DumpTimeKlassSubGraphInfoTable* HeapShared::_dump_time_subgraph_info_table = nullptr;
 597 HeapShared::RunTimeKlassSubGraphInfoTable   HeapShared::_run_time_subgraph_info_table;
 598 
 599 // Get the subgraph_info for Klass k. A new subgraph_info is created if
 600 // there is no existing one for k. The subgraph_info records the "buffered"
 601 // address of the class.
 602 KlassSubGraphInfo* HeapShared::init_subgraph_info(Klass* k, bool is_full_module_graph) {
 603   assert(CDSConfig::is_dumping_heap(), "dump time only");
 604   bool created;
 605   Klass* buffered_k = ArchiveBuilder::get_buffered_klass(k);
 606   KlassSubGraphInfo* info =
 607     _dump_time_subgraph_info_table->put_if_absent(k, KlassSubGraphInfo(buffered_k, is_full_module_graph),
 608                                                   &created);
 609   assert(created, "must not initialize twice");
 610   return info;
 611 }
 612 
 613 KlassSubGraphInfo* HeapShared::get_subgraph_info(Klass* k) {
 614   assert(CDSConfig::is_dumping_heap(), "dump time only");
 615   KlassSubGraphInfo* info = _dump_time_subgraph_info_table->get(k);
 616   assert(info != nullptr, "must have been initialized");
 617   return info;
 618 }
 619 
 620 // Add an entry field to the current KlassSubGraphInfo.
 621 void KlassSubGraphInfo::add_subgraph_entry_field(int static_field_offset, oop v) {
 622   assert(CDSConfig::is_dumping_heap(), "dump time only");
 623   if (_subgraph_entry_fields == nullptr) {
 624     _subgraph_entry_fields =
 625       new (mtClass) GrowableArray<int>(10, mtClass);
 626   }
 627   _subgraph_entry_fields->append(static_field_offset);
 628   _subgraph_entry_fields->append(HeapShared::append_root(v));
 629 }
 630 
 631 // Add the Klass* for an object in the current KlassSubGraphInfo's subgraphs.
 632 // Only objects of boot classes can be included in sub-graph.
 633 void KlassSubGraphInfo::add_subgraph_object_klass(Klass* orig_k) {
 634   assert(CDSConfig::is_dumping_heap(), "dump time only");
 635   Klass* buffered_k = ArchiveBuilder::get_buffered_klass(orig_k);
 636 
 637   if (_subgraph_object_klasses == nullptr) {
 638     _subgraph_object_klasses =
 639       new (mtClass) GrowableArray<Klass*>(50, mtClass);
 640   }
 641 
 642   assert(ArchiveBuilder::current()->is_in_buffer_space(buffered_k), "must be a shared class");
 643 
 644   if (_k == buffered_k) {
 645     // Don't add the Klass containing the sub-graph to it's own klass
 646     // initialization list.
 647     return;
 648   }
 649 
 650   if (buffered_k->is_instance_klass()) {
 651     assert(InstanceKlass::cast(buffered_k)->is_shared_boot_class(),
 652           "must be boot class");
 653     // vmClasses::xxx_klass() are not updated, need to check
 654     // the original Klass*
 655     if (orig_k == vmClasses::String_klass() ||
 656         orig_k == vmClasses::Object_klass()) {
 657       // Initialized early during VM initialization. No need to be added
 658       // to the sub-graph object class list.
 659       return;
 660     }
 661     check_allowed_klass(InstanceKlass::cast(orig_k));
 662   } else if (buffered_k->is_objArray_klass()) {
 663     Klass* abk = ObjArrayKlass::cast(buffered_k)->bottom_klass();
 664     if (abk->is_instance_klass()) {
 665       assert(InstanceKlass::cast(abk)->is_shared_boot_class(),
 666             "must be boot class");
 667       check_allowed_klass(InstanceKlass::cast(ObjArrayKlass::cast(orig_k)->bottom_klass()));
 668     }
 669     if (buffered_k == Universe::objectArrayKlassObj()) {
 670       // Initialized early during Universe::genesis. No need to be added
 671       // to the list.
 672       return;
 673     }
 674   } else {
 675     assert(buffered_k->is_typeArray_klass(), "must be");
 676     // Primitive type arrays are created early during Universe::genesis.
 677     return;
 678   }
 679 
 680   if (log_is_enabled(Debug, cds, heap)) {
 681     if (!_subgraph_object_klasses->contains(buffered_k)) {
 682       ResourceMark rm;
 683       log_debug(cds, heap)("Adding klass %s", orig_k->external_name());
 684     }
 685   }
 686 
 687   _subgraph_object_klasses->append_if_missing(buffered_k);
 688   _has_non_early_klasses |= is_non_early_klass(orig_k);
 689 }
 690 
 691 void KlassSubGraphInfo::check_allowed_klass(InstanceKlass* ik) {
 692   if (ik->module()->name() == vmSymbols::java_base()) {
 693     assert(ik->package() != nullptr, "classes in java.base cannot be in unnamed package");
 694     return;
 695   }
 696 
 697 #ifndef PRODUCT
 698   if (!ik->module()->is_named() && ik->package() == nullptr) {
 699     // This class is loaded by ArchiveHeapTestClass
 700     return;
 701   }
 702   const char* extra_msg = ", or in an unnamed package of an unnamed module";
 703 #else
 704   const char* extra_msg = "";
 705 #endif
 706 
 707   ResourceMark rm;
 708   log_error(cds, heap)("Class %s not allowed in archive heap. Must be in java.base%s",
 709                        ik->external_name(), extra_msg);
 710   MetaspaceShared::unrecoverable_writing_error();
 711 }
 712 
 713 bool KlassSubGraphInfo::is_non_early_klass(Klass* k) {
 714   if (k->is_objArray_klass()) {
 715     k = ObjArrayKlass::cast(k)->bottom_klass();
 716   }
 717   if (k->is_instance_klass()) {
 718     if (!SystemDictionaryShared::is_early_klass(InstanceKlass::cast(k))) {
 719       ResourceMark rm;
 720       log_info(cds, heap)("non-early: %s", k->external_name());
 721       return true;
 722     } else {
 723       return false;
 724     }
 725   } else {
 726     return false;
 727   }
 728 }
 729 
 730 // Initialize an archived subgraph_info_record from the given KlassSubGraphInfo.
 731 void ArchivedKlassSubGraphInfoRecord::init(KlassSubGraphInfo* info) {
 732   _k = info->klass();
 733   _entry_field_records = nullptr;
 734   _subgraph_object_klasses = nullptr;
 735   _is_full_module_graph = info->is_full_module_graph();
 736 
 737   if (_is_full_module_graph) {
 738     // Consider all classes referenced by the full module graph as early -- we will be
 739     // allocating objects of these classes during JVMTI early phase, so they cannot
 740     // be processed by (non-early) JVMTI ClassFileLoadHook
 741     _has_non_early_klasses = false;
 742   } else {
 743     _has_non_early_klasses = info->has_non_early_klasses();
 744   }
 745 
 746   if (_has_non_early_klasses) {
 747     ResourceMark rm;
 748     log_info(cds, heap)(
 749           "Subgraph of klass %s has non-early klasses and cannot be used when JVMTI ClassFileLoadHook is enabled",
 750           _k->external_name());
 751   }
 752 
 753   // populate the entry fields
 754   GrowableArray<int>* entry_fields = info->subgraph_entry_fields();
 755   if (entry_fields != nullptr) {
 756     int num_entry_fields = entry_fields->length();
 757     assert(num_entry_fields % 2 == 0, "sanity");
 758     _entry_field_records =
 759       ArchiveBuilder::new_ro_array<int>(num_entry_fields);
 760     for (int i = 0 ; i < num_entry_fields; i++) {
 761       _entry_field_records->at_put(i, entry_fields->at(i));
 762     }
 763   }
 764 
 765   // the Klasses of the objects in the sub-graphs
 766   GrowableArray<Klass*>* subgraph_object_klasses = info->subgraph_object_klasses();
 767   if (subgraph_object_klasses != nullptr) {
 768     int num_subgraphs_klasses = subgraph_object_klasses->length();
 769     _subgraph_object_klasses =
 770       ArchiveBuilder::new_ro_array<Klass*>(num_subgraphs_klasses);
 771     for (int i = 0; i < num_subgraphs_klasses; i++) {
 772       Klass* subgraph_k = subgraph_object_klasses->at(i);
 773       if (log_is_enabled(Info, cds, heap)) {
 774         ResourceMark rm;
 775         log_info(cds, heap)(
 776           "Archived object klass %s (%2d) => %s",
 777           _k->external_name(), i, subgraph_k->external_name());
 778       }
 779       _subgraph_object_klasses->at_put(i, subgraph_k);
 780       ArchivePtrMarker::mark_pointer(_subgraph_object_klasses->adr_at(i));
 781     }
 782   }
 783 
 784   ArchivePtrMarker::mark_pointer(&_k);
 785   ArchivePtrMarker::mark_pointer(&_entry_field_records);
 786   ArchivePtrMarker::mark_pointer(&_subgraph_object_klasses);
 787 }
 788 
 789 struct CopyKlassSubGraphInfoToArchive : StackObj {
 790   CompactHashtableWriter* _writer;
 791   CopyKlassSubGraphInfoToArchive(CompactHashtableWriter* writer) : _writer(writer) {}
 792 
 793   bool do_entry(Klass* klass, KlassSubGraphInfo& info) {
 794     if (info.subgraph_object_klasses() != nullptr || info.subgraph_entry_fields() != nullptr) {
 795       ArchivedKlassSubGraphInfoRecord* record =
 796         (ArchivedKlassSubGraphInfoRecord*)ArchiveBuilder::ro_region_alloc(sizeof(ArchivedKlassSubGraphInfoRecord));
 797       record->init(&info);
 798 
 799       Klass* buffered_k = ArchiveBuilder::get_buffered_klass(klass);
 800       unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary((address)buffered_k);
 801       u4 delta = ArchiveBuilder::current()->any_to_offset_u4(record);
 802       _writer->add(hash, delta);
 803     }
 804     return true; // keep on iterating
 805   }
 806 };
 807 
 808 // Build the records of archived subgraph infos, which include:
 809 // - Entry points to all subgraphs from the containing class mirror. The entry
 810 //   points are static fields in the mirror. For each entry point, the field
 811 //   offset, and value are recorded in the sub-graph
 812 //   info. The value is stored back to the corresponding field at runtime.
 813 // - A list of klasses that need to be loaded/initialized before archived
 814 //   java object sub-graph can be accessed at runtime.
 815 void HeapShared::write_subgraph_info_table() {
 816   // Allocate the contents of the hashtable(s) inside the RO region of the CDS archive.
 817   DumpTimeKlassSubGraphInfoTable* d_table = _dump_time_subgraph_info_table;
 818   CompactHashtableStats stats;
 819 
 820   _run_time_subgraph_info_table.reset();
 821 
 822   CompactHashtableWriter writer(d_table->_count, &stats);
 823   CopyKlassSubGraphInfoToArchive copy(&writer);
 824   d_table->iterate(&copy);
 825   writer.dump(&_run_time_subgraph_info_table, "subgraphs");
 826 
 827 #ifndef PRODUCT
 828   if (ArchiveHeapTestClass != nullptr) {
 829     size_t len = strlen(ArchiveHeapTestClass) + 1;
 830     Array<char>* array = ArchiveBuilder::new_ro_array<char>((int)len);
 831     strncpy(array->adr_at(0), ArchiveHeapTestClass, len);
 832     _archived_ArchiveHeapTestClass = array;
 833   }
 834 #endif
 835   if (log_is_enabled(Info, cds, heap)) {
 836     print_stats();
 837   }
 838 }
 839 
 840 void HeapShared::init_roots(oop roots_oop) {
 841   if (roots_oop != nullptr) {
 842     assert(ArchiveHeapLoader::is_in_use(), "must be");
 843     _roots = OopHandle(Universe::vm_global(), roots_oop);
 844   }
 845 }
 846 
 847 void HeapShared::serialize_tables(SerializeClosure* soc) {
 848 
 849 #ifndef PRODUCT
 850   soc->do_ptr(&_archived_ArchiveHeapTestClass);
 851   if (soc->reading() && _archived_ArchiveHeapTestClass != nullptr) {
 852     _test_class_name = _archived_ArchiveHeapTestClass->adr_at(0);
 853     setup_test_class(_test_class_name);
 854   }
 855 #endif
 856 
 857   _run_time_subgraph_info_table.serialize_header(soc);
 858 }
 859 
 860 static void verify_the_heap(Klass* k, const char* which) {
 861   if (VerifyArchivedFields > 0) {
 862     ResourceMark rm;
 863     log_info(cds, heap)("Verify heap %s initializing static field(s) in %s",
 864                         which, k->external_name());
 865 
 866     VM_Verify verify_op;
 867     VMThread::execute(&verify_op);
 868 
 869     if (VerifyArchivedFields > 1 && is_init_completed()) {
 870       // At this time, the oop->klass() of some archived objects in the heap may not
 871       // have been loaded into the system dictionary yet. Nevertheless, oop->klass() should
 872       // have enough information (object size, oop maps, etc) so that a GC can be safely
 873       // performed.
 874       //
 875       // -XX:VerifyArchivedFields=2 force a GC to happen in such an early stage
 876       // to check for GC safety.
 877       log_info(cds, heap)("Trigger GC %s initializing static field(s) in %s",
 878                           which, k->external_name());
 879       FlagSetting fs1(VerifyBeforeGC, true);
 880       FlagSetting fs2(VerifyDuringGC, true);
 881       FlagSetting fs3(VerifyAfterGC,  true);
 882       Universe::heap()->collect(GCCause::_java_lang_system_gc);
 883     }
 884   }
 885 }
 886 
 887 // Before GC can execute, we must ensure that all oops reachable from HeapShared::roots()
 888 // have a valid klass. I.e., oopDesc::klass() must have already been resolved.
 889 //
 890 // Note: if a ArchivedKlassSubGraphInfoRecord contains non-early classes, and JVMTI
 891 // ClassFileLoadHook is enabled, it's possible for this class to be dynamically replaced. In
 892 // this case, we will not load the ArchivedKlassSubGraphInfoRecord and will clear its roots.
 893 void HeapShared::resolve_classes(JavaThread* current) {
 894   assert(UseSharedSpaces, "runtime only!");
 895   if (!ArchiveHeapLoader::is_in_use()) {
 896     return; // nothing to do
 897   }
 898   resolve_classes_for_subgraphs(current, archive_subgraph_entry_fields);
 899   resolve_classes_for_subgraphs(current, fmg_archive_subgraph_entry_fields);
 900 }
 901 
 902 void HeapShared::resolve_classes_for_subgraphs(JavaThread* current, ArchivableStaticFieldInfo fields[]) {
 903   for (int i = 0; fields[i].valid(); i++) {
 904     ArchivableStaticFieldInfo* info = &fields[i];
 905     TempNewSymbol klass_name = SymbolTable::new_symbol(info->klass_name);
 906     InstanceKlass* k = SystemDictionaryShared::find_builtin_class(klass_name);
 907     assert(k != nullptr && k->is_shared_boot_class(), "sanity");
 908     resolve_classes_for_subgraph_of(current, k);
 909   }
 910 }
 911 
 912 void HeapShared::resolve_classes_for_subgraph_of(JavaThread* current, Klass* k) {
 913   JavaThread* THREAD = current;
 914   ExceptionMark em(THREAD);
 915   const ArchivedKlassSubGraphInfoRecord* record =
 916    resolve_or_init_classes_for_subgraph_of(k, /*do_init=*/false, THREAD);
 917   if (HAS_PENDING_EXCEPTION) {
 918    CLEAR_PENDING_EXCEPTION;
 919   }
 920   if (record == nullptr) {
 921    clear_archived_roots_of(k);
 922   }
 923 }
 924 
 925 void HeapShared::initialize_from_archived_subgraph(JavaThread* current, Klass* k) {
 926   JavaThread* THREAD = current;
 927   if (!ArchiveHeapLoader::is_in_use()) {
 928     return; // nothing to do
 929   }
 930 
 931   ExceptionMark em(THREAD);
 932   const ArchivedKlassSubGraphInfoRecord* record =
 933     resolve_or_init_classes_for_subgraph_of(k, /*do_init=*/true, THREAD);
 934 
 935   if (HAS_PENDING_EXCEPTION) {
 936     CLEAR_PENDING_EXCEPTION;
 937     // None of the field value will be set if there was an exception when initializing the classes.
 938     // The java code will not see any of the archived objects in the
 939     // subgraphs referenced from k in this case.
 940     return;
 941   }
 942 
 943   if (record != nullptr) {
 944     init_archived_fields_for(k, record);
 945   }
 946 }
 947 
 948 const ArchivedKlassSubGraphInfoRecord*
 949 HeapShared::resolve_or_init_classes_for_subgraph_of(Klass* k, bool do_init, TRAPS) {
 950   assert(!CDSConfig::is_dumping_heap(), "Should not be called when dumping heap");
 951 
 952   if (!k->is_shared()) {
 953     return nullptr;
 954   }
 955   unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary_quick(k);
 956   const ArchivedKlassSubGraphInfoRecord* record = _run_time_subgraph_info_table.lookup(k, hash, 0);
 957 
 958 #ifndef PRODUCT
 959   if (_test_class_name != nullptr && k->name()->equals(_test_class_name) && record != nullptr) {
 960     _test_class = k;
 961     _test_class_record = record;
 962   }
 963 #endif
 964 
 965   // Initialize from archived data. Currently this is done only
 966   // during VM initialization time. No lock is needed.
 967   if (record == nullptr) {
 968     if (log_is_enabled(Info, cds, heap)) {
 969       ResourceMark rm(THREAD);
 970       log_info(cds, heap)("subgraph %s is not recorded",
 971                           k->external_name());
 972     }
 973     return nullptr;
 974   } else {
 975     if (record->is_full_module_graph() && !CDSConfig::is_loading_full_module_graph()) {
 976       if (log_is_enabled(Info, cds, heap)) {
 977         ResourceMark rm(THREAD);
 978         log_info(cds, heap)("subgraph %s cannot be used because full module graph is disabled",
 979                             k->external_name());
 980       }
 981       return nullptr;
 982     }
 983 
 984     if (record->has_non_early_klasses() && JvmtiExport::should_post_class_file_load_hook()) {
 985       if (log_is_enabled(Info, cds, heap)) {
 986         ResourceMark rm(THREAD);
 987         log_info(cds, heap)("subgraph %s cannot be used because JVMTI ClassFileLoadHook is enabled",
 988                             k->external_name());
 989       }
 990       return nullptr;
 991     }
 992 
 993     if (log_is_enabled(Info, cds, heap)) {
 994       ResourceMark rm;
 995       log_info(cds, heap)("%s subgraph %s ", do_init ? "init" : "resolve", k->external_name());
 996     }
 997 
 998     resolve_or_init(k, do_init, CHECK_NULL);
 999 
1000     // Load/link/initialize the klasses of the objects in the subgraph.
1001     // nullptr class loader is used.
1002     Array<Klass*>* klasses = record->subgraph_object_klasses();
1003     if (klasses != nullptr) {
1004       for (int i = 0; i < klasses->length(); i++) {
1005         Klass* klass = klasses->at(i);
1006         if (!klass->is_shared()) {
1007           return nullptr;
1008         }
1009         resolve_or_init(klass, do_init, CHECK_NULL);
1010       }
1011     }
1012   }
1013 
1014   return record;
1015 }
1016 
1017 void HeapShared::resolve_or_init(Klass* k, bool do_init, TRAPS) {
1018   if (!do_init) {
1019     if (k->class_loader_data() == nullptr) {
1020       Klass* resolved_k = SystemDictionary::resolve_or_null(k->name(), CHECK);
1021       assert(resolved_k == k, "classes used by archived heap must not be replaced by JVMTI ClassFileLoadHook");
1022     }
1023   } else {
1024     assert(k->class_loader_data() != nullptr, "must have been resolved by HeapShared::resolve_classes");
1025     if (k->is_instance_klass()) {
1026       InstanceKlass* ik = InstanceKlass::cast(k);
1027       ik->initialize(CHECK);
1028     } else if (k->is_objArray_klass()) {
1029       ObjArrayKlass* oak = ObjArrayKlass::cast(k);
1030       oak->initialize(CHECK);
1031     }
1032   }
1033 }
1034 
1035 void HeapShared::init_archived_fields_for(Klass* k, const ArchivedKlassSubGraphInfoRecord* record) {
1036   verify_the_heap(k, "before");
1037 
1038   // Load the subgraph entry fields from the record and store them back to
1039   // the corresponding fields within the mirror.
1040   oop m = k->java_mirror();
1041   Array<int>* entry_field_records = record->entry_field_records();
1042   if (entry_field_records != nullptr) {
1043     int efr_len = entry_field_records->length();
1044     assert(efr_len % 2 == 0, "sanity");
1045     for (int i = 0; i < efr_len; i += 2) {
1046       int field_offset = entry_field_records->at(i);
1047       int root_index = entry_field_records->at(i+1);
1048       oop v = get_root(root_index, /*clear=*/true);
1049       m->obj_field_put(field_offset, v);
1050       log_debug(cds, heap)("  " PTR_FORMAT " init field @ %2d = " PTR_FORMAT, p2i(k), field_offset, p2i(v));
1051     }
1052 
1053     // Done. Java code can see the archived sub-graphs referenced from k's
1054     // mirror after this point.
1055     if (log_is_enabled(Info, cds, heap)) {
1056       ResourceMark rm;
1057       log_info(cds, heap)("initialize_from_archived_subgraph %s " PTR_FORMAT "%s",
1058                           k->external_name(), p2i(k), JvmtiExport::is_early_phase() ? " (early)" : "");
1059     }
1060   }
1061 
1062   verify_the_heap(k, "after ");
1063 }
1064 
1065 void HeapShared::clear_archived_roots_of(Klass* k) {
1066   unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary_quick(k);
1067   const ArchivedKlassSubGraphInfoRecord* record = _run_time_subgraph_info_table.lookup(k, hash, 0);
1068   if (record != nullptr) {
1069     Array<int>* entry_field_records = record->entry_field_records();
1070     if (entry_field_records != nullptr) {
1071       int efr_len = entry_field_records->length();
1072       assert(efr_len % 2 == 0, "sanity");
1073       for (int i = 0; i < efr_len; i += 2) {
1074         int root_index = entry_field_records->at(i+1);
1075         clear_root(root_index);
1076       }
1077     }
1078   }
1079 }
1080 
1081 class WalkOopAndArchiveClosure: public BasicOopIterateClosure {
1082   int _level;
1083   bool _record_klasses_only;
1084   KlassSubGraphInfo* _subgraph_info;
1085   oop _referencing_obj;
1086 
1087   // The following are for maintaining a stack for determining
1088   // CachedOopInfo::_referrer
1089   static WalkOopAndArchiveClosure* _current;
1090   WalkOopAndArchiveClosure* _last;
1091  public:
1092   WalkOopAndArchiveClosure(int level,
1093                            bool record_klasses_only,
1094                            KlassSubGraphInfo* subgraph_info,
1095                            oop orig) :
1096     _level(level),
1097     _record_klasses_only(record_klasses_only),
1098     _subgraph_info(subgraph_info),
1099     _referencing_obj(orig) {
1100     _last = _current;
1101     _current = this;
1102   }
1103   ~WalkOopAndArchiveClosure() {
1104     _current = _last;
1105   }
1106   void do_oop(narrowOop *p) { WalkOopAndArchiveClosure::do_oop_work(p); }
1107   void do_oop(      oop *p) { WalkOopAndArchiveClosure::do_oop_work(p); }
1108 
1109  protected:
1110   template <class T> void do_oop_work(T *p) {
1111     oop obj = RawAccess<>::oop_load(p);
1112     if (!CompressedOops::is_null(obj)) {
1113       size_t field_delta = pointer_delta(p, _referencing_obj, sizeof(char));
1114 
1115       if (!_record_klasses_only && log_is_enabled(Debug, cds, heap)) {
1116         ResourceMark rm;
1117         log_debug(cds, heap)("(%d) %s[" SIZE_FORMAT "] ==> " PTR_FORMAT " size " SIZE_FORMAT " %s", _level,
1118                              _referencing_obj->klass()->external_name(), field_delta,
1119                              p2i(obj), obj->size() * HeapWordSize, obj->klass()->external_name());
1120         if (log_is_enabled(Trace, cds, heap)) {
1121           LogTarget(Trace, cds, heap) log;
1122           LogStream out(log);
1123           obj->print_on(&out);
1124         }
1125       }
1126 
1127       bool success = HeapShared::archive_reachable_objects_from(
1128           _level + 1, _subgraph_info, obj);
1129       assert(success, "VM should have exited with unarchivable objects for _level > 1");
1130     }
1131   }
1132 
1133  public:
1134   static WalkOopAndArchiveClosure* current()  { return _current;              }
1135   oop referencing_obj()                       { return _referencing_obj;      }
1136   KlassSubGraphInfo* subgraph_info()          { return _subgraph_info;        }
1137 };
1138 
1139 WalkOopAndArchiveClosure* WalkOopAndArchiveClosure::_current = nullptr;
1140 
1141 HeapShared::CachedOopInfo HeapShared::make_cached_oop_info() {
1142   WalkOopAndArchiveClosure* walker = WalkOopAndArchiveClosure::current();
1143   oop referrer = (walker == nullptr) ? nullptr : walker->referencing_obj();
1144   return CachedOopInfo(referrer);
1145 }
1146 
1147 // (1) If orig_obj has not been archived yet, archive it.
1148 // (2) If orig_obj has not been seen yet (since start_recording_subgraph() was called),
1149 //     trace all  objects that are reachable from it, and make sure these objects are archived.
1150 // (3) Record the klasses of all orig_obj and all reachable objects.
1151 bool HeapShared::archive_reachable_objects_from(int level,
1152                                                 KlassSubGraphInfo* subgraph_info,
1153                                                 oop orig_obj) {
1154   assert(orig_obj != nullptr, "must be");
1155 
1156   if (!JavaClasses::is_supported_for_archiving(orig_obj)) {
1157     // This object has injected fields that cannot be supported easily, so we disallow them for now.
1158     // If you get an error here, you probably made a change in the JDK library that has added
1159     // these objects that are referenced (directly or indirectly) by static fields.
1160     ResourceMark rm;
1161     log_error(cds, heap)("Cannot archive object of class %s", orig_obj->klass()->external_name());
1162     MetaspaceShared::unrecoverable_writing_error();
1163   }
1164 
1165   // java.lang.Class instances cannot be included in an archived object sub-graph. We only support
1166   // them as Klass::_archived_mirror because they need to be specially restored at run time.
1167   //
1168   // If you get an error here, you probably made a change in the JDK library that has added a Class
1169   // object that is referenced (directly or indirectly) by static fields.
1170   if (java_lang_Class::is_instance(orig_obj) && subgraph_info != _default_subgraph_info) {
1171     log_error(cds, heap)("(%d) Unknown java.lang.Class object is in the archived sub-graph", level);
1172     MetaspaceShared::unrecoverable_writing_error();
1173   }
1174 
1175   if (has_been_seen_during_subgraph_recording(orig_obj)) {
1176     // orig_obj has already been archived and traced. Nothing more to do.
1177     return true;
1178   } else {
1179     set_has_been_seen_during_subgraph_recording(orig_obj);
1180   }
1181 
1182   bool already_archived = has_been_archived(orig_obj);
1183   bool record_klasses_only = already_archived;
1184   if (!already_archived) {
1185     ++_num_new_archived_objs;
1186     if (!archive_object(orig_obj)) {
1187       // Skip archiving the sub-graph referenced from the current entry field.
1188       ResourceMark rm;
1189       log_error(cds, heap)(
1190         "Cannot archive the sub-graph referenced from %s object ("
1191         PTR_FORMAT ") size " SIZE_FORMAT ", skipped.",
1192         orig_obj->klass()->external_name(), p2i(orig_obj), orig_obj->size() * HeapWordSize);
1193       if (level == 1) {
1194         // Don't archive a subgraph root that's too big. For archives static fields, that's OK
1195         // as the Java code will take care of initializing this field dynamically.
1196         return false;
1197       } else {
1198         // We don't know how to handle an object that has been archived, but some of its reachable
1199         // objects cannot be archived. Bail out for now. We might need to fix this in the future if
1200         // we have a real use case.
1201         MetaspaceShared::unrecoverable_writing_error();
1202       }
1203     }
1204   }
1205 
1206   Klass *orig_k = orig_obj->klass();
1207   subgraph_info->add_subgraph_object_klass(orig_k);
1208 
1209   WalkOopAndArchiveClosure walker(level, record_klasses_only, subgraph_info, orig_obj);
1210   orig_obj->oop_iterate(&walker);
1211 
1212   check_enum_obj(level + 1, subgraph_info, orig_obj);
1213   return true;
1214 }
1215 
1216 //
1217 // Start from the given static field in a java mirror and archive the
1218 // complete sub-graph of java heap objects that are reached directly
1219 // or indirectly from the starting object by following references.
1220 // Sub-graph archiving restrictions (current):
1221 //
1222 // - All classes of objects in the archived sub-graph (including the
1223 //   entry class) must be boot class only.
1224 // - No java.lang.Class instance (java mirror) can be included inside
1225 //   an archived sub-graph. Mirror can only be the sub-graph entry object.
1226 //
1227 // The Java heap object sub-graph archiving process (see
1228 // WalkOopAndArchiveClosure):
1229 //
1230 // 1) Java object sub-graph archiving starts from a given static field
1231 // within a Class instance (java mirror). If the static field is a
1232 // reference field and points to a non-null java object, proceed to
1233 // the next step.
1234 //
1235 // 2) Archives the referenced java object. If an archived copy of the
1236 // current object already exists, updates the pointer in the archived
1237 // copy of the referencing object to point to the current archived object.
1238 // Otherwise, proceed to the next step.
1239 //
1240 // 3) Follows all references within the current java object and recursively
1241 // archive the sub-graph of objects starting from each reference.
1242 //
1243 // 4) Updates the pointer in the archived copy of referencing object to
1244 // point to the current archived object.
1245 //
1246 // 5) The Klass of the current java object is added to the list of Klasses
1247 // for loading and initializing before any object in the archived graph can
1248 // be accessed at runtime.
1249 //
1250 void HeapShared::archive_reachable_objects_from_static_field(InstanceKlass *k,
1251                                                              const char* klass_name,
1252                                                              int field_offset,
1253                                                              const char* field_name) {
1254   assert(CDSConfig::is_dumping_heap(), "dump time only");
1255   assert(k->is_shared_boot_class(), "must be boot class");
1256 
1257   oop m = k->java_mirror();
1258 
1259   KlassSubGraphInfo* subgraph_info = get_subgraph_info(k);
1260   oop f = m->obj_field(field_offset);
1261 
1262   log_debug(cds, heap)("Start archiving from: %s::%s (" PTR_FORMAT ")", klass_name, field_name, p2i(f));
1263 
1264   if (!CompressedOops::is_null(f)) {
1265     if (log_is_enabled(Trace, cds, heap)) {
1266       LogTarget(Trace, cds, heap) log;
1267       LogStream out(log);
1268       f->print_on(&out);
1269     }
1270 
1271     bool success = archive_reachable_objects_from(1, subgraph_info, f);
1272     if (!success) {
1273       log_error(cds, heap)("Archiving failed %s::%s (some reachable objects cannot be archived)",
1274                            klass_name, field_name);
1275     } else {
1276       // Note: the field value is not preserved in the archived mirror.
1277       // Record the field as a new subGraph entry point. The recorded
1278       // information is restored from the archive at runtime.
1279       subgraph_info->add_subgraph_entry_field(field_offset, f);
1280       log_info(cds, heap)("Archived field %s::%s => " PTR_FORMAT, klass_name, field_name, p2i(f));
1281     }
1282   } else {
1283     // The field contains null, we still need to record the entry point,
1284     // so it can be restored at runtime.
1285     subgraph_info->add_subgraph_entry_field(field_offset, nullptr);
1286   }
1287 }
1288 
1289 #ifndef PRODUCT
1290 class VerifySharedOopClosure: public BasicOopIterateClosure {
1291  public:
1292   void do_oop(narrowOop *p) { VerifySharedOopClosure::do_oop_work(p); }
1293   void do_oop(      oop *p) { VerifySharedOopClosure::do_oop_work(p); }
1294 
1295  protected:
1296   template <class T> void do_oop_work(T *p) {
1297     oop obj = RawAccess<>::oop_load(p);
1298     if (!CompressedOops::is_null(obj)) {
1299       HeapShared::verify_reachable_objects_from(obj);
1300     }
1301   }
1302 };
1303 
1304 void HeapShared::verify_subgraph_from_static_field(InstanceKlass* k, int field_offset) {
1305   assert(CDSConfig::is_dumping_heap(), "dump time only");
1306   assert(k->is_shared_boot_class(), "must be boot class");
1307 
1308   oop m = k->java_mirror();
1309   oop f = m->obj_field(field_offset);
1310   if (!CompressedOops::is_null(f)) {
1311     verify_subgraph_from(f);
1312   }
1313 }
1314 
1315 void HeapShared::verify_subgraph_from(oop orig_obj) {
1316   if (!has_been_archived(orig_obj)) {
1317     // It's OK for the root of a subgraph to be not archived. See comments in
1318     // archive_reachable_objects_from().
1319     return;
1320   }
1321 
1322   // Verify that all objects reachable from orig_obj are archived.
1323   init_seen_objects_table();
1324   verify_reachable_objects_from(orig_obj);
1325   delete_seen_objects_table();
1326 }
1327 
1328 void HeapShared::verify_reachable_objects_from(oop obj) {
1329   _num_total_verifications ++;
1330   if (!has_been_seen_during_subgraph_recording(obj)) {
1331     set_has_been_seen_during_subgraph_recording(obj);
1332     assert(has_been_archived(obj), "must be");
1333     VerifySharedOopClosure walker;
1334     obj->oop_iterate(&walker);
1335   }
1336 }
1337 #endif
1338 
1339 // The "default subgraph" contains special objects (see heapShared.hpp) that
1340 // can be accessed before we load any Java classes (including java/lang/Class).
1341 // Make sure that these are only instances of the very few specific types
1342 // that we can handle.
1343 void HeapShared::check_default_subgraph_classes() {
1344   GrowableArray<Klass*>* klasses = _default_subgraph_info->subgraph_object_klasses();
1345   int num = klasses->length();
1346   for (int i = 0; i < num; i++) {
1347     Klass* subgraph_k = klasses->at(i);
1348     if (log_is_enabled(Info, cds, heap)) {
1349       ResourceMark rm;
1350       log_info(cds, heap)(
1351           "Archived object klass (default subgraph %d) => %s",
1352           i, subgraph_k->external_name());
1353     }
1354 
1355     guarantee(subgraph_k->name()->equals("java/lang/Class") ||
1356               subgraph_k->name()->equals("java/lang/String") ||
1357               subgraph_k->name()->equals("[Ljava/lang/Object;") ||
1358               subgraph_k->name()->equals("[C") ||
1359               subgraph_k->name()->equals("[B"),
1360               "default subgraph can have only these objects");
1361   }
1362 }
1363 
1364 HeapShared::SeenObjectsTable* HeapShared::_seen_objects_table = nullptr;
1365 int HeapShared::_num_new_walked_objs;
1366 int HeapShared::_num_new_archived_objs;
1367 int HeapShared::_num_old_recorded_klasses;
1368 
1369 int HeapShared::_num_total_subgraph_recordings = 0;
1370 int HeapShared::_num_total_walked_objs = 0;
1371 int HeapShared::_num_total_archived_objs = 0;
1372 int HeapShared::_num_total_recorded_klasses = 0;
1373 int HeapShared::_num_total_verifications = 0;
1374 
1375 bool HeapShared::has_been_seen_during_subgraph_recording(oop obj) {
1376   return _seen_objects_table->get(obj) != nullptr;
1377 }
1378 
1379 void HeapShared::set_has_been_seen_during_subgraph_recording(oop obj) {
1380   assert(!has_been_seen_during_subgraph_recording(obj), "sanity");
1381   _seen_objects_table->put(obj, true);
1382   ++ _num_new_walked_objs;
1383 }
1384 
1385 void HeapShared::start_recording_subgraph(InstanceKlass *k, const char* class_name, bool is_full_module_graph) {
1386   log_info(cds, heap)("Start recording subgraph(s) for archived fields in %s", class_name);
1387   init_subgraph_info(k, is_full_module_graph);
1388   init_seen_objects_table();
1389   _num_new_walked_objs = 0;
1390   _num_new_archived_objs = 0;
1391   _num_old_recorded_klasses = get_subgraph_info(k)->num_subgraph_object_klasses();
1392 }
1393 
1394 void HeapShared::done_recording_subgraph(InstanceKlass *k, const char* class_name) {
1395   int num_new_recorded_klasses = get_subgraph_info(k)->num_subgraph_object_klasses() -
1396     _num_old_recorded_klasses;
1397   log_info(cds, heap)("Done recording subgraph(s) for archived fields in %s: "
1398                       "walked %d objs, archived %d new objs, recorded %d classes",
1399                       class_name, _num_new_walked_objs, _num_new_archived_objs,
1400                       num_new_recorded_klasses);
1401 
1402   delete_seen_objects_table();
1403 
1404   _num_total_subgraph_recordings ++;
1405   _num_total_walked_objs      += _num_new_walked_objs;
1406   _num_total_archived_objs    += _num_new_archived_objs;
1407   _num_total_recorded_klasses +=  num_new_recorded_klasses;
1408 }
1409 
1410 class ArchivableStaticFieldFinder: public FieldClosure {
1411   InstanceKlass* _ik;
1412   Symbol* _field_name;
1413   bool _found;
1414   int _offset;
1415 public:
1416   ArchivableStaticFieldFinder(InstanceKlass* ik, Symbol* field_name) :
1417     _ik(ik), _field_name(field_name), _found(false), _offset(-1) {}
1418 
1419   virtual void do_field(fieldDescriptor* fd) {
1420     if (fd->name() == _field_name) {
1421       assert(!_found, "fields can never be overloaded");
1422       if (is_reference_type(fd->field_type())) {
1423         _found = true;
1424         _offset = fd->offset();
1425       }
1426     }
1427   }
1428   bool found()     { return _found;  }
1429   int offset()     { return _offset; }
1430 };
1431 
1432 void HeapShared::init_subgraph_entry_fields(ArchivableStaticFieldInfo fields[],
1433                                             TRAPS) {
1434   for (int i = 0; fields[i].valid(); i++) {
1435     ArchivableStaticFieldInfo* info = &fields[i];
1436     TempNewSymbol klass_name =  SymbolTable::new_symbol(info->klass_name);
1437     TempNewSymbol field_name =  SymbolTable::new_symbol(info->field_name);
1438     ResourceMark rm; // for stringStream::as_string() etc.
1439 
1440 #ifndef PRODUCT
1441     bool is_test_class = (ArchiveHeapTestClass != nullptr) && (strcmp(info->klass_name, ArchiveHeapTestClass) == 0);
1442 #else
1443     bool is_test_class = false;
1444 #endif
1445 
1446     if (is_test_class) {
1447       log_warning(cds)("Loading ArchiveHeapTestClass %s ...", ArchiveHeapTestClass);
1448     }
1449 
1450     Klass* k = SystemDictionary::resolve_or_fail(klass_name, true, THREAD);
1451     if (HAS_PENDING_EXCEPTION) {
1452       CLEAR_PENDING_EXCEPTION;
1453       stringStream st;
1454       st.print("Fail to initialize archive heap: %s cannot be loaded by the boot loader", info->klass_name);
1455       THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), st.as_string());
1456     }
1457 
1458     if (!k->is_instance_klass()) {
1459       stringStream st;
1460       st.print("Fail to initialize archive heap: %s is not an instance class", info->klass_name);
1461       THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), st.as_string());
1462     }
1463 
1464     InstanceKlass* ik = InstanceKlass::cast(k);
1465     assert(InstanceKlass::cast(ik)->is_shared_boot_class(),
1466            "Only support boot classes");
1467 
1468     if (is_test_class) {
1469       if (ik->module()->is_named()) {
1470         // We don't want ArchiveHeapTestClass to be abused to easily load/initialize arbitrary
1471         // core-lib classes. You need to at least append to the bootclasspath.
1472         stringStream st;
1473         st.print("ArchiveHeapTestClass %s is not in unnamed module", ArchiveHeapTestClass);
1474         THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), st.as_string());
1475       }
1476 
1477       if (ik->package() != nullptr) {
1478         // This restriction makes HeapShared::is_a_test_class_in_unnamed_module() easy.
1479         stringStream st;
1480         st.print("ArchiveHeapTestClass %s is not in unnamed package", ArchiveHeapTestClass);
1481         THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), st.as_string());
1482       }
1483     } else {
1484       if (ik->module()->name() != vmSymbols::java_base()) {
1485         // We don't want to deal with cases when a module is unavailable at runtime.
1486         // FUTURE -- load from archived heap only when module graph has not changed
1487         //           between dump and runtime.
1488         stringStream st;
1489         st.print("%s is not in java.base module", info->klass_name);
1490         THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), st.as_string());
1491       }
1492     }
1493 
1494     if (is_test_class) {
1495       log_warning(cds)("Initializing ArchiveHeapTestClass %s ...", ArchiveHeapTestClass);
1496     }
1497     ik->initialize(CHECK);
1498 
1499     ArchivableStaticFieldFinder finder(ik, field_name);
1500     ik->do_local_static_fields(&finder);
1501     if (!finder.found()) {
1502       stringStream st;
1503       st.print("Unable to find the static T_OBJECT field %s::%s", info->klass_name, info->field_name);
1504       THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), st.as_string());
1505     }
1506 
1507     info->klass = ik;
1508     info->offset = finder.offset();
1509   }
1510 }
1511 
1512 void HeapShared::init_subgraph_entry_fields(TRAPS) {
1513   assert(HeapShared::can_write(), "must be");
1514   _dump_time_subgraph_info_table = new (mtClass)DumpTimeKlassSubGraphInfoTable();
1515   init_subgraph_entry_fields(archive_subgraph_entry_fields, CHECK);
1516   if (CDSConfig::is_dumping_full_module_graph()) {
1517     init_subgraph_entry_fields(fmg_archive_subgraph_entry_fields, CHECK);
1518   }
1519 }
1520 
1521 #ifndef PRODUCT
1522 void HeapShared::setup_test_class(const char* test_class_name) {
1523   ArchivableStaticFieldInfo* p = archive_subgraph_entry_fields;
1524   int num_slots = sizeof(archive_subgraph_entry_fields) / sizeof(ArchivableStaticFieldInfo);
1525   assert(p[num_slots - 2].klass_name == nullptr, "must have empty slot that's patched below");
1526   assert(p[num_slots - 1].klass_name == nullptr, "must have empty slot that marks the end of the list");
1527 
1528   if (test_class_name != nullptr) {
1529     p[num_slots - 2].klass_name = test_class_name;
1530     p[num_slots - 2].field_name = ARCHIVE_TEST_FIELD_NAME;
1531   }
1532 }
1533 
1534 // See if ik is one of the test classes that are pulled in by -XX:ArchiveHeapTestClass
1535 // during runtime. This may be called before the module system is initialized so
1536 // we cannot rely on InstanceKlass::module(), etc.
1537 bool HeapShared::is_a_test_class_in_unnamed_module(Klass* ik) {
1538   if (_test_class != nullptr) {
1539     if (ik == _test_class) {
1540       return true;
1541     }
1542     Array<Klass*>* klasses = _test_class_record->subgraph_object_klasses();
1543     if (klasses == nullptr) {
1544       return false;
1545     }
1546 
1547     for (int i = 0; i < klasses->length(); i++) {
1548       Klass* k = klasses->at(i);
1549       if (k == ik) {
1550         Symbol* name;
1551         if (k->is_instance_klass()) {
1552           name = InstanceKlass::cast(k)->name();
1553         } else if (k->is_objArray_klass()) {
1554           Klass* bk = ObjArrayKlass::cast(k)->bottom_klass();
1555           if (!bk->is_instance_klass()) {
1556             return false;
1557           }
1558           name = bk->name();
1559         } else {
1560           return false;
1561         }
1562 
1563         // See KlassSubGraphInfo::check_allowed_klass() - only two types of
1564         // classes are allowed:
1565         //   (A) java.base classes (which must not be in the unnamed module)
1566         //   (B) test classes which must be in the unnamed package of the unnamed module.
1567         // So if we see a '/' character in the class name, it must be in (A);
1568         // otherwise it must be in (B).
1569         if (name->index_of_at(0, "/", 1)  >= 0) {
1570           return false; // (A)
1571         }
1572 
1573         return true; // (B)
1574       }
1575     }
1576   }
1577 
1578   return false;
1579 }
1580 #endif
1581 
1582 void HeapShared::init_for_dumping(TRAPS) {
1583   if (HeapShared::can_write()) {
1584     setup_test_class(ArchiveHeapTestClass);
1585     _dumped_interned_strings = new (mtClass)DumpedInternedStrings();
1586     init_subgraph_entry_fields(CHECK);
1587   }
1588 }
1589 
1590 void HeapShared::archive_object_subgraphs(ArchivableStaticFieldInfo fields[],
1591                                           bool is_full_module_graph) {
1592   _num_total_subgraph_recordings = 0;
1593   _num_total_walked_objs = 0;
1594   _num_total_archived_objs = 0;
1595   _num_total_recorded_klasses = 0;
1596   _num_total_verifications = 0;
1597 
1598   // For each class X that has one or more archived fields:
1599   // [1] Dump the subgraph of each archived field
1600   // [2] Create a list of all the class of the objects that can be reached
1601   //     by any of these static fields.
1602   //     At runtime, these classes are initialized before X's archived fields
1603   //     are restored by HeapShared::initialize_from_archived_subgraph().
1604   int i;
1605   for (int i = 0; fields[i].valid(); ) {
1606     ArchivableStaticFieldInfo* info = &fields[i];
1607     const char* klass_name = info->klass_name;
1608     start_recording_subgraph(info->klass, klass_name, is_full_module_graph);
1609 
1610     // If you have specified consecutive fields of the same klass in
1611     // fields[], these will be archived in the same
1612     // {start_recording_subgraph ... done_recording_subgraph} pass to
1613     // save time.
1614     for (; fields[i].valid(); i++) {
1615       ArchivableStaticFieldInfo* f = &fields[i];
1616       if (f->klass_name != klass_name) {
1617         break;
1618       }
1619 
1620       archive_reachable_objects_from_static_field(f->klass, f->klass_name,
1621                                                   f->offset, f->field_name);
1622     }
1623     done_recording_subgraph(info->klass, klass_name);
1624   }
1625 
1626   log_info(cds, heap)("Archived subgraph records = %d",
1627                       _num_total_subgraph_recordings);
1628   log_info(cds, heap)("  Walked %d objects", _num_total_walked_objs);
1629   log_info(cds, heap)("  Archived %d objects", _num_total_archived_objs);
1630   log_info(cds, heap)("  Recorded %d klasses", _num_total_recorded_klasses);
1631 
1632 #ifndef PRODUCT
1633   for (int i = 0; fields[i].valid(); i++) {
1634     ArchivableStaticFieldInfo* f = &fields[i];
1635     verify_subgraph_from_static_field(f->klass, f->offset);
1636   }
1637   log_info(cds, heap)("  Verified %d references", _num_total_verifications);
1638 #endif
1639 }
1640 
1641 // Not all the strings in the global StringTable are dumped into the archive, because
1642 // some of those strings may be only referenced by classes that are excluded from
1643 // the archive. We need to explicitly mark the strings that are:
1644 //   [1] used by classes that WILL be archived;
1645 //   [2] included in the SharedArchiveConfigFile.
1646 void HeapShared::add_to_dumped_interned_strings(oop string) {
1647   assert_at_safepoint(); // DumpedInternedStrings uses raw oops
1648   assert(!ArchiveHeapWriter::is_string_too_large_to_archive(string), "must be");
1649   bool created;
1650   _dumped_interned_strings->put_if_absent(string, true, &created);
1651 }
1652 
1653 #ifndef PRODUCT
1654 // At dump-time, find the location of all the non-null oop pointers in an archived heap
1655 // region. This way we can quickly relocate all the pointers without using
1656 // BasicOopIterateClosure at runtime.
1657 class FindEmbeddedNonNullPointers: public BasicOopIterateClosure {
1658   void* _start;
1659   BitMap *_oopmap;
1660   int _num_total_oops;
1661   int _num_null_oops;
1662  public:
1663   FindEmbeddedNonNullPointers(void* start, BitMap* oopmap)
1664     : _start(start), _oopmap(oopmap), _num_total_oops(0),  _num_null_oops(0) {}
1665 
1666   virtual void do_oop(narrowOop* p) {
1667     assert(UseCompressedOops, "sanity");
1668     _num_total_oops ++;
1669     narrowOop v = *p;
1670     if (!CompressedOops::is_null(v)) {
1671       size_t idx = p - (narrowOop*)_start;
1672       _oopmap->set_bit(idx);
1673     } else {
1674       _num_null_oops ++;
1675     }
1676   }
1677   virtual void do_oop(oop* p) {
1678     assert(!UseCompressedOops, "sanity");
1679     _num_total_oops ++;
1680     if ((*p) != nullptr) {
1681       size_t idx = p - (oop*)_start;
1682       _oopmap->set_bit(idx);
1683     } else {
1684       _num_null_oops ++;
1685     }
1686   }
1687   int num_total_oops() const { return _num_total_oops; }
1688   int num_null_oops()  const { return _num_null_oops; }
1689 };
1690 #endif
1691 
1692 #ifndef PRODUCT
1693 ResourceBitMap HeapShared::calculate_oopmap(MemRegion region) {
1694   size_t num_bits = region.byte_size() / (UseCompressedOops ? sizeof(narrowOop) : sizeof(oop));
1695   ResourceBitMap oopmap(num_bits);
1696 
1697   HeapWord* p   = region.start();
1698   HeapWord* end = region.end();
1699   FindEmbeddedNonNullPointers finder((void*)p, &oopmap);
1700 
1701   int num_objs = 0;
1702   while (p < end) {
1703     oop o = cast_to_oop(p);
1704     o->oop_iterate(&finder);
1705     p += o->size();
1706     ++ num_objs;
1707   }
1708 
1709   log_info(cds, heap)("calculate_oopmap: objects = %6d, oop fields = %7d (nulls = %7d)",
1710                       num_objs, finder.num_total_oops(), finder.num_null_oops());
1711   return oopmap;
1712 }
1713 
1714 #endif // !PRODUCT
1715 
1716 void HeapShared::count_allocation(size_t size) {
1717   _total_obj_count ++;
1718   _total_obj_size += size;
1719   for (int i = 0; i < ALLOC_STAT_SLOTS; i++) {
1720     if (size <= (size_t(1) << i)) {
1721       _alloc_count[i] ++;
1722       _alloc_size[i] += size;
1723       return;
1724     }
1725   }
1726 }
1727 
1728 static double avg_size(size_t size, size_t count) {
1729   double avg = 0;
1730   if (count > 0) {
1731     avg = double(size * HeapWordSize) / double(count);
1732   }
1733   return avg;
1734 }
1735 
1736 void HeapShared::print_stats() {
1737   size_t huge_count = _total_obj_count;
1738   size_t huge_size = _total_obj_size;
1739 
1740   for (int i = 0; i < ALLOC_STAT_SLOTS; i++) {
1741     size_t byte_size_limit = (size_t(1) << i) * HeapWordSize;
1742     size_t count = _alloc_count[i];
1743     size_t size = _alloc_size[i];
1744     log_info(cds, heap)(SIZE_FORMAT_W(8) " objects are <= " SIZE_FORMAT_W(-6)
1745                         " bytes (total " SIZE_FORMAT_W(8) " bytes, avg %8.1f bytes)",
1746                         count, byte_size_limit, size * HeapWordSize, avg_size(size, count));
1747     huge_count -= count;
1748     huge_size -= size;
1749   }
1750 
1751   log_info(cds, heap)(SIZE_FORMAT_W(8) " huge  objects               (total "  SIZE_FORMAT_W(8) " bytes"
1752                       ", avg %8.1f bytes)",
1753                       huge_count, huge_size * HeapWordSize,
1754                       avg_size(huge_size, huge_count));
1755   log_info(cds, heap)(SIZE_FORMAT_W(8) " total objects               (total "  SIZE_FORMAT_W(8) " bytes"
1756                       ", avg %8.1f bytes)",
1757                       _total_obj_count, _total_obj_size * HeapWordSize,
1758                       avg_size(_total_obj_size, _total_obj_count));
1759 }
1760 
1761 bool HeapShared::is_archived_boot_layer_available(JavaThread* current) {
1762   TempNewSymbol klass_name = SymbolTable::new_symbol(ARCHIVED_BOOT_LAYER_CLASS);
1763   InstanceKlass* k = SystemDictionary::find_instance_klass(current, klass_name, Handle(), Handle());
1764   if (k == nullptr) {
1765     return false;
1766   } else {
1767     TempNewSymbol field_name = SymbolTable::new_symbol(ARCHIVED_BOOT_LAYER_FIELD);
1768     TempNewSymbol field_signature = SymbolTable::new_symbol("Ljdk/internal/module/ArchivedBootLayer;");
1769     fieldDescriptor fd;
1770     if (k->find_field(field_name, field_signature, true, &fd) != nullptr) {
1771       oop m = k->java_mirror();
1772       oop f = m->obj_field(fd.offset());
1773       if (CompressedOops::is_null(f)) {
1774         return false;
1775       }
1776     } else {
1777       return false;
1778     }
1779   }
1780   return true;
1781 }
1782 
1783 #endif // INCLUDE_CDS_JAVA_HEAP