Path: blob/master/src/hotspot/share/services/heapDumper.cpp
41144 views
/*1* Copyright (c) 2005, 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 "jvm.h"26#include "classfile/classLoaderData.inline.hpp"27#include "classfile/classLoaderDataGraph.hpp"28#include "classfile/javaClasses.inline.hpp"29#include "classfile/symbolTable.hpp"30#include "classfile/vmClasses.hpp"31#include "classfile/vmSymbols.hpp"32#include "gc/shared/gcLocker.hpp"33#include "gc/shared/gcVMOperations.hpp"34#include "gc/shared/workgroup.hpp"35#include "jfr/jfrEvents.hpp"36#include "memory/allocation.inline.hpp"37#include "memory/resourceArea.hpp"38#include "memory/universe.hpp"39#include "oops/klass.inline.hpp"40#include "oops/objArrayKlass.hpp"41#include "oops/objArrayOop.inline.hpp"42#include "oops/oop.inline.hpp"43#include "oops/typeArrayOop.inline.hpp"44#include "runtime/frame.inline.hpp"45#include "runtime/handles.inline.hpp"46#include "runtime/javaCalls.hpp"47#include "runtime/jniHandles.hpp"48#include "runtime/os.hpp"49#include "runtime/reflectionUtils.hpp"50#include "runtime/thread.inline.hpp"51#include "runtime/threadSMR.hpp"52#include "runtime/vframe.hpp"53#include "runtime/vmThread.hpp"54#include "runtime/vmOperations.hpp"55#include "services/heapDumper.hpp"56#include "services/heapDumperCompression.hpp"57#include "services/threadService.hpp"58#include "utilities/macros.hpp"59#include "utilities/ostream.hpp"6061/*62* HPROF binary format - description copied from:63* src/share/demo/jvmti/hprof/hprof_io.c64*65*66* header "JAVA PROFILE 1.0.2" (0-terminated)67*68* u4 size of identifiers. Identifiers are used to represent69* UTF8 strings, objects, stack traces, etc. They usually70* have the same size as host pointers. For example, on71* Solaris and Win32, the size is 4.72* u4 high word73* u4 low word number of milliseconds since 0:00 GMT, 1/1/7074* [record]* a sequence of records.75*76*77* Record format:78*79* u1 a TAG denoting the type of the record80* u4 number of *microseconds* since the time stamp in the81* header. (wraps around in a little more than an hour)82* u4 number of bytes *remaining* in the record. Note that83* this number excludes the tag and the length field itself.84* [u1]* BODY of the record (a sequence of bytes)85*86*87* The following TAGs are supported:88*89* TAG BODY notes90*----------------------------------------------------------91* HPROF_UTF8 a UTF8-encoded name92*93* id name ID94* [u1]* UTF8 characters (no trailing zero)95*96* HPROF_LOAD_CLASS a newly loaded class97*98* u4 class serial number (> 0)99* id class object ID100* u4 stack trace serial number101* id class name ID102*103* HPROF_UNLOAD_CLASS an unloading class104*105* u4 class serial_number106*107* HPROF_FRAME a Java stack frame108*109* id stack frame ID110* id method name ID111* id method signature ID112* id source file name ID113* u4 class serial number114* i4 line number. >0: normal115* -1: unknown116* -2: compiled method117* -3: native method118*119* HPROF_TRACE a Java stack trace120*121* u4 stack trace serial number122* u4 thread serial number123* u4 number of frames124* [id]* stack frame IDs125*126*127* HPROF_ALLOC_SITES a set of heap allocation sites, obtained after GC128*129* u2 flags 0x0001: incremental vs. complete130* 0x0002: sorted by allocation vs. live131* 0x0004: whether to force a GC132* u4 cutoff ratio133* u4 total live bytes134* u4 total live instances135* u8 total bytes allocated136* u8 total instances allocated137* u4 number of sites that follow138* [u1 is_array: 0: normal object139* 2: object array140* 4: boolean array141* 5: char array142* 6: float array143* 7: double array144* 8: byte array145* 9: short array146* 10: int array147* 11: long array148* u4 class serial number (may be zero during startup)149* u4 stack trace serial number150* u4 number of bytes alive151* u4 number of instances alive152* u4 number of bytes allocated153* u4]* number of instance allocated154*155* HPROF_START_THREAD a newly started thread.156*157* u4 thread serial number (> 0)158* id thread object ID159* u4 stack trace serial number160* id thread name ID161* id thread group name ID162* id thread group parent name ID163*164* HPROF_END_THREAD a terminating thread.165*166* u4 thread serial number167*168* HPROF_HEAP_SUMMARY heap summary169*170* u4 total live bytes171* u4 total live instances172* u8 total bytes allocated173* u8 total instances allocated174*175* HPROF_HEAP_DUMP denote a heap dump176*177* [heap dump sub-records]*178*179* There are four kinds of heap dump sub-records:180*181* u1 sub-record type182*183* HPROF_GC_ROOT_UNKNOWN unknown root184*185* id object ID186*187* HPROF_GC_ROOT_THREAD_OBJ thread object188*189* id thread object ID (may be 0 for a190* thread newly attached through JNI)191* u4 thread sequence number192* u4 stack trace sequence number193*194* HPROF_GC_ROOT_JNI_GLOBAL JNI global ref root195*196* id object ID197* id JNI global ref ID198*199* HPROF_GC_ROOT_JNI_LOCAL JNI local ref200*201* id object ID202* u4 thread serial number203* u4 frame # in stack trace (-1 for empty)204*205* HPROF_GC_ROOT_JAVA_FRAME Java stack frame206*207* id object ID208* u4 thread serial number209* u4 frame # in stack trace (-1 for empty)210*211* HPROF_GC_ROOT_NATIVE_STACK Native stack212*213* id object ID214* u4 thread serial number215*216* HPROF_GC_ROOT_STICKY_CLASS System class217*218* id object ID219*220* HPROF_GC_ROOT_THREAD_BLOCK Reference from thread block221*222* id object ID223* u4 thread serial number224*225* HPROF_GC_ROOT_MONITOR_USED Busy monitor226*227* id object ID228*229* HPROF_GC_CLASS_DUMP dump of a class object230*231* id class object ID232* u4 stack trace serial number233* id super class object ID234* id class loader object ID235* id signers object ID236* id protection domain object ID237* id reserved238* id reserved239*240* u4 instance size (in bytes)241*242* u2 size of constant pool243* [u2, constant pool index,244* ty, type245* 2: object246* 4: boolean247* 5: char248* 6: float249* 7: double250* 8: byte251* 9: short252* 10: int253* 11: long254* vl]* and value255*256* u2 number of static fields257* [id, static field name,258* ty, type,259* vl]* and value260*261* u2 number of inst. fields (not inc. super)262* [id, instance field name,263* ty]* type264*265* HPROF_GC_INSTANCE_DUMP dump of a normal object266*267* id object ID268* u4 stack trace serial number269* id class object ID270* u4 number of bytes that follow271* [vl]* instance field values (class, followed272* by super, super's super ...)273*274* HPROF_GC_OBJ_ARRAY_DUMP dump of an object array275*276* id array object ID277* u4 stack trace serial number278* u4 number of elements279* id array class ID280* [id]* elements281*282* HPROF_GC_PRIM_ARRAY_DUMP dump of a primitive array283*284* id array object ID285* u4 stack trace serial number286* u4 number of elements287* u1 element type288* 4: boolean array289* 5: char array290* 6: float array291* 7: double array292* 8: byte array293* 9: short array294* 10: int array295* 11: long array296* [u1]* elements297*298* HPROF_CPU_SAMPLES a set of sample traces of running threads299*300* u4 total number of samples301* u4 # of traces302* [u4 # of samples303* u4]* stack trace serial number304*305* HPROF_CONTROL_SETTINGS the settings of on/off switches306*307* u4 0x00000001: alloc traces on/off308* 0x00000002: cpu sampling on/off309* u2 stack trace depth310*311*312* When the header is "JAVA PROFILE 1.0.2" a heap dump can optionally313* be generated as a sequence of heap dump segments. This sequence is314* terminated by an end record. The additional tags allowed by format315* "JAVA PROFILE 1.0.2" are:316*317* HPROF_HEAP_DUMP_SEGMENT denote a heap dump segment318*319* [heap dump sub-records]*320* The same sub-record types allowed by HPROF_HEAP_DUMP321*322* HPROF_HEAP_DUMP_END denotes the end of a heap dump323*324*/325326327// HPROF tags328329typedef enum {330// top-level records331HPROF_UTF8 = 0x01,332HPROF_LOAD_CLASS = 0x02,333HPROF_UNLOAD_CLASS = 0x03,334HPROF_FRAME = 0x04,335HPROF_TRACE = 0x05,336HPROF_ALLOC_SITES = 0x06,337HPROF_HEAP_SUMMARY = 0x07,338HPROF_START_THREAD = 0x0A,339HPROF_END_THREAD = 0x0B,340HPROF_HEAP_DUMP = 0x0C,341HPROF_CPU_SAMPLES = 0x0D,342HPROF_CONTROL_SETTINGS = 0x0E,343344// 1.0.2 record types345HPROF_HEAP_DUMP_SEGMENT = 0x1C,346HPROF_HEAP_DUMP_END = 0x2C,347348// field types349HPROF_ARRAY_OBJECT = 0x01,350HPROF_NORMAL_OBJECT = 0x02,351HPROF_BOOLEAN = 0x04,352HPROF_CHAR = 0x05,353HPROF_FLOAT = 0x06,354HPROF_DOUBLE = 0x07,355HPROF_BYTE = 0x08,356HPROF_SHORT = 0x09,357HPROF_INT = 0x0A,358HPROF_LONG = 0x0B,359360// data-dump sub-records361HPROF_GC_ROOT_UNKNOWN = 0xFF,362HPROF_GC_ROOT_JNI_GLOBAL = 0x01,363HPROF_GC_ROOT_JNI_LOCAL = 0x02,364HPROF_GC_ROOT_JAVA_FRAME = 0x03,365HPROF_GC_ROOT_NATIVE_STACK = 0x04,366HPROF_GC_ROOT_STICKY_CLASS = 0x05,367HPROF_GC_ROOT_THREAD_BLOCK = 0x06,368HPROF_GC_ROOT_MONITOR_USED = 0x07,369HPROF_GC_ROOT_THREAD_OBJ = 0x08,370HPROF_GC_CLASS_DUMP = 0x20,371HPROF_GC_INSTANCE_DUMP = 0x21,372HPROF_GC_OBJ_ARRAY_DUMP = 0x22,373HPROF_GC_PRIM_ARRAY_DUMP = 0x23374} hprofTag;375376// Default stack trace ID (used for dummy HPROF_TRACE record)377enum {378STACK_TRACE_ID = 1,379INITIAL_CLASS_COUNT = 200380};381382// Supports I/O operations for a dump383384class DumpWriter : public StackObj {385private:386enum {387io_buffer_max_size = 1*M,388io_buffer_max_waste = 10*K,389dump_segment_header_size = 9390};391392char* _buffer; // internal buffer393size_t _size;394size_t _pos;395396bool _in_dump_segment; // Are we currently in a dump segment?397bool _is_huge_sub_record; // Are we writing a sub-record larger than the buffer size?398DEBUG_ONLY(size_t _sub_record_left;) // The bytes not written for the current sub-record.399DEBUG_ONLY(bool _sub_record_ended;) // True if we have called the end_sub_record().400401CompressionBackend _backend; // Does the actual writing.402403void flush();404405char* buffer() const { return _buffer; }406size_t buffer_size() const { return _size; }407size_t position() const { return _pos; }408void set_position(size_t pos) { _pos = pos; }409410// Can be called if we have enough room in the buffer.411void write_fast(void* s, size_t len);412413// Returns true if we have enough room in the buffer for 'len' bytes.414bool can_write_fast(size_t len);415416public:417// Takes ownership of the writer and compressor.418DumpWriter(AbstractWriter* writer, AbstractCompressor* compressor);419420~DumpWriter();421422// total number of bytes written to the disk423julong bytes_written() const { return (julong) _backend.get_written(); }424425char const* error() const { return _backend.error(); }426427// writer functions428void write_raw(void* s, size_t len);429void write_u1(u1 x);430void write_u2(u2 x);431void write_u4(u4 x);432void write_u8(u8 x);433void write_objectID(oop o);434void write_symbolID(Symbol* o);435void write_classID(Klass* k);436void write_id(u4 x);437438// Start a new sub-record. Starts a new heap dump segment if needed.439void start_sub_record(u1 tag, u4 len);440// Ends the current sub-record.441void end_sub_record();442// Finishes the current dump segment if not already finished.443void finish_dump_segment();444445// Called by threads used for parallel writing.446void writer_loop() { _backend.thread_loop(); }447// Called when finished to release the threads.448void deactivate() { flush(); _backend.deactivate(); }449};450451// Check for error after constructing the object and destroy it in case of an error.452DumpWriter::DumpWriter(AbstractWriter* writer, AbstractCompressor* compressor) :453_buffer(NULL),454_size(0),455_pos(0),456_in_dump_segment(false),457_backend(writer, compressor, io_buffer_max_size, io_buffer_max_waste) {458flush();459}460461DumpWriter::~DumpWriter() {462flush();463}464465void DumpWriter::write_fast(void* s, size_t len) {466assert(!_in_dump_segment || (_sub_record_left >= len), "sub-record too large");467assert(buffer_size() - position() >= len, "Must fit");468debug_only(_sub_record_left -= len);469470memcpy(buffer() + position(), s, len);471set_position(position() + len);472}473474bool DumpWriter::can_write_fast(size_t len) {475return buffer_size() - position() >= len;476}477478// write raw bytes479void DumpWriter::write_raw(void* s, size_t len) {480assert(!_in_dump_segment || (_sub_record_left >= len), "sub-record too large");481debug_only(_sub_record_left -= len);482483// flush buffer to make room.484while (len > buffer_size() - position()) {485assert(!_in_dump_segment || _is_huge_sub_record,486"Cannot overflow in non-huge sub-record.");487488size_t to_write = buffer_size() - position();489memcpy(buffer() + position(), s, to_write);490s = (void*) ((char*) s + to_write);491len -= to_write;492set_position(position() + to_write);493flush();494}495496memcpy(buffer() + position(), s, len);497set_position(position() + len);498}499500// flush any buffered bytes to the file501void DumpWriter::flush() {502_backend.get_new_buffer(&_buffer, &_pos, &_size);503}504505// Makes sure we inline the fast write into the write_u* functions. This is a big speedup.506#define WRITE_KNOWN_TYPE(p, len) do { if (can_write_fast((len))) write_fast((p), (len)); \507else write_raw((p), (len)); } while (0)508509void DumpWriter::write_u1(u1 x) {510WRITE_KNOWN_TYPE((void*) &x, 1);511}512513void DumpWriter::write_u2(u2 x) {514u2 v;515Bytes::put_Java_u2((address)&v, x);516WRITE_KNOWN_TYPE((void*)&v, 2);517}518519void DumpWriter::write_u4(u4 x) {520u4 v;521Bytes::put_Java_u4((address)&v, x);522WRITE_KNOWN_TYPE((void*)&v, 4);523}524525void DumpWriter::write_u8(u8 x) {526u8 v;527Bytes::put_Java_u8((address)&v, x);528WRITE_KNOWN_TYPE((void*)&v, 8);529}530531void DumpWriter::write_objectID(oop o) {532address a = cast_from_oop<address>(o);533#ifdef _LP64534write_u8((u8)a);535#else536write_u4((u4)a);537#endif538}539540void DumpWriter::write_symbolID(Symbol* s) {541address a = (address)((uintptr_t)s);542#ifdef _LP64543write_u8((u8)a);544#else545write_u4((u4)a);546#endif547}548549void DumpWriter::write_id(u4 x) {550#ifdef _LP64551write_u8((u8) x);552#else553write_u4(x);554#endif555}556557// We use java mirror as the class ID558void DumpWriter::write_classID(Klass* k) {559write_objectID(k->java_mirror());560}561562void DumpWriter::finish_dump_segment() {563if (_in_dump_segment) {564assert(_sub_record_left == 0, "Last sub-record not written completely");565assert(_sub_record_ended, "sub-record must have ended");566567// Fix up the dump segment length if we haven't written a huge sub-record last568// (in which case the segment length was already set to the correct value initially).569if (!_is_huge_sub_record) {570assert(position() > dump_segment_header_size, "Dump segment should have some content");571Bytes::put_Java_u4((address) (buffer() + 5),572(u4) (position() - dump_segment_header_size));573}574575flush();576_in_dump_segment = false;577}578}579580void DumpWriter::start_sub_record(u1 tag, u4 len) {581if (!_in_dump_segment) {582if (position() > 0) {583flush();584}585586assert(position() == 0, "Must be at the start");587588write_u1(HPROF_HEAP_DUMP_SEGMENT);589write_u4(0); // timestamp590// Will be fixed up later if we add more sub-records. If this is a huge sub-record,591// this is already the correct length, since we don't add more sub-records.592write_u4(len);593_in_dump_segment = true;594_is_huge_sub_record = len > buffer_size() - dump_segment_header_size;595} else if (_is_huge_sub_record || (len > buffer_size() - position())) {596// This object will not fit in completely or the last sub-record was huge.597// Finish the current segement and try again.598finish_dump_segment();599start_sub_record(tag, len);600601return;602}603604debug_only(_sub_record_left = len);605debug_only(_sub_record_ended = false);606607write_u1(tag);608}609610void DumpWriter::end_sub_record() {611assert(_in_dump_segment, "must be in dump segment");612assert(_sub_record_left == 0, "sub-record not written completely");613assert(!_sub_record_ended, "Must not have ended yet");614debug_only(_sub_record_ended = true);615}616617// Support class with a collection of functions used when dumping the heap618619class DumperSupport : AllStatic {620public:621622// write a header of the given type623static void write_header(DumpWriter* writer, hprofTag tag, u4 len);624625// returns hprof tag for the given type signature626static hprofTag sig2tag(Symbol* sig);627// returns hprof tag for the given basic type628static hprofTag type2tag(BasicType type);629// Returns the size of the data to write.630static u4 sig2size(Symbol* sig);631632// returns the size of the instance of the given class633static u4 instance_size(Klass* k);634635// dump a jfloat636static void dump_float(DumpWriter* writer, jfloat f);637// dump a jdouble638static void dump_double(DumpWriter* writer, jdouble d);639// dumps the raw value of the given field640static void dump_field_value(DumpWriter* writer, char type, oop obj, int offset);641// returns the size of the static fields; also counts the static fields642static u4 get_static_fields_size(InstanceKlass* ik, u2& field_count);643// dumps static fields of the given class644static void dump_static_fields(DumpWriter* writer, Klass* k);645// dump the raw values of the instance fields of the given object646static void dump_instance_fields(DumpWriter* writer, oop o);647// get the count of the instance fields for a given class648static u2 get_instance_fields_count(InstanceKlass* ik);649// dumps the definition of the instance fields for a given class650static void dump_instance_field_descriptors(DumpWriter* writer, Klass* k);651// creates HPROF_GC_INSTANCE_DUMP record for the given object652static void dump_instance(DumpWriter* writer, oop o);653// creates HPROF_GC_CLASS_DUMP record for the given class and each of its654// array classes655static void dump_class_and_array_classes(DumpWriter* writer, Klass* k);656// creates HPROF_GC_CLASS_DUMP record for a given primitive array657// class (and each multi-dimensional array class too)658static void dump_basic_type_array_class(DumpWriter* writer, Klass* k);659660// creates HPROF_GC_OBJ_ARRAY_DUMP record for the given object array661static void dump_object_array(DumpWriter* writer, objArrayOop array);662// creates HPROF_GC_PRIM_ARRAY_DUMP record for the given type array663static void dump_prim_array(DumpWriter* writer, typeArrayOop array);664// create HPROF_FRAME record for the given method and bci665static void dump_stack_frame(DumpWriter* writer, int frame_serial_num, int class_serial_num, Method* m, int bci);666667// check if we need to truncate an array668static int calculate_array_max_length(DumpWriter* writer, arrayOop array, short header_size);669670// fixes up the current dump record and writes HPROF_HEAP_DUMP_END record671static void end_of_dump(DumpWriter* writer);672673static oop mask_dormant_archived_object(oop o) {674if (o != NULL && o->klass()->java_mirror() == NULL) {675// Ignore this object since the corresponding java mirror is not loaded.676// Might be a dormant archive object.677return NULL;678} else {679return o;680}681}682};683684// write a header of the given type685void DumperSupport:: write_header(DumpWriter* writer, hprofTag tag, u4 len) {686writer->write_u1((u1)tag);687writer->write_u4(0); // current ticks688writer->write_u4(len);689}690691// returns hprof tag for the given type signature692hprofTag DumperSupport::sig2tag(Symbol* sig) {693switch (sig->char_at(0)) {694case JVM_SIGNATURE_CLASS : return HPROF_NORMAL_OBJECT;695case JVM_SIGNATURE_ARRAY : return HPROF_NORMAL_OBJECT;696case JVM_SIGNATURE_BYTE : return HPROF_BYTE;697case JVM_SIGNATURE_CHAR : return HPROF_CHAR;698case JVM_SIGNATURE_FLOAT : return HPROF_FLOAT;699case JVM_SIGNATURE_DOUBLE : return HPROF_DOUBLE;700case JVM_SIGNATURE_INT : return HPROF_INT;701case JVM_SIGNATURE_LONG : return HPROF_LONG;702case JVM_SIGNATURE_SHORT : return HPROF_SHORT;703case JVM_SIGNATURE_BOOLEAN : return HPROF_BOOLEAN;704default : ShouldNotReachHere(); /* to shut up compiler */ return HPROF_BYTE;705}706}707708hprofTag DumperSupport::type2tag(BasicType type) {709switch (type) {710case T_BYTE : return HPROF_BYTE;711case T_CHAR : return HPROF_CHAR;712case T_FLOAT : return HPROF_FLOAT;713case T_DOUBLE : return HPROF_DOUBLE;714case T_INT : return HPROF_INT;715case T_LONG : return HPROF_LONG;716case T_SHORT : return HPROF_SHORT;717case T_BOOLEAN : return HPROF_BOOLEAN;718default : ShouldNotReachHere(); /* to shut up compiler */ return HPROF_BYTE;719}720}721722u4 DumperSupport::sig2size(Symbol* sig) {723switch (sig->char_at(0)) {724case JVM_SIGNATURE_CLASS:725case JVM_SIGNATURE_ARRAY: return sizeof(address);726case JVM_SIGNATURE_BOOLEAN:727case JVM_SIGNATURE_BYTE: return 1;728case JVM_SIGNATURE_SHORT:729case JVM_SIGNATURE_CHAR: return 2;730case JVM_SIGNATURE_INT:731case JVM_SIGNATURE_FLOAT: return 4;732case JVM_SIGNATURE_LONG:733case JVM_SIGNATURE_DOUBLE: return 8;734default: ShouldNotReachHere(); /* to shut up compiler */ return 0;735}736}737738// dump a jfloat739void DumperSupport::dump_float(DumpWriter* writer, jfloat f) {740if (g_isnan(f)) {741writer->write_u4(0x7fc00000); // collapsing NaNs742} else {743union {744int i;745float f;746} u;747u.f = (float)f;748writer->write_u4((u4)u.i);749}750}751752// dump a jdouble753void DumperSupport::dump_double(DumpWriter* writer, jdouble d) {754union {755jlong l;756double d;757} u;758if (g_isnan(d)) { // collapsing NaNs759u.l = (jlong)(0x7ff80000);760u.l = (u.l << 32);761} else {762u.d = (double)d;763}764writer->write_u8((u8)u.l);765}766767// dumps the raw value of the given field768void DumperSupport::dump_field_value(DumpWriter* writer, char type, oop obj, int offset) {769switch (type) {770case JVM_SIGNATURE_CLASS :771case JVM_SIGNATURE_ARRAY : {772oop o = obj->obj_field_access<ON_UNKNOWN_OOP_REF | AS_NO_KEEPALIVE>(offset);773if (o != NULL && log_is_enabled(Debug, cds, heap) && mask_dormant_archived_object(o) == NULL) {774ResourceMark rm;775log_debug(cds, heap)("skipped dormant archived object " INTPTR_FORMAT " (%s) referenced by " INTPTR_FORMAT " (%s)",776p2i(o), o->klass()->external_name(),777p2i(obj), obj->klass()->external_name());778}779o = mask_dormant_archived_object(o);780assert(oopDesc::is_oop_or_null(o), "Expected an oop or NULL at " PTR_FORMAT, p2i(o));781writer->write_objectID(o);782break;783}784case JVM_SIGNATURE_BYTE : {785jbyte b = obj->byte_field(offset);786writer->write_u1((u1)b);787break;788}789case JVM_SIGNATURE_CHAR : {790jchar c = obj->char_field(offset);791writer->write_u2((u2)c);792break;793}794case JVM_SIGNATURE_SHORT : {795jshort s = obj->short_field(offset);796writer->write_u2((u2)s);797break;798}799case JVM_SIGNATURE_FLOAT : {800jfloat f = obj->float_field(offset);801dump_float(writer, f);802break;803}804case JVM_SIGNATURE_DOUBLE : {805jdouble d = obj->double_field(offset);806dump_double(writer, d);807break;808}809case JVM_SIGNATURE_INT : {810jint i = obj->int_field(offset);811writer->write_u4((u4)i);812break;813}814case JVM_SIGNATURE_LONG : {815jlong l = obj->long_field(offset);816writer->write_u8((u8)l);817break;818}819case JVM_SIGNATURE_BOOLEAN : {820jboolean b = obj->bool_field(offset);821writer->write_u1((u1)b);822break;823}824default : {825ShouldNotReachHere();826break;827}828}829}830831// returns the size of the instance of the given class832u4 DumperSupport::instance_size(Klass* k) {833InstanceKlass* ik = InstanceKlass::cast(k);834u4 size = 0;835836for (FieldStream fld(ik, false, false); !fld.eos(); fld.next()) {837if (!fld.access_flags().is_static()) {838size += sig2size(fld.signature());839}840}841return size;842}843844u4 DumperSupport::get_static_fields_size(InstanceKlass* ik, u2& field_count) {845field_count = 0;846u4 size = 0;847848for (FieldStream fldc(ik, true, true); !fldc.eos(); fldc.next()) {849if (fldc.access_flags().is_static()) {850field_count++;851size += sig2size(fldc.signature());852}853}854855// Add in resolved_references which is referenced by the cpCache856// The resolved_references is an array per InstanceKlass holding the857// strings and other oops resolved from the constant pool.858oop resolved_references = ik->constants()->resolved_references_or_null();859if (resolved_references != NULL) {860field_count++;861size += sizeof(address);862863// Add in the resolved_references of the used previous versions of the class864// in the case of RedefineClasses865InstanceKlass* prev = ik->previous_versions();866while (prev != NULL && prev->constants()->resolved_references_or_null() != NULL) {867field_count++;868size += sizeof(address);869prev = prev->previous_versions();870}871}872873// Also provide a pointer to the init_lock if present, so there aren't unreferenced int[0]874// arrays.875oop init_lock = ik->init_lock();876if (init_lock != NULL) {877field_count++;878size += sizeof(address);879}880881// We write the value itself plus a name and a one byte type tag per field.882return size + field_count * (sizeof(address) + 1);883}884885// dumps static fields of the given class886void DumperSupport::dump_static_fields(DumpWriter* writer, Klass* k) {887InstanceKlass* ik = InstanceKlass::cast(k);888889// dump the field descriptors and raw values890for (FieldStream fld(ik, true, true); !fld.eos(); fld.next()) {891if (fld.access_flags().is_static()) {892Symbol* sig = fld.signature();893894writer->write_symbolID(fld.name()); // name895writer->write_u1(sig2tag(sig)); // type896897// value898dump_field_value(writer, sig->char_at(0), ik->java_mirror(), fld.offset());899}900}901902// Add resolved_references for each class that has them903oop resolved_references = ik->constants()->resolved_references_or_null();904if (resolved_references != NULL) {905writer->write_symbolID(vmSymbols::resolved_references_name()); // name906writer->write_u1(sig2tag(vmSymbols::object_array_signature())); // type907writer->write_objectID(resolved_references);908909// Also write any previous versions910InstanceKlass* prev = ik->previous_versions();911while (prev != NULL && prev->constants()->resolved_references_or_null() != NULL) {912writer->write_symbolID(vmSymbols::resolved_references_name()); // name913writer->write_u1(sig2tag(vmSymbols::object_array_signature())); // type914writer->write_objectID(prev->constants()->resolved_references());915prev = prev->previous_versions();916}917}918919// Add init lock to the end if the class is not yet initialized920oop init_lock = ik->init_lock();921if (init_lock != NULL) {922writer->write_symbolID(vmSymbols::init_lock_name()); // name923writer->write_u1(sig2tag(vmSymbols::int_array_signature())); // type924writer->write_objectID(init_lock);925}926}927928// dump the raw values of the instance fields of the given object929void DumperSupport::dump_instance_fields(DumpWriter* writer, oop o) {930InstanceKlass* ik = InstanceKlass::cast(o->klass());931932for (FieldStream fld(ik, false, false); !fld.eos(); fld.next()) {933if (!fld.access_flags().is_static()) {934Symbol* sig = fld.signature();935dump_field_value(writer, sig->char_at(0), o, fld.offset());936}937}938}939940// dumps the definition of the instance fields for a given class941u2 DumperSupport::get_instance_fields_count(InstanceKlass* ik) {942u2 field_count = 0;943944for (FieldStream fldc(ik, true, true); !fldc.eos(); fldc.next()) {945if (!fldc.access_flags().is_static()) field_count++;946}947948return field_count;949}950951// dumps the definition of the instance fields for a given class952void DumperSupport::dump_instance_field_descriptors(DumpWriter* writer, Klass* k) {953InstanceKlass* ik = InstanceKlass::cast(k);954955// dump the field descriptors956for (FieldStream fld(ik, true, true); !fld.eos(); fld.next()) {957if (!fld.access_flags().is_static()) {958Symbol* sig = fld.signature();959960writer->write_symbolID(fld.name()); // name961writer->write_u1(sig2tag(sig)); // type962}963}964}965966// creates HPROF_GC_INSTANCE_DUMP record for the given object967void DumperSupport::dump_instance(DumpWriter* writer, oop o) {968InstanceKlass* ik = InstanceKlass::cast(o->klass());969u4 is = instance_size(ik);970u4 size = 1 + sizeof(address) + 4 + sizeof(address) + 4 + is;971972writer->start_sub_record(HPROF_GC_INSTANCE_DUMP, size);973writer->write_objectID(o);974writer->write_u4(STACK_TRACE_ID);975976// class ID977writer->write_classID(ik);978979// number of bytes that follow980writer->write_u4(is);981982// field values983dump_instance_fields(writer, o);984985writer->end_sub_record();986}987988// creates HPROF_GC_CLASS_DUMP record for the given class and each of989// its array classes990void DumperSupport::dump_class_and_array_classes(DumpWriter* writer, Klass* k) {991InstanceKlass* ik = InstanceKlass::cast(k);992993// We can safepoint and do a heap dump at a point where we have a Klass,994// but no java mirror class has been setup for it. So we need to check995// that the class is at least loaded, to avoid crash from a null mirror.996if (!ik->is_loaded()) {997return;998}9991000u2 static_fields_count = 0;1001u4 static_size = get_static_fields_size(ik, static_fields_count);1002u2 instance_fields_count = get_instance_fields_count(ik);1003u4 instance_fields_size = instance_fields_count * (sizeof(address) + 1);1004u4 size = 1 + sizeof(address) + 4 + 6 * sizeof(address) + 4 + 2 + 2 + static_size + 2 + instance_fields_size;10051006writer->start_sub_record(HPROF_GC_CLASS_DUMP, size);10071008// class ID1009writer->write_classID(ik);1010writer->write_u4(STACK_TRACE_ID);10111012// super class ID1013InstanceKlass* java_super = ik->java_super();1014if (java_super == NULL) {1015writer->write_objectID(oop(NULL));1016} else {1017writer->write_classID(java_super);1018}10191020writer->write_objectID(ik->class_loader());1021writer->write_objectID(ik->signers());1022writer->write_objectID(ik->protection_domain());10231024// reserved1025writer->write_objectID(oop(NULL));1026writer->write_objectID(oop(NULL));10271028// instance size1029writer->write_u4(DumperSupport::instance_size(ik));10301031// size of constant pool - ignored by HAT 1.11032writer->write_u2(0);10331034// static fields1035writer->write_u2(static_fields_count);1036dump_static_fields(writer, ik);10371038// description of instance fields1039writer->write_u2(instance_fields_count);1040dump_instance_field_descriptors(writer, ik);10411042writer->end_sub_record();10431044// array classes1045k = ik->array_klass_or_null();1046while (k != NULL) {1047assert(k->is_objArray_klass(), "not an ObjArrayKlass");10481049u4 size = 1 + sizeof(address) + 4 + 6 * sizeof(address) + 4 + 2 + 2 + 2;1050writer->start_sub_record(HPROF_GC_CLASS_DUMP, size);1051writer->write_classID(k);1052writer->write_u4(STACK_TRACE_ID);10531054// super class of array classes is java.lang.Object1055java_super = k->java_super();1056assert(java_super != NULL, "checking");1057writer->write_classID(java_super);10581059writer->write_objectID(ik->class_loader());1060writer->write_objectID(ik->signers());1061writer->write_objectID(ik->protection_domain());10621063writer->write_objectID(oop(NULL)); // reserved1064writer->write_objectID(oop(NULL));1065writer->write_u4(0); // instance size1066writer->write_u2(0); // constant pool1067writer->write_u2(0); // static fields1068writer->write_u2(0); // instance fields10691070writer->end_sub_record();10711072// get the array class for the next rank1073k = k->array_klass_or_null();1074}1075}10761077// creates HPROF_GC_CLASS_DUMP record for a given primitive array1078// class (and each multi-dimensional array class too)1079void DumperSupport::dump_basic_type_array_class(DumpWriter* writer, Klass* k) {1080// array classes1081while (k != NULL) {1082Klass* klass = k;10831084u4 size = 1 + sizeof(address) + 4 + 6 * sizeof(address) + 4 + 2 + 2 + 2;1085writer->start_sub_record(HPROF_GC_CLASS_DUMP, size);1086writer->write_classID(klass);1087writer->write_u4(STACK_TRACE_ID);10881089// super class of array classes is java.lang.Object1090InstanceKlass* java_super = klass->java_super();1091assert(java_super != NULL, "checking");1092writer->write_classID(java_super);10931094writer->write_objectID(oop(NULL)); // loader1095writer->write_objectID(oop(NULL)); // signers1096writer->write_objectID(oop(NULL)); // protection domain10971098writer->write_objectID(oop(NULL)); // reserved1099writer->write_objectID(oop(NULL));1100writer->write_u4(0); // instance size1101writer->write_u2(0); // constant pool1102writer->write_u2(0); // static fields1103writer->write_u2(0); // instance fields11041105writer->end_sub_record();11061107// get the array class for the next rank1108k = klass->array_klass_or_null();1109}1110}11111112// Hprof uses an u4 as record length field,1113// which means we need to truncate arrays that are too long.1114int DumperSupport::calculate_array_max_length(DumpWriter* writer, arrayOop array, short header_size) {1115BasicType type = ArrayKlass::cast(array->klass())->element_type();1116assert(type >= T_BOOLEAN && type <= T_OBJECT, "invalid array element type");11171118int length = array->length();11191120int type_size;1121if (type == T_OBJECT) {1122type_size = sizeof(address);1123} else {1124type_size = type2aelembytes(type);1125}11261127size_t length_in_bytes = (size_t)length * type_size;1128uint max_bytes = max_juint - header_size;11291130if (length_in_bytes > max_bytes) {1131length = max_bytes / type_size;1132length_in_bytes = (size_t)length * type_size;11331134warning("cannot dump array of type %s[] with length %d; truncating to length %d",1135type2name_tab[type], array->length(), length);1136}1137return length;1138}11391140// creates HPROF_GC_OBJ_ARRAY_DUMP record for the given object array1141void DumperSupport::dump_object_array(DumpWriter* writer, objArrayOop array) {1142// sizeof(u1) + 2 * sizeof(u4) + sizeof(objectID) + sizeof(classID)1143short header_size = 1 + 2 * 4 + 2 * sizeof(address);1144int length = calculate_array_max_length(writer, array, header_size);1145u4 size = header_size + length * sizeof(address);11461147writer->start_sub_record(HPROF_GC_OBJ_ARRAY_DUMP, size);1148writer->write_objectID(array);1149writer->write_u4(STACK_TRACE_ID);1150writer->write_u4(length);11511152// array class ID1153writer->write_classID(array->klass());11541155// [id]* elements1156for (int index = 0; index < length; index++) {1157oop o = array->obj_at(index);1158if (o != NULL && log_is_enabled(Debug, cds, heap) && mask_dormant_archived_object(o) == NULL) {1159ResourceMark rm;1160log_debug(cds, heap)("skipped dormant archived object " INTPTR_FORMAT " (%s) referenced by " INTPTR_FORMAT " (%s)",1161p2i(o), o->klass()->external_name(),1162p2i(array), array->klass()->external_name());1163}1164o = mask_dormant_archived_object(o);1165writer->write_objectID(o);1166}11671168writer->end_sub_record();1169}11701171#define WRITE_ARRAY(Array, Type, Size, Length) \1172for (int i = 0; i < Length; i++) { writer->write_##Size((Size)Array->Type##_at(i)); }11731174// creates HPROF_GC_PRIM_ARRAY_DUMP record for the given type array1175void DumperSupport::dump_prim_array(DumpWriter* writer, typeArrayOop array) {1176BasicType type = TypeArrayKlass::cast(array->klass())->element_type();11771178// 2 * sizeof(u1) + 2 * sizeof(u4) + sizeof(objectID)1179short header_size = 2 * 1 + 2 * 4 + sizeof(address);11801181int length = calculate_array_max_length(writer, array, header_size);1182int type_size = type2aelembytes(type);1183u4 length_in_bytes = (u4)length * type_size;1184u4 size = header_size + length_in_bytes;11851186writer->start_sub_record(HPROF_GC_PRIM_ARRAY_DUMP, size);1187writer->write_objectID(array);1188writer->write_u4(STACK_TRACE_ID);1189writer->write_u4(length);1190writer->write_u1(type2tag(type));11911192// nothing to copy1193if (length == 0) {1194writer->end_sub_record();1195return;1196}11971198// If the byte ordering is big endian then we can copy most types directly11991200switch (type) {1201case T_INT : {1202if (Endian::is_Java_byte_ordering_different()) {1203WRITE_ARRAY(array, int, u4, length);1204} else {1205writer->write_raw((void*)(array->int_at_addr(0)), length_in_bytes);1206}1207break;1208}1209case T_BYTE : {1210writer->write_raw((void*)(array->byte_at_addr(0)), length_in_bytes);1211break;1212}1213case T_CHAR : {1214if (Endian::is_Java_byte_ordering_different()) {1215WRITE_ARRAY(array, char, u2, length);1216} else {1217writer->write_raw((void*)(array->char_at_addr(0)), length_in_bytes);1218}1219break;1220}1221case T_SHORT : {1222if (Endian::is_Java_byte_ordering_different()) {1223WRITE_ARRAY(array, short, u2, length);1224} else {1225writer->write_raw((void*)(array->short_at_addr(0)), length_in_bytes);1226}1227break;1228}1229case T_BOOLEAN : {1230if (Endian::is_Java_byte_ordering_different()) {1231WRITE_ARRAY(array, bool, u1, length);1232} else {1233writer->write_raw((void*)(array->bool_at_addr(0)), length_in_bytes);1234}1235break;1236}1237case T_LONG : {1238if (Endian::is_Java_byte_ordering_different()) {1239WRITE_ARRAY(array, long, u8, length);1240} else {1241writer->write_raw((void*)(array->long_at_addr(0)), length_in_bytes);1242}1243break;1244}12451246// handle float/doubles in a special value to ensure than NaNs are1247// written correctly. TO DO: Check if we can avoid this on processors that1248// use IEEE 754.12491250case T_FLOAT : {1251for (int i = 0; i < length; i++) {1252dump_float(writer, array->float_at(i));1253}1254break;1255}1256case T_DOUBLE : {1257for (int i = 0; i < length; i++) {1258dump_double(writer, array->double_at(i));1259}1260break;1261}1262default : ShouldNotReachHere();1263}12641265writer->end_sub_record();1266}12671268// create a HPROF_FRAME record of the given Method* and bci1269void DumperSupport::dump_stack_frame(DumpWriter* writer,1270int frame_serial_num,1271int class_serial_num,1272Method* m,1273int bci) {1274int line_number;1275if (m->is_native()) {1276line_number = -3; // native frame1277} else {1278line_number = m->line_number_from_bci(bci);1279}12801281write_header(writer, HPROF_FRAME, 4*oopSize + 2*sizeof(u4));1282writer->write_id(frame_serial_num); // frame serial number1283writer->write_symbolID(m->name()); // method's name1284writer->write_symbolID(m->signature()); // method's signature12851286assert(m->method_holder()->is_instance_klass(), "not InstanceKlass");1287writer->write_symbolID(m->method_holder()->source_file_name()); // source file name1288writer->write_u4(class_serial_num); // class serial number1289writer->write_u4((u4) line_number); // line number1290}129112921293// Support class used to generate HPROF_UTF8 records from the entries in the1294// SymbolTable.12951296class SymbolTableDumper : public SymbolClosure {1297private:1298DumpWriter* _writer;1299DumpWriter* writer() const { return _writer; }1300public:1301SymbolTableDumper(DumpWriter* writer) { _writer = writer; }1302void do_symbol(Symbol** p);1303};13041305void SymbolTableDumper::do_symbol(Symbol** p) {1306ResourceMark rm;1307Symbol* sym = load_symbol(p);1308int len = sym->utf8_length();1309if (len > 0) {1310char* s = sym->as_utf8();1311DumperSupport::write_header(writer(), HPROF_UTF8, oopSize + len);1312writer()->write_symbolID(sym);1313writer()->write_raw(s, len);1314}1315}13161317// Support class used to generate HPROF_GC_ROOT_JNI_LOCAL records13181319class JNILocalsDumper : public OopClosure {1320private:1321DumpWriter* _writer;1322u4 _thread_serial_num;1323int _frame_num;1324DumpWriter* writer() const { return _writer; }1325public:1326JNILocalsDumper(DumpWriter* writer, u4 thread_serial_num) {1327_writer = writer;1328_thread_serial_num = thread_serial_num;1329_frame_num = -1; // default - empty stack1330}1331void set_frame_number(int n) { _frame_num = n; }1332void do_oop(oop* obj_p);1333void do_oop(narrowOop* obj_p) { ShouldNotReachHere(); }1334};133513361337void JNILocalsDumper::do_oop(oop* obj_p) {1338// ignore null handles1339oop o = *obj_p;1340if (o != NULL) {1341u4 size = 1 + sizeof(address) + 4 + 4;1342writer()->start_sub_record(HPROF_GC_ROOT_JNI_LOCAL, size);1343writer()->write_objectID(o);1344writer()->write_u4(_thread_serial_num);1345writer()->write_u4((u4)_frame_num);1346writer()->end_sub_record();1347}1348}134913501351// Support class used to generate HPROF_GC_ROOT_JNI_GLOBAL records13521353class JNIGlobalsDumper : public OopClosure {1354private:1355DumpWriter* _writer;1356DumpWriter* writer() const { return _writer; }13571358public:1359JNIGlobalsDumper(DumpWriter* writer) {1360_writer = writer;1361}1362void do_oop(oop* obj_p);1363void do_oop(narrowOop* obj_p) { ShouldNotReachHere(); }1364};13651366void JNIGlobalsDumper::do_oop(oop* obj_p) {1367oop o = *obj_p;13681369// ignore these1370if (o == NULL) return;13711372// we ignore global ref to symbols and other internal objects1373if (o->is_instance() || o->is_objArray() || o->is_typeArray()) {1374u4 size = 1 + 2 * sizeof(address);1375writer()->start_sub_record(HPROF_GC_ROOT_JNI_GLOBAL, size);1376writer()->write_objectID(o);1377writer()->write_objectID((oopDesc*)obj_p); // global ref ID1378writer()->end_sub_record();1379}1380};13811382// Support class used to generate HPROF_GC_ROOT_STICKY_CLASS records13831384class StickyClassDumper : public KlassClosure {1385private:1386DumpWriter* _writer;1387DumpWriter* writer() const { return _writer; }1388public:1389StickyClassDumper(DumpWriter* writer) {1390_writer = writer;1391}1392void do_klass(Klass* k) {1393if (k->is_instance_klass()) {1394InstanceKlass* ik = InstanceKlass::cast(k);1395u4 size = 1 + sizeof(address);1396writer()->start_sub_record(HPROF_GC_ROOT_STICKY_CLASS, size);1397writer()->write_classID(ik);1398writer()->end_sub_record();1399}1400}1401};140214031404class VM_HeapDumper;14051406// Support class using when iterating over the heap.14071408class HeapObjectDumper : public ObjectClosure {1409private:1410DumpWriter* _writer;14111412DumpWriter* writer() { return _writer; }14131414public:1415HeapObjectDumper(DumpWriter* writer) {1416_writer = writer;1417}14181419// called for each object in the heap1420void do_object(oop o);1421};14221423void HeapObjectDumper::do_object(oop o) {1424// skip classes as these emitted as HPROF_GC_CLASS_DUMP records1425if (o->klass() == vmClasses::Class_klass()) {1426if (!java_lang_Class::is_primitive(o)) {1427return;1428}1429}14301431if (DumperSupport::mask_dormant_archived_object(o) == NULL) {1432log_debug(cds, heap)("skipped dormant archived object " INTPTR_FORMAT " (%s)", p2i(o), o->klass()->external_name());1433return;1434}14351436if (o->is_instance()) {1437// create a HPROF_GC_INSTANCE record for each object1438DumperSupport::dump_instance(writer(), o);1439} else if (o->is_objArray()) {1440// create a HPROF_GC_OBJ_ARRAY_DUMP record for each object array1441DumperSupport::dump_object_array(writer(), objArrayOop(o));1442} else if (o->is_typeArray()) {1443// create a HPROF_GC_PRIM_ARRAY_DUMP record for each type array1444DumperSupport::dump_prim_array(writer(), typeArrayOop(o));1445}1446}14471448// The VM operation that performs the heap dump1449class VM_HeapDumper : public VM_GC_Operation, public AbstractGangTask {1450private:1451static VM_HeapDumper* _global_dumper;1452static DumpWriter* _global_writer;1453DumpWriter* _local_writer;1454JavaThread* _oome_thread;1455Method* _oome_constructor;1456bool _gc_before_heap_dump;1457GrowableArray<Klass*>* _klass_map;1458ThreadStackTrace** _stack_traces;1459int _num_threads;14601461// accessors and setters1462static VM_HeapDumper* dumper() { assert(_global_dumper != NULL, "Error"); return _global_dumper; }1463static DumpWriter* writer() { assert(_global_writer != NULL, "Error"); return _global_writer; }1464void set_global_dumper() {1465assert(_global_dumper == NULL, "Error");1466_global_dumper = this;1467}1468void set_global_writer() {1469assert(_global_writer == NULL, "Error");1470_global_writer = _local_writer;1471}1472void clear_global_dumper() { _global_dumper = NULL; }1473void clear_global_writer() { _global_writer = NULL; }14741475bool skip_operation() const;14761477// writes a HPROF_LOAD_CLASS record1478class ClassesDo;1479static void do_load_class(Klass* k);14801481// writes a HPROF_GC_CLASS_DUMP record for the given class1482// (and each array class too)1483static void do_class_dump(Klass* k);14841485// writes a HPROF_GC_CLASS_DUMP records for a given basic type1486// array (and each multi-dimensional array too)1487static void do_basic_type_array_class_dump(Klass* k);14881489// HPROF_GC_ROOT_THREAD_OBJ records1490int do_thread(JavaThread* thread, u4 thread_serial_num);1491void do_threads();14921493void add_class_serial_number(Klass* k, int serial_num) {1494_klass_map->at_put_grow(serial_num, k);1495}14961497// HPROF_TRACE and HPROF_FRAME records1498void dump_stack_traces();14991500public:1501VM_HeapDumper(DumpWriter* writer, bool gc_before_heap_dump, bool oome) :1502VM_GC_Operation(0 /* total collections, dummy, ignored */,1503GCCause::_heap_dump /* GC Cause */,15040 /* total full collections, dummy, ignored */,1505gc_before_heap_dump),1506AbstractGangTask("dump heap") {1507_local_writer = writer;1508_gc_before_heap_dump = gc_before_heap_dump;1509_klass_map = new (ResourceObj::C_HEAP, mtServiceability) GrowableArray<Klass*>(INITIAL_CLASS_COUNT, mtServiceability);1510_stack_traces = NULL;1511_num_threads = 0;1512if (oome) {1513assert(!Thread::current()->is_VM_thread(), "Dump from OutOfMemoryError cannot be called by the VMThread");1514// get OutOfMemoryError zero-parameter constructor1515InstanceKlass* oome_ik = vmClasses::OutOfMemoryError_klass();1516_oome_constructor = oome_ik->find_method(vmSymbols::object_initializer_name(),1517vmSymbols::void_method_signature());1518// get thread throwing OOME when generating the heap dump at OOME1519_oome_thread = JavaThread::current();1520} else {1521_oome_thread = NULL;1522_oome_constructor = NULL;1523}1524}1525~VM_HeapDumper() {1526if (_stack_traces != NULL) {1527for (int i=0; i < _num_threads; i++) {1528delete _stack_traces[i];1529}1530FREE_C_HEAP_ARRAY(ThreadStackTrace*, _stack_traces);1531}1532delete _klass_map;1533}15341535VMOp_Type type() const { return VMOp_HeapDumper; }1536void doit();1537void work(uint worker_id);1538};153915401541VM_HeapDumper* VM_HeapDumper::_global_dumper = NULL;1542DumpWriter* VM_HeapDumper::_global_writer = NULL;15431544bool VM_HeapDumper::skip_operation() const {1545return false;1546}15471548// fixes up the current dump record and writes HPROF_HEAP_DUMP_END record1549void DumperSupport::end_of_dump(DumpWriter* writer) {1550writer->finish_dump_segment();15511552writer->write_u1(HPROF_HEAP_DUMP_END);1553writer->write_u4(0);1554writer->write_u4(0);1555}15561557// writes a HPROF_LOAD_CLASS record for the class (and each of its1558// array classes)1559void VM_HeapDumper::do_load_class(Klass* k) {1560static u4 class_serial_num = 0;15611562// len of HPROF_LOAD_CLASS record1563u4 remaining = 2*oopSize + 2*sizeof(u4);15641565// write a HPROF_LOAD_CLASS for the class and each array class1566do {1567DumperSupport::write_header(writer(), HPROF_LOAD_CLASS, remaining);15681569// class serial number is just a number1570writer()->write_u4(++class_serial_num);15711572// class ID1573Klass* klass = k;1574writer()->write_classID(klass);15751576// add the Klass* and class serial number pair1577dumper()->add_class_serial_number(klass, class_serial_num);15781579writer()->write_u4(STACK_TRACE_ID);15801581// class name ID1582Symbol* name = klass->name();1583writer()->write_symbolID(name);15841585// write a LOAD_CLASS record for the array type (if it exists)1586k = klass->array_klass_or_null();1587} while (k != NULL);1588}15891590// writes a HPROF_GC_CLASS_DUMP record for the given class1591void VM_HeapDumper::do_class_dump(Klass* k) {1592if (k->is_instance_klass()) {1593DumperSupport::dump_class_and_array_classes(writer(), k);1594}1595}15961597// writes a HPROF_GC_CLASS_DUMP records for a given basic type1598// array (and each multi-dimensional array too)1599void VM_HeapDumper::do_basic_type_array_class_dump(Klass* k) {1600DumperSupport::dump_basic_type_array_class(writer(), k);1601}16021603// Walk the stack of the given thread.1604// Dumps a HPROF_GC_ROOT_JAVA_FRAME record for each local1605// Dumps a HPROF_GC_ROOT_JNI_LOCAL record for each JNI local1606//1607// It returns the number of Java frames in this thread stack1608int VM_HeapDumper::do_thread(JavaThread* java_thread, u4 thread_serial_num) {1609JNILocalsDumper blk(writer(), thread_serial_num);16101611oop threadObj = java_thread->threadObj();1612assert(threadObj != NULL, "sanity check");16131614int stack_depth = 0;1615if (java_thread->has_last_Java_frame()) {16161617// vframes are resource allocated1618Thread* current_thread = Thread::current();1619ResourceMark rm(current_thread);1620HandleMark hm(current_thread);16211622RegisterMap reg_map(java_thread);1623frame f = java_thread->last_frame();1624vframe* vf = vframe::new_vframe(&f, ®_map, java_thread);1625frame* last_entry_frame = NULL;1626int extra_frames = 0;16271628if (java_thread == _oome_thread && _oome_constructor != NULL) {1629extra_frames++;1630}1631while (vf != NULL) {1632blk.set_frame_number(stack_depth);1633if (vf->is_java_frame()) {16341635// java frame (interpreted, compiled, ...)1636javaVFrame *jvf = javaVFrame::cast(vf);1637if (!(jvf->method()->is_native())) {1638StackValueCollection* locals = jvf->locals();1639for (int slot=0; slot<locals->size(); slot++) {1640if (locals->at(slot)->type() == T_OBJECT) {1641oop o = locals->obj_at(slot)();16421643if (o != NULL) {1644u4 size = 1 + sizeof(address) + 4 + 4;1645writer()->start_sub_record(HPROF_GC_ROOT_JAVA_FRAME, size);1646writer()->write_objectID(o);1647writer()->write_u4(thread_serial_num);1648writer()->write_u4((u4) (stack_depth + extra_frames));1649writer()->end_sub_record();1650}1651}1652}1653StackValueCollection *exprs = jvf->expressions();1654for(int index = 0; index < exprs->size(); index++) {1655if (exprs->at(index)->type() == T_OBJECT) {1656oop o = exprs->obj_at(index)();1657if (o != NULL) {1658u4 size = 1 + sizeof(address) + 4 + 4;1659writer()->start_sub_record(HPROF_GC_ROOT_JAVA_FRAME, size);1660writer()->write_objectID(o);1661writer()->write_u4(thread_serial_num);1662writer()->write_u4((u4) (stack_depth + extra_frames));1663writer()->end_sub_record();1664}1665}1666}1667} else {1668// native frame1669if (stack_depth == 0) {1670// JNI locals for the top frame.1671java_thread->active_handles()->oops_do(&blk);1672} else {1673if (last_entry_frame != NULL) {1674// JNI locals for the entry frame1675assert(last_entry_frame->is_entry_frame(), "checking");1676last_entry_frame->entry_frame_call_wrapper()->handles()->oops_do(&blk);1677}1678}1679}1680// increment only for Java frames1681stack_depth++;1682last_entry_frame = NULL;16831684} else {1685// externalVFrame - if it's an entry frame then report any JNI locals1686// as roots when we find the corresponding native javaVFrame1687frame* fr = vf->frame_pointer();1688assert(fr != NULL, "sanity check");1689if (fr->is_entry_frame()) {1690last_entry_frame = fr;1691}1692}1693vf = vf->sender();1694}1695} else {1696// no last java frame but there may be JNI locals1697java_thread->active_handles()->oops_do(&blk);1698}1699return stack_depth;1700}170117021703// write a HPROF_GC_ROOT_THREAD_OBJ record for each java thread. Then walk1704// the stack so that locals and JNI locals are dumped.1705void VM_HeapDumper::do_threads() {1706for (int i=0; i < _num_threads; i++) {1707JavaThread* thread = _stack_traces[i]->thread();1708oop threadObj = thread->threadObj();1709u4 thread_serial_num = i+1;1710u4 stack_serial_num = thread_serial_num + STACK_TRACE_ID;1711u4 size = 1 + sizeof(address) + 4 + 4;1712writer()->start_sub_record(HPROF_GC_ROOT_THREAD_OBJ, size);1713writer()->write_objectID(threadObj);1714writer()->write_u4(thread_serial_num); // thread number1715writer()->write_u4(stack_serial_num); // stack trace serial number1716writer()->end_sub_record();1717int num_frames = do_thread(thread, thread_serial_num);1718assert(num_frames == _stack_traces[i]->get_stack_depth(),1719"total number of Java frames not matched");1720}1721}172217231724// The VM operation that dumps the heap. The dump consists of the following1725// records:1726//1727// HPROF_HEADER1728// [HPROF_UTF8]*1729// [HPROF_LOAD_CLASS]*1730// [[HPROF_FRAME]*|HPROF_TRACE]*1731// [HPROF_GC_CLASS_DUMP]*1732// [HPROF_HEAP_DUMP_SEGMENT]*1733// HPROF_HEAP_DUMP_END1734//1735// The HPROF_TRACE records represent the stack traces where the heap dump1736// is generated and a "dummy trace" record which does not include1737// any frames. The dummy trace record is used to be referenced as the1738// unknown object alloc site.1739//1740// Each HPROF_HEAP_DUMP_SEGMENT record has a length followed by sub-records.1741// To allow the heap dump be generated in a single pass we remember the position1742// of the dump length and fix it up after all sub-records have been written.1743// To generate the sub-records we iterate over the heap, writing1744// HPROF_GC_INSTANCE_DUMP, HPROF_GC_OBJ_ARRAY_DUMP, and HPROF_GC_PRIM_ARRAY_DUMP1745// records as we go. Once that is done we write records for some of the GC1746// roots.17471748void VM_HeapDumper::doit() {17491750CollectedHeap* ch = Universe::heap();17511752ch->ensure_parsability(false); // must happen, even if collection does1753// not happen (e.g. due to GCLocker)17541755if (_gc_before_heap_dump) {1756if (GCLocker::is_active()) {1757warning("GC locker is held; pre-heapdump GC was skipped");1758} else {1759ch->collect_as_vm_thread(GCCause::_heap_dump);1760}1761}17621763// At this point we should be the only dumper active, so1764// the following should be safe.1765set_global_dumper();1766set_global_writer();17671768WorkGang* gang = ch->safepoint_workers();17691770if (gang == NULL) {1771work(0);1772} else {1773gang->run_task(this, gang->active_workers(), true);1774}17751776// Now we clear the global variables, so that a future dumper can run.1777clear_global_dumper();1778clear_global_writer();1779}17801781void VM_HeapDumper::work(uint worker_id) {1782if (!Thread::current()->is_VM_thread()) {1783writer()->writer_loop();1784return;1785}17861787// Write the file header - we always use 1.0.21788const char* header = "JAVA PROFILE 1.0.2";17891790// header is few bytes long - no chance to overflow int1791writer()->write_raw((void*)header, (int)strlen(header));1792writer()->write_u1(0); // terminator1793writer()->write_u4(oopSize);1794// timestamp is current time in ms1795writer()->write_u8(os::javaTimeMillis());17961797// HPROF_UTF8 records1798SymbolTableDumper sym_dumper(writer());1799SymbolTable::symbols_do(&sym_dumper);18001801// write HPROF_LOAD_CLASS records1802{1803LockedClassesDo locked_load_classes(&do_load_class);1804ClassLoaderDataGraph::classes_do(&locked_load_classes);1805}1806Universe::basic_type_classes_do(&do_load_class);18071808// write HPROF_FRAME and HPROF_TRACE records1809// this must be called after _klass_map is built when iterating the classes above.1810dump_stack_traces();18111812// Writes HPROF_GC_CLASS_DUMP records1813{1814LockedClassesDo locked_dump_class(&do_class_dump);1815ClassLoaderDataGraph::classes_do(&locked_dump_class);1816}1817Universe::basic_type_classes_do(&do_basic_type_array_class_dump);18181819// writes HPROF_GC_INSTANCE_DUMP records.1820// After each sub-record is written check_segment_length will be invoked1821// to check if the current segment exceeds a threshold. If so, a new1822// segment is started.1823// The HPROF_GC_CLASS_DUMP and HPROF_GC_INSTANCE_DUMP are the vast bulk1824// of the heap dump.1825HeapObjectDumper obj_dumper(writer());1826Universe::heap()->object_iterate(&obj_dumper);18271828// HPROF_GC_ROOT_THREAD_OBJ + frames + jni locals1829do_threads();18301831// HPROF_GC_ROOT_JNI_GLOBAL1832JNIGlobalsDumper jni_dumper(writer());1833JNIHandles::oops_do(&jni_dumper);1834// technically not jni roots, but global roots1835// for things like preallocated throwable backtraces1836Universe::vm_global()->oops_do(&jni_dumper);18371838// HPROF_GC_ROOT_STICKY_CLASS1839// These should be classes in the NULL class loader data, and not all classes1840// if !ClassUnloading1841StickyClassDumper class_dumper(writer());1842ClassLoaderData::the_null_class_loader_data()->classes_do(&class_dumper);18431844// Writes the HPROF_HEAP_DUMP_END record.1845DumperSupport::end_of_dump(writer());18461847// We are done with writing. Release the worker threads.1848writer()->deactivate();1849}18501851void VM_HeapDumper::dump_stack_traces() {1852// write a HPROF_TRACE record without any frames to be referenced as object alloc sites1853DumperSupport::write_header(writer(), HPROF_TRACE, 3*sizeof(u4));1854writer()->write_u4((u4) STACK_TRACE_ID);1855writer()->write_u4(0); // thread number1856writer()->write_u4(0); // frame count18571858_stack_traces = NEW_C_HEAP_ARRAY(ThreadStackTrace*, Threads::number_of_threads(), mtInternal);1859int frame_serial_num = 0;1860for (JavaThreadIteratorWithHandle jtiwh; JavaThread *thread = jtiwh.next(); ) {1861oop threadObj = thread->threadObj();1862if (threadObj != NULL && !thread->is_exiting() && !thread->is_hidden_from_external_view()) {1863// dump thread stack trace1864ResourceMark rm;1865ThreadStackTrace* stack_trace = new ThreadStackTrace(thread, false);1866stack_trace->dump_stack_at_safepoint(-1);1867_stack_traces[_num_threads++] = stack_trace;18681869// write HPROF_FRAME records for this thread's stack trace1870int depth = stack_trace->get_stack_depth();1871int thread_frame_start = frame_serial_num;1872int extra_frames = 0;1873// write fake frame that makes it look like the thread, which caused OOME,1874// is in the OutOfMemoryError zero-parameter constructor1875if (thread == _oome_thread && _oome_constructor != NULL) {1876int oome_serial_num = _klass_map->find(_oome_constructor->method_holder());1877// the class serial number starts from 11878assert(oome_serial_num > 0, "OutOfMemoryError class not found");1879DumperSupport::dump_stack_frame(writer(), ++frame_serial_num, oome_serial_num,1880_oome_constructor, 0);1881extra_frames++;1882}1883for (int j=0; j < depth; j++) {1884StackFrameInfo* frame = stack_trace->stack_frame_at(j);1885Method* m = frame->method();1886int class_serial_num = _klass_map->find(m->method_holder());1887// the class serial number starts from 11888assert(class_serial_num > 0, "class not found");1889DumperSupport::dump_stack_frame(writer(), ++frame_serial_num, class_serial_num, m, frame->bci());1890}1891depth += extra_frames;18921893// write HPROF_TRACE record for one thread1894DumperSupport::write_header(writer(), HPROF_TRACE, 3*sizeof(u4) + depth*oopSize);1895int stack_serial_num = _num_threads + STACK_TRACE_ID;1896writer()->write_u4(stack_serial_num); // stack trace serial number1897writer()->write_u4((u4) _num_threads); // thread serial number1898writer()->write_u4(depth); // frame count1899for (int j=1; j <= depth; j++) {1900writer()->write_id(thread_frame_start + j);1901}1902}1903}1904}19051906// dump the heap to given path.1907int HeapDumper::dump(const char* path, outputStream* out, int compression) {1908assert(path != NULL && strlen(path) > 0, "path missing");19091910// print message in interactive case1911if (out != NULL) {1912out->print_cr("Dumping heap to %s ...", path);1913timer()->start();1914}19151916// create JFR event1917EventHeapDump event;19181919AbstractCompressor* compressor = NULL;19201921if (compression > 0) {1922compressor = new (std::nothrow) GZipCompressor(compression);19231924if (compressor == NULL) {1925set_error("Could not allocate gzip compressor");1926return -1;1927}1928}19291930DumpWriter writer(new (std::nothrow) FileWriter(path), compressor);19311932if (writer.error() != NULL) {1933set_error(writer.error());1934if (out != NULL) {1935out->print_cr("Unable to create %s: %s", path,1936(error() != NULL) ? error() : "reason unknown");1937}1938return -1;1939}19401941// generate the dump1942VM_HeapDumper dumper(&writer, _gc_before_heap_dump, _oome);1943if (Thread::current()->is_VM_thread()) {1944assert(SafepointSynchronize::is_at_safepoint(), "Expected to be called at a safepoint");1945dumper.doit();1946} else {1947VMThread::execute(&dumper);1948}19491950// record any error that the writer may have encountered1951set_error(writer.error());19521953// emit JFR event1954if (error() == NULL) {1955event.set_destination(path);1956event.set_gcBeforeDump(_gc_before_heap_dump);1957event.set_size(writer.bytes_written());1958event.set_onOutOfMemoryError(_oome);1959event.commit();1960}19611962// print message in interactive case1963if (out != NULL) {1964timer()->stop();1965if (error() == NULL) {1966out->print_cr("Heap dump file created [" JULONG_FORMAT " bytes in %3.3f secs]",1967writer.bytes_written(), timer()->seconds());1968} else {1969out->print_cr("Dump file is incomplete: %s", writer.error());1970}1971}19721973return (writer.error() == NULL) ? 0 : -1;1974}19751976// stop timer (if still active), and free any error string we might be holding1977HeapDumper::~HeapDumper() {1978if (timer()->is_active()) {1979timer()->stop();1980}1981set_error(NULL);1982}198319841985// returns the error string (resource allocated), or NULL1986char* HeapDumper::error_as_C_string() const {1987if (error() != NULL) {1988char* str = NEW_RESOURCE_ARRAY(char, strlen(error())+1);1989strcpy(str, error());1990return str;1991} else {1992return NULL;1993}1994}19951996// set the error string1997void HeapDumper::set_error(char const* error) {1998if (_error != NULL) {1999os::free(_error);2000}2001if (error == NULL) {2002_error = NULL;2003} else {2004_error = os::strdup(error);2005assert(_error != NULL, "allocation failure");2006}2007}20082009// Called by out-of-memory error reporting by a single Java thread2010// outside of a JVM safepoint2011void HeapDumper::dump_heap_from_oome() {2012HeapDumper::dump_heap(true);2013}20142015// Called by error reporting by a single Java thread outside of a JVM safepoint,2016// or by heap dumping by the VM thread during a (GC) safepoint. Thus, these various2017// callers are strictly serialized and guaranteed not to interfere below. For more2018// general use, however, this method will need modification to prevent2019// inteference when updating the static variables base_path and dump_file_seq below.2020void HeapDumper::dump_heap() {2021HeapDumper::dump_heap(false);2022}20232024void HeapDumper::dump_heap(bool oome) {2025static char base_path[JVM_MAXPATHLEN] = {'\0'};2026static uint dump_file_seq = 0;2027char* my_path;2028const int max_digit_chars = 20;20292030const char* dump_file_name = "java_pid";2031const char* dump_file_ext = HeapDumpGzipLevel > 0 ? ".hprof.gz" : ".hprof";20322033// The dump file defaults to java_pid<pid>.hprof in the current working2034// directory. HeapDumpPath=<file> can be used to specify an alternative2035// dump file name or a directory where dump file is created.2036if (dump_file_seq == 0) { // first time in, we initialize base_path2037// Calculate potentially longest base path and check if we have enough2038// allocated statically.2039const size_t total_length =2040(HeapDumpPath == NULL ? 0 : strlen(HeapDumpPath)) +2041strlen(os::file_separator()) + max_digit_chars +2042strlen(dump_file_name) + strlen(dump_file_ext) + 1;2043if (total_length > sizeof(base_path)) {2044warning("Cannot create heap dump file. HeapDumpPath is too long.");2045return;2046}20472048bool use_default_filename = true;2049if (HeapDumpPath == NULL || HeapDumpPath[0] == '\0') {2050// HeapDumpPath=<file> not specified2051} else {2052strcpy(base_path, HeapDumpPath);2053// check if the path is a directory (must exist)2054DIR* dir = os::opendir(base_path);2055if (dir == NULL) {2056use_default_filename = false;2057} else {2058// HeapDumpPath specified a directory. We append a file separator2059// (if needed).2060os::closedir(dir);2061size_t fs_len = strlen(os::file_separator());2062if (strlen(base_path) >= fs_len) {2063char* end = base_path;2064end += (strlen(base_path) - fs_len);2065if (strcmp(end, os::file_separator()) != 0) {2066strcat(base_path, os::file_separator());2067}2068}2069}2070}2071// If HeapDumpPath wasn't a file name then we append the default name2072if (use_default_filename) {2073const size_t dlen = strlen(base_path); // if heap dump dir specified2074jio_snprintf(&base_path[dlen], sizeof(base_path)-dlen, "%s%d%s",2075dump_file_name, os::current_process_id(), dump_file_ext);2076}2077const size_t len = strlen(base_path) + 1;2078my_path = (char*)os::malloc(len, mtInternal);2079if (my_path == NULL) {2080warning("Cannot create heap dump file. Out of system memory.");2081return;2082}2083strncpy(my_path, base_path, len);2084} else {2085// Append a sequence number id for dumps following the first2086const size_t len = strlen(base_path) + max_digit_chars + 2; // for '.' and \02087my_path = (char*)os::malloc(len, mtInternal);2088if (my_path == NULL) {2089warning("Cannot create heap dump file. Out of system memory.");2090return;2091}2092jio_snprintf(my_path, len, "%s.%d", base_path, dump_file_seq);2093}2094dump_file_seq++; // increment seq number for next time we dump20952096HeapDumper dumper(false /* no GC before heap dump */,2097oome /* pass along out-of-memory-error flag */);2098dumper.dump(my_path, tty, HeapDumpGzipLevel);2099os::free(my_path);2100}210121022103