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