< prev index next >

src/hotspot/share/cds/heapShared.cpp

Print this page

  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"

  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 }

 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     }

 316       return nullptr;
 317     }
 318   }
 319   void set_oop(MetaspaceObj* ptr, oop o) {
 320     MutexLocker ml(ScratchObjects_lock, Mutex::_no_safepoint_check_flag);
 321     OopHandle handle(Universe::vm_global(), o);
 322     bool is_new = put(ptr, handle);
 323     assert(is_new, "cannot set twice");
 324   }
 325   void remove_oop(MetaspaceObj* ptr) {
 326     MutexLocker ml(ScratchObjects_lock, Mutex::_no_safepoint_check_flag);
 327     OopHandle* handle = get(ptr);
 328     if (handle != nullptr) {
 329       handle->release(Universe::vm_global());
 330       remove(ptr);
 331     }
 332   }
 333 };
 334 
 335 void HeapShared::add_scratch_resolved_references(ConstantPool* src, objArrayOop dest) {



 336   _scratch_references_table->set_oop(src, dest);
 337 }
 338 
 339 objArrayOop HeapShared::scratch_resolved_references(ConstantPool* src) {
 340   return (objArrayOop)_scratch_references_table->get_oop(src);
 341 }
 342 
 343 void HeapShared::init_scratch_objects(TRAPS) {
 344   for (int i = T_BOOLEAN; i < T_VOID+1; i++) {
 345     BasicType bt = (BasicType)i;
 346     if (!is_reference_type(bt)) {
 347       oop m = java_lang_Class::create_basic_type_mirror(type2name(bt), bt, CHECK);
 348       _scratch_basic_type_mirrors[i] = OopHandle(Universe::vm_global(), m);

 349     }
 350   }
 351   _scratch_java_mirror_table = new (mtClass)MetaspaceObjToOopHandleTable();
 352   _scratch_references_table = new (mtClass)MetaspaceObjToOopHandleTable();










































 353 }
 354 
 355 oop HeapShared::scratch_java_mirror(BasicType t) {
 356   assert((uint)t < T_VOID+1, "range check");
 357   assert(!is_reference_type(t), "sanity");
 358   return _scratch_basic_type_mirrors[t].resolve();
 359 }
 360 
 361 oop HeapShared::scratch_java_mirror(Klass* k) {
 362   return _scratch_java_mirror_table->get_oop(k);
 363 }
 364 
 365 void HeapShared::set_scratch_java_mirror(Klass* k, oop mirror) {

 366   _scratch_java_mirror_table->set_oop(k, mirror);
 367 }
 368 
 369 void HeapShared::remove_scratch_objects(Klass* k) {
 370   _scratch_java_mirror_table->remove_oop(k);
 371   if (k->is_instance_klass()) {
 372     _scratch_references_table->remove(InstanceKlass::cast(k)->constants());
 373   }
 374 }
 375 



























































































 376 void HeapShared::archive_java_mirrors() {


 377   for (int i = T_BOOLEAN; i < T_VOID+1; i++) {
 378     BasicType bt = (BasicType)i;
 379     if (!is_reference_type(bt)) {

 380       oop m = _scratch_basic_type_mirrors[i].resolve();
 381       assert(m != nullptr, "sanity");
 382       bool success = archive_reachable_objects_from(1, _default_subgraph_info, m);

 383       assert(success, "sanity");
 384 
 385       log_trace(cds, heap, mirror)(
 386         "Archived %s mirror object from " PTR_FORMAT,
 387         type2name(bt), p2i(m));
 388 
 389       Universe::set_archived_basic_type_mirror_index(bt, append_root(m));
 390     }
 391   }
 392 
 393   GrowableArray<Klass*>* klasses = ArchiveBuilder::current()->klasses();
 394   assert(klasses != nullptr, "sanity");
 395   for (int i = 0; i < klasses->length(); i++) {
 396     Klass* orig_k = klasses->at(i);

 397     oop m = scratch_java_mirror(orig_k);
 398     if (m != nullptr) {








 399       Klass* buffered_k = ArchiveBuilder::get_buffered_klass(orig_k);
 400       bool success = archive_reachable_objects_from(1, _default_subgraph_info, m);
 401       guarantee(success, "scratch mirrors must point to only archivable objects");
 402       buffered_k->set_archived_java_mirror(append_root(m));
 403       ResourceMark rm;
 404       log_trace(cds, heap, mirror)(
 405         "Archived %s mirror object from " PTR_FORMAT,
 406         buffered_k->external_name(), p2i(m));
 407 
 408       // archive the resolved_referenes array
 409       if (buffered_k->is_instance_klass()) {
 410         InstanceKlass* ik = InstanceKlass::cast(buffered_k);
 411         oop rr = ik->constants()->prepare_resolved_references_for_archiving();
 412         if (rr != nullptr && !ArchiveHeapWriter::is_too_large_to_archive(rr)) {
 413           bool success = HeapShared::archive_reachable_objects_from(1, _default_subgraph_info, rr);
 414           assert(success, "must be");
 415           int root_index = append_root(rr);
 416           ik->constants()->cache()->set_archived_references(root_index);
 417         }
 418       }
 419     }
 420   }
 421 }
 422 
 423 void HeapShared::archive_strings() {
 424   oop shared_strings_array = StringTable::init_shared_table(_dumped_interned_strings);
 425   bool success = archive_reachable_objects_from(1, _default_subgraph_info, shared_strings_array);
 426   // We must succeed because:
 427   // - _dumped_interned_strings do not contain any large strings.
 428   // - StringTable::init_shared_table() doesn't create any large arrays.
 429   assert(success, "shared strings array must not point to arrays or strings that are too large to archive");
 430   StringTable::set_shared_strings_array_index(append_root(shared_strings_array));
 431 }
 432 
 433 void HeapShared::mark_native_pointers(oop orig_obj) {
 434   if (java_lang_Class::is_instance(orig_obj)) {
 435     ArchiveHeapWriter::mark_native_pointer(orig_obj, java_lang_Class::klass_offset());
 436     ArchiveHeapWriter::mark_native_pointer(orig_obj, java_lang_Class::array_klass_offset());


 437   }
 438 }
 439 
 440 // -- Handling of Enum objects
 441 // Java Enum classes have synthetic <clinit> methods that look like this
 442 //     enum MyEnum {FOO, BAR}
 443 //     MyEnum::<clinint> {
 444 //        /*static final MyEnum*/ MyEnum::FOO = new MyEnum("FOO");
 445 //        /*static final MyEnum*/ MyEnum::BAR = new MyEnum("BAR");
 446 //     }
 447 //
 448 // If MyEnum::FOO object is referenced by any of the archived subgraphs, we must
 449 // ensure the archived value equals (in object address) to the runtime value of
 450 // MyEnum::FOO.
 451 //
 452 // However, since MyEnum::<clinint> is synthetically generated by javac, there's
 453 // no way of programmatically handling this inside the Java code (as you would handle
 454 // ModuleLayer::EMPTY_LAYER, for example).
 455 //
 456 // Instead, we archive all static field of such Enum classes. At runtime,
 457 // HeapShared::initialize_enum_klass() will skip the <clinit> method and pull
 458 // the static fields out of the archived heap.
 459 void HeapShared::check_enum_obj(int level,
 460                                 KlassSubGraphInfo* subgraph_info,
 461                                 oop orig_obj) {
 462   assert(level > 1, "must never be called at the first (outermost) level");
 463   Klass* k = orig_obj->klass();
 464   Klass* buffered_k = ArchiveBuilder::get_buffered_klass(k);
 465   if (!k->is_instance_klass()) {
 466     return;
 467   }
 468   InstanceKlass* ik = InstanceKlass::cast(k);
 469   if (ik->java_super() == vmClasses::Enum_klass() && !ik->has_archived_enum_objs()) {
 470     ResourceMark rm;
 471     ik->set_has_archived_enum_objs();
 472     buffered_k->set_has_archived_enum_objs();
 473     oop mirror = ik->java_mirror();
 474 
 475     for (JavaFieldStream fs(ik); !fs.done(); fs.next()) {
 476       if (fs.access_flags().is_static()) {
 477         fieldDescriptor& fd = fs.field_descriptor();
 478         if (fd.field_type() != T_OBJECT && fd.field_type() != T_ARRAY) {
 479           guarantee(false, "static field %s::%s must be T_OBJECT or T_ARRAY",
 480                     ik->external_name(), fd.name()->as_C_string());
 481         }
 482         oop oop_field = mirror->obj_field(fd.offset());
 483         if (oop_field == nullptr) {
 484           guarantee(false, "static field %s::%s must not be null",
 485                     ik->external_name(), fd.name()->as_C_string());
 486         } else if (oop_field->klass() != ik && oop_field->klass() != ik->array_klass_or_null()) {
 487           guarantee(false, "static field %s::%s is of the wrong type",
 488                     ik->external_name(), fd.name()->as_C_string());
 489         }
 490         bool success = archive_reachable_objects_from(level, subgraph_info, oop_field);
 491         assert(success, "VM should have exited with unarchivable objects for _level > 1");
 492         int root_index = append_root(oop_field);
 493         log_info(cds, heap)("Archived enum obj @%d %s::%s (" INTPTR_FORMAT ")",
 494                             root_index, ik->external_name(), fd.name()->as_C_string(),
 495                             p2i((oopDesc*)oop_field));
 496         SystemDictionaryShared::add_enum_klass_static_field(ik, root_index);
 497       }
 498     }
 499   }
 500 }
 501 
 502 // See comments in HeapShared::check_enum_obj()
 503 bool HeapShared::initialize_enum_klass(InstanceKlass* k, TRAPS) {
 504   if (!ArchiveHeapLoader::is_in_use()) {
 505     return false;
 506   }
 507 
 508   RunTimeClassInfo* info = RunTimeClassInfo::get_for(k);
 509   assert(info != nullptr, "sanity");
 510 
 511   if (log_is_enabled(Info, cds, heap)) {
 512     ResourceMark rm;
 513     log_info(cds, heap)("Initializing Enum class: %s", k->external_name());
 514   }







 515 
 516   oop mirror = k->java_mirror();
 517   int i = 0;
 518   for (JavaFieldStream fs(k); !fs.done(); fs.next()) {
 519     if (fs.access_flags().is_static()) {
 520       int root_index = info->enum_klass_static_field_root_index_at(i++);
 521       fieldDescriptor& fd = fs.field_descriptor();
 522       assert(fd.field_type() == T_OBJECT || fd.field_type() == T_ARRAY, "must be");
 523       mirror->obj_field_put(fd.offset(), get_root(root_index, /*clear=*/true));
 524     }
 525   }
 526   return true;
 527 }
 528 
 529 void HeapShared::archive_objects(ArchiveHeapInfo *heap_info) {
 530   {
 531     NoSafepointVerifier nsv;
 532 
 533     _default_subgraph_info = init_subgraph_info(vmClasses::Object_klass(), false);


 534 
 535     // Cache for recording where the archived objects are copied to
 536     create_archived_object_cache();
 537 
 538     log_info(cds)("Heap range = [" PTR_FORMAT " - "  PTR_FORMAT "]",
 539                    UseCompressedOops ? p2i(CompressedOops::begin()) :
 540                                        p2i((address)G1CollectedHeap::heap()->reserved().start()),
 541                    UseCompressedOops ? p2i(CompressedOops::end()) :
 542                                        p2i((address)G1CollectedHeap::heap()->reserved().end()));
 543     copy_objects();
 544 
 545     CDSHeapVerifier::verify();
 546     check_default_subgraph_classes();
 547   }
 548 
 549   ArchiveHeapWriter::write(_pending_roots, heap_info);
 550 }
 551 
 552 void HeapShared::copy_interned_strings() {
 553   init_seen_objects_table();
 554 
 555   auto copier = [&] (oop s, bool value_ignored) {
 556     assert(s != nullptr, "sanity");
 557     assert(!ArchiveHeapWriter::is_string_too_large_to_archive(s), "large strings must have been filtered");
 558     bool success = archive_reachable_objects_from(1, _default_subgraph_info, s);
 559     assert(success, "must be");
 560     // Prevent string deduplication from changing the value field to
 561     // something not in the archive.
 562     java_lang_String::set_deduplication_forbidden(s);
 563   };
 564   _dumped_interned_strings->iterate_all(copier);
 565 
 566   delete_seen_objects_table();
 567 }
 568 
 569 void HeapShared::copy_special_objects() {
 570   // Archive special objects that do not belong to any subgraphs
 571   init_seen_objects_table();
 572   archive_java_mirrors();
 573   archive_strings();

 574   delete_seen_objects_table();
 575 }
 576 
 577 void HeapShared::copy_objects() {
 578   assert(HeapShared::can_write(), "must be");
 579 
 580   copy_interned_strings();
 581   copy_special_objects();
 582 
 583   archive_object_subgraphs(archive_subgraph_entry_fields,
 584                            false /* is_full_module_graph */);
 585 
 586   if (CDSConfig::is_dumping_full_module_graph()) {
 587     archive_object_subgraphs(fmg_archive_subgraph_entry_fields,
 588                              true /* is_full_module_graph */);
 589     Modules::verify_archived_modules();
 590   }
 591 }
 592 
 593 //

 631 // Add the Klass* for an object in the current KlassSubGraphInfo's subgraphs.
 632 // Only objects of boot classes can be included in sub-graph.
 633 void KlassSubGraphInfo::add_subgraph_object_klass(Klass* orig_k) {
 634   assert(CDSConfig::is_dumping_heap(), "dump time only");
 635   Klass* buffered_k = ArchiveBuilder::get_buffered_klass(orig_k);
 636 
 637   if (_subgraph_object_klasses == nullptr) {
 638     _subgraph_object_klasses =
 639       new (mtClass) GrowableArray<Klass*>(50, mtClass);
 640   }
 641 
 642   assert(ArchiveBuilder::current()->is_in_buffer_space(buffered_k), "must be a shared class");
 643 
 644   if (_k == buffered_k) {
 645     // Don't add the Klass containing the sub-graph to it's own klass
 646     // initialization list.
 647     return;
 648   }
 649 
 650   if (buffered_k->is_instance_klass()) {
 651     assert(InstanceKlass::cast(buffered_k)->is_shared_boot_class(),
 652           "must be boot class");



 653     // vmClasses::xxx_klass() are not updated, need to check
 654     // the original Klass*
 655     if (orig_k == vmClasses::String_klass() ||
 656         orig_k == vmClasses::Object_klass()) {
 657       // Initialized early during VM initialization. No need to be added
 658       // to the sub-graph object class list.
 659       return;
 660     }
 661     check_allowed_klass(InstanceKlass::cast(orig_k));
 662   } else if (buffered_k->is_objArray_klass()) {
 663     Klass* abk = ObjArrayKlass::cast(buffered_k)->bottom_klass();
 664     if (abk->is_instance_klass()) {
 665       assert(InstanceKlass::cast(abk)->is_shared_boot_class(),
 666             "must be boot class");
 667       check_allowed_klass(InstanceKlass::cast(ObjArrayKlass::cast(orig_k)->bottom_klass()));
 668     }
 669     if (buffered_k == Universe::objectArrayKlassObj()) {
 670       // Initialized early during Universe::genesis. No need to be added
 671       // to the list.
 672       return;
 673     }
 674   } else {
 675     assert(buffered_k->is_typeArray_klass(), "must be");
 676     // Primitive type arrays are created early during Universe::genesis.
 677     return;
 678   }
 679 
 680   if (log_is_enabled(Debug, cds, heap)) {
 681     if (!_subgraph_object_klasses->contains(buffered_k)) {
 682       ResourceMark rm;
 683       log_debug(cds, heap)("Adding klass %s", orig_k->external_name());
 684     }
 685   }
 686 
 687   _subgraph_object_klasses->append_if_missing(buffered_k);
 688   _has_non_early_klasses |= is_non_early_klass(orig_k);
 689 }
 690 
 691 void KlassSubGraphInfo::check_allowed_klass(InstanceKlass* ik) {




 692   if (ik->module()->name() == vmSymbols::java_base()) {
 693     assert(ik->package() != nullptr, "classes in java.base cannot be in unnamed package");
 694     return;
 695   }
 696 
 697 #ifndef PRODUCT
 698   if (!ik->module()->is_named() && ik->package() == nullptr) {
 699     // This class is loaded by ArchiveHeapTestClass
 700     return;
 701   }
 702   const char* extra_msg = ", or in an unnamed package of an unnamed module";
 703 #else
 704   const char* extra_msg = "";
 705 #endif
 706 
 707   ResourceMark rm;
 708   log_error(cds, heap)("Class %s not allowed in archive heap. Must be in java.base%s",
 709                        ik->external_name(), extra_msg);
 710   MetaspaceShared::unrecoverable_writing_error();
 711 }

 769     _subgraph_object_klasses =
 770       ArchiveBuilder::new_ro_array<Klass*>(num_subgraphs_klasses);
 771     for (int i = 0; i < num_subgraphs_klasses; i++) {
 772       Klass* subgraph_k = subgraph_object_klasses->at(i);
 773       if (log_is_enabled(Info, cds, heap)) {
 774         ResourceMark rm;
 775         log_info(cds, heap)(
 776           "Archived object klass %s (%2d) => %s",
 777           _k->external_name(), i, subgraph_k->external_name());
 778       }
 779       _subgraph_object_klasses->at_put(i, subgraph_k);
 780       ArchivePtrMarker::mark_pointer(_subgraph_object_klasses->adr_at(i));
 781     }
 782   }
 783 
 784   ArchivePtrMarker::mark_pointer(&_k);
 785   ArchivePtrMarker::mark_pointer(&_entry_field_records);
 786   ArchivePtrMarker::mark_pointer(&_subgraph_object_klasses);
 787 }
 788 
 789 struct CopyKlassSubGraphInfoToArchive : StackObj {

 790   CompactHashtableWriter* _writer;
 791   CopyKlassSubGraphInfoToArchive(CompactHashtableWriter* writer) : _writer(writer) {}
 792 
 793   bool do_entry(Klass* klass, KlassSubGraphInfo& info) {
 794     if (info.subgraph_object_klasses() != nullptr || info.subgraph_entry_fields() != nullptr) {
 795       ArchivedKlassSubGraphInfoRecord* record =
 796         (ArchivedKlassSubGraphInfoRecord*)ArchiveBuilder::ro_region_alloc(sizeof(ArchivedKlassSubGraphInfoRecord));
 797       record->init(&info);
 798 
 799       Klass* buffered_k = ArchiveBuilder::get_buffered_klass(klass);
 800       unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary((address)buffered_k);
 801       u4 delta = ArchiveBuilder::current()->any_to_offset_u4(record);
 802       _writer->add(hash, delta);
 803     }
 804     return true; // keep on iterating
 805   }
 806 };
 807 







 808 // Build the records of archived subgraph infos, which include:
 809 // - Entry points to all subgraphs from the containing class mirror. The entry
 810 //   points are static fields in the mirror. For each entry point, the field
 811 //   offset, and value are recorded in the sub-graph
 812 //   info. The value is stored back to the corresponding field at runtime.
 813 // - A list of klasses that need to be loaded/initialized before archived
 814 //   java object sub-graph can be accessed at runtime.
 815 void HeapShared::write_subgraph_info_table() {
 816   // Allocate the contents of the hashtable(s) inside the RO region of the CDS archive.
 817   DumpTimeKlassSubGraphInfoTable* d_table = _dump_time_subgraph_info_table;
 818   CompactHashtableStats stats;
 819 
 820   _run_time_subgraph_info_table.reset();
 821 
 822   CompactHashtableWriter writer(d_table->_count, &stats);
 823   CopyKlassSubGraphInfoToArchive copy(&writer);
 824   d_table->iterate(&copy);
 825   writer.dump(&_run_time_subgraph_info_table, "subgraphs");
 826 


 827 #ifndef PRODUCT
 828   if (ArchiveHeapTestClass != nullptr) {
 829     size_t len = strlen(ArchiveHeapTestClass) + 1;
 830     Array<char>* array = ArchiveBuilder::new_ro_array<char>((int)len);
 831     strncpy(array->adr_at(0), ArchiveHeapTestClass, len);
 832     _archived_ArchiveHeapTestClass = array;
 833   }
 834 #endif
 835   if (log_is_enabled(Info, cds, heap)) {
 836     print_stats();
 837   }
 838 }
 839 




 840 void HeapShared::init_roots(oop roots_oop) {
 841   if (roots_oop != nullptr) {
 842     assert(ArchiveHeapLoader::is_in_use(), "must be");
 843     _roots = OopHandle(Universe::vm_global(), roots_oop);
 844   }
 845 }
 846 
 847 void HeapShared::serialize_tables(SerializeClosure* soc) {
 848 
 849 #ifndef PRODUCT
 850   soc->do_ptr(&_archived_ArchiveHeapTestClass);
 851   if (soc->reading() && _archived_ArchiveHeapTestClass != nullptr) {
 852     _test_class_name = _archived_ArchiveHeapTestClass->adr_at(0);
 853     setup_test_class(_test_class_name);
 854   }
 855 #endif
 856 
 857   _run_time_subgraph_info_table.serialize_header(soc);


 858 }
 859 
 860 static void verify_the_heap(Klass* k, const char* which) {
 861   if (VerifyArchivedFields > 0) {
 862     ResourceMark rm;
 863     log_info(cds, heap)("Verify heap %s initializing static field(s) in %s",
 864                         which, k->external_name());
 865 
 866     VM_Verify verify_op;
 867     VMThread::execute(&verify_op);
 868 
 869     if (VerifyArchivedFields > 1 && is_init_completed()) {
 870       // At this time, the oop->klass() of some archived objects in the heap may not
 871       // have been loaded into the system dictionary yet. Nevertheless, oop->klass() should
 872       // have enough information (object size, oop maps, etc) so that a GC can be safely
 873       // performed.
 874       //
 875       // -XX:VerifyArchivedFields=2 force a GC to happen in such an early stage
 876       // to check for GC safety.
 877       log_info(cds, heap)("Trigger GC %s initializing static field(s) in %s",

 905     TempNewSymbol klass_name = SymbolTable::new_symbol(info->klass_name);
 906     InstanceKlass* k = SystemDictionaryShared::find_builtin_class(klass_name);
 907     assert(k != nullptr && k->is_shared_boot_class(), "sanity");
 908     resolve_classes_for_subgraph_of(current, k);
 909   }
 910 }
 911 
 912 void HeapShared::resolve_classes_for_subgraph_of(JavaThread* current, Klass* k) {
 913   JavaThread* THREAD = current;
 914   ExceptionMark em(THREAD);
 915   const ArchivedKlassSubGraphInfoRecord* record =
 916    resolve_or_init_classes_for_subgraph_of(k, /*do_init=*/false, THREAD);
 917   if (HAS_PENDING_EXCEPTION) {
 918    CLEAR_PENDING_EXCEPTION;
 919   }
 920   if (record == nullptr) {
 921    clear_archived_roots_of(k);
 922   }
 923 }
 924 









































 925 void HeapShared::initialize_from_archived_subgraph(JavaThread* current, Klass* k) {
 926   JavaThread* THREAD = current;
 927   if (!ArchiveHeapLoader::is_in_use()) {
 928     return; // nothing to do
 929   }
 930 





 931   ExceptionMark em(THREAD);
 932   const ArchivedKlassSubGraphInfoRecord* record =
 933     resolve_or_init_classes_for_subgraph_of(k, /*do_init=*/true, THREAD);
 934 
 935   if (HAS_PENDING_EXCEPTION) {
 936     CLEAR_PENDING_EXCEPTION;
 937     // None of the field value will be set if there was an exception when initializing the classes.
 938     // The java code will not see any of the archived objects in the
 939     // subgraphs referenced from k in this case.
 940     return;
 941   }
 942 
 943   if (record != nullptr) {
 944     init_archived_fields_for(k, record);
 945   }
 946 }
 947 
 948 const ArchivedKlassSubGraphInfoRecord*
 949 HeapShared::resolve_or_init_classes_for_subgraph_of(Klass* k, bool do_init, TRAPS) {
 950   assert(!CDSConfig::is_dumping_heap(), "Should not be called when dumping heap");

 978         log_info(cds, heap)("subgraph %s cannot be used because full module graph is disabled",
 979                             k->external_name());
 980       }
 981       return nullptr;
 982     }
 983 
 984     if (record->has_non_early_klasses() && JvmtiExport::should_post_class_file_load_hook()) {
 985       if (log_is_enabled(Info, cds, heap)) {
 986         ResourceMark rm(THREAD);
 987         log_info(cds, heap)("subgraph %s cannot be used because JVMTI ClassFileLoadHook is enabled",
 988                             k->external_name());
 989       }
 990       return nullptr;
 991     }
 992 
 993     if (log_is_enabled(Info, cds, heap)) {
 994       ResourceMark rm;
 995       log_info(cds, heap)("%s subgraph %s ", do_init ? "init" : "resolve", k->external_name());
 996     }
 997 




















































 998     resolve_or_init(k, do_init, CHECK_NULL);
 999 
1000     // Load/link/initialize the klasses of the objects in the subgraph.
1001     // nullptr class loader is used.
1002     Array<Klass*>* klasses = record->subgraph_object_klasses();
1003     if (klasses != nullptr) {
1004       for (int i = 0; i < klasses->length(); i++) {
1005         Klass* klass = klasses->at(i);
1006         if (!klass->is_shared()) {
1007           return nullptr;
1008         }
1009         resolve_or_init(klass, do_init, CHECK_NULL);
1010       }
1011     }
1012   }
1013 
1014   return record;
1015 }
1016 













1017 void HeapShared::resolve_or_init(Klass* k, bool do_init, TRAPS) {
1018   if (!do_init) {
1019     if (k->class_loader_data() == nullptr) {
1020       Klass* resolved_k = SystemDictionary::resolve_or_null(k->name(), CHECK);
1021       assert(resolved_k == k, "classes used by archived heap must not be replaced by JVMTI ClassFileLoadHook");
1022     }
1023   } else {
1024     assert(k->class_loader_data() != nullptr, "must have been resolved by HeapShared::resolve_classes");
1025     if (k->is_instance_klass()) {
1026       InstanceKlass* ik = InstanceKlass::cast(k);
1027       ik->initialize(CHECK);
1028     } else if (k->is_objArray_klass()) {
1029       ObjArrayKlass* oak = ObjArrayKlass::cast(k);
1030       oak->initialize(CHECK);
1031     }
1032   }
1033 }
1034 
1035 void HeapShared::init_archived_fields_for(Klass* k, const ArchivedKlassSubGraphInfoRecord* record) {
1036   verify_the_heap(k, "before");

1066   unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary_quick(k);
1067   const ArchivedKlassSubGraphInfoRecord* record = _run_time_subgraph_info_table.lookup(k, hash, 0);
1068   if (record != nullptr) {
1069     Array<int>* entry_field_records = record->entry_field_records();
1070     if (entry_field_records != nullptr) {
1071       int efr_len = entry_field_records->length();
1072       assert(efr_len % 2 == 0, "sanity");
1073       for (int i = 0; i < efr_len; i += 2) {
1074         int root_index = entry_field_records->at(i+1);
1075         clear_root(root_index);
1076       }
1077     }
1078   }
1079 }
1080 
1081 class WalkOopAndArchiveClosure: public BasicOopIterateClosure {
1082   int _level;
1083   bool _record_klasses_only;
1084   KlassSubGraphInfo* _subgraph_info;
1085   oop _referencing_obj;
1086 
1087   // The following are for maintaining a stack for determining
1088   // CachedOopInfo::_referrer
1089   static WalkOopAndArchiveClosure* _current;
1090   WalkOopAndArchiveClosure* _last;
1091  public:
1092   WalkOopAndArchiveClosure(int level,
1093                            bool record_klasses_only,
1094                            KlassSubGraphInfo* subgraph_info,
1095                            oop orig) :
1096     _level(level),
1097     _record_klasses_only(record_klasses_only),
1098     _subgraph_info(subgraph_info),
1099     _referencing_obj(orig) {
1100     _last = _current;
1101     _current = this;
1102   }
1103   ~WalkOopAndArchiveClosure() {
1104     _current = _last;
1105   }
1106   void do_oop(narrowOop *p) { WalkOopAndArchiveClosure::do_oop_work(p); }
1107   void do_oop(      oop *p) { WalkOopAndArchiveClosure::do_oop_work(p); }
1108 
1109  protected:
1110   template <class T> void do_oop_work(T *p) {
1111     oop obj = RawAccess<>::oop_load(p);
1112     if (!CompressedOops::is_null(obj)) {
1113       size_t field_delta = pointer_delta(p, _referencing_obj, sizeof(char));
1114 
1115       if (!_record_klasses_only && log_is_enabled(Debug, cds, heap)) {
1116         ResourceMark rm;
1117         log_debug(cds, heap)("(%d) %s[" SIZE_FORMAT "] ==> " PTR_FORMAT " size " SIZE_FORMAT " %s", _level,
1118                              _referencing_obj->klass()->external_name(), field_delta,
1119                              p2i(obj), obj->size() * HeapWordSize, obj->klass()->external_name());
1120         if (log_is_enabled(Trace, cds, heap)) {
1121           LogTarget(Trace, cds, heap) log;
1122           LogStream out(log);
1123           obj->print_on(&out);
1124         }
1125       }
1126 
1127       bool success = HeapShared::archive_reachable_objects_from(
1128           _level + 1, _subgraph_info, obj);
1129       assert(success, "VM should have exited with unarchivable objects for _level > 1");
1130     }
1131   }
1132 
1133  public:
1134   static WalkOopAndArchiveClosure* current()  { return _current;              }
1135   oop referencing_obj()                       { return _referencing_obj;      }
1136   KlassSubGraphInfo* subgraph_info()          { return _subgraph_info;        }
1137 };
1138 
1139 WalkOopAndArchiveClosure* WalkOopAndArchiveClosure::_current = nullptr;
1140 
1141 HeapShared::CachedOopInfo HeapShared::make_cached_oop_info() {
1142   WalkOopAndArchiveClosure* walker = WalkOopAndArchiveClosure::current();
1143   oop referrer = (walker == nullptr) ? nullptr : walker->referencing_obj();
1144   return CachedOopInfo(referrer);
1145 }
1146 























































1147 // (1) If orig_obj has not been archived yet, archive it.
1148 // (2) If orig_obj has not been seen yet (since start_recording_subgraph() was called),
1149 //     trace all  objects that are reachable from it, and make sure these objects are archived.
1150 // (3) Record the klasses of all orig_obj and all reachable objects.
1151 bool HeapShared::archive_reachable_objects_from(int level,
1152                                                 KlassSubGraphInfo* subgraph_info,
1153                                                 oop orig_obj) {

1154   assert(orig_obj != nullptr, "must be");
1155 
1156   if (!JavaClasses::is_supported_for_archiving(orig_obj)) {
1157     // This object has injected fields that cannot be supported easily, so we disallow them for now.
1158     // If you get an error here, you probably made a change in the JDK library that has added
1159     // these objects that are referenced (directly or indirectly) by static fields.
1160     ResourceMark rm;
1161     log_error(cds, heap)("Cannot archive object of class %s", orig_obj->klass()->external_name());
1162     MetaspaceShared::unrecoverable_writing_error();
1163   }
1164 
1165   // java.lang.Class instances cannot be included in an archived object sub-graph. We only support
1166   // them as Klass::_archived_mirror because they need to be specially restored at run time.
1167   //
1168   // If you get an error here, you probably made a change in the JDK library that has added a Class
1169   // object that is referenced (directly or indirectly) by static fields.
1170   if (java_lang_Class::is_instance(orig_obj) && subgraph_info != _default_subgraph_info) {
1171     log_error(cds, heap)("(%d) Unknown java.lang.Class object is in the archived sub-graph", level);
1172     MetaspaceShared::unrecoverable_writing_error();














1173   }

1174 
1175   if (has_been_seen_during_subgraph_recording(orig_obj)) {
1176     // orig_obj has already been archived and traced. Nothing more to do.
1177     return true;
1178   } else {
1179     set_has_been_seen_during_subgraph_recording(orig_obj);
1180   }
1181 
1182   bool already_archived = has_been_archived(orig_obj);
1183   bool record_klasses_only = already_archived;
1184   if (!already_archived) {
1185     ++_num_new_archived_objs;
1186     if (!archive_object(orig_obj)) {
1187       // Skip archiving the sub-graph referenced from the current entry field.
1188       ResourceMark rm;
1189       log_error(cds, heap)(
1190         "Cannot archive the sub-graph referenced from %s object ("
1191         PTR_FORMAT ") size " SIZE_FORMAT ", skipped.",
1192         orig_obj->klass()->external_name(), p2i(orig_obj), orig_obj->size() * HeapWordSize);
1193       if (level == 1) {
1194         // Don't archive a subgraph root that's too big. For archives static fields, that's OK
1195         // as the Java code will take care of initializing this field dynamically.
1196         return false;
1197       } else {
1198         // We don't know how to handle an object that has been archived, but some of its reachable
1199         // objects cannot be archived. Bail out for now. We might need to fix this in the future if
1200         // we have a real use case.
1201         MetaspaceShared::unrecoverable_writing_error();
1202       }
1203     }
1204   }
1205 
1206   Klass *orig_k = orig_obj->klass();
1207   subgraph_info->add_subgraph_object_klass(orig_k);
1208 
1209   WalkOopAndArchiveClosure walker(level, record_klasses_only, subgraph_info, orig_obj);
1210   orig_obj->oop_iterate(&walker);
1211 
1212   check_enum_obj(level + 1, subgraph_info, orig_obj);


1213   return true;
1214 }
1215 
1216 //
1217 // Start from the given static field in a java mirror and archive the
1218 // complete sub-graph of java heap objects that are reached directly
1219 // or indirectly from the starting object by following references.
1220 // Sub-graph archiving restrictions (current):
1221 //
1222 // - All classes of objects in the archived sub-graph (including the
1223 //   entry class) must be boot class only.
1224 // - No java.lang.Class instance (java mirror) can be included inside
1225 //   an archived sub-graph. Mirror can only be the sub-graph entry object.
1226 //
1227 // The Java heap object sub-graph archiving process (see
1228 // WalkOopAndArchiveClosure):
1229 //
1230 // 1) Java object sub-graph archiving starts from a given static field
1231 // within a Class instance (java mirror). If the static field is a
1232 // reference field and points to a non-null java object, proceed to

1310   if (!CompressedOops::is_null(f)) {
1311     verify_subgraph_from(f);
1312   }
1313 }
1314 
1315 void HeapShared::verify_subgraph_from(oop orig_obj) {
1316   if (!has_been_archived(orig_obj)) {
1317     // It's OK for the root of a subgraph to be not archived. See comments in
1318     // archive_reachable_objects_from().
1319     return;
1320   }
1321 
1322   // Verify that all objects reachable from orig_obj are archived.
1323   init_seen_objects_table();
1324   verify_reachable_objects_from(orig_obj);
1325   delete_seen_objects_table();
1326 }
1327 
1328 void HeapShared::verify_reachable_objects_from(oop obj) {
1329   _num_total_verifications ++;




1330   if (!has_been_seen_during_subgraph_recording(obj)) {
1331     set_has_been_seen_during_subgraph_recording(obj);
1332     assert(has_been_archived(obj), "must be");
1333     VerifySharedOopClosure walker;
1334     obj->oop_iterate(&walker);
1335   }
1336 }
1337 #endif
1338 
1339 // The "default subgraph" contains special objects (see heapShared.hpp) that
1340 // can be accessed before we load any Java classes (including java/lang/Class).
1341 // Make sure that these are only instances of the very few specific types
1342 // that we can handle.
1343 void HeapShared::check_default_subgraph_classes() {
1344   GrowableArray<Klass*>* klasses = _default_subgraph_info->subgraph_object_klasses();
1345   int num = klasses->length();

1346   for (int i = 0; i < num; i++) {
1347     Klass* subgraph_k = klasses->at(i);
1348     if (log_is_enabled(Info, cds, heap)) {
1349       ResourceMark rm;
1350       log_info(cds, heap)(
1351           "Archived object klass (default subgraph %d) => %s",
1352           i, subgraph_k->external_name());
1353     }
1354 
1355     guarantee(subgraph_k->name()->equals("java/lang/Class") ||
1356               subgraph_k->name()->equals("java/lang/String") ||
1357               subgraph_k->name()->equals("[Ljava/lang/Object;") ||
1358               subgraph_k->name()->equals("[C") ||
1359               subgraph_k->name()->equals("[B"),
1360               "default subgraph can have only these objects");






1361   }
1362 }
1363 
1364 HeapShared::SeenObjectsTable* HeapShared::_seen_objects_table = nullptr;
1365 int HeapShared::_num_new_walked_objs;
1366 int HeapShared::_num_new_archived_objs;
1367 int HeapShared::_num_old_recorded_klasses;
1368 
1369 int HeapShared::_num_total_subgraph_recordings = 0;
1370 int HeapShared::_num_total_walked_objs = 0;
1371 int HeapShared::_num_total_archived_objs = 0;
1372 int HeapShared::_num_total_recorded_klasses = 0;
1373 int HeapShared::_num_total_verifications = 0;
1374 
1375 bool HeapShared::has_been_seen_during_subgraph_recording(oop obj) {
1376   return _seen_objects_table->get(obj) != nullptr;
1377 }
1378 
1379 void HeapShared::set_has_been_seen_during_subgraph_recording(oop obj) {
1380   assert(!has_been_seen_during_subgraph_recording(obj), "sanity");

1422       if (is_reference_type(fd->field_type())) {
1423         _found = true;
1424         _offset = fd->offset();
1425       }
1426     }
1427   }
1428   bool found()     { return _found;  }
1429   int offset()     { return _offset; }
1430 };
1431 
1432 void HeapShared::init_subgraph_entry_fields(ArchivableStaticFieldInfo fields[],
1433                                             TRAPS) {
1434   for (int i = 0; fields[i].valid(); i++) {
1435     ArchivableStaticFieldInfo* info = &fields[i];
1436     TempNewSymbol klass_name =  SymbolTable::new_symbol(info->klass_name);
1437     TempNewSymbol field_name =  SymbolTable::new_symbol(info->field_name);
1438     ResourceMark rm; // for stringStream::as_string() etc.
1439 
1440 #ifndef PRODUCT
1441     bool is_test_class = (ArchiveHeapTestClass != nullptr) && (strcmp(info->klass_name, ArchiveHeapTestClass) == 0);

1442 #else
1443     bool is_test_class = false;

1444 #endif
1445 
1446     if (is_test_class) {
1447       log_warning(cds)("Loading ArchiveHeapTestClass %s ...", ArchiveHeapTestClass);
1448     }
1449 
1450     Klass* k = SystemDictionary::resolve_or_fail(klass_name, true, THREAD);
1451     if (HAS_PENDING_EXCEPTION) {
1452       CLEAR_PENDING_EXCEPTION;
1453       stringStream st;
1454       st.print("Fail to initialize archive heap: %s cannot be loaded by the boot loader", info->klass_name);
1455       THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), st.as_string());
1456     }
1457 
1458     if (!k->is_instance_klass()) {
1459       stringStream st;
1460       st.print("Fail to initialize archive heap: %s is not an instance class", info->klass_name);
1461       THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), st.as_string());
1462     }
1463 
1464     InstanceKlass* ik = InstanceKlass::cast(k);
1465     assert(InstanceKlass::cast(ik)->is_shared_boot_class(),
1466            "Only support boot classes");
1467 
1468     if (is_test_class) {
1469       if (ik->module()->is_named()) {
1470         // We don't want ArchiveHeapTestClass to be abused to easily load/initialize arbitrary
1471         // core-lib classes. You need to at least append to the bootclasspath.
1472         stringStream st;
1473         st.print("ArchiveHeapTestClass %s is not in unnamed module", ArchiveHeapTestClass);
1474         THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), st.as_string());
1475       }
1476 
1477       if (ik->package() != nullptr) {
1478         // This restriction makes HeapShared::is_a_test_class_in_unnamed_module() easy.
1479         stringStream st;
1480         st.print("ArchiveHeapTestClass %s is not in unnamed package", ArchiveHeapTestClass);
1481         THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), st.as_string());
1482       }
1483     } else {
1484       if (ik->module()->name() != vmSymbols::java_base()) {
1485         // We don't want to deal with cases when a module is unavailable at runtime.
1486         // FUTURE -- load from archived heap only when module graph has not changed
1487         //           between dump and runtime.
1488         stringStream st;
1489         st.print("%s is not in java.base module", info->klass_name);
1490         THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), st.as_string());
1491       }
1492     }
1493 
1494     if (is_test_class) {
1495       log_warning(cds)("Initializing ArchiveHeapTestClass %s ...", ArchiveHeapTestClass);
1496     }
1497     ik->initialize(CHECK);
1498 
1499     ArchivableStaticFieldFinder finder(ik, field_name);
1500     ik->do_local_static_fields(&finder);
1501     if (!finder.found()) {
1502       stringStream st;
1503       st.print("Unable to find the static T_OBJECT field %s::%s", info->klass_name, info->field_name);
1504       THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), st.as_string());
1505     }
1506 
1507     info->klass = ik;
1508     info->offset = finder.offset();
1509   }
1510 }
1511 
1512 void HeapShared::init_subgraph_entry_fields(TRAPS) {
1513   assert(HeapShared::can_write(), "must be");
1514   _dump_time_subgraph_info_table = new (mtClass)DumpTimeKlassSubGraphInfoTable();
1515   init_subgraph_entry_fields(archive_subgraph_entry_fields, CHECK);

1567         // So if we see a '/' character in the class name, it must be in (A);
1568         // otherwise it must be in (B).
1569         if (name->index_of_at(0, "/", 1)  >= 0) {
1570           return false; // (A)
1571         }
1572 
1573         return true; // (B)
1574       }
1575     }
1576   }
1577 
1578   return false;
1579 }
1580 #endif
1581 
1582 void HeapShared::init_for_dumping(TRAPS) {
1583   if (HeapShared::can_write()) {
1584     setup_test_class(ArchiveHeapTestClass);
1585     _dumped_interned_strings = new (mtClass)DumpedInternedStrings();
1586     init_subgraph_entry_fields(CHECK);

1587   }
1588 }
1589 
1590 void HeapShared::archive_object_subgraphs(ArchivableStaticFieldInfo fields[],
1591                                           bool is_full_module_graph) {
1592   _num_total_subgraph_recordings = 0;
1593   _num_total_walked_objs = 0;
1594   _num_total_archived_objs = 0;
1595   _num_total_recorded_klasses = 0;
1596   _num_total_verifications = 0;
1597 
1598   // For each class X that has one or more archived fields:
1599   // [1] Dump the subgraph of each archived field
1600   // [2] Create a list of all the class of the objects that can be reached
1601   //     by any of these static fields.
1602   //     At runtime, these classes are initialized before X's archived fields
1603   //     are restored by HeapShared::initialize_from_archived_subgraph().
1604   int i;
1605   for (int i = 0; fields[i].valid(); ) {
1606     ArchivableStaticFieldInfo* info = &fields[i];
1607     const char* klass_name = info->klass_name;
1608     start_recording_subgraph(info->klass, klass_name, is_full_module_graph);
1609 

1610     // If you have specified consecutive fields of the same klass in
1611     // fields[], these will be archived in the same
1612     // {start_recording_subgraph ... done_recording_subgraph} pass to
1613     // save time.
1614     for (; fields[i].valid(); i++) {
1615       ArchivableStaticFieldInfo* f = &fields[i];
1616       if (f->klass_name != klass_name) {
1617         break;
1618       }
1619 

1620       archive_reachable_objects_from_static_field(f->klass, f->klass_name,
1621                                                   f->offset, f->field_name);
1622     }
1623     done_recording_subgraph(info->klass, klass_name);
1624   }
1625 
1626   log_info(cds, heap)("Archived subgraph records = %d",
1627                       _num_total_subgraph_recordings);
1628   log_info(cds, heap)("  Walked %d objects", _num_total_walked_objs);
1629   log_info(cds, heap)("  Archived %d objects", _num_total_archived_objs);
1630   log_info(cds, heap)("  Recorded %d klasses", _num_total_recorded_klasses);
1631 
1632 #ifndef PRODUCT
1633   for (int i = 0; fields[i].valid(); i++) {
1634     ArchivableStaticFieldInfo* f = &fields[i];
1635     verify_subgraph_from_static_field(f->klass, f->offset);
1636   }
1637   log_info(cds, heap)("  Verified %d references", _num_total_verifications);
1638 #endif
1639 }

  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "cds/archiveBuilder.hpp"
  27 #include "cds/archiveHeapLoader.hpp"
  28 #include "cds/archiveHeapWriter.hpp"
  29 #include "cds/archiveUtils.hpp"
  30 #include "cds/cdsConfig.hpp"
  31 #include "cds/cdsEnumKlass.hpp"
  32 #include "cds/cdsHeapVerifier.hpp"
  33 #include "cds/classPrelinker.hpp"
  34 #include "cds/heapShared.hpp"
  35 #include "cds/metaspaceShared.hpp"
  36 #include "classfile/classLoaderData.hpp"
  37 #include "classfile/javaClasses.inline.hpp"
  38 #include "classfile/modules.hpp"
  39 #include "classfile/stringTable.hpp"
  40 #include "classfile/symbolTable.hpp"
  41 #include "classfile/systemDictionary.hpp"
  42 #include "classfile/systemDictionaryShared.hpp"
  43 #include "classfile/vmClasses.hpp"
  44 #include "classfile/vmSymbols.hpp"
  45 #include "gc/shared/collectedHeap.hpp"
  46 #include "gc/shared/gcLocker.hpp"
  47 #include "gc/shared/gcVMOperations.hpp"
  48 #include "logging/log.hpp"
  49 #include "logging/logStream.hpp"
  50 #include "memory/iterator.inline.hpp"
  51 #include "memory/resourceArea.hpp"
  52 #include "memory/universe.hpp"
  53 #include "oops/compressedOops.inline.hpp"

  67 #include "gc/g1/g1CollectedHeap.hpp"
  68 #endif
  69 
  70 #if INCLUDE_CDS_JAVA_HEAP
  71 
  72 struct ArchivableStaticFieldInfo {
  73   const char* klass_name;
  74   const char* field_name;
  75   InstanceKlass* klass;
  76   int offset;
  77   BasicType type;
  78 
  79   ArchivableStaticFieldInfo(const char* k, const char* f)
  80   : klass_name(k), field_name(f), klass(nullptr), offset(0), type(T_ILLEGAL) {}
  81 
  82   bool valid() {
  83     return klass_name != nullptr;
  84   }
  85 };
  86 
  87 class HeapShared::ArchivingObjectMark : public StackObj {
  88 public:
  89   ArchivingObjectMark(oop obj) {
  90     _trace->push(obj);
  91   }
  92   ~ArchivingObjectMark() {
  93     _trace->pop();
  94   }
  95 };
  96 
  97 class HeapShared::ContextMark : public StackObj {
  98   ResourceMark rm;
  99 public:
 100   ContextMark(const char* c) : rm{} {
 101     _context->push(c);
 102   }
 103   ~ContextMark() {
 104     _context->pop();
 105   }
 106 };
 107 
 108 bool HeapShared::_disable_writing = false;
 109 bool HeapShared::_box_classes_inited = false;
 110 DumpedInternedStrings *HeapShared::_dumped_interned_strings = nullptr;
 111 
 112 size_t HeapShared::_alloc_count[HeapShared::ALLOC_STAT_SLOTS];
 113 size_t HeapShared::_alloc_size[HeapShared::ALLOC_STAT_SLOTS];
 114 size_t HeapShared::_total_obj_count;
 115 size_t HeapShared::_total_obj_size;
 116 
 117 #ifndef PRODUCT
 118 #define ARCHIVE_TEST_FIELD_NAME "archivedObjects"
 119 static Array<char>* _archived_ArchiveHeapTestClass = nullptr;
 120 static const char* _test_class_name = nullptr;
 121 static const Klass* _test_class = nullptr;
 122 static const ArchivedKlassSubGraphInfoRecord* _test_class_record = nullptr;
 123 #endif
 124 
 125 
 126 //
 127 // If you add new entries to the following tables, you should know what you're doing!
 128 //
 129 
 130 static ArchivableStaticFieldInfo archive_subgraph_entry_fields[] = {
 131   {"java/lang/Integer$IntegerCache",              "archivedCache"},
 132   {"java/lang/Long$LongCache",                    "archivedCache"},
 133   {"java/lang/Byte$ByteCache",                    "archivedCache"},
 134   {"java/lang/Short$ShortCache",                  "archivedCache"},
 135   {"java/lang/Character$CharacterCache",          "archivedCache"},
 136   {"java/util/jar/Attributes$Name",               "KNOWN_NAMES"},
 137   {"sun/util/locale/BaseLocale",                  "constantBaseLocales"},
 138   {"jdk/internal/module/ArchivedModuleGraph",     "archivedModuleGraph"},
 139   {"java/util/ImmutableCollections",              "archivedObjects"},
 140   {"java/lang/ModuleLayer",                       "EMPTY_LAYER"},
 141   {"java/lang/module/Configuration",              "EMPTY_CONFIGURATION"},
 142   {"jdk/internal/math/FDBigInteger",              "archivedCaches"},
 143   {"java/lang/invoke/DirectMethodHandle",         "archivedObjects"},
 144   {"java/lang/invoke/MethodType",                 "archivedObjects"},
 145   {"java/lang/invoke/LambdaForm$NamedFunction",   "archivedObjects"},
 146   {"java/lang/reflect/Proxy$ProxyBuilder",        "archivedData"},
 147 #ifndef PRODUCT
 148   {nullptr, nullptr}, // Extra slot for -XX:ArchiveHeapTestClass
 149 #endif
 150   {nullptr, nullptr},
 151 };
 152 
 153 // full module graph
 154 static ArchivableStaticFieldInfo fmg_archive_subgraph_entry_fields[] = {
 155   {"jdk/internal/loader/ArchivedClassLoaders",    "archivedClassLoaders"},
 156   {ARCHIVED_BOOT_LAYER_CLASS,                     ARCHIVED_BOOT_LAYER_FIELD},
 157   {"java/lang/Module$ArchivedData",               "archivedData"},
 158   {nullptr, nullptr},
 159 };
 160 
 161 KlassSubGraphInfo* HeapShared::_default_subgraph_info;
 162 ArchivedKlassSubGraphInfoRecord* HeapShared::_runtime_default_subgraph_info;
 163 GrowableArrayCHeap<oop, mtClassShared>* HeapShared::_pending_roots = nullptr;
 164 GrowableArrayCHeap<oop, mtClassShared>* HeapShared::_trace = nullptr;
 165 GrowableArrayCHeap<const char*, mtClassShared>* HeapShared::_context = nullptr;
 166 OopHandle HeapShared::_roots;
 167 OopHandle HeapShared::_scratch_basic_type_mirrors[T_VOID+1];
 168 
 169 OopHandle HeapShared::_scratch_null_ptr_exception_instance;
 170 OopHandle HeapShared::_scratch_arithmetic_exception_instance;
 171 OopHandle HeapShared::_scratch_virtual_machine_error_instance;
 172 OopHandle HeapShared::_scratch_array_index_oob_exception_instance;
 173 OopHandle HeapShared::_scratch_array_store_exception_instance;
 174 OopHandle HeapShared::_scratch_class_cast_exception_instance;
 175 
 176 MetaspaceObjToOopHandleTable* HeapShared::_scratch_java_mirror_table = nullptr;
 177 MetaspaceObjToOopHandleTable* HeapShared::_scratch_references_table = nullptr;
 178 int HeapShared::_permobj_segments = 0;
 179 
 180 static bool is_subgraph_root_class_of(ArchivableStaticFieldInfo fields[], InstanceKlass* ik) {
 181   for (int i = 0; fields[i].valid(); i++) {
 182     if (fields[i].klass == ik) {
 183       return true;
 184     }
 185   }
 186   return false;
 187 }
 188 
 189 bool HeapShared::is_subgraph_root_class(InstanceKlass* ik) {
 190   return is_subgraph_root_class_of(archive_subgraph_entry_fields, ik) ||
 191          is_subgraph_root_class_of(fmg_archive_subgraph_entry_fields, ik);
 192 }
 193 
 194 unsigned HeapShared::oop_hash(oop const& p) {
 195   // Do not call p->identity_hash() as that will update the
 196   // object header.
 197   return primitive_hash(cast_from_oop<intptr_t>(p));
 198 }

 248 
 249 bool HeapShared::has_been_archived(oop obj) {
 250   assert(CDSConfig::is_dumping_heap(), "dump-time only");
 251   return archived_object_cache()->get(obj) != nullptr;
 252 }
 253 
 254 int HeapShared::append_root(oop obj) {
 255   assert(CDSConfig::is_dumping_heap(), "dump-time only");
 256 
 257   // No GC should happen since we aren't scanning _pending_roots.
 258   assert(Thread::current() == (Thread*)VMThread::vm_thread(), "should be in vm thread");
 259 
 260   if (_pending_roots == nullptr) {
 261     _pending_roots = new GrowableArrayCHeap<oop, mtClassShared>(500);
 262   }
 263 
 264   return _pending_roots->append(obj);
 265 }
 266 
 267 objArrayOop HeapShared::roots() {
 268   if (CDSConfig::is_dumping_heap() && !CDSConfig::is_dumping_final_static_archive()) {
 269     assert(Thread::current() == (Thread*)VMThread::vm_thread(), "should be in vm thread");
 270     if (!HeapShared::can_write()) {
 271       return nullptr;
 272     }
 273   } else {
 274     assert(UseSharedSpaces, "must be");
 275   }
 276 
 277   objArrayOop roots = (objArrayOop)_roots.resolve();
 278   assert(roots != nullptr, "should have been initialized");
 279   return roots;
 280 }
 281 
 282 static unsigned int oop_handle_hash(const OopHandle& oh) {
 283   oop o = oh.resolve();
 284   if (o == nullptr) {
 285     return 0;
 286   } else {
 287     return o->identity_hash();
 288   }
 289 }
 290 
 291 static bool oop_handle_equals(const OopHandle& a, const OopHandle& b) {
 292   return a.resolve() == b.resolve();
 293 }
 294 
 295 class OrigToScratchObjectTable: public ResourceHashtable<OopHandle, OopHandle,
 296     36137, // prime number
 297     AnyObj::C_HEAP,
 298     mtClassShared,
 299     oop_handle_hash,
 300     oop_handle_equals> {};
 301 
 302 static OrigToScratchObjectTable* _orig_to_scratch_object_table = nullptr;
 303 
 304 void HeapShared::track_scratch_object(oop orig_obj, oop scratch_obj) {
 305   MutexLocker ml(ArchivedObjectTables_lock, Mutex::_no_safepoint_check_flag);
 306   if (_orig_to_scratch_object_table == nullptr) {
 307     _orig_to_scratch_object_table = new (mtClass)OrigToScratchObjectTable();
 308   }
 309 
 310   OopHandle orig_h(Universe::vm_global(), orig_obj);
 311   OopHandle scratch_h(Universe::vm_global(), scratch_obj);
 312   _orig_to_scratch_object_table->put_when_absent(orig_h, scratch_h);
 313 }
 314 
 315 oop HeapShared::orig_to_scratch_object(oop orig_obj) {
 316   MutexLocker ml(ArchivedObjectTables_lock, Mutex::_no_safepoint_check_flag);
 317   if (_orig_to_scratch_object_table != nullptr) {
 318     OopHandle orig(&orig_obj);
 319     OopHandle* v = _orig_to_scratch_object_table->get(orig);
 320     if (v != nullptr) {
 321       return v->resolve();
 322     }
 323   }
 324   return nullptr;
 325 }
 326 
 327 class ArchivedObjectPermanentIndexTable: public ResourceHashtable<OopHandle, int,
 328     36137, // prime number
 329     AnyObj::C_HEAP,
 330     mtClassShared,
 331     oop_handle_hash,
 332     oop_handle_equals> {};
 333 
 334 static ArchivedObjectPermanentIndexTable* _permanent_index_table = nullptr;
 335 
 336 void HeapShared::add_to_permanent_index_table(oop obj, int index) {
 337   assert_locked_or_safepoint(ArchivedObjectTables_lock);
 338 
 339   if (_permanent_index_table == nullptr) {
 340     _permanent_index_table = new (mtClass)ArchivedObjectPermanentIndexTable();
 341   }
 342   OopHandle oh(Universe::vm_global(), obj);
 343   _permanent_index_table->put(oh, index);
 344 }
 345 
 346 int HeapShared::get_archived_object_permanent_index(oop obj) {
 347   if (!UsePermanentHeapObjects) {
 348     return -1;
 349   }
 350   if (!CDSConfig::is_dumping_heap() && _permobj_segments <= 0) {
 351     return -1;
 352   }
 353 
 354   MutexLocker ml(ArchivedObjectTables_lock, Mutex::_no_safepoint_check_flag);
 355 
 356   if (!CDSConfig::is_dumping_heap() && _permanent_index_table == nullptr) {
 357     int first_permobj_segment = roots()->length() - _permobj_segments;
 358     for (int i = 0; i < _permobj_segments; i++) {
 359       objArrayOop a = (objArrayOop)roots()->obj_at(i + first_permobj_segment);
 360       for (int j = 0; j < a->length(); j++) {
 361         int index = (i << ArchiveHeapWriter::PERMOBJ_SEGMENT_MAX_SHIFT) + j;
 362         add_to_permanent_index_table(a->obj_at(j), index);
 363       }
 364     }
 365   }
 366 
 367   if (_permanent_index_table != nullptr) {
 368     if (_orig_to_scratch_object_table != nullptr) {
 369       OopHandle orig(&obj);
 370       OopHandle* v = _orig_to_scratch_object_table->get(orig);
 371       if (v != nullptr) {
 372         obj = v->resolve();
 373       }
 374     }
 375     OopHandle tmp(&obj);
 376     int* v = _permanent_index_table->get(tmp);
 377     if (v != nullptr) {
 378       int n = *v;
 379       return n;
 380     }
 381   }
 382 
 383   return -1;
 384 }
 385 
 386 oop HeapShared::get_archived_object(int permanent_index) {
 387   if (ArchiveHeapLoader::is_in_use()) {
 388     assert(_permobj_segments > 0, "must be");
 389 
 390     int first_permobj_segment = roots()->length() - _permobj_segments;
 391     int upper = permanent_index >> ArchiveHeapWriter::PERMOBJ_SEGMENT_MAX_SHIFT;
 392     int lower = permanent_index &  ArchiveHeapWriter::PERMOBJ_SEGMENT_MAX_MASK;
 393     objArrayOop a = (objArrayOop)roots()->obj_at(upper + first_permobj_segment);
 394     return a->obj_at(lower);
 395   } else {
 396     assert(CDSConfig::is_dumping_heap(), "must be");
 397     return ArchiveHeapWriter::get_perm_object_by_index(permanent_index);
 398   }
 399 }
 400 
 401 // Returns an objArray that contains all the roots of the archived objects
 402 oop HeapShared::get_root(int index, bool clear) {
 403   assert(index >= 0, "sanity");
 404   assert(!CDSConfig::is_dumping_heap() && UseSharedSpaces, "runtime only");
 405   assert(!_roots.is_empty(), "must have loaded shared heap");
 406   oop result = roots()->obj_at(index);
 407   if (clear) {
 408     clear_root(index);
 409   }
 410   return result;
 411 }
 412 
 413 void HeapShared::clear_root(int index) {
 414   assert(index >= 0, "sanity");
 415   assert(UseSharedSpaces, "must be");
 416   if (ArchiveHeapLoader::is_in_use()) {
 417     if (log_is_enabled(Debug, cds, heap)) {
 418       oop old = roots()->obj_at(index);
 419       log_debug(cds, heap)("Clearing root %d: was " PTR_FORMAT, index, p2i(old));
 420     }

 475       return nullptr;
 476     }
 477   }
 478   void set_oop(MetaspaceObj* ptr, oop o) {
 479     MutexLocker ml(ScratchObjects_lock, Mutex::_no_safepoint_check_flag);
 480     OopHandle handle(Universe::vm_global(), o);
 481     bool is_new = put(ptr, handle);
 482     assert(is_new, "cannot set twice");
 483   }
 484   void remove_oop(MetaspaceObj* ptr) {
 485     MutexLocker ml(ScratchObjects_lock, Mutex::_no_safepoint_check_flag);
 486     OopHandle* handle = get(ptr);
 487     if (handle != nullptr) {
 488       handle->release(Universe::vm_global());
 489       remove(ptr);
 490     }
 491   }
 492 };
 493 
 494 void HeapShared::add_scratch_resolved_references(ConstantPool* src, objArrayOop dest) {
 495   if (_scratch_references_table == nullptr) {
 496     _scratch_references_table = new (mtClass)MetaspaceObjToOopHandleTable();
 497   }
 498   _scratch_references_table->set_oop(src, dest);
 499 }
 500 
 501 objArrayOop HeapShared::scratch_resolved_references(ConstantPool* src) {
 502   return (objArrayOop)_scratch_references_table->get_oop(src);
 503 }
 504 
 505 void HeapShared::init_scratch_objects(TRAPS) {
 506   for (int i = T_BOOLEAN; i < T_VOID+1; i++) {
 507     BasicType bt = (BasicType)i;
 508     if (!is_reference_type(bt)) {
 509       oop m = java_lang_Class::create_basic_type_mirror(type2name(bt), bt, CHECK);
 510       _scratch_basic_type_mirrors[i] = OopHandle(Universe::vm_global(), m);
 511       track_scratch_object(Universe::java_mirror(bt), m);
 512     }
 513   }
 514   _scratch_java_mirror_table = new (mtClass)MetaspaceObjToOopHandleTable();
 515   if (_scratch_references_table == nullptr) {
 516     _scratch_references_table = new (mtClass)MetaspaceObjToOopHandleTable();
 517   }
 518 }
 519 
 520 OopHandle HeapShared::init_scratch_exception(oop orig_exception_obj, TRAPS) {
 521   Symbol* klass_name = orig_exception_obj->klass()->name();
 522   oop scratch_obj = java_lang_Throwable::create_exception_instance(klass_name, CHECK_(OopHandle()));
 523   track_scratch_object(orig_exception_obj, scratch_obj);
 524   return OopHandle(Universe::vm_global(), scratch_obj);
 525 }
 526 
 527 void HeapShared::init_scratch_exceptions(TRAPS) {
 528   _scratch_null_ptr_exception_instance        = init_scratch_exception(Universe::null_ptr_exception_instance(),        CHECK);
 529   _scratch_arithmetic_exception_instance      = init_scratch_exception(Universe::arithmetic_exception_instance(),      CHECK);
 530   _scratch_virtual_machine_error_instance     = init_scratch_exception(Universe::virtual_machine_error_instance(),     CHECK);
 531   _scratch_array_index_oob_exception_instance = init_scratch_exception(Universe::array_index_oob_exception_instance(), CHECK);
 532   _scratch_array_store_exception_instance     = init_scratch_exception(Universe::array_store_exception_instance(),     CHECK);
 533   _scratch_class_cast_exception_instance      = init_scratch_exception(Universe::class_cast_exception_instance(),      CHECK);
 534 }
 535 // Given java_mirror that represents a (primitive or reference) type T,
 536 // return the "scratch" version that represents the same type T.
 537 // Note that if java_mirror will be returned if it's already a
 538 // scratch mirror.
 539 //
 540 // See java_lang_Class::create_scratch_mirror() for more info.
 541 oop HeapShared::scratch_java_mirror(oop java_mirror) {
 542   assert(java_lang_Class::is_instance(java_mirror), "must be");
 543 
 544   for (int i = T_BOOLEAN; i < T_VOID+1; i++) {
 545     BasicType bt = (BasicType)i;
 546     if (!is_reference_type(bt)) {
 547       if (_scratch_basic_type_mirrors[i].resolve() == java_mirror) {
 548         return java_mirror;
 549       }
 550     }
 551   }
 552 
 553   if (java_lang_Class::is_primitive(java_mirror)) {
 554     return scratch_java_mirror(java_lang_Class::as_BasicType(java_mirror));
 555   } else {
 556     return scratch_java_mirror(java_lang_Class::as_Klass(java_mirror));
 557   }
 558 }
 559 
 560 oop HeapShared::scratch_java_mirror(BasicType t) {
 561   assert((uint)t < T_VOID+1, "range check");
 562   assert(!is_reference_type(t), "sanity");
 563   return _scratch_basic_type_mirrors[t].resolve();
 564 }
 565 
 566 oop HeapShared::scratch_java_mirror(Klass* k) {
 567   return _scratch_java_mirror_table->get_oop(k);
 568 }
 569 
 570 void HeapShared::set_scratch_java_mirror(Klass* k, oop mirror) {
 571   track_scratch_object(k->java_mirror(), mirror);
 572   _scratch_java_mirror_table->set_oop(k, mirror);
 573 }
 574 
 575 void HeapShared::remove_scratch_objects(Klass* k) {
 576   _scratch_java_mirror_table->remove_oop(k);
 577   if (k->is_instance_klass()) {
 578     _scratch_references_table->remove(InstanceKlass::cast(k)->constants());
 579   }
 580 }
 581 
 582 bool HeapShared::is_lambda_form_klass(InstanceKlass* ik) {
 583   return ik->is_hidden() &&
 584     (ik->name()->starts_with("java/lang/invoke/LambdaForm$MH+") ||
 585      ik->name()->starts_with("java/lang/invoke/LambdaForm$DMH+") ||
 586      ik->name()->starts_with("java/lang/invoke/LambdaForm$BMH+"));
 587      
 588 }
 589 
 590 bool HeapShared::is_lambda_proxy_klass(InstanceKlass* ik) {
 591   return ik->is_hidden() && (ik->name()->index_of_at(0, "$$Lambda+", 9) > 0);
 592 }
 593 
 594 bool HeapShared::is_archivable_hidden_klass(InstanceKlass* ik) {
 595   return is_lambda_form_klass(ik) || is_lambda_proxy_klass(ik);
 596 }
 597 
 598 void HeapShared::copy_preinitialized_mirror(Klass* orig_k, oop orig_mirror, oop m) {
 599   if (!orig_k->is_instance_klass()) {
 600     return;
 601   }
 602   InstanceKlass* ik = InstanceKlass::cast(orig_k);
 603 
 604   if (HeapShared::is_archivable_hidden_klass(ik)) {
 605     // We can't rerun the <clinit> method of hidden classes as we don't save
 606     // the classData, so we must archive its mirror in initialized state.
 607     assert(ik->is_initialized(), "must be");
 608   }
 609 
 610   if (!ik->is_initialized() || !ClassPrelinker::can_archive_preinitialized_mirror(ik)) {
 611     return;
 612   }
 613 
 614   int nfields = 0;
 615   for (JavaFieldStream fs(ik); !fs.done(); fs.next()) {
 616     if (fs.access_flags().is_static()) {
 617       fieldDescriptor& fd = fs.field_descriptor();
 618       int offset = fd.offset();
 619       switch (fd.field_type()) {
 620       case T_OBJECT:
 621       case T_ARRAY:
 622         m->obj_field_put(offset, orig_mirror->obj_field(offset));
 623         break;
 624       case T_BOOLEAN:
 625         m->bool_field_put(offset, orig_mirror->bool_field(offset));
 626         break;
 627       case T_BYTE:
 628         m->byte_field_put(offset, orig_mirror->byte_field(offset));
 629         break;
 630       case T_SHORT:
 631         m->short_field_put(offset, orig_mirror->short_field(offset));
 632         break;
 633       case T_CHAR:
 634         m->char_field_put(offset, orig_mirror->char_field(offset));
 635         break;
 636       case T_INT:
 637         m->int_field_put(offset, orig_mirror->int_field(offset));
 638         break;
 639       case T_LONG:
 640         m->long_field_put(offset, orig_mirror->long_field(offset));
 641         break;
 642       case T_FLOAT:
 643         m->float_field_put(offset, orig_mirror->float_field(offset));
 644         break;
 645       case T_DOUBLE:
 646         m->double_field_put(offset, orig_mirror->double_field(offset));
 647         break;
 648       default:
 649         ShouldNotReachHere();
 650       }
 651       nfields ++;
 652     }
 653   }
 654   if (log_is_enabled(Info, cds, init)) {
 655     ResourceMark rm;
 656     log_debug(cds, init)("copied %3d field(s) in preinitialized mirror %s%s", nfields, ik->external_name(),
 657                          ik->is_hidden() ? " (hidden)" : "");
 658   }
 659 
 660   InstanceKlass* buffered_ik = ArchiveBuilder::current()->get_buffered_addr(ik);
 661   buffered_ik->set_has_preinitialized_mirror();
 662 }
 663 
 664 static void copy_java_mirror_hashcode(oop orig_mirror, oop scratch_m) {
 665   int src_hash = orig_mirror->identity_hash();
 666   scratch_m->set_mark(markWord::prototype().copy_set_hash(src_hash));
 667   assert(scratch_m->mark().is_unlocked(), "sanity");
 668 
 669   DEBUG_ONLY(int archived_hash = scratch_m->identity_hash());
 670   assert(src_hash == archived_hash, "Java mirror wrong hash: original %x, scratch %x", src_hash, archived_hash);
 671 }
 672 
 673 void HeapShared::archive_java_mirrors() {
 674   SystemDictionaryShared::reset_preinit_check();
 675 
 676   for (int i = T_BOOLEAN; i < T_VOID+1; i++) {
 677     BasicType bt = (BasicType)i;
 678     if (!is_reference_type(bt)) {
 679       oop orig_mirror = Universe::java_mirror(bt);
 680       oop m = _scratch_basic_type_mirrors[i].resolve();
 681       assert(m != nullptr, "sanity");
 682       copy_java_mirror_hashcode(orig_mirror, m);
 683       bool success = archive_reachable_objects_from(1, _default_subgraph_info, orig_mirror);
 684       assert(success, "sanity");
 685 
 686       log_trace(cds, heap, mirror)(
 687         "Archived %s mirror object from " PTR_FORMAT,
 688         type2name(bt), p2i(m));
 689 
 690       Universe::set_archived_basic_type_mirror_index(bt, append_root(m));
 691     }
 692   }
 693 
 694   GrowableArray<Klass*>* klasses = ArchiveBuilder::current()->klasses();
 695   assert(klasses != nullptr, "sanity");
 696   for (int i = 0; i < klasses->length(); i++) {
 697     Klass* orig_k = klasses->at(i);
 698     oop orig_mirror = orig_k->java_mirror();
 699     oop m = scratch_java_mirror(orig_k);
 700     if (m != nullptr) {
 701       copy_java_mirror_hashcode(orig_mirror, m);
 702       copy_preinitialized_mirror(orig_k, orig_mirror, m);
 703       if (ArchiveReflectionData && java_lang_Class::has_reflection_data(orig_mirror)) {
 704         oop reflection_data = java_lang_Class::reflection_data(orig_mirror);
 705         bool success = archive_reachable_objects_from(1, _default_subgraph_info, reflection_data);
 706         guarantee(success, "");
 707         java_lang_Class::set_reflection_data(m, reflection_data);
 708       }
 709       Klass* buffered_k = ArchiveBuilder::get_buffered_klass(orig_k);
 710       bool success = archive_reachable_objects_from(1, _default_subgraph_info, orig_mirror);
 711       guarantee(success, "scratch mirrors must point to only archivable objects");
 712       buffered_k->set_archived_java_mirror(append_root(m));
 713       ResourceMark rm;
 714       log_trace(cds, heap, mirror)(
 715         "Archived %s mirror object from " PTR_FORMAT,
 716         buffered_k->external_name(), p2i(m));
 717 
 718       // archive the resolved_referenes array
 719       if (buffered_k->is_instance_klass()) {
 720         InstanceKlass* ik = InstanceKlass::cast(buffered_k);
 721         oop rr = ik->constants()->prepare_resolved_references_for_archiving();
 722         if (rr != nullptr && !ArchiveHeapWriter::is_too_large_to_archive(rr)) {
 723           bool success = HeapShared::archive_reachable_objects_from(1, _default_subgraph_info, rr);
 724           assert(success, "must be");
 725           int root_index = append_root(rr);
 726           ik->constants()->cache()->set_archived_references(root_index);
 727         }
 728       }
 729     }
 730   }
 731 }
 732 
 733 void HeapShared::archive_strings() {
 734   oop shared_strings_array = StringTable::init_shared_table(_dumped_interned_strings);
 735   bool success = archive_reachable_objects_from(1, _default_subgraph_info, shared_strings_array);
 736   // We must succeed because:
 737   // - _dumped_interned_strings do not contain any large strings.
 738   // - StringTable::init_shared_table() doesn't create any large arrays.
 739   assert(success, "shared strings array must not point to arrays or strings that are too large to archive");
 740   StringTable::set_shared_strings_array_index(append_root(shared_strings_array));
 741 }
 742 
 743 void HeapShared::archive_exception_instances() {
 744   {
 745     oop m = _scratch_null_ptr_exception_instance.resolve();
 746     bool success = archive_reachable_objects_from(1, _default_subgraph_info, m /*Universe::null_ptr_exception_instance()*/);
 747     assert(success, "sanity");
 748     Universe::set_archived_null_ptr_exception_instance_index(append_root(m));
 749   }
 750   {
 751     oop m = _scratch_arithmetic_exception_instance.resolve();
 752     bool success = archive_reachable_objects_from(1, _default_subgraph_info, m /*Universe::arithmetic_exception_instance()*/);
 753     assert(success, "sanity");
 754     Universe::set_archived_arithmetic_exception_instance_index(append_root(m));
























 755   }
 756   {
 757     oop m = _scratch_virtual_machine_error_instance.resolve();
 758     bool success = archive_reachable_objects_from(1, _default_subgraph_info, m /*Universe::virtual_machine_error_instance()*/);
 759     assert(success, "sanity");
 760     Universe::set_archived_virtual_machine_error_instance_index(append_root(m));


























 761   }
 762   {
 763     oop m = _scratch_array_index_oob_exception_instance.resolve();
 764     bool success = archive_reachable_objects_from(1, _default_subgraph_info, m /*Universe::array_index_oob_exception_instance()*/);
 765     assert(success, "sanity");
 766     Universe::set_archived_array_index_oob_exception_instance_index(append_root(m));

 767   }
 768   {
 769     oop m = _scratch_array_store_exception_instance.resolve();
 770     bool success = archive_reachable_objects_from(1, _default_subgraph_info, m /*Universe::array_store_exception_instance()*/);
 771     assert(success, "sanity");
 772     Universe::set_archived_array_store_exception_instance_index(append_root(m));


 773   }
 774   {
 775     oop m = _scratch_class_cast_exception_instance.resolve();
 776     bool success = archive_reachable_objects_from(1, _default_subgraph_info, m /*Universe::class_cast_exception_instance()*/);
 777     assert(success, "sanity");
 778     Universe::set_archived_class_cast_exception_instance_index(append_root(m));
 779   }
 780 }
 781 
 782 void HeapShared::mark_native_pointers(oop orig_obj) {
 783   if (java_lang_Class::is_instance(orig_obj)) {
 784     ArchiveHeapWriter::mark_native_pointer(orig_obj, java_lang_Class::klass_offset());
 785     ArchiveHeapWriter::mark_native_pointer(orig_obj, java_lang_Class::array_klass_offset());
 786   } else if (java_lang_invoke_ResolvedMethodName::is_instance(orig_obj)) {
 787     ArchiveHeapWriter::mark_native_pointer(orig_obj, java_lang_invoke_ResolvedMethodName::vmtarget_offset());



 788   }

 789 }
 790 
 791 void HeapShared::archive_objects(ArchiveHeapInfo *heap_info) {
 792   {
 793     NoSafepointVerifier nsv;
 794 
 795     _default_subgraph_info = init_subgraph_info(vmClasses::Object_klass(), false);
 796     _trace = new GrowableArrayCHeap<oop, mtClassShared>(250);
 797     _context = new GrowableArrayCHeap<const char*, mtClassShared>(250);
 798 
 799     // Cache for recording where the archived objects are copied to
 800     create_archived_object_cache();
 801 
 802     log_info(cds)("Heap range = [" PTR_FORMAT " - "  PTR_FORMAT "]",
 803                    UseCompressedOops ? p2i(CompressedOops::begin()) :
 804                                        p2i((address)G1CollectedHeap::heap()->reserved().start()),
 805                    UseCompressedOops ? p2i(CompressedOops::end()) :
 806                                        p2i((address)G1CollectedHeap::heap()->reserved().end()));
 807     copy_objects();
 808 
 809     CDSHeapVerifier::verify();
 810     check_default_subgraph_classes();
 811   }
 812 
 813   ArchiveHeapWriter::write(_pending_roots, heap_info);
 814 }
 815 
 816 void HeapShared::copy_interned_strings() {
 817   init_seen_objects_table();
 818 
 819   auto copier = [&] (oop s, bool value_ignored) {
 820     assert(s != nullptr, "sanity");
 821     assert(!ArchiveHeapWriter::is_string_too_large_to_archive(s), "large strings must have been filtered");
 822     bool success = archive_reachable_objects_from(1, _default_subgraph_info, s);
 823     assert(success, "must be");
 824     // Prevent string deduplication from changing the value field to
 825     // something not in the archive.
 826     java_lang_String::set_deduplication_forbidden(s);
 827   };
 828   _dumped_interned_strings->iterate_all(copier);
 829 
 830   delete_seen_objects_table();
 831 }
 832 
 833 void HeapShared::copy_special_objects() {
 834   // Archive special objects that do not belong to any subgraphs
 835   init_seen_objects_table();
 836   archive_java_mirrors();
 837   archive_strings();
 838   archive_exception_instances();
 839   delete_seen_objects_table();
 840 }
 841 
 842 void HeapShared::copy_objects() {
 843   assert(HeapShared::can_write(), "must be");
 844 
 845   copy_interned_strings();
 846   copy_special_objects();
 847 
 848   archive_object_subgraphs(archive_subgraph_entry_fields,
 849                            false /* is_full_module_graph */);
 850 
 851   if (CDSConfig::is_dumping_full_module_graph()) {
 852     archive_object_subgraphs(fmg_archive_subgraph_entry_fields,
 853                              true /* is_full_module_graph */);
 854     Modules::verify_archived_modules();
 855   }
 856 }
 857 
 858 //

 896 // Add the Klass* for an object in the current KlassSubGraphInfo's subgraphs.
 897 // Only objects of boot classes can be included in sub-graph.
 898 void KlassSubGraphInfo::add_subgraph_object_klass(Klass* orig_k) {
 899   assert(CDSConfig::is_dumping_heap(), "dump time only");
 900   Klass* buffered_k = ArchiveBuilder::get_buffered_klass(orig_k);
 901 
 902   if (_subgraph_object_klasses == nullptr) {
 903     _subgraph_object_klasses =
 904       new (mtClass) GrowableArray<Klass*>(50, mtClass);
 905   }
 906 
 907   assert(ArchiveBuilder::current()->is_in_buffer_space(buffered_k), "must be a shared class");
 908 
 909   if (_k == buffered_k) {
 910     // Don't add the Klass containing the sub-graph to it's own klass
 911     // initialization list.
 912     return;
 913   }
 914 
 915   if (buffered_k->is_instance_klass()) {
 916     if (!ArchiveInvokeDynamic) {
 917       // FIXME: this supports Lambda Proxy classes
 918       assert(InstanceKlass::cast(buffered_k)->is_shared_boot_class(),
 919              "must be boot class");
 920     }
 921     // vmClasses::xxx_klass() are not updated, need to check
 922     // the original Klass*
 923     if (orig_k == vmClasses::String_klass() ||
 924         orig_k == vmClasses::Object_klass()) {
 925       // Initialized early during VM initialization. No need to be added
 926       // to the sub-graph object class list.
 927       return;
 928     }
 929     check_allowed_klass(InstanceKlass::cast(orig_k));
 930   } else if (buffered_k->is_objArray_klass()) {
 931     Klass* abk = ObjArrayKlass::cast(buffered_k)->bottom_klass();
 932     if (abk->is_instance_klass()) {
 933       assert(InstanceKlass::cast(abk)->is_shared_boot_class(),
 934             "must be boot class");
 935       check_allowed_klass(InstanceKlass::cast(ObjArrayKlass::cast(orig_k)->bottom_klass()));
 936     }
 937     if (buffered_k == Universe::objectArrayKlassObj()) {
 938       // Initialized early during Universe::genesis. No need to be added
 939       // to the list.
 940       return;
 941     }
 942   } else {
 943     assert(buffered_k->is_typeArray_klass(), "must be");
 944     // Primitive type arrays are created early during Universe::genesis.
 945     return;
 946   }
 947 
 948   if (log_is_enabled(Debug, cds, heap)) {
 949     if (!_subgraph_object_klasses->contains(buffered_k)) {
 950       ResourceMark rm;
 951       log_debug(cds, heap)("Adding klass %s", orig_k->external_name());
 952     }
 953   }
 954 
 955   _subgraph_object_klasses->append_if_missing(buffered_k);
 956   _has_non_early_klasses |= is_non_early_klass(orig_k);
 957 }
 958 
 959 void KlassSubGraphInfo::check_allowed_klass(InstanceKlass* ik) {
 960   if (ArchiveInvokeDynamic) {
 961     // FIXME -- this allows LambdaProxy classes
 962     return;
 963   }
 964   if (ik->module()->name() == vmSymbols::java_base()) {
 965     assert(ik->package() != nullptr, "classes in java.base cannot be in unnamed package");
 966     return;
 967   }
 968 
 969 #ifndef PRODUCT
 970   if (!ik->module()->is_named() && ik->package() == nullptr) {
 971     // This class is loaded by ArchiveHeapTestClass
 972     return;
 973   }
 974   const char* extra_msg = ", or in an unnamed package of an unnamed module";
 975 #else
 976   const char* extra_msg = "";
 977 #endif
 978 
 979   ResourceMark rm;
 980   log_error(cds, heap)("Class %s not allowed in archive heap. Must be in java.base%s",
 981                        ik->external_name(), extra_msg);
 982   MetaspaceShared::unrecoverable_writing_error();
 983 }

1041     _subgraph_object_klasses =
1042       ArchiveBuilder::new_ro_array<Klass*>(num_subgraphs_klasses);
1043     for (int i = 0; i < num_subgraphs_klasses; i++) {
1044       Klass* subgraph_k = subgraph_object_klasses->at(i);
1045       if (log_is_enabled(Info, cds, heap)) {
1046         ResourceMark rm;
1047         log_info(cds, heap)(
1048           "Archived object klass %s (%2d) => %s",
1049           _k->external_name(), i, subgraph_k->external_name());
1050       }
1051       _subgraph_object_klasses->at_put(i, subgraph_k);
1052       ArchivePtrMarker::mark_pointer(_subgraph_object_klasses->adr_at(i));
1053     }
1054   }
1055 
1056   ArchivePtrMarker::mark_pointer(&_k);
1057   ArchivePtrMarker::mark_pointer(&_entry_field_records);
1058   ArchivePtrMarker::mark_pointer(&_subgraph_object_klasses);
1059 }
1060 
1061 class HeapShared::CopyKlassSubGraphInfoToArchive : StackObj {
1062 public:
1063   CompactHashtableWriter* _writer;
1064   CopyKlassSubGraphInfoToArchive(CompactHashtableWriter* writer) : _writer(writer) {}
1065 
1066   bool do_entry(Klass* klass, KlassSubGraphInfo& info) {
1067     if (info.subgraph_object_klasses() != nullptr || info.subgraph_entry_fields() != nullptr) {
1068       ArchivedKlassSubGraphInfoRecord* record = HeapShared::archive_subgraph_info(&info);



1069       Klass* buffered_k = ArchiveBuilder::get_buffered_klass(klass);
1070       unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary((address)buffered_k);
1071       u4 delta = ArchiveBuilder::current()->any_to_offset_u4(record);
1072       _writer->add(hash, delta);
1073     }
1074     return true; // keep on iterating
1075   }
1076 };
1077 
1078 ArchivedKlassSubGraphInfoRecord* HeapShared::archive_subgraph_info(KlassSubGraphInfo* info) {
1079   ArchivedKlassSubGraphInfoRecord* record =
1080       (ArchivedKlassSubGraphInfoRecord*)ArchiveBuilder::ro_region_alloc(sizeof(ArchivedKlassSubGraphInfoRecord));
1081   record->init(info);
1082   return record;
1083 }
1084 
1085 // Build the records of archived subgraph infos, which include:
1086 // - Entry points to all subgraphs from the containing class mirror. The entry
1087 //   points are static fields in the mirror. For each entry point, the field
1088 //   offset, and value are recorded in the sub-graph
1089 //   info. The value is stored back to the corresponding field at runtime.
1090 // - A list of klasses that need to be loaded/initialized before archived
1091 //   java object sub-graph can be accessed at runtime.
1092 void HeapShared::write_subgraph_info_table() {
1093   // Allocate the contents of the hashtable(s) inside the RO region of the CDS archive.
1094   DumpTimeKlassSubGraphInfoTable* d_table = _dump_time_subgraph_info_table;
1095   CompactHashtableStats stats;
1096 
1097   _run_time_subgraph_info_table.reset();
1098 
1099   CompactHashtableWriter writer(d_table->_count, &stats);
1100   CopyKlassSubGraphInfoToArchive copy(&writer);
1101   d_table->iterate(&copy);
1102   writer.dump(&_run_time_subgraph_info_table, "subgraphs");
1103 
1104   _runtime_default_subgraph_info = archive_subgraph_info(_default_subgraph_info);
1105 
1106 #ifndef PRODUCT
1107   if (ArchiveHeapTestClass != nullptr) {
1108     size_t len = strlen(ArchiveHeapTestClass) + 1;
1109     Array<char>* array = ArchiveBuilder::new_ro_array<char>((int)len);
1110     strncpy(array->adr_at(0), ArchiveHeapTestClass, len);
1111     _archived_ArchiveHeapTestClass = array;
1112   }
1113 #endif
1114   if (log_is_enabled(Info, cds, heap)) {
1115     print_stats();
1116   }
1117 }
1118 
1119 void HeapShared::serialize_misc_info(SerializeClosure* soc) {
1120   soc->do_int(&_permobj_segments);
1121 }
1122 
1123 void HeapShared::init_roots(oop roots_oop) {
1124   if (roots_oop != nullptr) {
1125     assert(ArchiveHeapLoader::is_in_use(), "must be");
1126     _roots = OopHandle(Universe::vm_global(), roots_oop);
1127   }
1128 }
1129 
1130 void HeapShared::serialize_tables(SerializeClosure* soc) {
1131 
1132 #ifndef PRODUCT
1133   soc->do_ptr(&_archived_ArchiveHeapTestClass);
1134   if (soc->reading() && _archived_ArchiveHeapTestClass != nullptr) {
1135     _test_class_name = _archived_ArchiveHeapTestClass->adr_at(0);
1136     setup_test_class(_test_class_name);
1137   }
1138 #endif
1139 
1140   _run_time_subgraph_info_table.serialize_header(soc);
1141   soc->do_ptr(&_runtime_default_subgraph_info);
1142 
1143 }
1144 
1145 static void verify_the_heap(Klass* k, const char* which) {
1146   if (VerifyArchivedFields > 0) {
1147     ResourceMark rm;
1148     log_info(cds, heap)("Verify heap %s initializing static field(s) in %s",
1149                         which, k->external_name());
1150 
1151     VM_Verify verify_op;
1152     VMThread::execute(&verify_op);
1153 
1154     if (VerifyArchivedFields > 1 && is_init_completed()) {
1155       // At this time, the oop->klass() of some archived objects in the heap may not
1156       // have been loaded into the system dictionary yet. Nevertheless, oop->klass() should
1157       // have enough information (object size, oop maps, etc) so that a GC can be safely
1158       // performed.
1159       //
1160       // -XX:VerifyArchivedFields=2 force a GC to happen in such an early stage
1161       // to check for GC safety.
1162       log_info(cds, heap)("Trigger GC %s initializing static field(s) in %s",

1190     TempNewSymbol klass_name = SymbolTable::new_symbol(info->klass_name);
1191     InstanceKlass* k = SystemDictionaryShared::find_builtin_class(klass_name);
1192     assert(k != nullptr && k->is_shared_boot_class(), "sanity");
1193     resolve_classes_for_subgraph_of(current, k);
1194   }
1195 }
1196 
1197 void HeapShared::resolve_classes_for_subgraph_of(JavaThread* current, Klass* k) {
1198   JavaThread* THREAD = current;
1199   ExceptionMark em(THREAD);
1200   const ArchivedKlassSubGraphInfoRecord* record =
1201    resolve_or_init_classes_for_subgraph_of(k, /*do_init=*/false, THREAD);
1202   if (HAS_PENDING_EXCEPTION) {
1203    CLEAR_PENDING_EXCEPTION;
1204   }
1205   if (record == nullptr) {
1206    clear_archived_roots_of(k);
1207   }
1208 }
1209 
1210 void HeapShared::initialize_java_lang_invoke(TRAPS) {
1211   if (CDSConfig::is_loading_invokedynamic() || ArchiveInvokeDynamic) {
1212     resolve_or_init("java/lang/invoke/Invokers$Holder", true, CHECK);
1213     resolve_or_init("java/lang/invoke/MethodHandle", true, CHECK);
1214     resolve_or_init("java/lang/invoke/MethodHandleNatives", true, CHECK);
1215     resolve_or_init("java/lang/invoke/DirectMethodHandle$Holder", true, CHECK);
1216     resolve_or_init("java/lang/invoke/DelegatingMethodHandle$Holder", true, CHECK);
1217     resolve_or_init("java/lang/invoke/LambdaForm$Holder", true, CHECK);
1218     resolve_or_init("java/lang/invoke/BoundMethodHandle$Species_L", true, CHECK);
1219   }
1220 }
1221 
1222 void HeapShared::initialize_default_subgraph_classes(Handle loader, TRAPS) {
1223   if (!ArchiveHeapLoader::is_in_use()) {
1224     return;
1225   }
1226 
1227   assert( _runtime_default_subgraph_info != nullptr, "must be");
1228   Array<Klass*>* klasses = _runtime_default_subgraph_info->subgraph_object_klasses();
1229   if (klasses != nullptr) {
1230     for (int pass = 0; pass < 2; pass ++) {
1231       for (int i = 0; i < klasses->length(); i++) {
1232         Klass* k = klasses->at(i);
1233         if (k->class_loader_data() == nullptr) {
1234           // This class is not yet loaded. We will initialize it in a later phase.
1235           continue;
1236         }
1237         if (k->class_loader() == loader()) {
1238           if (pass == 0) {
1239             if (k->is_instance_klass()) {
1240               InstanceKlass::cast(k)->link_class(CHECK);
1241             }
1242           } else {
1243             resolve_or_init(k, /*do_init*/true, CHECK);
1244           }
1245         }
1246       }
1247     }
1248   }
1249 }
1250 
1251 void HeapShared::initialize_from_archived_subgraph(JavaThread* current, Klass* k) {
1252   JavaThread* THREAD = current;
1253   if (!ArchiveHeapLoader::is_in_use()) {
1254     return; // nothing to do
1255   }
1256 
1257   // The subgraphs may reference java_mirrors of the box classes like
1258   // java/lang/Boolean. It may not be necessary, but for sanity, we force
1259   // the box classes to be initialized before any subgraph can be initialized.
1260   assert(_box_classes_inited, "must be");
1261 
1262   ExceptionMark em(THREAD);
1263   const ArchivedKlassSubGraphInfoRecord* record =
1264     resolve_or_init_classes_for_subgraph_of(k, /*do_init=*/true, THREAD);
1265 
1266   if (HAS_PENDING_EXCEPTION) {
1267     CLEAR_PENDING_EXCEPTION;
1268     // None of the field value will be set if there was an exception when initializing the classes.
1269     // The java code will not see any of the archived objects in the
1270     // subgraphs referenced from k in this case.
1271     return;
1272   }
1273 
1274   if (record != nullptr) {
1275     init_archived_fields_for(k, record);
1276   }
1277 }
1278 
1279 const ArchivedKlassSubGraphInfoRecord*
1280 HeapShared::resolve_or_init_classes_for_subgraph_of(Klass* k, bool do_init, TRAPS) {
1281   assert(!CDSConfig::is_dumping_heap(), "Should not be called when dumping heap");

1309         log_info(cds, heap)("subgraph %s cannot be used because full module graph is disabled",
1310                             k->external_name());
1311       }
1312       return nullptr;
1313     }
1314 
1315     if (record->has_non_early_klasses() && JvmtiExport::should_post_class_file_load_hook()) {
1316       if (log_is_enabled(Info, cds, heap)) {
1317         ResourceMark rm(THREAD);
1318         log_info(cds, heap)("subgraph %s cannot be used because JVMTI ClassFileLoadHook is enabled",
1319                             k->external_name());
1320       }
1321       return nullptr;
1322     }
1323 
1324     if (log_is_enabled(Info, cds, heap)) {
1325       ResourceMark rm;
1326       log_info(cds, heap)("%s subgraph %s ", do_init ? "init" : "resolve", k->external_name());
1327     }
1328 
1329     if (do_init && k->name() == vmSymbols::java_lang_invoke_MethodType()) {
1330       // FIXME - hack.
1331       //
1332       // (The real fix would be to archive the MethodType class in its already initialized state. That
1333       //  way we don't need to re-execute the <clinit> methods)
1334       //
1335       // We need to do this to break a cycle in the way the archived subgraphs are restored. Without this block, we
1336       // have the following sequence
1337       //
1338       // MethodType.<clinit>()
1339       //  -> CDS.initializeFromArchive(MethodType.class);
1340       //   -> (this "if" block)
1341       //   -> resolve_or_init("MethodType", ...); // this does nothing because MethodType.<clinit> is already executing
1342       //   -> resolve_or_init("DirectMethodHandle", ...); // this class is in record->subgraph_object_klasses();
1343       //      -> DirectMethodHandle.<clinit>()
1344       //          -> MethodType.methodType()
1345       //             -> MethodType.genericMethodType()
1346       //               -> aaload MethodType.objectOnlyTypes[n]; <<<< here
1347       //
1348       // We need to restore MethodType.objectOnlyTypes here, or else the above aaload will
1349       // get an NPE.
1350       Array<int>* entry_field_records = record->entry_field_records();
1351       assert(entry_field_records != nullptr, "must be");
1352       int efr_len = entry_field_records->length();
1353       assert(efr_len == 2, "must be");
1354       int root_index = entry_field_records->at(1);
1355       oop obj = get_root(root_index, /*clear=*/false);
1356       if (obj != nullptr) {
1357         objArrayOop archivedObjects = objArrayOop(obj);
1358         InstanceKlass* ik = InstanceKlass::cast(k);
1359         oop m = ik->java_mirror();
1360 
1361         {
1362           fieldDescriptor fd;
1363           TempNewSymbol name = SymbolTable::new_symbol("archivedMethodTypes");
1364           TempNewSymbol sig  = SymbolTable::new_symbol("Ljava/util/HashMap;");
1365           Klass* result = ik->find_field(name, sig, true, &fd);
1366           assert(result != nullptr, "must be");
1367           m->obj_field_put(fd.offset(), archivedObjects->obj_at(0));
1368         }
1369 
1370         {
1371           fieldDescriptor fd;
1372           TempNewSymbol name = SymbolTable::new_symbol("objectOnlyTypes");
1373           TempNewSymbol sig  = SymbolTable::new_symbol("[Ljava/lang/invoke/MethodType;");
1374           Klass* result = ik->find_field(name, sig, true, &fd);
1375           assert(result != nullptr, "must be");
1376           m->obj_field_put(fd.offset(), archivedObjects->obj_at(1));
1377         }
1378       }
1379     }
1380 
1381     resolve_or_init(k, do_init, CHECK_NULL);
1382 
1383     // Load/link/initialize the klasses of the objects in the subgraph.
1384     // nullptr class loader is used.
1385     Array<Klass*>* klasses = record->subgraph_object_klasses();
1386     if (klasses != nullptr) {
1387       for (int i = 0; i < klasses->length(); i++) {
1388         Klass* klass = klasses->at(i);
1389         if (!klass->is_shared()) {
1390           return nullptr;
1391         }
1392         resolve_or_init(klass, do_init, CHECK_NULL);
1393       }
1394     }
1395   }
1396 
1397   return record;
1398 }
1399 
1400 void HeapShared::resolve_or_init(const char* klass_name, bool do_init, TRAPS) {
1401   TempNewSymbol klass_name_sym =  SymbolTable::new_symbol(klass_name);
1402   InstanceKlass* k = SystemDictionaryShared::find_builtin_class(klass_name_sym);
1403   if (k == nullptr) {
1404     return;
1405   }
1406   assert(k->is_shared_boot_class(), "sanity");
1407   resolve_or_init(k, false, CHECK);
1408   if (do_init) {
1409     resolve_or_init(k, true, CHECK);
1410   }
1411 }
1412 
1413 void HeapShared::resolve_or_init(Klass* k, bool do_init, TRAPS) {
1414   if (!do_init) {
1415     if (k->class_loader_data() == nullptr) {
1416       Klass* resolved_k = SystemDictionary::resolve_or_null(k->name(), CHECK);
1417       assert(resolved_k == k, "classes used by archived heap must not be replaced by JVMTI ClassFileLoadHook");
1418     }
1419   } else {
1420     assert(k->class_loader_data() != nullptr, "must have been resolved by HeapShared::resolve_classes");
1421     if (k->is_instance_klass()) {
1422       InstanceKlass* ik = InstanceKlass::cast(k);
1423       ik->initialize(CHECK);
1424     } else if (k->is_objArray_klass()) {
1425       ObjArrayKlass* oak = ObjArrayKlass::cast(k);
1426       oak->initialize(CHECK);
1427     }
1428   }
1429 }
1430 
1431 void HeapShared::init_archived_fields_for(Klass* k, const ArchivedKlassSubGraphInfoRecord* record) {
1432   verify_the_heap(k, "before");

1462   unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary_quick(k);
1463   const ArchivedKlassSubGraphInfoRecord* record = _run_time_subgraph_info_table.lookup(k, hash, 0);
1464   if (record != nullptr) {
1465     Array<int>* entry_field_records = record->entry_field_records();
1466     if (entry_field_records != nullptr) {
1467       int efr_len = entry_field_records->length();
1468       assert(efr_len % 2 == 0, "sanity");
1469       for (int i = 0; i < efr_len; i += 2) {
1470         int root_index = entry_field_records->at(i+1);
1471         clear_root(root_index);
1472       }
1473     }
1474   }
1475 }
1476 
1477 class WalkOopAndArchiveClosure: public BasicOopIterateClosure {
1478   int _level;
1479   bool _record_klasses_only;
1480   KlassSubGraphInfo* _subgraph_info;
1481   oop _referencing_obj;

1482   // The following are for maintaining a stack for determining
1483   // CachedOopInfo::_referrer
1484   static WalkOopAndArchiveClosure* _current;
1485   WalkOopAndArchiveClosure* _last;
1486  public:
1487   WalkOopAndArchiveClosure(int level,
1488                            bool record_klasses_only,
1489                            KlassSubGraphInfo* subgraph_info,
1490                            oop orig) :
1491     _level(level),
1492     _record_klasses_only(record_klasses_only),
1493     _subgraph_info(subgraph_info),
1494     _referencing_obj(orig) {
1495     _last = _current;
1496     _current = this;
1497   }
1498   ~WalkOopAndArchiveClosure() {
1499     _current = _last;
1500   }
1501   void do_oop(narrowOop *p) { WalkOopAndArchiveClosure::do_oop_work(p); }
1502   void do_oop(      oop *p) { WalkOopAndArchiveClosure::do_oop_work(p); }
1503 
1504  protected:
1505   template <class T> void do_oop_work(T *p) {
1506     oop obj = RawAccess<>::oop_load(p);
1507     if (!CompressedOops::is_null(obj)) {
1508       size_t field_delta = pointer_delta(p, _referencing_obj, sizeof(char));

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




1616   if (java_lang_Class::is_instance(orig_obj) && subgraph_info != _default_subgraph_info) {
1617     if (can_mirror_be_used_in_subgraph(orig_obj)) {
1618       orig_obj = scratch_java_mirror(orig_obj);
1619       assert(orig_obj != nullptr, "must be archived");
1620     } else {
1621       // Don't follow the fields -- they will be nulled out when the mirror was copied
1622 
1623       // FIXME - we should preserve the static fields of LambdaForm classes (and other hidden classes?)
1624       // so we need to walk the oop fields.
1625       orig_obj = scratch_java_mirror(orig_obj);
1626       assert(orig_obj != nullptr, "must be archived");
1627     }
1628   }
1629 #else
1630   if (java_lang_Class::is_instance(orig_obj)) {
1631     orig_obj = scratch_java_mirror(orig_obj);
1632     assert(orig_obj != nullptr, "must be archived");
1633   }
1634 #endif
1635 
1636   if (has_been_seen_during_subgraph_recording(orig_obj)) {
1637     // orig_obj has already been archived and traced. Nothing more to do.
1638     return true;
1639   } else {
1640     set_has_been_seen_during_subgraph_recording(orig_obj);
1641   }
1642 
1643   bool already_archived = has_been_archived(orig_obj);
1644   bool record_klasses_only = already_archived;
1645   if (!already_archived) {
1646     ++_num_new_archived_objs;
1647     if (!archive_object(orig_obj)) {
1648       // Skip archiving the sub-graph referenced from the current entry field.
1649       ResourceMark rm;
1650       log_error(cds, heap)(
1651         "Cannot archive the sub-graph referenced from %s object ("
1652         PTR_FORMAT ") size " SIZE_FORMAT ", skipped.",
1653         orig_obj->klass()->external_name(), p2i(orig_obj), orig_obj->size() * HeapWordSize);
1654       if (level == 1) {
1655         // Don't archive a subgraph root that's too big. For archives static fields, that's OK
1656         // as the Java code will take care of initializing this field dynamically.
1657         return false;
1658       } else {
1659         // We don't know how to handle an object that has been archived, but some of its reachable
1660         // objects cannot be archived. Bail out for now. We might need to fix this in the future if
1661         // we have a real use case.
1662         exit_on_error();
1663       }
1664     }
1665   }
1666 
1667   Klass *orig_k = orig_obj->klass();
1668   subgraph_info->add_subgraph_object_klass(orig_k);
1669 
1670   WalkOopAndArchiveClosure walker(level, record_klasses_only, subgraph_info, orig_obj);
1671   orig_obj->oop_iterate(&walker);
1672 
1673   if (CDSEnumKlass::is_enum_obj(orig_obj)) {
1674     CDSEnumKlass::handle_enum_obj(level + 1, subgraph_info, orig_obj);
1675   }
1676   return true;
1677 }
1678 
1679 //
1680 // Start from the given static field in a java mirror and archive the
1681 // complete sub-graph of java heap objects that are reached directly
1682 // or indirectly from the starting object by following references.
1683 // Sub-graph archiving restrictions (current):
1684 //
1685 // - All classes of objects in the archived sub-graph (including the
1686 //   entry class) must be boot class only.
1687 // - No java.lang.Class instance (java mirror) can be included inside
1688 //   an archived sub-graph. Mirror can only be the sub-graph entry object.
1689 //
1690 // The Java heap object sub-graph archiving process (see
1691 // WalkOopAndArchiveClosure):
1692 //
1693 // 1) Java object sub-graph archiving starts from a given static field
1694 // within a Class instance (java mirror). If the static field is a
1695 // reference field and points to a non-null java object, proceed to

1773   if (!CompressedOops::is_null(f)) {
1774     verify_subgraph_from(f);
1775   }
1776 }
1777 
1778 void HeapShared::verify_subgraph_from(oop orig_obj) {
1779   if (!has_been_archived(orig_obj)) {
1780     // It's OK for the root of a subgraph to be not archived. See comments in
1781     // archive_reachable_objects_from().
1782     return;
1783   }
1784 
1785   // Verify that all objects reachable from orig_obj are archived.
1786   init_seen_objects_table();
1787   verify_reachable_objects_from(orig_obj);
1788   delete_seen_objects_table();
1789 }
1790 
1791 void HeapShared::verify_reachable_objects_from(oop obj) {
1792   _num_total_verifications ++;
1793   if (java_lang_Class::is_instance(obj)) {
1794     obj = scratch_java_mirror(obj);
1795     assert(obj != nullptr, "must be");
1796   }
1797   if (!has_been_seen_during_subgraph_recording(obj)) {
1798     set_has_been_seen_during_subgraph_recording(obj);
1799     assert(has_been_archived(obj), "must be");
1800     VerifySharedOopClosure walker;
1801     obj->oop_iterate(&walker);
1802   }
1803 }
1804 #endif
1805 
1806 // The "default subgraph" contains special objects (see heapShared.hpp) that
1807 // can be accessed before we load any Java classes (including java/lang/Class).
1808 // Make sure that these are only instances of the very few specific types
1809 // that we can handle.
1810 void HeapShared::check_default_subgraph_classes() {
1811   GrowableArray<Klass*>* klasses = _default_subgraph_info->subgraph_object_klasses();
1812   int num = klasses->length();
1813   int warned = 0;
1814   for (int i = 0; i < num; i++) {
1815     Klass* subgraph_k = klasses->at(i);
1816     if (log_is_enabled(Info, cds, heap)) {
1817       ResourceMark rm;
1818       log_info(cds, heap)(
1819           "Archived object klass (default subgraph %d) => %s",
1820           i, subgraph_k->external_name());
1821     }
1822 
1823     if (subgraph_k->is_instance_klass()) {
1824       InstanceKlass* ik = InstanceKlass::cast(subgraph_k);
1825       Symbol* name = ik->name();
1826       if (!name->equals("java/lang/Class") &&
1827           !name->equals("java/lang/String") &&
1828           !is_archivable_hidden_klass(ik)) {
1829         ResourceMark rm;
1830         const char* category = ArchiveUtils::class_category(ik);
1831         log_info(cds)("TODO: Archived unusual klass (default subgraph %2d) => %-5s %s",
1832                       ++warned, category, ik->external_name());
1833       }
1834     }
1835   }
1836 }
1837 
1838 HeapShared::SeenObjectsTable* HeapShared::_seen_objects_table = nullptr;
1839 int HeapShared::_num_new_walked_objs;
1840 int HeapShared::_num_new_archived_objs;
1841 int HeapShared::_num_old_recorded_klasses;
1842 
1843 int HeapShared::_num_total_subgraph_recordings = 0;
1844 int HeapShared::_num_total_walked_objs = 0;
1845 int HeapShared::_num_total_archived_objs = 0;
1846 int HeapShared::_num_total_recorded_klasses = 0;
1847 int HeapShared::_num_total_verifications = 0;
1848 
1849 bool HeapShared::has_been_seen_during_subgraph_recording(oop obj) {
1850   return _seen_objects_table->get(obj) != nullptr;
1851 }
1852 
1853 void HeapShared::set_has_been_seen_during_subgraph_recording(oop obj) {
1854   assert(!has_been_seen_during_subgraph_recording(obj), "sanity");

1896       if (is_reference_type(fd->field_type())) {
1897         _found = true;
1898         _offset = fd->offset();
1899       }
1900     }
1901   }
1902   bool found()     { return _found;  }
1903   int offset()     { return _offset; }
1904 };
1905 
1906 void HeapShared::init_subgraph_entry_fields(ArchivableStaticFieldInfo fields[],
1907                                             TRAPS) {
1908   for (int i = 0; fields[i].valid(); i++) {
1909     ArchivableStaticFieldInfo* info = &fields[i];
1910     TempNewSymbol klass_name =  SymbolTable::new_symbol(info->klass_name);
1911     TempNewSymbol field_name =  SymbolTable::new_symbol(info->field_name);
1912     ResourceMark rm; // for stringStream::as_string() etc.
1913 
1914 #ifndef PRODUCT
1915     bool is_test_class = (ArchiveHeapTestClass != nullptr) && (strcmp(info->klass_name, ArchiveHeapTestClass) == 0);
1916     const char* test_class_name = ArchiveHeapTestClass;
1917 #else
1918     bool is_test_class = false;
1919     const char* test_class_name = "";
1920 #endif
1921 
1922     if (is_test_class) {
1923       log_warning(cds)("Loading ArchiveHeapTestClass %s ...", test_class_name);
1924     }
1925 
1926     Klass* k = SystemDictionary::resolve_or_fail(klass_name, true, THREAD);
1927     if (HAS_PENDING_EXCEPTION) {
1928       CLEAR_PENDING_EXCEPTION;
1929       stringStream st;
1930       st.print("Fail to initialize archive heap: %s cannot be loaded by the boot loader", info->klass_name);
1931       THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), st.as_string());
1932     }
1933 
1934     if (!k->is_instance_klass()) {
1935       stringStream st;
1936       st.print("Fail to initialize archive heap: %s is not an instance class", info->klass_name);
1937       THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), st.as_string());
1938     }
1939 
1940     InstanceKlass* ik = InstanceKlass::cast(k);
1941     assert(InstanceKlass::cast(ik)->is_shared_boot_class(),
1942            "Only support boot classes");
1943 
1944     if (is_test_class) {
1945       if (ik->module()->is_named()) {
1946         // We don't want ArchiveHeapTestClass to be abused to easily load/initialize arbitrary
1947         // core-lib classes. You need to at least append to the bootclasspath.
1948         stringStream st;
1949         st.print("ArchiveHeapTestClass %s is not in unnamed module", test_class_name);
1950         THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), st.as_string());
1951       }
1952 
1953       if (ik->package() != nullptr) {
1954         // This restriction makes HeapShared::is_a_test_class_in_unnamed_module() easy.
1955         stringStream st;
1956         st.print("ArchiveHeapTestClass %s is not in unnamed package", test_class_name);
1957         THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), st.as_string());
1958       }
1959     } else {
1960       if (ik->module()->name() != vmSymbols::java_base()) {
1961         // We don't want to deal with cases when a module is unavailable at runtime.
1962         // FUTURE -- load from archived heap only when module graph has not changed
1963         //           between dump and runtime.
1964         stringStream st;
1965         st.print("%s is not in java.base module", info->klass_name);
1966         THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), st.as_string());
1967       }
1968     }
1969 
1970     if (is_test_class) {
1971       log_warning(cds)("Initializing ArchiveHeapTestClass %s ...", test_class_name);
1972     }
1973     ik->initialize(CHECK);
1974 
1975     ArchivableStaticFieldFinder finder(ik, field_name);
1976     ik->do_local_static_fields(&finder);
1977     if (!finder.found()) {
1978       stringStream st;
1979       st.print("Unable to find the static T_OBJECT field %s::%s", info->klass_name, info->field_name);
1980       THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), st.as_string());
1981     }
1982 
1983     info->klass = ik;
1984     info->offset = finder.offset();
1985   }
1986 }
1987 
1988 void HeapShared::init_subgraph_entry_fields(TRAPS) {
1989   assert(HeapShared::can_write(), "must be");
1990   _dump_time_subgraph_info_table = new (mtClass)DumpTimeKlassSubGraphInfoTable();
1991   init_subgraph_entry_fields(archive_subgraph_entry_fields, CHECK);

2043         // So if we see a '/' character in the class name, it must be in (A);
2044         // otherwise it must be in (B).
2045         if (name->index_of_at(0, "/", 1)  >= 0) {
2046           return false; // (A)
2047         }
2048 
2049         return true; // (B)
2050       }
2051     }
2052   }
2053 
2054   return false;
2055 }
2056 #endif
2057 
2058 void HeapShared::init_for_dumping(TRAPS) {
2059   if (HeapShared::can_write()) {
2060     setup_test_class(ArchiveHeapTestClass);
2061     _dumped_interned_strings = new (mtClass)DumpedInternedStrings();
2062     init_subgraph_entry_fields(CHECK);
2063     init_scratch_exceptions(CHECK);
2064   }
2065 }
2066 
2067 void HeapShared::archive_object_subgraphs(ArchivableStaticFieldInfo fields[],
2068                                           bool is_full_module_graph) {
2069   _num_total_subgraph_recordings = 0;
2070   _num_total_walked_objs = 0;
2071   _num_total_archived_objs = 0;
2072   _num_total_recorded_klasses = 0;
2073   _num_total_verifications = 0;
2074 
2075   // For each class X that has one or more archived fields:
2076   // [1] Dump the subgraph of each archived field
2077   // [2] Create a list of all the class of the objects that can be reached
2078   //     by any of these static fields.
2079   //     At runtime, these classes are initialized before X's archived fields
2080   //     are restored by HeapShared::initialize_from_archived_subgraph().
2081   int i;
2082   for (int i = 0; fields[i].valid(); ) {
2083     ArchivableStaticFieldInfo* info = &fields[i];
2084     const char* klass_name = info->klass_name;
2085     start_recording_subgraph(info->klass, klass_name, is_full_module_graph);
2086 
2087     ContextMark cm(klass_name);
2088     // If you have specified consecutive fields of the same klass in
2089     // fields[], these will be archived in the same
2090     // {start_recording_subgraph ... done_recording_subgraph} pass to
2091     // save time.
2092     for (; fields[i].valid(); i++) {
2093       ArchivableStaticFieldInfo* f = &fields[i];
2094       if (f->klass_name != klass_name) {
2095         break;
2096       }
2097 
2098       ContextMark cm(f->field_name);
2099       archive_reachable_objects_from_static_field(f->klass, f->klass_name,
2100                                                   f->offset, f->field_name);
2101     }
2102     done_recording_subgraph(info->klass, klass_name);
2103   }
2104 
2105   log_info(cds, heap)("Archived subgraph records = %d",
2106                       _num_total_subgraph_recordings);
2107   log_info(cds, heap)("  Walked %d objects", _num_total_walked_objs);
2108   log_info(cds, heap)("  Archived %d objects", _num_total_archived_objs);
2109   log_info(cds, heap)("  Recorded %d klasses", _num_total_recorded_klasses);
2110 
2111 #ifndef PRODUCT
2112   for (int i = 0; fields[i].valid(); i++) {
2113     ArchivableStaticFieldInfo* f = &fields[i];
2114     verify_subgraph_from_static_field(f->klass, f->offset);
2115   }
2116   log_info(cds, heap)("  Verified %d references", _num_total_verifications);
2117 #endif
2118 }
< prev index next >