Path: blob/master/src/hotspot/share/cds/heapShared.cpp
41144 views
/*1* Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*22*/2324#include "precompiled.hpp"25#include "cds/archiveBuilder.hpp"26#include "cds/archiveUtils.hpp"27#include "cds/filemap.hpp"28#include "cds/heapShared.inline.hpp"29#include "cds/metaspaceShared.hpp"30#include "classfile/classLoaderData.hpp"31#include "classfile/classLoaderDataShared.hpp"32#include "classfile/javaClasses.inline.hpp"33#include "classfile/moduleEntry.hpp"34#include "classfile/stringTable.hpp"35#include "classfile/symbolTable.hpp"36#include "classfile/systemDictionary.hpp"37#include "classfile/systemDictionaryShared.hpp"38#include "classfile/vmClasses.hpp"39#include "classfile/vmSymbols.hpp"40#include "gc/shared/gcLocker.hpp"41#include "gc/shared/gcVMOperations.hpp"42#include "logging/log.hpp"43#include "logging/logMessage.hpp"44#include "logging/logStream.hpp"45#include "memory/iterator.inline.hpp"46#include "memory/metadataFactory.hpp"47#include "memory/metaspaceClosure.hpp"48#include "memory/resourceArea.hpp"49#include "memory/universe.hpp"50#include "oops/compressedOops.inline.hpp"51#include "oops/fieldStreams.inline.hpp"52#include "oops/objArrayOop.hpp"53#include "oops/oop.inline.hpp"54#include "prims/jvmtiExport.hpp"55#include "runtime/fieldDescriptor.inline.hpp"56#include "runtime/globals_extension.hpp"57#include "runtime/init.hpp"58#include "runtime/java.hpp"59#include "runtime/javaCalls.hpp"60#include "runtime/safepointVerifiers.hpp"61#include "utilities/bitMap.inline.hpp"62#include "utilities/copy.hpp"63#if INCLUDE_G1GC64#include "gc/g1/g1CollectedHeap.hpp"65#endif6667#if INCLUDE_CDS_JAVA_HEAP6869bool HeapShared::_closed_archive_heap_region_mapped = false;70bool HeapShared::_open_archive_heap_region_mapped = false;71bool HeapShared::_archive_heap_region_fixed = false;72address HeapShared::_narrow_oop_base;73int HeapShared::_narrow_oop_shift;74DumpedInternedStrings *HeapShared::_dumped_interned_strings = NULL;7576//77// If you add new entries to the following tables, you should know what you're doing!78//7980// Entry fields for shareable subgraphs archived in the closed archive heap81// region. Warning: Objects in the subgraphs should not have reference fields82// assigned at runtime.83static ArchivableStaticFieldInfo closed_archive_subgraph_entry_fields[] = {84{"java/lang/Integer$IntegerCache", "archivedCache"},85{"java/lang/Long$LongCache", "archivedCache"},86{"java/lang/Byte$ByteCache", "archivedCache"},87{"java/lang/Short$ShortCache", "archivedCache"},88{"java/lang/Character$CharacterCache", "archivedCache"},89{"java/util/jar/Attributes$Name", "KNOWN_NAMES"},90{"sun/util/locale/BaseLocale", "constantBaseLocales"},91};92// Entry fields for subgraphs archived in the open archive heap region.93static ArchivableStaticFieldInfo open_archive_subgraph_entry_fields[] = {94{"jdk/internal/module/ArchivedModuleGraph", "archivedModuleGraph"},95{"java/util/ImmutableCollections", "archivedObjects"},96{"java/lang/ModuleLayer", "EMPTY_LAYER"},97{"java/lang/module/Configuration", "EMPTY_CONFIGURATION"},98{"jdk/internal/math/FDBigInteger", "archivedCaches"},99};100101// Entry fields for subgraphs archived in the open archive heap region (full module graph).102static ArchivableStaticFieldInfo fmg_open_archive_subgraph_entry_fields[] = {103{"jdk/internal/loader/ArchivedClassLoaders", "archivedClassLoaders"},104{"jdk/internal/module/ArchivedBootLayer", "archivedBootLayer"},105{"java/lang/Module$ArchivedData", "archivedData"},106};107108const static int num_closed_archive_subgraph_entry_fields =109sizeof(closed_archive_subgraph_entry_fields) / sizeof(ArchivableStaticFieldInfo);110const static int num_open_archive_subgraph_entry_fields =111sizeof(open_archive_subgraph_entry_fields) / sizeof(ArchivableStaticFieldInfo);112const static int num_fmg_open_archive_subgraph_entry_fields =113sizeof(fmg_open_archive_subgraph_entry_fields) / sizeof(ArchivableStaticFieldInfo);114115GrowableArrayCHeap<oop, mtClassShared>* HeapShared::_pending_roots = NULL;116narrowOop HeapShared::_roots_narrow;117OopHandle HeapShared::_roots;118119////////////////////////////////////////////////////////////////120//121// Java heap object archiving support122//123////////////////////////////////////////////////////////////////124void HeapShared::fixup_mapped_heap_regions() {125FileMapInfo *mapinfo = FileMapInfo::current_info();126mapinfo->fixup_mapped_heap_regions();127set_archive_heap_region_fixed();128if (is_mapped()) {129_roots = OopHandle(Universe::vm_global(), decode_from_archive(_roots_narrow));130if (!MetaspaceShared::use_full_module_graph()) {131// Need to remove all the archived java.lang.Module objects from HeapShared::roots().132ClassLoaderDataShared::clear_archived_oops();133}134}135SystemDictionaryShared::update_archived_mirror_native_pointers();136}137138unsigned HeapShared::oop_hash(oop const& p) {139assert(!p->mark().has_bias_pattern(),140"this object should never have been locked"); // so identity_hash won't safepoin141unsigned hash = (unsigned)p->identity_hash();142return hash;143}144145static void reset_states(oop obj, TRAPS) {146Handle h_obj(THREAD, obj);147InstanceKlass* klass = InstanceKlass::cast(obj->klass());148TempNewSymbol method_name = SymbolTable::new_symbol("resetArchivedStates");149Symbol* method_sig = vmSymbols::void_method_signature();150151while (klass != NULL) {152Method* method = klass->find_method(method_name, method_sig);153if (method != NULL) {154assert(method->is_private(), "must be");155if (log_is_enabled(Debug, cds)) {156ResourceMark rm(THREAD);157log_debug(cds)(" calling %s", method->name_and_sig_as_C_string());158}159JavaValue result(T_VOID);160JavaCalls::call_special(&result, h_obj, klass,161method_name, method_sig, CHECK);162}163klass = klass->java_super();164}165}166167void HeapShared::reset_archived_object_states(TRAPS) {168assert(DumpSharedSpaces, "dump-time only");169log_debug(cds)("Resetting platform loader");170reset_states(SystemDictionary::java_platform_loader(), CHECK);171log_debug(cds)("Resetting system loader");172reset_states(SystemDictionary::java_system_loader(), CHECK);173}174175HeapShared::ArchivedObjectCache* HeapShared::_archived_object_cache = NULL;176oop HeapShared::find_archived_heap_object(oop obj) {177assert(DumpSharedSpaces, "dump-time only");178ArchivedObjectCache* cache = archived_object_cache();179oop* p = cache->get(obj);180if (p != NULL) {181return *p;182} else {183return NULL;184}185}186187int HeapShared::append_root(oop obj) {188assert(DumpSharedSpaces, "dump-time only");189190// No GC should happen since we aren't scanning _pending_roots.191assert(Thread::current() == (Thread*)VMThread::vm_thread(), "should be in vm thread");192193if (_pending_roots == NULL) {194_pending_roots = new GrowableArrayCHeap<oop, mtClassShared>(500);195}196197return _pending_roots->append(obj);198}199200objArrayOop HeapShared::roots() {201if (DumpSharedSpaces) {202assert(Thread::current() == (Thread*)VMThread::vm_thread(), "should be in vm thread");203if (!is_heap_object_archiving_allowed()) {204return NULL;205}206} else {207assert(UseSharedSpaces, "must be");208}209210objArrayOop roots = (objArrayOop)_roots.resolve();211assert(roots != NULL, "should have been initialized");212return roots;213}214215void HeapShared::set_roots(narrowOop roots) {216assert(UseSharedSpaces, "runtime only");217assert(open_archive_heap_region_mapped(), "must be");218_roots_narrow = roots;219}220221// Returns an objArray that contains all the roots of the archived objects222oop HeapShared::get_root(int index, bool clear) {223assert(index >= 0, "sanity");224if (DumpSharedSpaces) {225assert(Thread::current() == (Thread*)VMThread::vm_thread(), "should be in vm thread");226assert(_pending_roots != NULL, "sanity");227return _pending_roots->at(index);228} else {229assert(UseSharedSpaces, "must be");230assert(!_roots.is_empty(), "must have loaded shared heap");231oop result = roots()->obj_at(index);232if (clear) {233clear_root(index);234}235return result;236}237}238239void HeapShared::clear_root(int index) {240assert(index >= 0, "sanity");241assert(UseSharedSpaces, "must be");242if (open_archive_heap_region_mapped()) {243if (log_is_enabled(Debug, cds, heap)) {244oop old = roots()->obj_at(index);245log_debug(cds, heap)("Clearing root %d: was " PTR_FORMAT, index, p2i(old));246}247roots()->obj_at_put(index, NULL);248}249}250251oop HeapShared::archive_heap_object(oop obj) {252assert(DumpSharedSpaces, "dump-time only");253254oop ao = find_archived_heap_object(obj);255if (ao != NULL) {256// already archived257return ao;258}259260int len = obj->size();261if (G1CollectedHeap::heap()->is_archive_alloc_too_large(len)) {262log_debug(cds, heap)("Cannot archive, object (" PTR_FORMAT ") is too large: " SIZE_FORMAT,263p2i(obj), (size_t)obj->size());264return NULL;265}266267oop archived_oop = cast_to_oop(G1CollectedHeap::heap()->archive_mem_allocate(len));268if (archived_oop != NULL) {269Copy::aligned_disjoint_words(cast_from_oop<HeapWord*>(obj), cast_from_oop<HeapWord*>(archived_oop), len);270// Reinitialize markword to remove age/marking/locking/etc.271//272// We need to retain the identity_hash, because it may have been used by some hashtables273// in the shared heap. This also has the side effect of pre-initializing the274// identity_hash for all shared objects, so they are less likely to be written275// into during run time, increasing the potential of memory sharing.276int hash_original = obj->identity_hash();277archived_oop->set_mark(markWord::prototype().copy_set_hash(hash_original));278assert(archived_oop->mark().is_unlocked(), "sanity");279280DEBUG_ONLY(int hash_archived = archived_oop->identity_hash());281assert(hash_original == hash_archived, "Different hash codes: original %x, archived %x", hash_original, hash_archived);282283ArchivedObjectCache* cache = archived_object_cache();284cache->put(obj, archived_oop);285if (log_is_enabled(Debug, cds, heap)) {286ResourceMark rm;287log_debug(cds, heap)("Archived heap object " PTR_FORMAT " ==> " PTR_FORMAT " : %s",288p2i(obj), p2i(archived_oop), obj->klass()->external_name());289}290} else {291log_error(cds, heap)(292"Cannot allocate space for object " PTR_FORMAT " in archived heap region",293p2i(obj));294vm_direct_exit(-1,295err_msg("Out of memory. Please run with a larger Java heap, current MaxHeapSize = "296SIZE_FORMAT "M", MaxHeapSize/M));297}298return archived_oop;299}300301void HeapShared::archive_klass_objects() {302GrowableArray<Klass*>* klasses = ArchiveBuilder::current()->klasses();303assert(klasses != NULL, "sanity");304for (int i = 0; i < klasses->length(); i++) {305Klass* k = ArchiveBuilder::get_relocated_klass(klasses->at(i));306307// archive mirror object308java_lang_Class::archive_mirror(k);309310// archive the resolved_referenes array311if (k->is_instance_klass()) {312InstanceKlass* ik = InstanceKlass::cast(k);313ik->constants()->archive_resolved_references();314}315}316}317318void HeapShared::run_full_gc_in_vm_thread() {319if (is_heap_object_archiving_allowed()) {320// Avoid fragmentation while archiving heap objects.321// We do this inside a safepoint, so that no further allocation can happen after GC322// has finished.323if (GCLocker::is_active()) {324// Just checking for safety ...325// This should not happen during -Xshare:dump. If you see this, probably the Java core lib326// has been modified such that JNI code is executed in some clean up threads after327// we have finished class loading.328log_warning(cds)("GC locker is held, unable to start extra compacting GC. This may produce suboptimal results.");329} else {330log_info(cds)("Run GC ...");331Universe::heap()->collect_as_vm_thread(GCCause::_archive_time_gc);332log_info(cds)("Run GC done");333}334}335}336337void HeapShared::archive_java_heap_objects(GrowableArray<MemRegion>* closed,338GrowableArray<MemRegion>* open) {339340G1HeapVerifier::verify_ready_for_archiving();341342{343NoSafepointVerifier nsv;344345// Cache for recording where the archived objects are copied to346create_archived_object_cache();347348log_info(cds)("Heap range = [" PTR_FORMAT " - " PTR_FORMAT "]",349p2i(CompressedOops::begin()), p2i(CompressedOops::end()));350log_info(cds)("Dumping objects to closed archive heap region ...");351copy_closed_archive_heap_objects(closed);352353log_info(cds)("Dumping objects to open archive heap region ...");354copy_open_archive_heap_objects(open);355356destroy_archived_object_cache();357}358359G1HeapVerifier::verify_archive_regions();360}361362void HeapShared::copy_closed_archive_heap_objects(363GrowableArray<MemRegion> * closed_archive) {364assert(is_heap_object_archiving_allowed(), "Cannot archive java heap objects");365366G1CollectedHeap::heap()->begin_archive_alloc_range();367368// Archive interned string objects369StringTable::write_to_archive(_dumped_interned_strings);370371archive_object_subgraphs(closed_archive_subgraph_entry_fields,372num_closed_archive_subgraph_entry_fields,373true /* is_closed_archive */,374false /* is_full_module_graph */);375376G1CollectedHeap::heap()->end_archive_alloc_range(closed_archive,377os::vm_allocation_granularity());378}379380void HeapShared::copy_open_archive_heap_objects(381GrowableArray<MemRegion> * open_archive) {382assert(is_heap_object_archiving_allowed(), "Cannot archive java heap objects");383384G1CollectedHeap::heap()->begin_archive_alloc_range(true /* open */);385386java_lang_Class::archive_basic_type_mirrors();387388archive_klass_objects();389390archive_object_subgraphs(open_archive_subgraph_entry_fields,391num_open_archive_subgraph_entry_fields,392false /* is_closed_archive */,393false /* is_full_module_graph */);394if (MetaspaceShared::use_full_module_graph()) {395archive_object_subgraphs(fmg_open_archive_subgraph_entry_fields,396num_fmg_open_archive_subgraph_entry_fields,397false /* is_closed_archive */,398true /* is_full_module_graph */);399ClassLoaderDataShared::init_archived_oops();400}401402copy_roots();403404G1CollectedHeap::heap()->end_archive_alloc_range(open_archive,405os::vm_allocation_granularity());406}407408// Copy _pending_archive_roots into an objArray409void HeapShared::copy_roots() {410int length = _pending_roots != NULL ? _pending_roots->length() : 0;411int size = objArrayOopDesc::object_size(length);412Klass* k = Universe::objectArrayKlassObj(); // already relocated to point to archived klass413HeapWord* mem = G1CollectedHeap::heap()->archive_mem_allocate(size);414415memset(mem, 0, size * BytesPerWord);416{417// This is copied from MemAllocator::finish418if (UseBiasedLocking) {419oopDesc::set_mark(mem, k->prototype_header());420} else {421oopDesc::set_mark(mem, markWord::prototype());422}423oopDesc::release_set_klass(mem, k);424}425{426// This is copied from ObjArrayAllocator::initialize427arrayOopDesc::set_length(mem, length);428}429430_roots = OopHandle(Universe::vm_global(), cast_to_oop(mem));431for (int i = 0; i < length; i++) {432roots()->obj_at_put(i, _pending_roots->at(i));433}434log_info(cds)("archived obj roots[%d] = %d words, klass = %p, obj = %p", length, size, k, mem);435}436437void HeapShared::init_narrow_oop_decoding(address base, int shift) {438_narrow_oop_base = base;439_narrow_oop_shift = shift;440}441442//443// Subgraph archiving support444//445HeapShared::DumpTimeKlassSubGraphInfoTable* HeapShared::_dump_time_subgraph_info_table = NULL;446HeapShared::RunTimeKlassSubGraphInfoTable HeapShared::_run_time_subgraph_info_table;447448// Get the subgraph_info for Klass k. A new subgraph_info is created if449// there is no existing one for k. The subgraph_info records the relocated450// Klass* of the original k.451KlassSubGraphInfo* HeapShared::init_subgraph_info(Klass* k, bool is_full_module_graph) {452assert(DumpSharedSpaces, "dump time only");453bool created;454Klass* relocated_k = ArchiveBuilder::get_relocated_klass(k);455KlassSubGraphInfo* info =456_dump_time_subgraph_info_table->put_if_absent(relocated_k, KlassSubGraphInfo(relocated_k, is_full_module_graph),457&created);458assert(created, "must not initialize twice");459return info;460}461462KlassSubGraphInfo* HeapShared::get_subgraph_info(Klass* k) {463assert(DumpSharedSpaces, "dump time only");464Klass* relocated_k = ArchiveBuilder::get_relocated_klass(k);465KlassSubGraphInfo* info = _dump_time_subgraph_info_table->get(relocated_k);466assert(info != NULL, "must have been initialized");467return info;468}469470// Add an entry field to the current KlassSubGraphInfo.471void KlassSubGraphInfo::add_subgraph_entry_field(472int static_field_offset, oop v, bool is_closed_archive) {473assert(DumpSharedSpaces, "dump time only");474if (_subgraph_entry_fields == NULL) {475_subgraph_entry_fields =476new(ResourceObj::C_HEAP, mtClass) GrowableArray<int>(10, mtClass);477}478_subgraph_entry_fields->append(static_field_offset);479_subgraph_entry_fields->append(HeapShared::append_root(v));480}481482// Add the Klass* for an object in the current KlassSubGraphInfo's subgraphs.483// Only objects of boot classes can be included in sub-graph.484void KlassSubGraphInfo::add_subgraph_object_klass(Klass* orig_k) {485assert(DumpSharedSpaces, "dump time only");486Klass* relocated_k = ArchiveBuilder::get_relocated_klass(orig_k);487488if (_subgraph_object_klasses == NULL) {489_subgraph_object_klasses =490new(ResourceObj::C_HEAP, mtClass) GrowableArray<Klass*>(50, mtClass);491}492493assert(ArchiveBuilder::current()->is_in_buffer_space(relocated_k), "must be a shared class");494495if (_k == relocated_k) {496// Don't add the Klass containing the sub-graph to it's own klass497// initialization list.498return;499}500501if (relocated_k->is_instance_klass()) {502assert(InstanceKlass::cast(relocated_k)->is_shared_boot_class(),503"must be boot class");504// vmClasses::xxx_klass() are not updated, need to check505// the original Klass*506if (orig_k == vmClasses::String_klass() ||507orig_k == vmClasses::Object_klass()) {508// Initialized early during VM initialization. No need to be added509// to the sub-graph object class list.510return;511}512} else if (relocated_k->is_objArray_klass()) {513Klass* abk = ObjArrayKlass::cast(relocated_k)->bottom_klass();514if (abk->is_instance_klass()) {515assert(InstanceKlass::cast(abk)->is_shared_boot_class(),516"must be boot class");517}518if (relocated_k == Universe::objectArrayKlassObj()) {519// Initialized early during Universe::genesis. No need to be added520// to the list.521return;522}523} else {524assert(relocated_k->is_typeArray_klass(), "must be");525// Primitive type arrays are created early during Universe::genesis.526return;527}528529if (log_is_enabled(Debug, cds, heap)) {530if (!_subgraph_object_klasses->contains(relocated_k)) {531ResourceMark rm;532log_debug(cds, heap)("Adding klass %s", orig_k->external_name());533}534}535536_subgraph_object_klasses->append_if_missing(relocated_k);537_has_non_early_klasses |= is_non_early_klass(orig_k);538}539540bool KlassSubGraphInfo::is_non_early_klass(Klass* k) {541if (k->is_objArray_klass()) {542k = ObjArrayKlass::cast(k)->bottom_klass();543}544if (k->is_instance_klass()) {545if (!SystemDictionaryShared::is_early_klass(InstanceKlass::cast(k))) {546ResourceMark rm;547log_info(cds, heap)("non-early: %s", k->external_name());548return true;549} else {550return false;551}552} else {553return false;554}555}556557// Initialize an archived subgraph_info_record from the given KlassSubGraphInfo.558void ArchivedKlassSubGraphInfoRecord::init(KlassSubGraphInfo* info) {559_k = info->klass();560_entry_field_records = NULL;561_subgraph_object_klasses = NULL;562_is_full_module_graph = info->is_full_module_graph();563564if (_is_full_module_graph) {565// Consider all classes referenced by the full module graph as early -- we will be566// allocating objects of these classes during JVMTI early phase, so they cannot567// be processed by (non-early) JVMTI ClassFileLoadHook568_has_non_early_klasses = false;569} else {570_has_non_early_klasses = info->has_non_early_klasses();571}572573if (_has_non_early_klasses) {574ResourceMark rm;575log_info(cds, heap)(576"Subgraph of klass %s has non-early klasses and cannot be used when JVMTI ClassFileLoadHook is enabled",577_k->external_name());578}579580// populate the entry fields581GrowableArray<int>* entry_fields = info->subgraph_entry_fields();582if (entry_fields != NULL) {583int num_entry_fields = entry_fields->length();584assert(num_entry_fields % 2 == 0, "sanity");585_entry_field_records =586ArchiveBuilder::new_ro_array<int>(num_entry_fields);587for (int i = 0 ; i < num_entry_fields; i++) {588_entry_field_records->at_put(i, entry_fields->at(i));589}590}591592// the Klasses of the objects in the sub-graphs593GrowableArray<Klass*>* subgraph_object_klasses = info->subgraph_object_klasses();594if (subgraph_object_klasses != NULL) {595int num_subgraphs_klasses = subgraph_object_klasses->length();596_subgraph_object_klasses =597ArchiveBuilder::new_ro_array<Klass*>(num_subgraphs_klasses);598for (int i = 0; i < num_subgraphs_klasses; i++) {599Klass* subgraph_k = subgraph_object_klasses->at(i);600if (log_is_enabled(Info, cds, heap)) {601ResourceMark rm;602log_info(cds, heap)(603"Archived object klass %s (%2d) => %s",604_k->external_name(), i, subgraph_k->external_name());605}606_subgraph_object_klasses->at_put(i, subgraph_k);607ArchivePtrMarker::mark_pointer(_subgraph_object_klasses->adr_at(i));608}609}610611ArchivePtrMarker::mark_pointer(&_k);612ArchivePtrMarker::mark_pointer(&_entry_field_records);613ArchivePtrMarker::mark_pointer(&_subgraph_object_klasses);614}615616struct CopyKlassSubGraphInfoToArchive : StackObj {617CompactHashtableWriter* _writer;618CopyKlassSubGraphInfoToArchive(CompactHashtableWriter* writer) : _writer(writer) {}619620bool do_entry(Klass* klass, KlassSubGraphInfo& info) {621if (info.subgraph_object_klasses() != NULL || info.subgraph_entry_fields() != NULL) {622ArchivedKlassSubGraphInfoRecord* record =623(ArchivedKlassSubGraphInfoRecord*)ArchiveBuilder::ro_region_alloc(sizeof(ArchivedKlassSubGraphInfoRecord));624record->init(&info);625626unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary((address)klass);627u4 delta = ArchiveBuilder::current()->any_to_offset_u4(record);628_writer->add(hash, delta);629}630return true; // keep on iterating631}632};633634// Build the records of archived subgraph infos, which include:635// - Entry points to all subgraphs from the containing class mirror. The entry636// points are static fields in the mirror. For each entry point, the field637// offset, value and is_closed_archive flag are recorded in the sub-graph638// info. The value is stored back to the corresponding field at runtime.639// - A list of klasses that need to be loaded/initialized before archived640// java object sub-graph can be accessed at runtime.641void HeapShared::write_subgraph_info_table() {642// Allocate the contents of the hashtable(s) inside the RO region of the CDS archive.643DumpTimeKlassSubGraphInfoTable* d_table = _dump_time_subgraph_info_table;644CompactHashtableStats stats;645646_run_time_subgraph_info_table.reset();647648CompactHashtableWriter writer(d_table->_count, &stats);649CopyKlassSubGraphInfoToArchive copy(&writer);650d_table->iterate(©);651652writer.dump(&_run_time_subgraph_info_table, "subgraphs");653}654655void HeapShared::serialize_subgraph_info_table_header(SerializeClosure* soc) {656_run_time_subgraph_info_table.serialize_header(soc);657}658659static void verify_the_heap(Klass* k, const char* which) {660if (VerifyArchivedFields) {661ResourceMark rm;662log_info(cds, heap)("Verify heap %s initializing static field(s) in %s",663which, k->external_name());664665VM_Verify verify_op;666VMThread::execute(&verify_op);667668if (!FLAG_IS_DEFAULT(VerifyArchivedFields)) {669// If VerifyArchivedFields has a non-default value (e.g., specified on the command-line), do670// more expensive checks.671if (is_init_completed()) {672FlagSetting fs1(VerifyBeforeGC, true);673FlagSetting fs2(VerifyDuringGC, true);674FlagSetting fs3(VerifyAfterGC, true);675Universe::heap()->collect(GCCause::_java_lang_system_gc);676}677}678}679}680681// Before GC can execute, we must ensure that all oops reachable from HeapShared::roots()682// have a valid klass. I.e., oopDesc::klass() must have already been resolved.683//684// Note: if a ArchivedKlassSubGraphInfoRecord contains non-early classes, and JVMTI685// ClassFileLoadHook is enabled, it's possible for this class to be dynamically replaced. In686// this case, we will not load the ArchivedKlassSubGraphInfoRecord and will clear its roots.687void HeapShared::resolve_classes(JavaThread* THREAD) {688if (!is_mapped()) {689return; // nothing to do690}691resolve_classes_for_subgraphs(closed_archive_subgraph_entry_fields,692num_closed_archive_subgraph_entry_fields,693THREAD);694resolve_classes_for_subgraphs(open_archive_subgraph_entry_fields,695num_open_archive_subgraph_entry_fields,696THREAD);697resolve_classes_for_subgraphs(fmg_open_archive_subgraph_entry_fields,698num_fmg_open_archive_subgraph_entry_fields,699THREAD);700}701702void HeapShared::resolve_classes_for_subgraphs(ArchivableStaticFieldInfo fields[],703int num, JavaThread* THREAD) {704for (int i = 0; i < num; i++) {705ArchivableStaticFieldInfo* info = &fields[i];706TempNewSymbol klass_name = SymbolTable::new_symbol(info->klass_name);707InstanceKlass* k = SystemDictionaryShared::find_builtin_class(klass_name);708assert(k != NULL && k->is_shared_boot_class(), "sanity");709resolve_classes_for_subgraph_of(k, THREAD);710}711}712713void HeapShared::resolve_classes_for_subgraph_of(Klass* k, JavaThread* THREAD) {714ExceptionMark em(THREAD);715const ArchivedKlassSubGraphInfoRecord* record =716resolve_or_init_classes_for_subgraph_of(k, /*do_init=*/false, THREAD);717if (HAS_PENDING_EXCEPTION) {718CLEAR_PENDING_EXCEPTION;719}720if (record == NULL) {721clear_archived_roots_of(k);722}723}724725void HeapShared::initialize_from_archived_subgraph(Klass* k, JavaThread* THREAD) {726if (!is_mapped()) {727return; // nothing to do728}729730ExceptionMark em(THREAD);731const ArchivedKlassSubGraphInfoRecord* record =732resolve_or_init_classes_for_subgraph_of(k, /*do_init=*/true, THREAD);733734if (HAS_PENDING_EXCEPTION) {735CLEAR_PENDING_EXCEPTION;736// None of the field value will be set if there was an exception when initializing the classes.737// The java code will not see any of the archived objects in the738// subgraphs referenced from k in this case.739return;740}741742if (record != NULL) {743init_archived_fields_for(k, record);744}745}746747const ArchivedKlassSubGraphInfoRecord*748HeapShared::resolve_or_init_classes_for_subgraph_of(Klass* k, bool do_init, TRAPS) {749assert(!DumpSharedSpaces, "Should not be called with DumpSharedSpaces");750751if (!k->is_shared()) {752return NULL;753}754unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary_quick(k);755const ArchivedKlassSubGraphInfoRecord* record = _run_time_subgraph_info_table.lookup(k, hash, 0);756757// Initialize from archived data. Currently this is done only758// during VM initialization time. No lock is needed.759if (record != NULL) {760if (record->is_full_module_graph() && !MetaspaceShared::use_full_module_graph()) {761if (log_is_enabled(Info, cds, heap)) {762ResourceMark rm(THREAD);763log_info(cds, heap)("subgraph %s cannot be used because full module graph is disabled",764k->external_name());765}766return NULL;767}768769if (record->has_non_early_klasses() && JvmtiExport::should_post_class_file_load_hook()) {770if (log_is_enabled(Info, cds, heap)) {771ResourceMark rm(THREAD);772log_info(cds, heap)("subgraph %s cannot be used because JVMTI ClassFileLoadHook is enabled",773k->external_name());774}775return NULL;776}777778resolve_or_init(k, do_init, CHECK_NULL);779780// Load/link/initialize the klasses of the objects in the subgraph.781// NULL class loader is used.782Array<Klass*>* klasses = record->subgraph_object_klasses();783if (klasses != NULL) {784for (int i = 0; i < klasses->length(); i++) {785Klass* klass = klasses->at(i);786if (!klass->is_shared()) {787return NULL;788}789resolve_or_init(klass, do_init, CHECK_NULL);790}791}792}793794return record;795}796797void HeapShared::resolve_or_init(Klass* k, bool do_init, TRAPS) {798if (!do_init) {799if (k->class_loader_data() == NULL) {800Klass* resolved_k = SystemDictionary::resolve_or_null(k->name(), CHECK);801assert(resolved_k == k, "classes used by archived heap must not be replaced by JVMTI ClassFileLoadHook");802}803} else {804assert(k->class_loader_data() != NULL, "must have been resolved by HeapShared::resolve_classes");805if (k->is_instance_klass()) {806InstanceKlass* ik = InstanceKlass::cast(k);807ik->initialize(CHECK);808} else if (k->is_objArray_klass()) {809ObjArrayKlass* oak = ObjArrayKlass::cast(k);810oak->initialize(CHECK);811}812}813}814815void HeapShared::init_archived_fields_for(Klass* k, const ArchivedKlassSubGraphInfoRecord* record) {816verify_the_heap(k, "before");817818// Load the subgraph entry fields from the record and store them back to819// the corresponding fields within the mirror.820oop m = k->java_mirror();821Array<int>* entry_field_records = record->entry_field_records();822if (entry_field_records != NULL) {823int efr_len = entry_field_records->length();824assert(efr_len % 2 == 0, "sanity");825for (int i = 0; i < efr_len; i += 2) {826int field_offset = entry_field_records->at(i);827int root_index = entry_field_records->at(i+1);828oop v = get_root(root_index, /*clear=*/true);829m->obj_field_put(field_offset, v);830log_debug(cds, heap)(" " PTR_FORMAT " init field @ %2d = " PTR_FORMAT, p2i(k), field_offset, p2i(v));831}832833// Done. Java code can see the archived sub-graphs referenced from k's834// mirror after this point.835if (log_is_enabled(Info, cds, heap)) {836ResourceMark rm;837log_info(cds, heap)("initialize_from_archived_subgraph %s " PTR_FORMAT "%s",838k->external_name(), p2i(k), JvmtiExport::is_early_phase() ? " (early)" : "");839}840}841842verify_the_heap(k, "after ");843}844845void HeapShared::clear_archived_roots_of(Klass* k) {846unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary_quick(k);847const ArchivedKlassSubGraphInfoRecord* record = _run_time_subgraph_info_table.lookup(k, hash, 0);848if (record != NULL) {849Array<int>* entry_field_records = record->entry_field_records();850if (entry_field_records != NULL) {851int efr_len = entry_field_records->length();852assert(efr_len % 2 == 0, "sanity");853for (int i = 0; i < efr_len; i += 2) {854int root_index = entry_field_records->at(i+1);855clear_root(root_index);856}857}858}859}860861class WalkOopAndArchiveClosure: public BasicOopIterateClosure {862int _level;863bool _is_closed_archive;864bool _record_klasses_only;865KlassSubGraphInfo* _subgraph_info;866oop _orig_referencing_obj;867oop _archived_referencing_obj;868public:869WalkOopAndArchiveClosure(int level,870bool is_closed_archive,871bool record_klasses_only,872KlassSubGraphInfo* subgraph_info,873oop orig, oop archived) :874_level(level), _is_closed_archive(is_closed_archive),875_record_klasses_only(record_klasses_only),876_subgraph_info(subgraph_info),877_orig_referencing_obj(orig), _archived_referencing_obj(archived) {}878void do_oop(narrowOop *p) { WalkOopAndArchiveClosure::do_oop_work(p); }879void do_oop( oop *p) { WalkOopAndArchiveClosure::do_oop_work(p); }880881protected:882template <class T> void do_oop_work(T *p) {883oop obj = RawAccess<>::oop_load(p);884if (!CompressedOops::is_null(obj)) {885assert(!HeapShared::is_archived_object(obj),886"original objects must not point to archived objects");887888size_t field_delta = pointer_delta(p, _orig_referencing_obj, sizeof(char));889T* new_p = (T*)(cast_from_oop<address>(_archived_referencing_obj) + field_delta);890891if (!_record_klasses_only && log_is_enabled(Debug, cds, heap)) {892ResourceMark rm;893log_debug(cds, heap)("(%d) %s[" SIZE_FORMAT "] ==> " PTR_FORMAT " size %d %s", _level,894_orig_referencing_obj->klass()->external_name(), field_delta,895p2i(obj), obj->size() * HeapWordSize, obj->klass()->external_name());896LogTarget(Trace, cds, heap) log;897LogStream out(log);898obj->print_on(&out);899}900901oop archived = HeapShared::archive_reachable_objects_from(902_level + 1, _subgraph_info, obj, _is_closed_archive);903assert(archived != NULL, "VM should have exited with unarchivable objects for _level > 1");904assert(HeapShared::is_archived_object(archived), "must be");905906if (!_record_klasses_only) {907// Update the reference in the archived copy of the referencing object.908log_debug(cds, heap)("(%d) updating oop @[" PTR_FORMAT "] " PTR_FORMAT " ==> " PTR_FORMAT,909_level, p2i(new_p), p2i(obj), p2i(archived));910RawAccess<IS_NOT_NULL>::oop_store(new_p, archived);911}912}913}914};915916void HeapShared::check_closed_archive_heap_region_object(InstanceKlass* k) {917// Check fields in the object918for (JavaFieldStream fs(k); !fs.done(); fs.next()) {919if (!fs.access_flags().is_static()) {920BasicType ft = fs.field_descriptor().field_type();921if (!fs.access_flags().is_final() && is_reference_type(ft)) {922ResourceMark rm;923log_warning(cds, heap)(924"Please check reference field in %s instance in closed archive heap region: %s %s",925k->external_name(), (fs.name())->as_C_string(),926(fs.signature())->as_C_string());927}928}929}930}931932void HeapShared::check_module_oop(oop orig_module_obj) {933assert(DumpSharedSpaces, "must be");934assert(java_lang_Module::is_instance(orig_module_obj), "must be");935ModuleEntry* orig_module_ent = java_lang_Module::module_entry_raw(orig_module_obj);936if (orig_module_ent == NULL) {937// These special Module objects are created in Java code. They are not938// defined via Modules::define_module(), so they don't have a ModuleEntry:939// java.lang.Module::ALL_UNNAMED_MODULE940// java.lang.Module::EVERYONE_MODULE941// jdk.internal.loader.ClassLoaders$BootClassLoader::unnamedModule942assert(java_lang_Module::name(orig_module_obj) == NULL, "must be unnamed");943log_info(cds, heap)("Module oop with No ModuleEntry* @[" PTR_FORMAT "]", p2i(orig_module_obj));944} else {945ClassLoaderData* loader_data = orig_module_ent->loader_data();946assert(loader_data->is_builtin_class_loader_data(), "must be");947}948}949950951// (1) If orig_obj has not been archived yet, archive it.952// (2) If orig_obj has not been seen yet (since start_recording_subgraph() was called),953// trace all objects that are reachable from it, and make sure these objects are archived.954// (3) Record the klasses of all orig_obj and all reachable objects.955oop HeapShared::archive_reachable_objects_from(int level,956KlassSubGraphInfo* subgraph_info,957oop orig_obj,958bool is_closed_archive) {959assert(orig_obj != NULL, "must be");960assert(!is_archived_object(orig_obj), "sanity");961962if (!JavaClasses::is_supported_for_archiving(orig_obj)) {963// This object has injected fields that cannot be supported easily, so we disallow them for now.964// If you get an error here, you probably made a change in the JDK library that has added965// these objects that are referenced (directly or indirectly) by static fields.966ResourceMark rm;967log_error(cds, heap)("Cannot archive object of class %s", orig_obj->klass()->external_name());968vm_direct_exit(1);969}970971// java.lang.Class instances cannot be included in an archived object sub-graph. We only support972// them as Klass::_archived_mirror because they need to be specially restored at run time.973//974// If you get an error here, you probably made a change in the JDK library that has added a Class975// object that is referenced (directly or indirectly) by static fields.976if (java_lang_Class::is_instance(orig_obj)) {977log_error(cds, heap)("(%d) Unknown java.lang.Class object is in the archived sub-graph", level);978vm_direct_exit(1);979}980981oop archived_obj = find_archived_heap_object(orig_obj);982if (java_lang_String::is_instance(orig_obj) && archived_obj != NULL) {983// To save time, don't walk strings that are already archived. They just contain984// pointers to a type array, whose klass doesn't need to be recorded.985return archived_obj;986}987988if (has_been_seen_during_subgraph_recording(orig_obj)) {989// orig_obj has already been archived and traced. Nothing more to do.990return archived_obj;991} else {992set_has_been_seen_during_subgraph_recording(orig_obj);993}994995bool record_klasses_only = (archived_obj != NULL);996if (archived_obj == NULL) {997++_num_new_archived_objs;998archived_obj = archive_heap_object(orig_obj);999if (archived_obj == NULL) {1000// Skip archiving the sub-graph referenced from the current entry field.1001ResourceMark rm;1002log_error(cds, heap)(1003"Cannot archive the sub-graph referenced from %s object ("1004PTR_FORMAT ") size %d, skipped.",1005orig_obj->klass()->external_name(), p2i(orig_obj), orig_obj->size() * HeapWordSize);1006if (level == 1) {1007// Don't archive a subgraph root that's too big. For archives static fields, that's OK1008// as the Java code will take care of initializing this field dynamically.1009return NULL;1010} else {1011// We don't know how to handle an object that has been archived, but some of its reachable1012// objects cannot be archived. Bail out for now. We might need to fix this in the future if1013// we have a real use case.1014vm_direct_exit(1);1015}1016}10171018if (java_lang_Module::is_instance(orig_obj)) {1019check_module_oop(orig_obj);1020java_lang_Module::set_module_entry(archived_obj, NULL);1021java_lang_Module::set_loader(archived_obj, NULL);1022} else if (java_lang_ClassLoader::is_instance(orig_obj)) {1023// class_data will be restored explicitly at run time.1024guarantee(orig_obj == SystemDictionary::java_platform_loader() ||1025orig_obj == SystemDictionary::java_system_loader() ||1026java_lang_ClassLoader::loader_data_raw(orig_obj) == NULL, "must be");1027java_lang_ClassLoader::release_set_loader_data(archived_obj, NULL);1028}1029}10301031assert(archived_obj != NULL, "must be");1032Klass *orig_k = orig_obj->klass();1033subgraph_info->add_subgraph_object_klass(orig_k);10341035WalkOopAndArchiveClosure walker(level, is_closed_archive, record_klasses_only,1036subgraph_info, orig_obj, archived_obj);1037orig_obj->oop_iterate(&walker);1038if (is_closed_archive && orig_k->is_instance_klass()) {1039check_closed_archive_heap_region_object(InstanceKlass::cast(orig_k));1040}1041return archived_obj;1042}10431044//1045// Start from the given static field in a java mirror and archive the1046// complete sub-graph of java heap objects that are reached directly1047// or indirectly from the starting object by following references.1048// Sub-graph archiving restrictions (current):1049//1050// - All classes of objects in the archived sub-graph (including the1051// entry class) must be boot class only.1052// - No java.lang.Class instance (java mirror) can be included inside1053// an archived sub-graph. Mirror can only be the sub-graph entry object.1054//1055// The Java heap object sub-graph archiving process (see1056// WalkOopAndArchiveClosure):1057//1058// 1) Java object sub-graph archiving starts from a given static field1059// within a Class instance (java mirror). If the static field is a1060// refererence field and points to a non-null java object, proceed to1061// the next step.1062//1063// 2) Archives the referenced java object. If an archived copy of the1064// current object already exists, updates the pointer in the archived1065// copy of the referencing object to point to the current archived object.1066// Otherwise, proceed to the next step.1067//1068// 3) Follows all references within the current java object and recursively1069// archive the sub-graph of objects starting from each reference.1070//1071// 4) Updates the pointer in the archived copy of referencing object to1072// point to the current archived object.1073//1074// 5) The Klass of the current java object is added to the list of Klasses1075// for loading and initialzing before any object in the archived graph can1076// be accessed at runtime.1077//1078void HeapShared::archive_reachable_objects_from_static_field(InstanceKlass *k,1079const char* klass_name,1080int field_offset,1081const char* field_name,1082bool is_closed_archive) {1083assert(DumpSharedSpaces, "dump time only");1084assert(k->is_shared_boot_class(), "must be boot class");10851086oop m = k->java_mirror();10871088KlassSubGraphInfo* subgraph_info = get_subgraph_info(k);1089oop f = m->obj_field(field_offset);10901091log_debug(cds, heap)("Start archiving from: %s::%s (" PTR_FORMAT ")", klass_name, field_name, p2i(f));10921093if (!CompressedOops::is_null(f)) {1094if (log_is_enabled(Trace, cds, heap)) {1095LogTarget(Trace, cds, heap) log;1096LogStream out(log);1097f->print_on(&out);1098}10991100oop af = archive_reachable_objects_from(1, subgraph_info, f, is_closed_archive);11011102if (af == NULL) {1103log_error(cds, heap)("Archiving failed %s::%s (some reachable objects cannot be archived)",1104klass_name, field_name);1105} else {1106// Note: the field value is not preserved in the archived mirror.1107// Record the field as a new subGraph entry point. The recorded1108// information is restored from the archive at runtime.1109subgraph_info->add_subgraph_entry_field(field_offset, af, is_closed_archive);1110log_info(cds, heap)("Archived field %s::%s => " PTR_FORMAT, klass_name, field_name, p2i(af));1111}1112} else {1113// The field contains null, we still need to record the entry point,1114// so it can be restored at runtime.1115subgraph_info->add_subgraph_entry_field(field_offset, NULL, false);1116}1117}11181119#ifndef PRODUCT1120class VerifySharedOopClosure: public BasicOopIterateClosure {1121private:1122bool _is_archived;11231124public:1125VerifySharedOopClosure(bool is_archived) : _is_archived(is_archived) {}11261127void do_oop(narrowOop *p) { VerifySharedOopClosure::do_oop_work(p); }1128void do_oop( oop *p) { VerifySharedOopClosure::do_oop_work(p); }11291130protected:1131template <class T> void do_oop_work(T *p) {1132oop obj = RawAccess<>::oop_load(p);1133if (!CompressedOops::is_null(obj)) {1134HeapShared::verify_reachable_objects_from(obj, _is_archived);1135}1136}1137};11381139void HeapShared::verify_subgraph_from_static_field(InstanceKlass* k, int field_offset) {1140assert(DumpSharedSpaces, "dump time only");1141assert(k->is_shared_boot_class(), "must be boot class");11421143oop m = k->java_mirror();1144oop f = m->obj_field(field_offset);1145if (!CompressedOops::is_null(f)) {1146verify_subgraph_from(f);1147}1148}11491150void HeapShared::verify_subgraph_from(oop orig_obj) {1151oop archived_obj = find_archived_heap_object(orig_obj);1152if (archived_obj == NULL) {1153// It's OK for the root of a subgraph to be not archived. See comments in1154// archive_reachable_objects_from().1155return;1156}11571158// Verify that all objects reachable from orig_obj are archived.1159init_seen_objects_table();1160verify_reachable_objects_from(orig_obj, false);1161delete_seen_objects_table();11621163// Note: we could also verify that all objects reachable from the archived1164// copy of orig_obj can only point to archived objects, with:1165// init_seen_objects_table();1166// verify_reachable_objects_from(archived_obj, true);1167// init_seen_objects_table();1168// but that's already done in G1HeapVerifier::verify_archive_regions so we1169// won't do it here.1170}11711172void HeapShared::verify_reachable_objects_from(oop obj, bool is_archived) {1173_num_total_verifications ++;1174if (!has_been_seen_during_subgraph_recording(obj)) {1175set_has_been_seen_during_subgraph_recording(obj);11761177if (is_archived) {1178assert(is_archived_object(obj), "must be");1179assert(find_archived_heap_object(obj) == NULL, "must be");1180} else {1181assert(!is_archived_object(obj), "must be");1182assert(find_archived_heap_object(obj) != NULL, "must be");1183}11841185VerifySharedOopClosure walker(is_archived);1186obj->oop_iterate(&walker);1187}1188}1189#endif11901191HeapShared::SeenObjectsTable* HeapShared::_seen_objects_table = NULL;1192int HeapShared::_num_new_walked_objs;1193int HeapShared::_num_new_archived_objs;1194int HeapShared::_num_old_recorded_klasses;11951196int HeapShared::_num_total_subgraph_recordings = 0;1197int HeapShared::_num_total_walked_objs = 0;1198int HeapShared::_num_total_archived_objs = 0;1199int HeapShared::_num_total_recorded_klasses = 0;1200int HeapShared::_num_total_verifications = 0;12011202bool HeapShared::has_been_seen_during_subgraph_recording(oop obj) {1203return _seen_objects_table->get(obj) != NULL;1204}12051206void HeapShared::set_has_been_seen_during_subgraph_recording(oop obj) {1207assert(!has_been_seen_during_subgraph_recording(obj), "sanity");1208_seen_objects_table->put(obj, true);1209++ _num_new_walked_objs;1210}12111212void HeapShared::start_recording_subgraph(InstanceKlass *k, const char* class_name, bool is_full_module_graph) {1213log_info(cds, heap)("Start recording subgraph(s) for archived fields in %s", class_name);1214init_subgraph_info(k, is_full_module_graph);1215init_seen_objects_table();1216_num_new_walked_objs = 0;1217_num_new_archived_objs = 0;1218_num_old_recorded_klasses = get_subgraph_info(k)->num_subgraph_object_klasses();1219}12201221void HeapShared::done_recording_subgraph(InstanceKlass *k, const char* class_name) {1222int num_new_recorded_klasses = get_subgraph_info(k)->num_subgraph_object_klasses() -1223_num_old_recorded_klasses;1224log_info(cds, heap)("Done recording subgraph(s) for archived fields in %s: "1225"walked %d objs, archived %d new objs, recorded %d classes",1226class_name, _num_new_walked_objs, _num_new_archived_objs,1227num_new_recorded_klasses);12281229delete_seen_objects_table();12301231_num_total_subgraph_recordings ++;1232_num_total_walked_objs += _num_new_walked_objs;1233_num_total_archived_objs += _num_new_archived_objs;1234_num_total_recorded_klasses += num_new_recorded_klasses;1235}12361237class ArchivableStaticFieldFinder: public FieldClosure {1238InstanceKlass* _ik;1239Symbol* _field_name;1240bool _found;1241int _offset;1242public:1243ArchivableStaticFieldFinder(InstanceKlass* ik, Symbol* field_name) :1244_ik(ik), _field_name(field_name), _found(false), _offset(-1) {}12451246virtual void do_field(fieldDescriptor* fd) {1247if (fd->name() == _field_name) {1248assert(!_found, "fields cannot be overloaded");1249assert(is_reference_type(fd->field_type()), "can archive only fields that are references");1250_found = true;1251_offset = fd->offset();1252}1253}1254bool found() { return _found; }1255int offset() { return _offset; }1256};12571258void HeapShared::init_subgraph_entry_fields(ArchivableStaticFieldInfo fields[],1259int num, TRAPS) {1260for (int i = 0; i < num; i++) {1261ArchivableStaticFieldInfo* info = &fields[i];1262TempNewSymbol klass_name = SymbolTable::new_symbol(info->klass_name);1263TempNewSymbol field_name = SymbolTable::new_symbol(info->field_name);12641265Klass* k = SystemDictionary::resolve_or_fail(klass_name, true, CHECK);1266InstanceKlass* ik = InstanceKlass::cast(k);1267assert(InstanceKlass::cast(ik)->is_shared_boot_class(),1268"Only support boot classes");1269ik->initialize(CHECK);12701271ArchivableStaticFieldFinder finder(ik, field_name);1272ik->do_local_static_fields(&finder);1273assert(finder.found(), "field must exist");12741275info->klass = ik;1276info->offset = finder.offset();1277}1278}12791280void HeapShared::init_subgraph_entry_fields(TRAPS) {1281assert(is_heap_object_archiving_allowed(), "Sanity check");1282_dump_time_subgraph_info_table = new (ResourceObj::C_HEAP, mtClass)DumpTimeKlassSubGraphInfoTable();1283init_subgraph_entry_fields(closed_archive_subgraph_entry_fields,1284num_closed_archive_subgraph_entry_fields,1285CHECK);1286init_subgraph_entry_fields(open_archive_subgraph_entry_fields,1287num_open_archive_subgraph_entry_fields,1288CHECK);1289if (MetaspaceShared::use_full_module_graph()) {1290init_subgraph_entry_fields(fmg_open_archive_subgraph_entry_fields,1291num_fmg_open_archive_subgraph_entry_fields,1292CHECK);1293}1294}12951296void HeapShared::init_for_dumping(TRAPS) {1297if (is_heap_object_archiving_allowed()) {1298_dumped_interned_strings = new (ResourceObj::C_HEAP, mtClass)DumpedInternedStrings();1299init_subgraph_entry_fields(CHECK);1300}1301}13021303void HeapShared::archive_object_subgraphs(ArchivableStaticFieldInfo fields[],1304int num, bool is_closed_archive,1305bool is_full_module_graph) {1306_num_total_subgraph_recordings = 0;1307_num_total_walked_objs = 0;1308_num_total_archived_objs = 0;1309_num_total_recorded_klasses = 0;1310_num_total_verifications = 0;13111312// For each class X that has one or more archived fields:1313// [1] Dump the subgraph of each archived field1314// [2] Create a list of all the class of the objects that can be reached1315// by any of these static fields.1316// At runtime, these classes are initialized before X's archived fields1317// are restored by HeapShared::initialize_from_archived_subgraph().1318int i;1319for (i = 0; i < num; ) {1320ArchivableStaticFieldInfo* info = &fields[i];1321const char* klass_name = info->klass_name;1322start_recording_subgraph(info->klass, klass_name, is_full_module_graph);13231324// If you have specified consecutive fields of the same klass in1325// fields[], these will be archived in the same1326// {start_recording_subgraph ... done_recording_subgraph} pass to1327// save time.1328for (; i < num; i++) {1329ArchivableStaticFieldInfo* f = &fields[i];1330if (f->klass_name != klass_name) {1331break;1332}13331334archive_reachable_objects_from_static_field(f->klass, f->klass_name,1335f->offset, f->field_name,1336is_closed_archive);1337}1338done_recording_subgraph(info->klass, klass_name);1339}13401341log_info(cds, heap)("Archived subgraph records in %s archive heap region = %d",1342is_closed_archive ? "closed" : "open",1343_num_total_subgraph_recordings);1344log_info(cds, heap)(" Walked %d objects", _num_total_walked_objs);1345log_info(cds, heap)(" Archived %d objects", _num_total_archived_objs);1346log_info(cds, heap)(" Recorded %d klasses", _num_total_recorded_klasses);13471348#ifndef PRODUCT1349for (int i = 0; i < num; i++) {1350ArchivableStaticFieldInfo* f = &fields[i];1351verify_subgraph_from_static_field(f->klass, f->offset);1352}1353log_info(cds, heap)(" Verified %d references", _num_total_verifications);1354#endif1355}13561357// Not all the strings in the global StringTable are dumped into the archive, because1358// some of those strings may be only referenced by classes that are excluded from1359// the archive. We need to explicitly mark the strings that are:1360// [1] used by classes that WILL be archived;1361// [2] included in the SharedArchiveConfigFile.1362void HeapShared::add_to_dumped_interned_strings(oop string) {1363assert_at_safepoint(); // DumpedInternedStrings uses raw oops1364bool created;1365_dumped_interned_strings->put_if_absent(string, true, &created);1366}13671368// At dump-time, find the location of all the non-null oop pointers in an archived heap1369// region. This way we can quickly relocate all the pointers without using1370// BasicOopIterateClosure at runtime.1371class FindEmbeddedNonNullPointers: public BasicOopIterateClosure {1372narrowOop* _start;1373BitMap *_oopmap;1374int _num_total_oops;1375int _num_null_oops;1376public:1377FindEmbeddedNonNullPointers(narrowOop* start, BitMap* oopmap)1378: _start(start), _oopmap(oopmap), _num_total_oops(0), _num_null_oops(0) {}13791380virtual void do_oop(narrowOop* p) {1381_num_total_oops ++;1382narrowOop v = *p;1383if (!CompressedOops::is_null(v)) {1384size_t idx = p - _start;1385_oopmap->set_bit(idx);1386} else {1387_num_null_oops ++;1388}1389}1390virtual void do_oop(oop *p) {1391ShouldNotReachHere();1392}1393int num_total_oops() const { return _num_total_oops; }1394int num_null_oops() const { return _num_null_oops; }1395};13961397ResourceBitMap HeapShared::calculate_oopmap(MemRegion region) {1398assert(UseCompressedOops, "must be");1399size_t num_bits = region.byte_size() / sizeof(narrowOop);1400ResourceBitMap oopmap(num_bits);14011402HeapWord* p = region.start();1403HeapWord* end = region.end();1404FindEmbeddedNonNullPointers finder((narrowOop*)p, &oopmap);1405ArchiveBuilder* builder = DumpSharedSpaces ? ArchiveBuilder::current() : NULL;14061407int num_objs = 0;1408while (p < end) {1409oop o = cast_to_oop(p);1410o->oop_iterate(&finder);1411p += o->size();1412if (DumpSharedSpaces) {1413builder->relocate_klass_ptr(o);1414}1415++ num_objs;1416}14171418log_info(cds, heap)("calculate_oopmap: objects = %6d, embedded oops = %7d, nulls = %7d",1419num_objs, finder.num_total_oops(), finder.num_null_oops());1420return oopmap;1421}14221423// Patch all the embedded oop pointers inside an archived heap region,1424// to be consistent with the runtime oop encoding.1425class PatchEmbeddedPointers: public BitMapClosure {1426narrowOop* _start;14271428public:1429PatchEmbeddedPointers(narrowOop* start) : _start(start) {}14301431bool do_bit(size_t offset) {1432narrowOop* p = _start + offset;1433narrowOop v = *p;1434assert(!CompressedOops::is_null(v), "null oops should have been filtered out at dump time");1435oop o = HeapShared::decode_from_archive(v);1436RawAccess<IS_NOT_NULL>::oop_store(p, o);1437return true;1438}1439};14401441void HeapShared::patch_archived_heap_embedded_pointers(MemRegion region, address oopmap,1442size_t oopmap_size_in_bits) {1443BitMapView bm((BitMap::bm_word_t*)oopmap, oopmap_size_in_bits);14441445#ifndef PRODUCT1446ResourceMark rm;1447ResourceBitMap checkBm = calculate_oopmap(region);1448assert(bm.is_same(checkBm), "sanity");1449#endif14501451PatchEmbeddedPointers patcher((narrowOop*)region.start());1452bm.iterate(&patcher);1453}14541455#endif // INCLUDE_CDS_JAVA_HEAP145614571458