Path: blob/master/src/hotspot/share/memory/heapInspection.cpp
40950 views
/*1* Copyright (c) 2002, 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 "classfile/classLoaderData.inline.hpp"26#include "classfile/classLoaderDataGraph.hpp"27#include "classfile/moduleEntry.hpp"28#include "classfile/vmClasses.hpp"29#include "gc/shared/collectedHeap.hpp"30#include "logging/log.hpp"31#include "logging/logTag.hpp"32#include "memory/heapInspection.hpp"33#include "memory/resourceArea.hpp"34#include "memory/universe.hpp"35#include "oops/oop.inline.hpp"36#include "oops/reflectionAccessorImplKlassHelper.hpp"37#include "runtime/atomic.hpp"38#include "runtime/os.hpp"39#include "services/memTracker.hpp"40#include "utilities/globalDefinitions.hpp"41#include "utilities/macros.hpp"42#include "utilities/stack.inline.hpp"4344// HeapInspection4546inline KlassInfoEntry::~KlassInfoEntry() {47if (_subclasses != NULL) {48delete _subclasses;49}50}5152inline void KlassInfoEntry::add_subclass(KlassInfoEntry* cie) {53if (_subclasses == NULL) {54_subclasses = new (ResourceObj::C_HEAP, mtServiceability) GrowableArray<KlassInfoEntry*>(4, mtServiceability);55}56_subclasses->append(cie);57}5859int KlassInfoEntry::compare(KlassInfoEntry* e1, KlassInfoEntry* e2) {60if(e1->_instance_words > e2->_instance_words) {61return -1;62} else if(e1->_instance_words < e2->_instance_words) {63return 1;64}65// Sort alphabetically, note 'Z' < '[' < 'a', but it's better to group66// the array classes before all the instance classes.67ResourceMark rm;68const char* name1 = e1->klass()->external_name();69const char* name2 = e2->klass()->external_name();70bool d1 = (name1[0] == JVM_SIGNATURE_ARRAY);71bool d2 = (name2[0] == JVM_SIGNATURE_ARRAY);72if (d1 && !d2) {73return -1;74} else if (d2 && !d1) {75return 1;76} else {77return strcmp(name1, name2);78}79}8081const char* KlassInfoEntry::name() const {82const char* name;83if (_klass->name() != NULL) {84name = _klass->external_name();85} else {86if (_klass == Universe::boolArrayKlassObj()) name = "<boolArrayKlass>"; else87if (_klass == Universe::charArrayKlassObj()) name = "<charArrayKlass>"; else88if (_klass == Universe::floatArrayKlassObj()) name = "<floatArrayKlass>"; else89if (_klass == Universe::doubleArrayKlassObj()) name = "<doubleArrayKlass>"; else90if (_klass == Universe::byteArrayKlassObj()) name = "<byteArrayKlass>"; else91if (_klass == Universe::shortArrayKlassObj()) name = "<shortArrayKlass>"; else92if (_klass == Universe::intArrayKlassObj()) name = "<intArrayKlass>"; else93if (_klass == Universe::longArrayKlassObj()) name = "<longArrayKlass>"; else94name = "<no name>";95}96return name;97}9899void KlassInfoEntry::print_on(outputStream* st) const {100ResourceMark rm;101102// simplify the formatting (ILP32 vs LP64) - always cast the numbers to 64-bit103ModuleEntry* module = _klass->module();104if (module->is_named()) {105st->print_cr(INT64_FORMAT_W(13) " " UINT64_FORMAT_W(13) " %s (%s%s%s)",106(int64_t)_instance_count,107(uint64_t)_instance_words * HeapWordSize,108name(),109module->name()->as_C_string(),110module->version() != NULL ? "@" : "",111module->version() != NULL ? module->version()->as_C_string() : "");112} else {113st->print_cr(INT64_FORMAT_W(13) " " UINT64_FORMAT_W(13) " %s",114(int64_t)_instance_count,115(uint64_t)_instance_words * HeapWordSize,116name());117}118}119120KlassInfoEntry* KlassInfoBucket::lookup(Klass* const k) {121// Can happen if k is an archived class that we haven't loaded yet.122if (k->java_mirror_no_keepalive() == NULL) {123return NULL;124}125126KlassInfoEntry* elt = _list;127while (elt != NULL) {128if (elt->is_equal(k)) {129return elt;130}131elt = elt->next();132}133elt = new (std::nothrow) KlassInfoEntry(k, list());134// We may be out of space to allocate the new entry.135if (elt != NULL) {136set_list(elt);137}138return elt;139}140141void KlassInfoBucket::iterate(KlassInfoClosure* cic) {142KlassInfoEntry* elt = _list;143while (elt != NULL) {144cic->do_cinfo(elt);145elt = elt->next();146}147}148149void KlassInfoBucket::empty() {150KlassInfoEntry* elt = _list;151_list = NULL;152while (elt != NULL) {153KlassInfoEntry* next = elt->next();154delete elt;155elt = next;156}157}158159class KlassInfoTable::AllClassesFinder : public LockedClassesDo {160KlassInfoTable *_table;161public:162AllClassesFinder(KlassInfoTable* table) : _table(table) {}163virtual void do_klass(Klass* k) {164// This has the SIDE EFFECT of creating a KlassInfoEntry165// for <k>, if one doesn't exist yet.166_table->lookup(k);167}168};169170171KlassInfoTable::KlassInfoTable(bool add_all_classes) {172_size_of_instances_in_words = 0;173_ref = (HeapWord*) Universe::boolArrayKlassObj();174_buckets =175(KlassInfoBucket*) AllocateHeap(sizeof(KlassInfoBucket) * _num_buckets,176mtInternal, CURRENT_PC, AllocFailStrategy::RETURN_NULL);177if (_buckets != NULL) {178for (int index = 0; index < _num_buckets; index++) {179_buckets[index].initialize();180}181if (add_all_classes) {182AllClassesFinder finder(this);183ClassLoaderDataGraph::classes_do(&finder);184}185}186}187188KlassInfoTable::~KlassInfoTable() {189if (_buckets != NULL) {190for (int index = 0; index < _num_buckets; index++) {191_buckets[index].empty();192}193FREE_C_HEAP_ARRAY(KlassInfoBucket, _buckets);194_buckets = NULL;195}196}197198uint KlassInfoTable::hash(const Klass* p) {199return (uint)(((uintptr_t)p - (uintptr_t)_ref) >> 2);200}201202KlassInfoEntry* KlassInfoTable::lookup(Klass* k) {203uint idx = hash(k) % _num_buckets;204assert(_buckets != NULL, "Allocation failure should have been caught");205KlassInfoEntry* e = _buckets[idx].lookup(k);206// Lookup may fail if this is a new klass for which we207// could not allocate space for an new entry, or if it's208// an archived class that we haven't loaded yet.209assert(e == NULL || k == e->klass(), "must be equal");210return e;211}212213// Return false if the entry could not be recorded on account214// of running out of space required to create a new entry.215bool KlassInfoTable::record_instance(const oop obj) {216Klass* k = obj->klass();217KlassInfoEntry* elt = lookup(k);218// elt may be NULL if it's a new klass for which we219// could not allocate space for a new entry in the hashtable.220if (elt != NULL) {221elt->set_count(elt->count() + 1);222elt->set_words(elt->words() + obj->size());223_size_of_instances_in_words += obj->size();224return true;225} else {226return false;227}228}229230void KlassInfoTable::iterate(KlassInfoClosure* cic) {231assert(_buckets != NULL, "Allocation failure should have been caught");232for (int index = 0; index < _num_buckets; index++) {233_buckets[index].iterate(cic);234}235}236237size_t KlassInfoTable::size_of_instances_in_words() const {238return _size_of_instances_in_words;239}240241// Return false if the entry could not be recorded on account242// of running out of space required to create a new entry.243bool KlassInfoTable::merge_entry(const KlassInfoEntry* cie) {244Klass* k = cie->klass();245KlassInfoEntry* elt = lookup(k);246// elt may be NULL if it's a new klass for which we247// could not allocate space for a new entry in the hashtable.248if (elt != NULL) {249elt->set_count(elt->count() + cie->count());250elt->set_words(elt->words() + cie->words());251_size_of_instances_in_words += cie->words();252return true;253}254return false;255}256257class KlassInfoTableMergeClosure : public KlassInfoClosure {258private:259KlassInfoTable* _dest;260bool _success;261public:262KlassInfoTableMergeClosure(KlassInfoTable* table) : _dest(table), _success(true) {}263void do_cinfo(KlassInfoEntry* cie) {264_success &= _dest->merge_entry(cie);265}266bool success() { return _success; }267};268269// merge from table270bool KlassInfoTable::merge(KlassInfoTable* table) {271KlassInfoTableMergeClosure closure(this);272table->iterate(&closure);273return closure.success();274}275276int KlassInfoHisto::sort_helper(KlassInfoEntry** e1, KlassInfoEntry** e2) {277return (*e1)->compare(*e1,*e2);278}279280KlassInfoHisto::KlassInfoHisto(KlassInfoTable* cit) :281_cit(cit) {282_elements = new (ResourceObj::C_HEAP, mtServiceability) GrowableArray<KlassInfoEntry*>(_histo_initial_size, mtServiceability);283}284285KlassInfoHisto::~KlassInfoHisto() {286delete _elements;287}288289void KlassInfoHisto::add(KlassInfoEntry* cie) {290elements()->append(cie);291}292293void KlassInfoHisto::sort() {294elements()->sort(KlassInfoHisto::sort_helper);295}296297void KlassInfoHisto::print_elements(outputStream* st) const {298// simplify the formatting (ILP32 vs LP64) - store the sum in 64-bit299int64_t total = 0;300uint64_t totalw = 0;301for(int i=0; i < elements()->length(); i++) {302st->print("%4d: ", i+1);303elements()->at(i)->print_on(st);304total += elements()->at(i)->count();305totalw += elements()->at(i)->words();306}307st->print_cr("Total " INT64_FORMAT_W(13) " " UINT64_FORMAT_W(13),308total, totalw * HeapWordSize);309}310311class HierarchyClosure : public KlassInfoClosure {312private:313GrowableArray<KlassInfoEntry*> *_elements;314public:315HierarchyClosure(GrowableArray<KlassInfoEntry*> *_elements) : _elements(_elements) {}316317void do_cinfo(KlassInfoEntry* cie) {318// ignore array classes319if (cie->klass()->is_instance_klass()) {320_elements->append(cie);321}322}323};324325void KlassHierarchy::print_class_hierarchy(outputStream* st, bool print_interfaces,326bool print_subclasses, char* classname) {327ResourceMark rm;328Stack <KlassInfoEntry*, mtClass> class_stack;329GrowableArray<KlassInfoEntry*> elements;330331// Add all classes to the KlassInfoTable, which allows for quick lookup.332// A KlassInfoEntry will be created for each class.333KlassInfoTable cit(true);334if (cit.allocation_failed()) {335st->print_cr("ERROR: Ran out of C-heap; hierarchy not generated");336return;337}338339// Add all created KlassInfoEntry instances to the elements array for easy340// iteration, and to allow each KlassInfoEntry instance to have a unique index.341HierarchyClosure hc(&elements);342cit.iterate(&hc);343344for(int i = 0; i < elements.length(); i++) {345KlassInfoEntry* cie = elements.at(i);346Klass* super = cie->klass()->super();347348// Set the index for the class.349cie->set_index(i + 1);350351// Add the class to the subclass array of its superclass.352if (super != NULL) {353KlassInfoEntry* super_cie = cit.lookup(super);354assert(super_cie != NULL, "could not lookup superclass");355super_cie->add_subclass(cie);356}357}358359// Set the do_print flag for each class that should be printed.360for(int i = 0; i < elements.length(); i++) {361KlassInfoEntry* cie = elements.at(i);362if (classname == NULL) {363// We are printing all classes.364cie->set_do_print(true);365} else {366// We are only printing the hierarchy of a specific class.367if (strcmp(classname, cie->klass()->external_name()) == 0) {368KlassHierarchy::set_do_print_for_class_hierarchy(cie, &cit, print_subclasses);369}370}371}372373// Now we do a depth first traversal of the class hierachry. The class_stack will374// maintain the list of classes we still need to process. Start things off375// by priming it with java.lang.Object.376KlassInfoEntry* jlo_cie = cit.lookup(vmClasses::Object_klass());377assert(jlo_cie != NULL, "could not lookup java.lang.Object");378class_stack.push(jlo_cie);379380// Repeatedly pop the top item off the stack, print its class info,381// and push all of its subclasses on to the stack. Do this until there382// are no classes left on the stack.383while (!class_stack.is_empty()) {384KlassInfoEntry* curr_cie = class_stack.pop();385if (curr_cie->do_print()) {386print_class(st, curr_cie, print_interfaces);387if (curr_cie->subclasses() != NULL) {388// Current class has subclasses, so push all of them onto the stack.389for (int i = 0; i < curr_cie->subclasses()->length(); i++) {390KlassInfoEntry* cie = curr_cie->subclasses()->at(i);391if (cie->do_print()) {392class_stack.push(cie);393}394}395}396}397}398399st->flush();400}401402// Sets the do_print flag for every superclass and subclass of the specified class.403void KlassHierarchy::set_do_print_for_class_hierarchy(KlassInfoEntry* cie, KlassInfoTable* cit,404bool print_subclasses) {405// Set do_print for all superclasses of this class.406Klass* super = ((InstanceKlass*)cie->klass())->java_super();407while (super != NULL) {408KlassInfoEntry* super_cie = cit->lookup(super);409super_cie->set_do_print(true);410super = super->super();411}412413// Set do_print for this class and all of its subclasses.414Stack <KlassInfoEntry*, mtClass> class_stack;415class_stack.push(cie);416while (!class_stack.is_empty()) {417KlassInfoEntry* curr_cie = class_stack.pop();418curr_cie->set_do_print(true);419if (print_subclasses && curr_cie->subclasses() != NULL) {420// Current class has subclasses, so push all of them onto the stack.421for (int i = 0; i < curr_cie->subclasses()->length(); i++) {422KlassInfoEntry* cie = curr_cie->subclasses()->at(i);423class_stack.push(cie);424}425}426}427}428429static void print_indent(outputStream* st, int indent) {430while (indent != 0) {431st->print("|");432indent--;433if (indent != 0) {434st->print(" ");435}436}437}438439// Print the class name and its unique ClassLoader identifer.440static void print_classname(outputStream* st, Klass* klass) {441oop loader_oop = klass->class_loader_data()->class_loader();442st->print("%s/", klass->external_name());443if (loader_oop == NULL) {444st->print("null");445} else {446st->print(INTPTR_FORMAT, p2i(klass->class_loader_data()));447}448}449450static void print_interface(outputStream* st, InstanceKlass* intf_klass, const char* intf_type, int indent) {451print_indent(st, indent);452st->print(" implements ");453print_classname(st, intf_klass);454st->print(" (%s intf)\n", intf_type);455}456457void KlassHierarchy::print_class(outputStream* st, KlassInfoEntry* cie, bool print_interfaces) {458ResourceMark rm;459InstanceKlass* klass = (InstanceKlass*)cie->klass();460int indent = 0;461462// Print indentation with proper indicators of superclass.463Klass* super = klass->super();464while (super != NULL) {465super = super->super();466indent++;467}468print_indent(st, indent);469if (indent != 0) st->print("--");470471// Print the class name, its unique ClassLoader identifer, and if it is an interface.472print_classname(st, klass);473if (klass->is_interface()) {474st->print(" (intf)");475}476// Special treatment for generated core reflection accessor classes: print invocation target.477if (ReflectionAccessorImplKlassHelper::is_generated_accessor(klass)) {478st->print(" (invokes: ");479ReflectionAccessorImplKlassHelper::print_invocation_target(st, klass);480st->print(")");481}482st->print("\n");483484// Print any interfaces the class has.485if (print_interfaces) {486Array<InstanceKlass*>* local_intfs = klass->local_interfaces();487Array<InstanceKlass*>* trans_intfs = klass->transitive_interfaces();488for (int i = 0; i < local_intfs->length(); i++) {489print_interface(st, local_intfs->at(i), "declared", indent);490}491for (int i = 0; i < trans_intfs->length(); i++) {492InstanceKlass* trans_interface = trans_intfs->at(i);493// Only print transitive interfaces if they are not also declared.494if (!local_intfs->contains(trans_interface)) {495print_interface(st, trans_interface, "inherited", indent);496}497}498}499}500501void KlassInfoHisto::print_histo_on(outputStream* st) {502st->print_cr(" num #instances #bytes class name (module)");503st->print_cr("-------------------------------------------------------");504print_elements(st);505}506507class HistoClosure : public KlassInfoClosure {508private:509KlassInfoHisto* _cih;510public:511HistoClosure(KlassInfoHisto* cih) : _cih(cih) {}512513void do_cinfo(KlassInfoEntry* cie) {514_cih->add(cie);515}516};517518class RecordInstanceClosure : public ObjectClosure {519private:520KlassInfoTable* _cit;521uintx _missed_count;522BoolObjectClosure* _filter;523public:524RecordInstanceClosure(KlassInfoTable* cit, BoolObjectClosure* filter) :525_cit(cit), _missed_count(0), _filter(filter) {}526527void do_object(oop obj) {528if (should_visit(obj)) {529if (!_cit->record_instance(obj)) {530_missed_count++;531}532}533}534535uintx missed_count() { return _missed_count; }536537private:538bool should_visit(oop obj) {539return _filter == NULL || _filter->do_object_b(obj);540}541};542543// Heap inspection for every worker.544// When native OOM happens for KlassInfoTable, set _success to false.545void ParHeapInspectTask::work(uint worker_id) {546uintx missed_count = 0;547bool merge_success = true;548if (!Atomic::load(&_success)) {549// other worker has failed on parallel iteration.550return;551}552553KlassInfoTable cit(false);554if (cit.allocation_failed()) {555// fail to allocate memory, stop parallel mode556Atomic::store(&_success, false);557return;558}559RecordInstanceClosure ric(&cit, _filter);560_poi->object_iterate(&ric, worker_id);561missed_count = ric.missed_count();562{563MutexLocker x(&_mutex);564merge_success = _shared_cit->merge(&cit);565}566if (merge_success) {567Atomic::add(&_missed_count, missed_count);568} else {569Atomic::store(&_success, false);570}571}572573uintx HeapInspection::populate_table(KlassInfoTable* cit, BoolObjectClosure *filter, uint parallel_thread_num) {574575// Try parallel first.576if (parallel_thread_num > 1) {577ResourceMark rm;578579WorkGang* gang = Universe::heap()->safepoint_workers();580if (gang != NULL) {581// The GC provided a WorkGang to be used during a safepoint.582583// Can't run with more threads than provided by the WorkGang.584WithUpdatedActiveWorkers update_and_restore(gang, parallel_thread_num);585586ParallelObjectIterator* poi = Universe::heap()->parallel_object_iterator(gang->active_workers());587if (poi != NULL) {588// The GC supports parallel object iteration.589590ParHeapInspectTask task(poi, cit, filter);591// Run task with the active workers.592gang->run_task(&task);593594delete poi;595if (task.success()) {596return task.missed_count();597}598}599}600}601602ResourceMark rm;603// If no parallel iteration available, run serially.604RecordInstanceClosure ric(cit, filter);605Universe::heap()->object_iterate(&ric);606return ric.missed_count();607}608609void HeapInspection::heap_inspection(outputStream* st, uint parallel_thread_num) {610ResourceMark rm;611612KlassInfoTable cit(false);613if (!cit.allocation_failed()) {614// populate table with object allocation info615uintx missed_count = populate_table(&cit, NULL, parallel_thread_num);616if (missed_count != 0) {617log_info(gc, classhisto)("WARNING: Ran out of C-heap; undercounted " UINTX_FORMAT618" total instances in data below",619missed_count);620}621622// Sort and print klass instance info623KlassInfoHisto histo(&cit);624HistoClosure hc(&histo);625626cit.iterate(&hc);627628histo.sort();629histo.print_histo_on(st);630} else {631st->print_cr("ERROR: Ran out of C-heap; histogram not generated");632}633st->flush();634}635636class FindInstanceClosure : public ObjectClosure {637private:638Klass* _klass;639GrowableArray<oop>* _result;640641public:642FindInstanceClosure(Klass* k, GrowableArray<oop>* result) : _klass(k), _result(result) {};643644void do_object(oop obj) {645if (obj->is_a(_klass)) {646// obj was read with AS_NO_KEEPALIVE, or equivalent.647// The object needs to be kept alive when it is published.648Universe::heap()->keep_alive(obj);649650_result->append(obj);651}652}653};654655void HeapInspection::find_instances_at_safepoint(Klass* k, GrowableArray<oop>* result) {656assert(SafepointSynchronize::is_at_safepoint(), "all threads are stopped");657assert(Heap_lock->is_locked(), "should have the Heap_lock");658659// Ensure that the heap is parsable660Universe::heap()->ensure_parsability(false); // no need to retire TALBs661662// Iterate over objects in the heap663FindInstanceClosure fic(k, result);664Universe::heap()->object_iterate(&fic);665}666667668