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     obj->identity_hash();
 287     CachedOopInfo info = make_cached_oop_info(obj);
 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 int HeapShared::archive_exception_instance(oop exception) {
 434   bool success = archive_reachable_objects_from(1, _default_subgraph_info, exception);
 435   assert(success, "sanity");
 436   return append_root(exception);
 437 }
 438 
 439 void HeapShared::mark_native_pointers(oop orig_obj) {
 440   if (java_lang_Class::is_instance(orig_obj)) {
 441     ArchiveHeapWriter::mark_native_pointer(orig_obj, java_lang_Class::klass_offset());
 442     ArchiveHeapWriter::mark_native_pointer(orig_obj, java_lang_Class::array_klass_offset());


 443   }
 444 }
 445 
 446 bool HeapShared::has_oop_pointers(oop src_obj) {
 447   CachedOopInfo* info = archived_object_cache()->get(src_obj);
 448   assert(info != nullptr, "must be");
 449   return info->has_oop_pointers();
 450 }
 451 
 452 bool HeapShared::has_native_pointers(oop src_obj) {
 453   CachedOopInfo* info = archived_object_cache()->get(src_obj);
 454   assert(info != nullptr, "must be");
 455   return info->has_native_pointers();
 456 }
 457 
 458 void HeapShared::set_has_native_pointers(oop src_obj) {
 459   CachedOopInfo* info = archived_object_cache()->get(src_obj);
 460   assert(info != nullptr, "must be");
 461   info->set_has_native_pointers();
 462 }
 463 
 464 // -- Handling of Enum objects
 465 // Java Enum classes have synthetic <clinit> methods that look like this
 466 //     enum MyEnum {FOO, BAR}
 467 //     MyEnum::<clinint> {
 468 //        /*static final MyEnum*/ MyEnum::FOO = new MyEnum("FOO");
 469 //        /*static final MyEnum*/ MyEnum::BAR = new MyEnum("BAR");
 470 //     }
 471 //
 472 // If MyEnum::FOO object is referenced by any of the archived subgraphs, we must
 473 // ensure the archived value equals (in object address) to the runtime value of
 474 // MyEnum::FOO.
 475 //
 476 // However, since MyEnum::<clinint> is synthetically generated by javac, there's
 477 // no way of programmatically handling this inside the Java code (as you would handle
 478 // ModuleLayer::EMPTY_LAYER, for example).
 479 //
 480 // Instead, we archive all static field of such Enum classes. At runtime,
 481 // HeapShared::initialize_enum_klass() will skip the <clinit> method and pull
 482 // the static fields out of the archived heap.
 483 void HeapShared::check_enum_obj(int level,
 484                                 KlassSubGraphInfo* subgraph_info,
 485                                 oop orig_obj) {
 486   assert(level > 1, "must never be called at the first (outermost) level");
 487   Klass* k = orig_obj->klass();
 488   Klass* buffered_k = ArchiveBuilder::get_buffered_klass(k);
 489   if (!k->is_instance_klass()) {
 490     return;
 491   }
 492   InstanceKlass* ik = InstanceKlass::cast(k);
 493   if (ik->java_super() == vmClasses::Enum_klass() && !ik->has_archived_enum_objs()) {
 494     ResourceMark rm;
 495     ik->set_has_archived_enum_objs();
 496     buffered_k->set_has_archived_enum_objs();
 497     oop mirror = ik->java_mirror();
 498 
 499     for (JavaFieldStream fs(ik); !fs.done(); fs.next()) {
 500       if (fs.access_flags().is_static()) {
 501         fieldDescriptor& fd = fs.field_descriptor();
 502         if (fd.field_type() != T_OBJECT && fd.field_type() != T_ARRAY) {
 503           guarantee(false, "static field %s::%s must be T_OBJECT or T_ARRAY",
 504                     ik->external_name(), fd.name()->as_C_string());
 505         }
 506         oop oop_field = mirror->obj_field(fd.offset());
 507         if (oop_field == nullptr) {
 508           guarantee(false, "static field %s::%s must not be null",
 509                     ik->external_name(), fd.name()->as_C_string());
 510         } else if (oop_field->klass() != ik && oop_field->klass() != ik->array_klass_or_null()) {
 511           guarantee(false, "static field %s::%s is of the wrong type",
 512                     ik->external_name(), fd.name()->as_C_string());
 513         }
 514         bool success = archive_reachable_objects_from(level, subgraph_info, oop_field);
 515         assert(success, "VM should have exited with unarchivable objects for _level > 1");
 516         int root_index = append_root(oop_field);
 517         log_info(cds, heap)("Archived enum obj @%d %s::%s (" INTPTR_FORMAT ")",
 518                             root_index, ik->external_name(), fd.name()->as_C_string(),
 519                             p2i((oopDesc*)oop_field));
 520         SystemDictionaryShared::add_enum_klass_static_field(ik, root_index);
 521       }
 522     }
 523   }
 524 }
 525 
 526 // See comments in HeapShared::check_enum_obj()
 527 bool HeapShared::initialize_enum_klass(InstanceKlass* k, TRAPS) {
 528   if (!ArchiveHeapLoader::is_in_use()) {
 529     return false;
 530   }
 531 
 532   RunTimeClassInfo* info = RunTimeClassInfo::get_for(k);
 533   assert(info != nullptr, "sanity");
 534 
 535   if (log_is_enabled(Info, cds, heap)) {
 536     ResourceMark rm;
 537     log_info(cds, heap)("Initializing Enum class: %s", k->external_name());
 538   }
 539 
 540   oop mirror = k->java_mirror();
 541   int i = 0;
 542   for (JavaFieldStream fs(k); !fs.done(); fs.next()) {
 543     if (fs.access_flags().is_static()) {
 544       int root_index = info->enum_klass_static_field_root_index_at(i++);
 545       fieldDescriptor& fd = fs.field_descriptor();
 546       assert(fd.field_type() == T_OBJECT || fd.field_type() == T_ARRAY, "must be");
 547       mirror->obj_field_put(fd.offset(), get_root(root_index, /*clear=*/true));
 548     }
 549   }
 550   return true;
 551 }
 552 
 553 void HeapShared::archive_objects(ArchiveHeapInfo *heap_info) {
 554   {
 555     NoSafepointVerifier nsv;
 556 
 557     _default_subgraph_info = init_subgraph_info(vmClasses::Object_klass(), false);


 558 
 559     // Cache for recording where the archived objects are copied to
 560     create_archived_object_cache();
 561 
 562     log_info(cds)("Heap range = [" PTR_FORMAT " - "  PTR_FORMAT "]",
 563                    UseCompressedOops ? p2i(CompressedOops::begin()) :
 564                                        p2i((address)G1CollectedHeap::heap()->reserved().start()),
 565                    UseCompressedOops ? p2i(CompressedOops::end()) :
 566                                        p2i((address)G1CollectedHeap::heap()->reserved().end()));
 567     copy_objects();
 568 
 569     CDSHeapVerifier::verify();
 570     check_default_subgraph_classes();
 571   }
 572 
 573   ArchiveHeapWriter::write(_pending_roots, heap_info);
 574 }
 575 
 576 void HeapShared::copy_interned_strings() {
 577   init_seen_objects_table();
 578 
 579   auto copier = [&] (oop s, bool value_ignored) {
 580     assert(s != nullptr, "sanity");
 581     assert(!ArchiveHeapWriter::is_string_too_large_to_archive(s), "large strings must have been filtered");
 582     bool success = archive_reachable_objects_from(1, _default_subgraph_info, s);
 583     assert(success, "must be");
 584     // Prevent string deduplication from changing the value field to
 585     // something not in the archive.
 586     java_lang_String::set_deduplication_forbidden(s);
 587   };
 588   _dumped_interned_strings->iterate_all(copier);
 589 
 590   delete_seen_objects_table();
 591 }
 592 
 593 void HeapShared::copy_special_objects() {
 594   // Archive special objects that do not belong to any subgraphs
 595   init_seen_objects_table();
 596   archive_java_mirrors();
 597   archive_strings();
 598   Universe::archive_exception_instances();
 599   delete_seen_objects_table();
 600 }
 601 
 602 void HeapShared::copy_objects() {
 603   assert(HeapShared::can_write(), "must be");
 604 
 605   copy_interned_strings();
 606   copy_special_objects();
 607 
 608   archive_object_subgraphs(archive_subgraph_entry_fields,
 609                            false /* is_full_module_graph */);
 610 
 611   if (CDSConfig::is_dumping_full_module_graph()) {
 612     archive_object_subgraphs(fmg_archive_subgraph_entry_fields,
 613                              true /* is_full_module_graph */);
 614     Modules::verify_archived_modules();
 615   }
 616 }
 617 
 618 //
 619 // Subgraph archiving support
 620 //
 621 HeapShared::DumpTimeKlassSubGraphInfoTable* HeapShared::_dump_time_subgraph_info_table = nullptr;
 622 HeapShared::RunTimeKlassSubGraphInfoTable   HeapShared::_run_time_subgraph_info_table;
 623 
 624 // Get the subgraph_info for Klass k. A new subgraph_info is created if
 625 // there is no existing one for k. The subgraph_info records the "buffered"
 626 // address of the class.
 627 KlassSubGraphInfo* HeapShared::init_subgraph_info(Klass* k, bool is_full_module_graph) {
 628   assert(CDSConfig::is_dumping_heap(), "dump time only");
 629   bool created;
 630   Klass* buffered_k = ArchiveBuilder::get_buffered_klass(k);
 631   KlassSubGraphInfo* info =
 632     _dump_time_subgraph_info_table->put_if_absent(k, KlassSubGraphInfo(buffered_k, is_full_module_graph),
 633                                                   &created);
 634   assert(created, "must not initialize twice");
 635   return info;
 636 }
 637 
 638 KlassSubGraphInfo* HeapShared::get_subgraph_info(Klass* k) {
 639   assert(CDSConfig::is_dumping_heap(), "dump time only");
 640   KlassSubGraphInfo* info = _dump_time_subgraph_info_table->get(k);
 641   assert(info != nullptr, "must have been initialized");
 642   return info;
 643 }
 644 
 645 // Add an entry field to the current KlassSubGraphInfo.
 646 void KlassSubGraphInfo::add_subgraph_entry_field(int static_field_offset, oop v) {
 647   assert(CDSConfig::is_dumping_heap(), "dump time only");
 648   if (_subgraph_entry_fields == nullptr) {
 649     _subgraph_entry_fields =
 650       new (mtClass) GrowableArray<int>(10, mtClass);
 651   }
 652   _subgraph_entry_fields->append(static_field_offset);
 653   _subgraph_entry_fields->append(HeapShared::append_root(v));
 654 }
 655 
 656 // Add the Klass* for an object in the current KlassSubGraphInfo's subgraphs.
 657 // Only objects of boot classes can be included in sub-graph.
 658 void KlassSubGraphInfo::add_subgraph_object_klass(Klass* orig_k) {
 659   assert(CDSConfig::is_dumping_heap(), "dump time only");
 660   Klass* buffered_k = ArchiveBuilder::get_buffered_klass(orig_k);
 661 
 662   if (_subgraph_object_klasses == nullptr) {
 663     _subgraph_object_klasses =
 664       new (mtClass) GrowableArray<Klass*>(50, mtClass);
 665   }
 666 
 667   assert(ArchiveBuilder::current()->is_in_buffer_space(buffered_k), "must be a shared class");
 668 
 669   if (_k == buffered_k) {
 670     // Don't add the Klass containing the sub-graph to it's own klass
 671     // initialization list.
 672     return;
 673   }
 674 
 675   if (buffered_k->is_instance_klass()) {
 676     assert(InstanceKlass::cast(buffered_k)->is_shared_boot_class(),
 677           "must be boot class");



 678     // vmClasses::xxx_klass() are not updated, need to check
 679     // the original Klass*
 680     if (orig_k == vmClasses::String_klass() ||
 681         orig_k == vmClasses::Object_klass()) {
 682       // Initialized early during VM initialization. No need to be added
 683       // to the sub-graph object class list.
 684       return;
 685     }
 686     check_allowed_klass(InstanceKlass::cast(orig_k));
 687   } else if (buffered_k->is_objArray_klass()) {
 688     Klass* abk = ObjArrayKlass::cast(buffered_k)->bottom_klass();
 689     if (abk->is_instance_klass()) {
 690       assert(InstanceKlass::cast(abk)->is_shared_boot_class(),
 691             "must be boot class");
 692       check_allowed_klass(InstanceKlass::cast(ObjArrayKlass::cast(orig_k)->bottom_klass()));
 693     }
 694     if (buffered_k == Universe::objectArrayKlassObj()) {
 695       // Initialized early during Universe::genesis. No need to be added
 696       // to the list.
 697       return;
 698     }
 699   } else {
 700     assert(buffered_k->is_typeArray_klass(), "must be");
 701     // Primitive type arrays are created early during Universe::genesis.
 702     return;
 703   }
 704 
 705   if (log_is_enabled(Debug, cds, heap)) {
 706     if (!_subgraph_object_klasses->contains(buffered_k)) {
 707       ResourceMark rm;
 708       log_debug(cds, heap)("Adding klass %s", orig_k->external_name());
 709     }
 710   }
 711 
 712   _subgraph_object_klasses->append_if_missing(buffered_k);
 713   _has_non_early_klasses |= is_non_early_klass(orig_k);
 714 }
 715 
 716 void KlassSubGraphInfo::check_allowed_klass(InstanceKlass* ik) {




 717   if (ik->module()->name() == vmSymbols::java_base()) {
 718     assert(ik->package() != nullptr, "classes in java.base cannot be in unnamed package");
 719     return;
 720   }
 721 
 722 #ifndef PRODUCT
 723   if (!ik->module()->is_named() && ik->package() == nullptr) {
 724     // This class is loaded by ArchiveHeapTestClass
 725     return;
 726   }
 727   const char* extra_msg = ", or in an unnamed package of an unnamed module";
 728 #else
 729   const char* extra_msg = "";
 730 #endif
 731 
 732   ResourceMark rm;
 733   log_error(cds, heap)("Class %s not allowed in archive heap. Must be in java.base%s",
 734                        ik->external_name(), extra_msg);
 735   MetaspaceShared::unrecoverable_writing_error();
 736 }
 737 
 738 bool KlassSubGraphInfo::is_non_early_klass(Klass* k) {
 739   if (k->is_objArray_klass()) {
 740     k = ObjArrayKlass::cast(k)->bottom_klass();
 741   }
 742   if (k->is_instance_klass()) {
 743     if (!SystemDictionaryShared::is_early_klass(InstanceKlass::cast(k))) {
 744       ResourceMark rm;
 745       log_info(cds, heap)("non-early: %s", k->external_name());
 746       return true;
 747     } else {
 748       return false;
 749     }
 750   } else {
 751     return false;
 752   }
 753 }
 754 
 755 // Initialize an archived subgraph_info_record from the given KlassSubGraphInfo.
 756 void ArchivedKlassSubGraphInfoRecord::init(KlassSubGraphInfo* info) {
 757   _k = info->klass();
 758   _entry_field_records = nullptr;
 759   _subgraph_object_klasses = nullptr;
 760   _is_full_module_graph = info->is_full_module_graph();
 761 
 762   if (_is_full_module_graph) {
 763     // Consider all classes referenced by the full module graph as early -- we will be
 764     // allocating objects of these classes during JVMTI early phase, so they cannot
 765     // be processed by (non-early) JVMTI ClassFileLoadHook
 766     _has_non_early_klasses = false;
 767   } else {
 768     _has_non_early_klasses = info->has_non_early_klasses();
 769   }
 770 
 771   if (_has_non_early_klasses) {
 772     ResourceMark rm;
 773     log_info(cds, heap)(
 774           "Subgraph of klass %s has non-early klasses and cannot be used when JVMTI ClassFileLoadHook is enabled",
 775           _k->external_name());
 776   }
 777 
 778   // populate the entry fields
 779   GrowableArray<int>* entry_fields = info->subgraph_entry_fields();
 780   if (entry_fields != nullptr) {
 781     int num_entry_fields = entry_fields->length();
 782     assert(num_entry_fields % 2 == 0, "sanity");
 783     _entry_field_records =
 784       ArchiveBuilder::new_ro_array<int>(num_entry_fields);
 785     for (int i = 0 ; i < num_entry_fields; i++) {
 786       _entry_field_records->at_put(i, entry_fields->at(i));
 787     }
 788   }
 789 
 790   // the Klasses of the objects in the sub-graphs
 791   GrowableArray<Klass*>* subgraph_object_klasses = info->subgraph_object_klasses();
 792   if (subgraph_object_klasses != nullptr) {
 793     int num_subgraphs_klasses = subgraph_object_klasses->length();
 794     _subgraph_object_klasses =
 795       ArchiveBuilder::new_ro_array<Klass*>(num_subgraphs_klasses);
 796     for (int i = 0; i < num_subgraphs_klasses; i++) {
 797       Klass* subgraph_k = subgraph_object_klasses->at(i);
 798       if (log_is_enabled(Info, cds, heap)) {
 799         ResourceMark rm;
 800         log_info(cds, heap)(
 801           "Archived object klass %s (%2d) => %s",
 802           _k->external_name(), i, subgraph_k->external_name());
 803       }
 804       _subgraph_object_klasses->at_put(i, subgraph_k);
 805       ArchivePtrMarker::mark_pointer(_subgraph_object_klasses->adr_at(i));
 806     }
 807   }
 808 
 809   ArchivePtrMarker::mark_pointer(&_k);
 810   ArchivePtrMarker::mark_pointer(&_entry_field_records);
 811   ArchivePtrMarker::mark_pointer(&_subgraph_object_klasses);
 812 }
 813 
 814 struct CopyKlassSubGraphInfoToArchive : StackObj {

 815   CompactHashtableWriter* _writer;
 816   CopyKlassSubGraphInfoToArchive(CompactHashtableWriter* writer) : _writer(writer) {}
 817 
 818   bool do_entry(Klass* klass, KlassSubGraphInfo& info) {
 819     if (info.subgraph_object_klasses() != nullptr || info.subgraph_entry_fields() != nullptr) {
 820       ArchivedKlassSubGraphInfoRecord* record =
 821         (ArchivedKlassSubGraphInfoRecord*)ArchiveBuilder::ro_region_alloc(sizeof(ArchivedKlassSubGraphInfoRecord));
 822       record->init(&info);
 823 
 824       Klass* buffered_k = ArchiveBuilder::get_buffered_klass(klass);
 825       unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary((address)buffered_k);
 826       u4 delta = ArchiveBuilder::current()->any_to_offset_u4(record);
 827       _writer->add(hash, delta);
 828     }
 829     return true; // keep on iterating
 830   }
 831 };
 832 







 833 // Build the records of archived subgraph infos, which include:
 834 // - Entry points to all subgraphs from the containing class mirror. The entry
 835 //   points are static fields in the mirror. For each entry point, the field
 836 //   offset, and value are recorded in the sub-graph
 837 //   info. The value is stored back to the corresponding field at runtime.
 838 // - A list of klasses that need to be loaded/initialized before archived
 839 //   java object sub-graph can be accessed at runtime.
 840 void HeapShared::write_subgraph_info_table() {
 841   // Allocate the contents of the hashtable(s) inside the RO region of the CDS archive.
 842   DumpTimeKlassSubGraphInfoTable* d_table = _dump_time_subgraph_info_table;
 843   CompactHashtableStats stats;
 844 
 845   _run_time_subgraph_info_table.reset();
 846 
 847   CompactHashtableWriter writer(d_table->_count, &stats);
 848   CopyKlassSubGraphInfoToArchive copy(&writer);
 849   d_table->iterate(&copy);
 850   writer.dump(&_run_time_subgraph_info_table, "subgraphs");
 851 


 852 #ifndef PRODUCT
 853   if (ArchiveHeapTestClass != nullptr) {
 854     size_t len = strlen(ArchiveHeapTestClass) + 1;
 855     Array<char>* array = ArchiveBuilder::new_ro_array<char>((int)len);
 856     strncpy(array->adr_at(0), ArchiveHeapTestClass, len);
 857     _archived_ArchiveHeapTestClass = array;
 858   }
 859 #endif
 860   if (log_is_enabled(Info, cds, heap)) {
 861     print_stats();
 862   }
 863 }
 864 




 865 void HeapShared::init_roots(oop roots_oop) {
 866   if (roots_oop != nullptr) {
 867     assert(ArchiveHeapLoader::is_in_use(), "must be");
 868     _roots = OopHandle(Universe::vm_global(), roots_oop);
 869   }
 870 }
 871 
 872 void HeapShared::serialize_tables(SerializeClosure* soc) {
 873 
 874 #ifndef PRODUCT
 875   soc->do_ptr(&_archived_ArchiveHeapTestClass);
 876   if (soc->reading() && _archived_ArchiveHeapTestClass != nullptr) {
 877     _test_class_name = _archived_ArchiveHeapTestClass->adr_at(0);
 878     setup_test_class(_test_class_name);
 879   }
 880 #endif
 881 
 882   _run_time_subgraph_info_table.serialize_header(soc);


 883 }
 884 
 885 static void verify_the_heap(Klass* k, const char* which) {
 886   if (VerifyArchivedFields > 0) {
 887     ResourceMark rm;
 888     log_info(cds, heap)("Verify heap %s initializing static field(s) in %s",
 889                         which, k->external_name());
 890 
 891     VM_Verify verify_op;
 892     VMThread::execute(&verify_op);
 893 
 894     if (VerifyArchivedFields > 1 && is_init_completed()) {
 895       // At this time, the oop->klass() of some archived objects in the heap may not
 896       // have been loaded into the system dictionary yet. Nevertheless, oop->klass() should
 897       // have enough information (object size, oop maps, etc) so that a GC can be safely
 898       // performed.
 899       //
 900       // -XX:VerifyArchivedFields=2 force a GC to happen in such an early stage
 901       // to check for GC safety.
 902       log_info(cds, heap)("Trigger GC %s initializing static field(s) in %s",
 903                           which, k->external_name());
 904       FlagSetting fs1(VerifyBeforeGC, true);
 905       FlagSetting fs2(VerifyDuringGC, true);
 906       FlagSetting fs3(VerifyAfterGC,  true);
 907       Universe::heap()->collect(GCCause::_java_lang_system_gc);
 908     }
 909   }
 910 }
 911 
 912 // Before GC can execute, we must ensure that all oops reachable from HeapShared::roots()
 913 // have a valid klass. I.e., oopDesc::klass() must have already been resolved.
 914 //
 915 // Note: if a ArchivedKlassSubGraphInfoRecord contains non-early classes, and JVMTI
 916 // ClassFileLoadHook is enabled, it's possible for this class to be dynamically replaced. In
 917 // this case, we will not load the ArchivedKlassSubGraphInfoRecord and will clear its roots.
 918 void HeapShared::resolve_classes(JavaThread* current) {
 919   assert(UseSharedSpaces, "runtime only!");
 920   if (!ArchiveHeapLoader::is_in_use()) {
 921     return; // nothing to do
 922   }













 923   resolve_classes_for_subgraphs(current, archive_subgraph_entry_fields);
 924   resolve_classes_for_subgraphs(current, fmg_archive_subgraph_entry_fields);
 925 }
 926 
 927 void HeapShared::resolve_classes_for_subgraphs(JavaThread* current, ArchivableStaticFieldInfo fields[]) {
 928   for (int i = 0; fields[i].valid(); i++) {
 929     ArchivableStaticFieldInfo* info = &fields[i];
 930     TempNewSymbol klass_name = SymbolTable::new_symbol(info->klass_name);
 931     InstanceKlass* k = SystemDictionaryShared::find_builtin_class(klass_name);
 932     assert(k != nullptr && k->is_shared_boot_class(), "sanity");
 933     resolve_classes_for_subgraph_of(current, k);
 934   }
 935 }
 936 
 937 void HeapShared::resolve_classes_for_subgraph_of(JavaThread* current, Klass* k) {
 938   JavaThread* THREAD = current;
 939   ExceptionMark em(THREAD);
 940   const ArchivedKlassSubGraphInfoRecord* record =
 941    resolve_or_init_classes_for_subgraph_of(k, /*do_init=*/false, THREAD);
 942   if (HAS_PENDING_EXCEPTION) {
 943    CLEAR_PENDING_EXCEPTION;
 944   }
 945   if (record == nullptr) {
 946    clear_archived_roots_of(k);
 947   }
 948 }
 949 









































 950 void HeapShared::initialize_from_archived_subgraph(JavaThread* current, Klass* k) {
 951   JavaThread* THREAD = current;
 952   if (!ArchiveHeapLoader::is_in_use()) {
 953     return; // nothing to do
 954   }
 955 
 956   ExceptionMark em(THREAD);
 957   const ArchivedKlassSubGraphInfoRecord* record =
 958     resolve_or_init_classes_for_subgraph_of(k, /*do_init=*/true, THREAD);
 959 
 960   if (HAS_PENDING_EXCEPTION) {
 961     CLEAR_PENDING_EXCEPTION;
 962     // None of the field value will be set if there was an exception when initializing the classes.
 963     // The java code will not see any of the archived objects in the
 964     // subgraphs referenced from k in this case.
 965     return;
 966   }
 967 
 968   if (record != nullptr) {
 969     init_archived_fields_for(k, record);
 970   }
 971 }
 972 
 973 const ArchivedKlassSubGraphInfoRecord*
 974 HeapShared::resolve_or_init_classes_for_subgraph_of(Klass* k, bool do_init, TRAPS) {
 975   assert(!CDSConfig::is_dumping_heap(), "Should not be called when dumping heap");
 976 
 977   if (!k->is_shared()) {
 978     return nullptr;
 979   }
 980   unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary_quick(k);
 981   const ArchivedKlassSubGraphInfoRecord* record = _run_time_subgraph_info_table.lookup(k, hash, 0);
 982 
 983 #ifndef PRODUCT
 984   if (_test_class_name != nullptr && k->name()->equals(_test_class_name) && record != nullptr) {
 985     _test_class = k;
 986     _test_class_record = record;
 987   }
 988 #endif
 989 
 990   // Initialize from archived data. Currently this is done only
 991   // during VM initialization time. No lock is needed.
 992   if (record == nullptr) {
 993     if (log_is_enabled(Info, cds, heap)) {
 994       ResourceMark rm(THREAD);
 995       log_info(cds, heap)("subgraph %s is not recorded",
 996                           k->external_name());
 997     }
 998     return nullptr;
 999   } else {
1000     if (record->is_full_module_graph() && !CDSConfig::is_using_full_module_graph()) {
1001       if (log_is_enabled(Info, cds, heap)) {
1002         ResourceMark rm(THREAD);
1003         log_info(cds, heap)("subgraph %s cannot be used because full module graph is disabled",
1004                             k->external_name());
1005       }
1006       return nullptr;
1007     }
1008 
1009     if (record->has_non_early_klasses() && JvmtiExport::should_post_class_file_load_hook()) {
1010       if (log_is_enabled(Info, cds, heap)) {
1011         ResourceMark rm(THREAD);
1012         log_info(cds, heap)("subgraph %s cannot be used because JVMTI ClassFileLoadHook is enabled",
1013                             k->external_name());
1014       }
1015       return nullptr;
1016     }
1017 
1018     if (log_is_enabled(Info, cds, heap)) {
1019       ResourceMark rm;
1020       log_info(cds, heap)("%s subgraph %s ", do_init ? "init" : "resolve", k->external_name());
1021     }
1022 




















































1023     resolve_or_init(k, do_init, CHECK_NULL);
1024 
1025     // Load/link/initialize the klasses of the objects in the subgraph.
1026     // nullptr class loader is used.
1027     Array<Klass*>* klasses = record->subgraph_object_klasses();
1028     if (klasses != nullptr) {
1029       for (int i = 0; i < klasses->length(); i++) {
1030         Klass* klass = klasses->at(i);
1031         if (!klass->is_shared()) {
1032           return nullptr;
1033         }
1034         resolve_or_init(klass, do_init, CHECK_NULL);
1035       }
1036     }
1037   }
1038 
1039   return record;
1040 }
1041 













1042 void HeapShared::resolve_or_init(Klass* k, bool do_init, TRAPS) {
1043   if (!do_init) {
1044     if (k->class_loader_data() == nullptr) {
1045       Klass* resolved_k = SystemDictionary::resolve_or_null(k->name(), CHECK);
1046       assert(resolved_k == k, "classes used by archived heap must not be replaced by JVMTI ClassFileLoadHook");
1047     }
1048   } else {
1049     assert(k->class_loader_data() != nullptr, "must have been resolved by HeapShared::resolve_classes");
1050     if (k->is_instance_klass()) {
1051       InstanceKlass* ik = InstanceKlass::cast(k);
1052       ik->initialize(CHECK);
1053     } else if (k->is_objArray_klass()) {
1054       ObjArrayKlass* oak = ObjArrayKlass::cast(k);
1055       oak->initialize(CHECK);
1056     }
1057   }
1058 }
1059 
1060 void HeapShared::init_archived_fields_for(Klass* k, const ArchivedKlassSubGraphInfoRecord* record) {
1061   verify_the_heap(k, "before");
1062 
1063   // Load the subgraph entry fields from the record and store them back to
1064   // the corresponding fields within the mirror.
1065   oop m = k->java_mirror();
1066   Array<int>* entry_field_records = record->entry_field_records();
1067   if (entry_field_records != nullptr) {
1068     int efr_len = entry_field_records->length();
1069     assert(efr_len % 2 == 0, "sanity");
1070     for (int i = 0; i < efr_len; i += 2) {
1071       int field_offset = entry_field_records->at(i);
1072       int root_index = entry_field_records->at(i+1);
1073       oop v = get_root(root_index, /*clear=*/true);
1074       m->obj_field_put(field_offset, v);
1075       log_debug(cds, heap)("  " PTR_FORMAT " init field @ %2d = " PTR_FORMAT, p2i(k), field_offset, p2i(v));
1076     }
1077 
1078     // Done. Java code can see the archived sub-graphs referenced from k's
1079     // mirror after this point.
1080     if (log_is_enabled(Info, cds, heap)) {
1081       ResourceMark rm;
1082       log_info(cds, heap)("initialize_from_archived_subgraph %s " PTR_FORMAT "%s",
1083                           k->external_name(), p2i(k), JvmtiExport::is_early_phase() ? " (early)" : "");
1084     }
1085   }
1086 
1087   verify_the_heap(k, "after ");
1088 }
1089 
1090 void HeapShared::clear_archived_roots_of(Klass* k) {
1091   unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary_quick(k);
1092   const ArchivedKlassSubGraphInfoRecord* record = _run_time_subgraph_info_table.lookup(k, hash, 0);
1093   if (record != nullptr) {
1094     Array<int>* entry_field_records = record->entry_field_records();
1095     if (entry_field_records != nullptr) {
1096       int efr_len = entry_field_records->length();
1097       assert(efr_len % 2 == 0, "sanity");
1098       for (int i = 0; i < efr_len; i += 2) {
1099         int root_index = entry_field_records->at(i+1);
1100         clear_root(root_index);
1101       }
1102     }
1103   }
1104 }
1105 
1106 class WalkOopAndArchiveClosure: public BasicOopIterateClosure {
1107   int _level;
1108   bool _record_klasses_only;
1109   KlassSubGraphInfo* _subgraph_info;
1110   oop _referencing_obj;
1111 
1112   // The following are for maintaining a stack for determining
1113   // CachedOopInfo::_referrer
1114   static WalkOopAndArchiveClosure* _current;
1115   WalkOopAndArchiveClosure* _last;
1116  public:
1117   WalkOopAndArchiveClosure(int level,
1118                            bool record_klasses_only,
1119                            KlassSubGraphInfo* subgraph_info,
1120                            oop orig) :
1121     _level(level),
1122     _record_klasses_only(record_klasses_only),
1123     _subgraph_info(subgraph_info),
1124     _referencing_obj(orig) {
1125     _last = _current;
1126     _current = this;
1127   }
1128   ~WalkOopAndArchiveClosure() {
1129     _current = _last;
1130   }
1131   void do_oop(narrowOop *p) { WalkOopAndArchiveClosure::do_oop_work(p); }
1132   void do_oop(      oop *p) { WalkOopAndArchiveClosure::do_oop_work(p); }
1133 
1134  protected:
1135   template <class T> void do_oop_work(T *p) {
1136     oop obj = RawAccess<>::oop_load(p);
1137     if (!CompressedOops::is_null(obj)) {
1138       size_t field_delta = pointer_delta(p, _referencing_obj, sizeof(char));
1139 
1140       if (!_record_klasses_only && log_is_enabled(Debug, cds, heap)) {
1141         ResourceMark rm;
1142         log_debug(cds, heap)("(%d) %s[" SIZE_FORMAT "] ==> " PTR_FORMAT " size " SIZE_FORMAT " %s", _level,
1143                              _referencing_obj->klass()->external_name(), field_delta,
1144                              p2i(obj), obj->size() * HeapWordSize, obj->klass()->external_name());
1145         if (log_is_enabled(Trace, cds, heap)) {
1146           LogTarget(Trace, cds, heap) log;
1147           LogStream out(log);
1148           obj->print_on(&out);
1149         }
1150       }
1151 
1152       bool success = HeapShared::archive_reachable_objects_from(
1153           _level + 1, _subgraph_info, obj);
1154       assert(success, "VM should have exited with unarchivable objects for _level > 1");
1155     }
1156   }
1157 
1158  public:
1159   static WalkOopAndArchiveClosure* current()  { return _current;              }
1160   oop referencing_obj()                       { return _referencing_obj;      }
1161   KlassSubGraphInfo* subgraph_info()          { return _subgraph_info;        }
1162 };
1163 
1164 WalkOopAndArchiveClosure* WalkOopAndArchiveClosure::_current = nullptr;
1165 
1166 // Checks if an oop has any non-null oop fields
1167 class PointsToOopsChecker : public BasicOopIterateClosure {
1168   bool _result;
1169 
1170   template <class T> void check(T *p) {
1171     _result |= (HeapAccess<>::oop_load(p) != nullptr);
1172   }
1173 
1174 public:
1175   PointsToOopsChecker() : _result(false) {}
1176   void do_oop(narrowOop *p) { check(p); }
1177   void do_oop(      oop *p) { check(p); }
1178   bool result() { return _result; }
1179 };
1180 
1181 HeapShared::CachedOopInfo HeapShared::make_cached_oop_info(oop obj) {
1182   WalkOopAndArchiveClosure* walker = WalkOopAndArchiveClosure::current();
1183   oop referrer = (walker == nullptr) ? nullptr : walker->referencing_obj();
1184   PointsToOopsChecker points_to_oops_checker;
1185   obj->oop_iterate(&points_to_oops_checker);
1186   return CachedOopInfo(referrer, points_to_oops_checker.result());
1187 }
1188 






















































1189 // (1) If orig_obj has not been archived yet, archive it.
1190 // (2) If orig_obj has not been seen yet (since start_recording_subgraph() was called),
1191 //     trace all  objects that are reachable from it, and make sure these objects are archived.
1192 // (3) Record the klasses of all orig_obj and all reachable objects.
1193 bool HeapShared::archive_reachable_objects_from(int level,
1194                                                 KlassSubGraphInfo* subgraph_info,
1195                                                 oop orig_obj) {

1196   assert(orig_obj != nullptr, "must be");
1197 
1198   if (!JavaClasses::is_supported_for_archiving(orig_obj)) {
1199     // This object has injected fields that cannot be supported easily, so we disallow them for now.
1200     // If you get an error here, you probably made a change in the JDK library that has added
1201     // these objects that are referenced (directly or indirectly) by static fields.
1202     ResourceMark rm;
1203     log_error(cds, heap)("Cannot archive object of class %s", orig_obj->klass()->external_name());
1204     MetaspaceShared::unrecoverable_writing_error();
1205   }
1206 
1207   // java.lang.Class instances cannot be included in an archived object sub-graph. We only support
1208   // them as Klass::_archived_mirror because they need to be specially restored at run time.
1209   //
1210   // If you get an error here, you probably made a change in the JDK library that has added a Class
1211   // object that is referenced (directly or indirectly) by static fields.
1212   if (java_lang_Class::is_instance(orig_obj) && subgraph_info != _default_subgraph_info) {
1213     log_error(cds, heap)("(%d) Unknown java.lang.Class object is in the archived sub-graph", level);
1214     MetaspaceShared::unrecoverable_writing_error();














1215   }

1216 
1217   if (has_been_seen_during_subgraph_recording(orig_obj)) {
1218     // orig_obj has already been archived and traced. Nothing more to do.
1219     return true;
1220   } else {
1221     set_has_been_seen_during_subgraph_recording(orig_obj);
1222   }
1223 
1224   bool already_archived = has_been_archived(orig_obj);
1225   bool record_klasses_only = already_archived;
1226   if (!already_archived) {
1227     ++_num_new_archived_objs;
1228     if (!archive_object(orig_obj)) {
1229       // Skip archiving the sub-graph referenced from the current entry field.
1230       ResourceMark rm;
1231       log_error(cds, heap)(
1232         "Cannot archive the sub-graph referenced from %s object ("
1233         PTR_FORMAT ") size " SIZE_FORMAT ", skipped.",
1234         orig_obj->klass()->external_name(), p2i(orig_obj), orig_obj->size() * HeapWordSize);
1235       if (level == 1) {
1236         // Don't archive a subgraph root that's too big. For archives static fields, that's OK
1237         // as the Java code will take care of initializing this field dynamically.
1238         return false;
1239       } else {
1240         // We don't know how to handle an object that has been archived, but some of its reachable
1241         // objects cannot be archived. Bail out for now. We might need to fix this in the future if
1242         // we have a real use case.
1243         MetaspaceShared::unrecoverable_writing_error();
1244       }
1245     }
1246   }
1247 
1248   Klass *orig_k = orig_obj->klass();
1249   subgraph_info->add_subgraph_object_klass(orig_k);
1250 
1251   WalkOopAndArchiveClosure walker(level, record_klasses_only, subgraph_info, orig_obj);
1252   orig_obj->oop_iterate(&walker);
1253 
1254   check_enum_obj(level + 1, subgraph_info, orig_obj);


1255   return true;
1256 }
1257 
1258 //
1259 // Start from the given static field in a java mirror and archive the
1260 // complete sub-graph of java heap objects that are reached directly
1261 // or indirectly from the starting object by following references.
1262 // Sub-graph archiving restrictions (current):
1263 //
1264 // - All classes of objects in the archived sub-graph (including the
1265 //   entry class) must be boot class only.
1266 // - No java.lang.Class instance (java mirror) can be included inside
1267 //   an archived sub-graph. Mirror can only be the sub-graph entry object.
1268 //
1269 // The Java heap object sub-graph archiving process (see
1270 // WalkOopAndArchiveClosure):
1271 //
1272 // 1) Java object sub-graph archiving starts from a given static field
1273 // within a Class instance (java mirror). If the static field is a
1274 // reference field and points to a non-null java object, proceed to
1275 // the next step.
1276 //
1277 // 2) Archives the referenced java object. If an archived copy of the
1278 // current object already exists, updates the pointer in the archived
1279 // copy of the referencing object to point to the current archived object.
1280 // Otherwise, proceed to the next step.
1281 //
1282 // 3) Follows all references within the current java object and recursively
1283 // archive the sub-graph of objects starting from each reference.
1284 //
1285 // 4) Updates the pointer in the archived copy of referencing object to
1286 // point to the current archived object.
1287 //
1288 // 5) The Klass of the current java object is added to the list of Klasses
1289 // for loading and initializing before any object in the archived graph can
1290 // be accessed at runtime.
1291 //
1292 void HeapShared::archive_reachable_objects_from_static_field(InstanceKlass *k,
1293                                                              const char* klass_name,
1294                                                              int field_offset,
1295                                                              const char* field_name) {
1296   assert(CDSConfig::is_dumping_heap(), "dump time only");
1297   assert(k->is_shared_boot_class(), "must be boot class");
1298 
1299   oop m = k->java_mirror();
1300 
1301   KlassSubGraphInfo* subgraph_info = get_subgraph_info(k);
1302   oop f = m->obj_field(field_offset);
1303 
1304   log_debug(cds, heap)("Start archiving from: %s::%s (" PTR_FORMAT ")", klass_name, field_name, p2i(f));
1305 
1306   if (!CompressedOops::is_null(f)) {
1307     if (log_is_enabled(Trace, cds, heap)) {
1308       LogTarget(Trace, cds, heap) log;
1309       LogStream out(log);
1310       f->print_on(&out);
1311     }
1312 
1313     bool success = archive_reachable_objects_from(1, subgraph_info, f);
1314     if (!success) {
1315       log_error(cds, heap)("Archiving failed %s::%s (some reachable objects cannot be archived)",
1316                            klass_name, field_name);
1317     } else {
1318       // Note: the field value is not preserved in the archived mirror.
1319       // Record the field as a new subGraph entry point. The recorded
1320       // information is restored from the archive at runtime.
1321       subgraph_info->add_subgraph_entry_field(field_offset, f);
1322       log_info(cds, heap)("Archived field %s::%s => " PTR_FORMAT, klass_name, field_name, p2i(f));
1323     }
1324   } else {
1325     // The field contains null, we still need to record the entry point,
1326     // so it can be restored at runtime.
1327     subgraph_info->add_subgraph_entry_field(field_offset, nullptr);
1328   }
1329 }
1330 
1331 #ifndef PRODUCT
1332 class VerifySharedOopClosure: public BasicOopIterateClosure {
1333  public:
1334   void do_oop(narrowOop *p) { VerifySharedOopClosure::do_oop_work(p); }
1335   void do_oop(      oop *p) { VerifySharedOopClosure::do_oop_work(p); }
1336 
1337  protected:
1338   template <class T> void do_oop_work(T *p) {
1339     oop obj = RawAccess<>::oop_load(p);
1340     if (!CompressedOops::is_null(obj)) {
1341       HeapShared::verify_reachable_objects_from(obj);
1342     }
1343   }
1344 };
1345 
1346 void HeapShared::verify_subgraph_from_static_field(InstanceKlass* k, int field_offset) {
1347   assert(CDSConfig::is_dumping_heap(), "dump time only");
1348   assert(k->is_shared_boot_class(), "must be boot class");
1349 
1350   oop m = k->java_mirror();
1351   oop f = m->obj_field(field_offset);
1352   if (!CompressedOops::is_null(f)) {
1353     verify_subgraph_from(f);
1354   }
1355 }
1356 
1357 void HeapShared::verify_subgraph_from(oop orig_obj) {
1358   if (!has_been_archived(orig_obj)) {
1359     // It's OK for the root of a subgraph to be not archived. See comments in
1360     // archive_reachable_objects_from().
1361     return;
1362   }
1363 
1364   // Verify that all objects reachable from orig_obj are archived.
1365   init_seen_objects_table();
1366   verify_reachable_objects_from(orig_obj);
1367   delete_seen_objects_table();
1368 }
1369 
1370 void HeapShared::verify_reachable_objects_from(oop obj) {
1371   _num_total_verifications ++;




1372   if (!has_been_seen_during_subgraph_recording(obj)) {
1373     set_has_been_seen_during_subgraph_recording(obj);
1374     assert(has_been_archived(obj), "must be");
1375     VerifySharedOopClosure walker;
1376     obj->oop_iterate(&walker);
1377   }
1378 }
1379 #endif
1380 
1381 // The "default subgraph" contains special objects (see heapShared.hpp) that
1382 // can be accessed before we load any Java classes (including java/lang/Class).
1383 // Make sure that these are only instances of the very few specific types
1384 // that we can handle.
1385 void HeapShared::check_default_subgraph_classes() {
1386   GrowableArray<Klass*>* klasses = _default_subgraph_info->subgraph_object_klasses();
1387   int num = klasses->length();

1388   for (int i = 0; i < num; i++) {
1389     Klass* subgraph_k = klasses->at(i);
1390     if (log_is_enabled(Info, cds, heap)) {
1391       ResourceMark rm;
1392       log_info(cds, heap)(
1393           "Archived object klass (default subgraph %d) => %s",
1394           i, subgraph_k->external_name());
1395     }
1396 
1397     Symbol* name = ArchiveBuilder::current()->get_source_addr(subgraph_k->name());
1398     guarantee(name == vmSymbols::java_lang_Class() ||
1399               name == vmSymbols::java_lang_String() ||
1400               name == vmSymbols::java_lang_ArithmeticException() ||
1401               name == vmSymbols::java_lang_NullPointerException() ||
1402               name == vmSymbols::java_lang_VirtualMachineError() ||
1403               name == vmSymbols::object_array_signature() ||
1404               name == vmSymbols::byte_array_signature() ||
1405               name == vmSymbols::char_array_signature(),
1406               "default subgraph can have only these objects");








1407   }
1408 }
1409 
1410 HeapShared::SeenObjectsTable* HeapShared::_seen_objects_table = nullptr;
1411 int HeapShared::_num_new_walked_objs;
1412 int HeapShared::_num_new_archived_objs;
1413 int HeapShared::_num_old_recorded_klasses;
1414 
1415 int HeapShared::_num_total_subgraph_recordings = 0;
1416 int HeapShared::_num_total_walked_objs = 0;
1417 int HeapShared::_num_total_archived_objs = 0;
1418 int HeapShared::_num_total_recorded_klasses = 0;
1419 int HeapShared::_num_total_verifications = 0;
1420 
1421 bool HeapShared::has_been_seen_during_subgraph_recording(oop obj) {
1422   return _seen_objects_table->get(obj) != nullptr;
1423 }
1424 
1425 void HeapShared::set_has_been_seen_during_subgraph_recording(oop obj) {
1426   assert(!has_been_seen_during_subgraph_recording(obj), "sanity");
1427   _seen_objects_table->put(obj, true);
1428   ++ _num_new_walked_objs;
1429 }
1430 
1431 void HeapShared::start_recording_subgraph(InstanceKlass *k, const char* class_name, bool is_full_module_graph) {
1432   log_info(cds, heap)("Start recording subgraph(s) for archived fields in %s", class_name);
1433   init_subgraph_info(k, is_full_module_graph);
1434   init_seen_objects_table();
1435   _num_new_walked_objs = 0;
1436   _num_new_archived_objs = 0;
1437   _num_old_recorded_klasses = get_subgraph_info(k)->num_subgraph_object_klasses();
1438 }
1439 
1440 void HeapShared::done_recording_subgraph(InstanceKlass *k, const char* class_name) {
1441   int num_new_recorded_klasses = get_subgraph_info(k)->num_subgraph_object_klasses() -
1442     _num_old_recorded_klasses;
1443   log_info(cds, heap)("Done recording subgraph(s) for archived fields in %s: "
1444                       "walked %d objs, archived %d new objs, recorded %d classes",
1445                       class_name, _num_new_walked_objs, _num_new_archived_objs,
1446                       num_new_recorded_klasses);
1447 
1448   delete_seen_objects_table();
1449 
1450   _num_total_subgraph_recordings ++;
1451   _num_total_walked_objs      += _num_new_walked_objs;
1452   _num_total_archived_objs    += _num_new_archived_objs;
1453   _num_total_recorded_klasses +=  num_new_recorded_klasses;
1454 }
1455 
1456 class ArchivableStaticFieldFinder: public FieldClosure {
1457   InstanceKlass* _ik;
1458   Symbol* _field_name;
1459   bool _found;
1460   int _offset;
1461 public:
1462   ArchivableStaticFieldFinder(InstanceKlass* ik, Symbol* field_name) :
1463     _ik(ik), _field_name(field_name), _found(false), _offset(-1) {}
1464 
1465   virtual void do_field(fieldDescriptor* fd) {
1466     if (fd->name() == _field_name) {
1467       assert(!_found, "fields can never be overloaded");
1468       if (is_reference_type(fd->field_type())) {
1469         _found = true;
1470         _offset = fd->offset();
1471       }
1472     }
1473   }
1474   bool found()     { return _found;  }
1475   int offset()     { return _offset; }
1476 };
1477 
1478 void HeapShared::init_subgraph_entry_fields(ArchivableStaticFieldInfo fields[],
1479                                             TRAPS) {
1480   for (int i = 0; fields[i].valid(); i++) {
1481     ArchivableStaticFieldInfo* info = &fields[i];
1482     TempNewSymbol klass_name =  SymbolTable::new_symbol(info->klass_name);
1483     TempNewSymbol field_name =  SymbolTable::new_symbol(info->field_name);
1484     ResourceMark rm; // for stringStream::as_string() etc.
1485 
1486 #ifndef PRODUCT
1487     bool is_test_class = (ArchiveHeapTestClass != nullptr) && (strcmp(info->klass_name, ArchiveHeapTestClass) == 0);
1488     const char* test_class_name = ArchiveHeapTestClass;
1489 #else
1490     bool is_test_class = false;
1491     const char* test_class_name = ""; // avoid C++ printf checks warnings.
1492 #endif
1493 
1494     if (is_test_class) {
1495       log_warning(cds)("Loading ArchiveHeapTestClass %s ...", test_class_name);
1496     }
1497 
1498     Klass* k = SystemDictionary::resolve_or_fail(klass_name, true, THREAD);
1499     if (HAS_PENDING_EXCEPTION) {
1500       CLEAR_PENDING_EXCEPTION;
1501       stringStream st;
1502       st.print("Fail to initialize archive heap: %s cannot be loaded by the boot loader", info->klass_name);
1503       THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), st.as_string());
1504     }
1505 
1506     if (!k->is_instance_klass()) {
1507       stringStream st;
1508       st.print("Fail to initialize archive heap: %s is not an instance class", info->klass_name);
1509       THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), st.as_string());
1510     }
1511 
1512     InstanceKlass* ik = InstanceKlass::cast(k);
1513     assert(InstanceKlass::cast(ik)->is_shared_boot_class(),
1514            "Only support boot classes");
1515 
1516     if (is_test_class) {
1517       if (ik->module()->is_named()) {
1518         // We don't want ArchiveHeapTestClass to be abused to easily load/initialize arbitrary
1519         // core-lib classes. You need to at least append to the bootclasspath.
1520         stringStream st;
1521         st.print("ArchiveHeapTestClass %s is not in unnamed module", test_class_name);
1522         THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), st.as_string());
1523       }
1524 
1525       if (ik->package() != nullptr) {
1526         // This restriction makes HeapShared::is_a_test_class_in_unnamed_module() easy.
1527         stringStream st;
1528         st.print("ArchiveHeapTestClass %s is not in unnamed package", test_class_name);
1529         THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), st.as_string());
1530       }
1531     } else {
1532       if (ik->module()->name() != vmSymbols::java_base()) {
1533         // We don't want to deal with cases when a module is unavailable at runtime.
1534         // FUTURE -- load from archived heap only when module graph has not changed
1535         //           between dump and runtime.
1536         stringStream st;
1537         st.print("%s is not in java.base module", info->klass_name);
1538         THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), st.as_string());
1539       }
1540     }
1541 
1542     if (is_test_class) {
1543       log_warning(cds)("Initializing ArchiveHeapTestClass %s ...", test_class_name);
1544     }
1545     ik->initialize(CHECK);
1546 
1547     ArchivableStaticFieldFinder finder(ik, field_name);
1548     ik->do_local_static_fields(&finder);
1549     if (!finder.found()) {
1550       stringStream st;
1551       st.print("Unable to find the static T_OBJECT field %s::%s", info->klass_name, info->field_name);
1552       THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), st.as_string());
1553     }
1554 
1555     info->klass = ik;
1556     info->offset = finder.offset();
1557   }
1558 }
1559 
1560 void HeapShared::init_subgraph_entry_fields(TRAPS) {
1561   assert(HeapShared::can_write(), "must be");
1562   _dump_time_subgraph_info_table = new (mtClass)DumpTimeKlassSubGraphInfoTable();
1563   init_subgraph_entry_fields(archive_subgraph_entry_fields, CHECK);
1564   if (CDSConfig::is_dumping_full_module_graph()) {
1565     init_subgraph_entry_fields(fmg_archive_subgraph_entry_fields, CHECK);
1566   }
1567 }
1568 
1569 #ifndef PRODUCT
1570 void HeapShared::setup_test_class(const char* test_class_name) {
1571   ArchivableStaticFieldInfo* p = archive_subgraph_entry_fields;
1572   int num_slots = sizeof(archive_subgraph_entry_fields) / sizeof(ArchivableStaticFieldInfo);
1573   assert(p[num_slots - 2].klass_name == nullptr, "must have empty slot that's patched below");
1574   assert(p[num_slots - 1].klass_name == nullptr, "must have empty slot that marks the end of the list");
1575 
1576   if (test_class_name != nullptr) {
1577     p[num_slots - 2].klass_name = test_class_name;
1578     p[num_slots - 2].field_name = ARCHIVE_TEST_FIELD_NAME;
1579   }
1580 }
1581 
1582 // See if ik is one of the test classes that are pulled in by -XX:ArchiveHeapTestClass
1583 // during runtime. This may be called before the module system is initialized so
1584 // we cannot rely on InstanceKlass::module(), etc.
1585 bool HeapShared::is_a_test_class_in_unnamed_module(Klass* ik) {
1586   if (_test_class != nullptr) {
1587     if (ik == _test_class) {
1588       return true;
1589     }
1590     Array<Klass*>* klasses = _test_class_record->subgraph_object_klasses();
1591     if (klasses == nullptr) {
1592       return false;
1593     }
1594 
1595     for (int i = 0; i < klasses->length(); i++) {
1596       Klass* k = klasses->at(i);
1597       if (k == ik) {
1598         Symbol* name;
1599         if (k->is_instance_klass()) {
1600           name = InstanceKlass::cast(k)->name();
1601         } else if (k->is_objArray_klass()) {
1602           Klass* bk = ObjArrayKlass::cast(k)->bottom_klass();
1603           if (!bk->is_instance_klass()) {
1604             return false;
1605           }
1606           name = bk->name();
1607         } else {
1608           return false;
1609         }
1610 
1611         // See KlassSubGraphInfo::check_allowed_klass() - only two types of
1612         // classes are allowed:
1613         //   (A) java.base classes (which must not be in the unnamed module)
1614         //   (B) test classes which must be in the unnamed package of the unnamed module.
1615         // So if we see a '/' character in the class name, it must be in (A);
1616         // otherwise it must be in (B).
1617         if (name->index_of_at(0, "/", 1)  >= 0) {
1618           return false; // (A)
1619         }
1620 
1621         return true; // (B)
1622       }
1623     }
1624   }
1625 
1626   return false;
1627 }
1628 #endif
1629 
1630 void HeapShared::init_for_dumping(TRAPS) {
1631   if (HeapShared::can_write()) {
1632     setup_test_class(ArchiveHeapTestClass);
1633     _dumped_interned_strings = new (mtClass)DumpedInternedStrings();
1634     init_subgraph_entry_fields(CHECK);
1635   }
1636 }
1637 
1638 void HeapShared::archive_object_subgraphs(ArchivableStaticFieldInfo fields[],
1639                                           bool is_full_module_graph) {
1640   _num_total_subgraph_recordings = 0;
1641   _num_total_walked_objs = 0;
1642   _num_total_archived_objs = 0;
1643   _num_total_recorded_klasses = 0;
1644   _num_total_verifications = 0;
1645 
1646   // For each class X that has one or more archived fields:
1647   // [1] Dump the subgraph of each archived field
1648   // [2] Create a list of all the class of the objects that can be reached
1649   //     by any of these static fields.
1650   //     At runtime, these classes are initialized before X's archived fields
1651   //     are restored by HeapShared::initialize_from_archived_subgraph().
1652   int i;
1653   for (int i = 0; fields[i].valid(); ) {
1654     ArchivableStaticFieldInfo* info = &fields[i];
1655     const char* klass_name = info->klass_name;
1656     start_recording_subgraph(info->klass, klass_name, is_full_module_graph);
1657 

1658     // If you have specified consecutive fields of the same klass in
1659     // fields[], these will be archived in the same
1660     // {start_recording_subgraph ... done_recording_subgraph} pass to
1661     // save time.
1662     for (; fields[i].valid(); i++) {
1663       ArchivableStaticFieldInfo* f = &fields[i];
1664       if (f->klass_name != klass_name) {
1665         break;
1666       }
1667 

1668       archive_reachable_objects_from_static_field(f->klass, f->klass_name,
1669                                                   f->offset, f->field_name);
1670     }
1671     done_recording_subgraph(info->klass, klass_name);
1672   }
1673 
1674   log_info(cds, heap)("Archived subgraph records = %d",
1675                       _num_total_subgraph_recordings);
1676   log_info(cds, heap)("  Walked %d objects", _num_total_walked_objs);
1677   log_info(cds, heap)("  Archived %d objects", _num_total_archived_objs);
1678   log_info(cds, heap)("  Recorded %d klasses", _num_total_recorded_klasses);
1679 
1680 #ifndef PRODUCT
1681   for (int i = 0; fields[i].valid(); i++) {
1682     ArchivableStaticFieldInfo* f = &fields[i];
1683     verify_subgraph_from_static_field(f->klass, f->offset);
1684   }
1685   log_info(cds, heap)("  Verified %d references", _num_total_verifications);
1686 #endif
1687 }
1688 
1689 // Not all the strings in the global StringTable are dumped into the archive, because
1690 // some of those strings may be only referenced by classes that are excluded from
1691 // the archive. We need to explicitly mark the strings that are:
1692 //   [1] used by classes that WILL be archived;
1693 //   [2] included in the SharedArchiveConfigFile.
1694 void HeapShared::add_to_dumped_interned_strings(oop string) {
1695   assert_at_safepoint(); // DumpedInternedStrings uses raw oops
1696   assert(!ArchiveHeapWriter::is_string_too_large_to_archive(string), "must be");
1697   bool created;
1698   _dumped_interned_strings->put_if_absent(string, true, &created);
1699 }
1700 
1701 #ifndef PRODUCT
1702 // At dump-time, find the location of all the non-null oop pointers in an archived heap
1703 // region. This way we can quickly relocate all the pointers without using
1704 // BasicOopIterateClosure at runtime.
1705 class FindEmbeddedNonNullPointers: public BasicOopIterateClosure {
1706   void* _start;
1707   BitMap *_oopmap;
1708   int _num_total_oops;
1709   int _num_null_oops;
1710  public:
1711   FindEmbeddedNonNullPointers(void* start, BitMap* oopmap)
1712     : _start(start), _oopmap(oopmap), _num_total_oops(0),  _num_null_oops(0) {}
1713 
1714   virtual void do_oop(narrowOop* p) {
1715     assert(UseCompressedOops, "sanity");
1716     _num_total_oops ++;
1717     narrowOop v = *p;
1718     if (!CompressedOops::is_null(v)) {
1719       size_t idx = p - (narrowOop*)_start;
1720       _oopmap->set_bit(idx);
1721     } else {
1722       _num_null_oops ++;
1723     }
1724   }
1725   virtual void do_oop(oop* p) {
1726     assert(!UseCompressedOops, "sanity");
1727     _num_total_oops ++;
1728     if ((*p) != nullptr) {
1729       size_t idx = p - (oop*)_start;
1730       _oopmap->set_bit(idx);
1731     } else {
1732       _num_null_oops ++;
1733     }
1734   }
1735   int num_total_oops() const { return _num_total_oops; }
1736   int num_null_oops()  const { return _num_null_oops; }
1737 };
1738 #endif
1739 
1740 #ifndef PRODUCT
1741 ResourceBitMap HeapShared::calculate_oopmap(MemRegion region) {
1742   size_t num_bits = region.byte_size() / (UseCompressedOops ? sizeof(narrowOop) : sizeof(oop));
1743   ResourceBitMap oopmap(num_bits);
1744 
1745   HeapWord* p   = region.start();
1746   HeapWord* end = region.end();
1747   FindEmbeddedNonNullPointers finder((void*)p, &oopmap);
1748 
1749   int num_objs = 0;
1750   while (p < end) {
1751     oop o = cast_to_oop(p);
1752     o->oop_iterate(&finder);
1753     p += o->size();
1754     ++ num_objs;
1755   }
1756 
1757   log_info(cds, heap)("calculate_oopmap: objects = %6d, oop fields = %7d (nulls = %7d)",
1758                       num_objs, finder.num_total_oops(), finder.num_null_oops());
1759   return oopmap;
1760 }
1761 
1762 #endif // !PRODUCT
1763 
1764 void HeapShared::count_allocation(size_t size) {
1765   _total_obj_count ++;
1766   _total_obj_size += size;
1767   for (int i = 0; i < ALLOC_STAT_SLOTS; i++) {
1768     if (size <= (size_t(1) << i)) {
1769       _alloc_count[i] ++;
1770       _alloc_size[i] += size;
1771       return;
1772     }
1773   }
1774 }
1775 
1776 static double avg_size(size_t size, size_t count) {
1777   double avg = 0;
1778   if (count > 0) {
1779     avg = double(size * HeapWordSize) / double(count);
1780   }
1781   return avg;
1782 }
1783 
1784 void HeapShared::print_stats() {
1785   size_t huge_count = _total_obj_count;
1786   size_t huge_size = _total_obj_size;
1787 
1788   for (int i = 0; i < ALLOC_STAT_SLOTS; i++) {
1789     size_t byte_size_limit = (size_t(1) << i) * HeapWordSize;
1790     size_t count = _alloc_count[i];
1791     size_t size = _alloc_size[i];
1792     log_info(cds, heap)(SIZE_FORMAT_W(8) " objects are <= " SIZE_FORMAT_W(-6)
1793                         " bytes (total " SIZE_FORMAT_W(8) " bytes, avg %8.1f bytes)",
1794                         count, byte_size_limit, size * HeapWordSize, avg_size(size, count));
1795     huge_count -= count;
1796     huge_size -= size;
1797   }
1798 
1799   log_info(cds, heap)(SIZE_FORMAT_W(8) " huge  objects               (total "  SIZE_FORMAT_W(8) " bytes"
1800                       ", avg %8.1f bytes)",
1801                       huge_count, huge_size * HeapWordSize,
1802                       avg_size(huge_size, huge_count));
1803   log_info(cds, heap)(SIZE_FORMAT_W(8) " total objects               (total "  SIZE_FORMAT_W(8) " bytes"
1804                       ", avg %8.1f bytes)",
1805                       _total_obj_count, _total_obj_size * HeapWordSize,
1806                       avg_size(_total_obj_size, _total_obj_count));
1807 }
1808 
1809 bool HeapShared::is_archived_boot_layer_available(JavaThread* current) {
1810   TempNewSymbol klass_name = SymbolTable::new_symbol(ARCHIVED_BOOT_LAYER_CLASS);
1811   InstanceKlass* k = SystemDictionary::find_instance_klass(current, klass_name, Handle(), Handle());
1812   if (k == nullptr) {
1813     return false;
1814   } else {
1815     TempNewSymbol field_name = SymbolTable::new_symbol(ARCHIVED_BOOT_LAYER_FIELD);
1816     TempNewSymbol field_signature = SymbolTable::new_symbol("Ljdk/internal/module/ArchivedBootLayer;");
1817     fieldDescriptor fd;
1818     if (k->find_field(field_name, field_signature, true, &fd) != nullptr) {
1819       oop m = k->java_mirror();
1820       oop f = m->obj_field(fd.offset());
1821       if (CompressedOops::is_null(f)) {
1822         return false;
1823       }
1824     } else {
1825       return false;
1826     }
1827   }
1828   return true;
1829 }
1830 
1831 #endif // INCLUDE_CDS_JAVA_HEAP
--- EOF ---