1 /* 2 * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 * 23 */ 24 25 #include "precompiled.hpp" 26 #include "jvm.h" 27 #include "classfile/symbolTable.hpp" 28 #include "classfile/systemDictionary.hpp" 29 #include "classfile/vmSymbols.hpp" 30 #include "gc/shared/gcLocker.inline.hpp" 31 #include "gc/shared/genCollectedHeap.hpp" 32 #include "gc/shared/vmGCOperations.hpp" 33 #include "memory/allocation.inline.hpp" 34 #include "memory/resourceArea.hpp" 35 #include "memory/universe.hpp" 36 #include "oops/objArrayKlass.hpp" 37 #include "oops/objArrayOop.inline.hpp" 38 #include "oops/oop.inline.hpp" 39 #include "oops/typeArrayOop.inline.hpp" 40 #include "runtime/frame.inline.hpp" 41 #include "runtime/handles.inline.hpp" 42 #include "runtime/javaCalls.hpp" 43 #include "runtime/jniHandles.hpp" 44 #include "runtime/os.hpp" 45 #include "runtime/reflectionUtils.hpp" 46 #include "runtime/thread.inline.hpp" 47 #include "runtime/threadSMR.hpp" 48 #include "runtime/vframe.hpp" 49 #include "runtime/vmThread.hpp" 50 #include "runtime/vm_operations.hpp" 51 #include "services/heapDumper.hpp" 52 #include "services/threadService.hpp" 53 #include "utilities/macros.hpp" 54 #include "utilities/ostream.hpp" 55 #if INCLUDE_ALL_GCS 56 #include "gc/parallel/parallelScavengeHeap.hpp" 57 #endif // INCLUDE_ALL_GCS 58 59 /* 60 * HPROF binary format - description copied from: 61 * src/share/demo/jvmti/hprof/hprof_io.c 62 * 63 * 64 * header "JAVA PROFILE 1.0.2" (0-terminated) 65 * 66 * u4 size of identifiers. Identifiers are used to represent 67 * UTF8 strings, objects, stack traces, etc. They usually 68 * have the same size as host pointers. For example, on 69 * Solaris and Win32, the size is 4. 70 * u4 high word 71 * u4 low word number of milliseconds since 0:00 GMT, 1/1/70 72 * [record]* a sequence of records. 73 * 74 * 75 * Record format: 76 * 77 * u1 a TAG denoting the type of the record 78 * u4 number of *microseconds* since the time stamp in the 79 * header. (wraps around in a little more than an hour) 80 * u4 number of bytes *remaining* in the record. Note that 81 * this number excludes the tag and the length field itself. 82 * [u1]* BODY of the record (a sequence of bytes) 83 * 84 * 85 * The following TAGs are supported: 86 * 87 * TAG BODY notes 88 *---------------------------------------------------------- 89 * HPROF_UTF8 a UTF8-encoded name 90 * 91 * id name ID 92 * [u1]* UTF8 characters (no trailing zero) 93 * 94 * HPROF_LOAD_CLASS a newly loaded class 95 * 96 * u4 class serial number (> 0) 97 * id class object ID 98 * u4 stack trace serial number 99 * id class name ID 100 * 101 * HPROF_UNLOAD_CLASS an unloading class 102 * 103 * u4 class serial_number 104 * 105 * HPROF_FRAME a Java stack frame 106 * 107 * id stack frame ID 108 * id method name ID 109 * id method signature ID 110 * id source file name ID 111 * u4 class serial number 112 * i4 line number. >0: normal 113 * -1: unknown 114 * -2: compiled method 115 * -3: native method 116 * 117 * HPROF_TRACE a Java stack trace 118 * 119 * u4 stack trace serial number 120 * u4 thread serial number 121 * u4 number of frames 122 * [id]* stack frame IDs 123 * 124 * 125 * HPROF_ALLOC_SITES a set of heap allocation sites, obtained after GC 126 * 127 * u2 flags 0x0001: incremental vs. complete 128 * 0x0002: sorted by allocation vs. live 129 * 0x0004: whether to force a GC 130 * u4 cutoff ratio 131 * u4 total live bytes 132 * u4 total live instances 133 * u8 total bytes allocated 134 * u8 total instances allocated 135 * u4 number of sites that follow 136 * [u1 is_array: 0: normal object 137 * 2: object array 138 * 4: boolean array 139 * 5: char array 140 * 6: float array 141 * 7: double array 142 * 8: byte array 143 * 9: short array 144 * 10: int array 145 * 11: long array 146 * u4 class serial number (may be zero during startup) 147 * u4 stack trace serial number 148 * u4 number of bytes alive 149 * u4 number of instances alive 150 * u4 number of bytes allocated 151 * u4]* number of instance allocated 152 * 153 * HPROF_START_THREAD a newly started thread. 154 * 155 * u4 thread serial number (> 0) 156 * id thread object ID 157 * u4 stack trace serial number 158 * id thread name ID 159 * id thread group name ID 160 * id thread group parent name ID 161 * 162 * HPROF_END_THREAD a terminating thread. 163 * 164 * u4 thread serial number 165 * 166 * HPROF_HEAP_SUMMARY heap summary 167 * 168 * u4 total live bytes 169 * u4 total live instances 170 * u8 total bytes allocated 171 * u8 total instances allocated 172 * 173 * HPROF_HEAP_DUMP denote a heap dump 174 * 175 * [heap dump sub-records]* 176 * 177 * There are four kinds of heap dump sub-records: 178 * 179 * u1 sub-record type 180 * 181 * HPROF_GC_ROOT_UNKNOWN unknown root 182 * 183 * id object ID 184 * 185 * HPROF_GC_ROOT_THREAD_OBJ thread object 186 * 187 * id thread object ID (may be 0 for a 188 * thread newly attached through JNI) 189 * u4 thread sequence number 190 * u4 stack trace sequence number 191 * 192 * HPROF_GC_ROOT_JNI_GLOBAL JNI global ref root 193 * 194 * id object ID 195 * id JNI global ref ID 196 * 197 * HPROF_GC_ROOT_JNI_LOCAL JNI local ref 198 * 199 * id object ID 200 * u4 thread serial number 201 * u4 frame # in stack trace (-1 for empty) 202 * 203 * HPROF_GC_ROOT_JAVA_FRAME Java stack frame 204 * 205 * id object ID 206 * u4 thread serial number 207 * u4 frame # in stack trace (-1 for empty) 208 * 209 * HPROF_GC_ROOT_NATIVE_STACK Native stack 210 * 211 * id object ID 212 * u4 thread serial number 213 * 214 * HPROF_GC_ROOT_STICKY_CLASS System class 215 * 216 * id object ID 217 * 218 * HPROF_GC_ROOT_THREAD_BLOCK Reference from thread block 219 * 220 * id object ID 221 * u4 thread serial number 222 * 223 * HPROF_GC_ROOT_MONITOR_USED Busy monitor 224 * 225 * id object ID 226 * 227 * HPROF_GC_CLASS_DUMP dump of a class object 228 * 229 * id class object ID 230 * u4 stack trace serial number 231 * id super class object ID 232 * id class loader object ID 233 * id signers object ID 234 * id protection domain object ID 235 * id reserved 236 * id reserved 237 * 238 * u4 instance size (in bytes) 239 * 240 * u2 size of constant pool 241 * [u2, constant pool index, 242 * ty, type 243 * 2: object 244 * 4: boolean 245 * 5: char 246 * 6: float 247 * 7: double 248 * 8: byte 249 * 9: short 250 * 10: int 251 * 11: long 252 * vl]* and value 253 * 254 * u2 number of static fields 255 * [id, static field name, 256 * ty, type, 257 * vl]* and value 258 * 259 * u2 number of inst. fields (not inc. super) 260 * [id, instance field name, 261 * ty]* type 262 * 263 * HPROF_GC_INSTANCE_DUMP dump of a normal object 264 * 265 * id object ID 266 * u4 stack trace serial number 267 * id class object ID 268 * u4 number of bytes that follow 269 * [vl]* instance field values (class, followed 270 * by super, super's super ...) 271 * 272 * HPROF_GC_OBJ_ARRAY_DUMP dump of an object array 273 * 274 * id array object ID 275 * u4 stack trace serial number 276 * u4 number of elements 277 * id array class ID 278 * [id]* elements 279 * 280 * HPROF_GC_PRIM_ARRAY_DUMP dump of a primitive array 281 * 282 * id array object ID 283 * u4 stack trace serial number 284 * u4 number of elements 285 * u1 element type 286 * 4: boolean array 287 * 5: char array 288 * 6: float array 289 * 7: double array 290 * 8: byte array 291 * 9: short array 292 * 10: int array 293 * 11: long array 294 * [u1]* elements 295 * 296 * HPROF_CPU_SAMPLES a set of sample traces of running threads 297 * 298 * u4 total number of samples 299 * u4 # of traces 300 * [u4 # of samples 301 * u4]* stack trace serial number 302 * 303 * HPROF_CONTROL_SETTINGS the settings of on/off switches 304 * 305 * u4 0x00000001: alloc traces on/off 306 * 0x00000002: cpu sampling on/off 307 * u2 stack trace depth 308 * 309 * 310 * When the header is "JAVA PROFILE 1.0.2" a heap dump can optionally 311 * be generated as a sequence of heap dump segments. This sequence is 312 * terminated by an end record. The additional tags allowed by format 313 * "JAVA PROFILE 1.0.2" are: 314 * 315 * HPROF_HEAP_DUMP_SEGMENT denote a heap dump segment 316 * 317 * [heap dump sub-records]* 318 * The same sub-record types allowed by HPROF_HEAP_DUMP 319 * 320 * HPROF_HEAP_DUMP_END denotes the end of a heap dump 321 * 322 */ 323 324 325 // HPROF tags 326 327 typedef enum { 328 // top-level records 329 HPROF_UTF8 = 0x01, 330 HPROF_LOAD_CLASS = 0x02, 331 HPROF_UNLOAD_CLASS = 0x03, 332 HPROF_FRAME = 0x04, 333 HPROF_TRACE = 0x05, 334 HPROF_ALLOC_SITES = 0x06, 335 HPROF_HEAP_SUMMARY = 0x07, 336 HPROF_START_THREAD = 0x0A, 337 HPROF_END_THREAD = 0x0B, 338 HPROF_HEAP_DUMP = 0x0C, 339 HPROF_CPU_SAMPLES = 0x0D, 340 HPROF_CONTROL_SETTINGS = 0x0E, 341 342 // 1.0.2 record types 343 HPROF_HEAP_DUMP_SEGMENT = 0x1C, 344 HPROF_HEAP_DUMP_END = 0x2C, 345 346 // field types 347 HPROF_ARRAY_OBJECT = 0x01, 348 HPROF_NORMAL_OBJECT = 0x02, 349 HPROF_BOOLEAN = 0x04, 350 HPROF_CHAR = 0x05, 351 HPROF_FLOAT = 0x06, 352 HPROF_DOUBLE = 0x07, 353 HPROF_BYTE = 0x08, 354 HPROF_SHORT = 0x09, 355 HPROF_INT = 0x0A, 356 HPROF_LONG = 0x0B, 357 358 // data-dump sub-records 359 HPROF_GC_ROOT_UNKNOWN = 0xFF, 360 HPROF_GC_ROOT_JNI_GLOBAL = 0x01, 361 HPROF_GC_ROOT_JNI_LOCAL = 0x02, 362 HPROF_GC_ROOT_JAVA_FRAME = 0x03, 363 HPROF_GC_ROOT_NATIVE_STACK = 0x04, 364 HPROF_GC_ROOT_STICKY_CLASS = 0x05, 365 HPROF_GC_ROOT_THREAD_BLOCK = 0x06, 366 HPROF_GC_ROOT_MONITOR_USED = 0x07, 367 HPROF_GC_ROOT_THREAD_OBJ = 0x08, 368 HPROF_GC_CLASS_DUMP = 0x20, 369 HPROF_GC_INSTANCE_DUMP = 0x21, 370 HPROF_GC_OBJ_ARRAY_DUMP = 0x22, 371 HPROF_GC_PRIM_ARRAY_DUMP = 0x23 372 } hprofTag; 373 374 // Default stack trace ID (used for dummy HPROF_TRACE record) 375 enum { 376 STACK_TRACE_ID = 1, 377 INITIAL_CLASS_COUNT = 200 378 }; 379 380 // Supports I/O operations on a dump file 381 382 class DumpWriter : public StackObj { 383 private: 384 enum { 385 io_buffer_size = 8*M 386 }; 387 388 int _fd; // file descriptor (-1 if dump file not open) 389 julong _bytes_written; // number of byte written to dump file 390 391 char* _buffer; // internal buffer 392 size_t _size; 393 size_t _pos; 394 395 jlong _dump_start; 396 397 char* _error; // error message when I/O fails 398 399 void set_file_descriptor(int fd) { _fd = fd; } 400 int file_descriptor() const { return _fd; } 401 402 char* buffer() const { return _buffer; } 403 size_t buffer_size() const { return _size; } 404 size_t position() const { return _pos; } 405 void set_position(size_t pos) { _pos = pos; } 406 407 void set_error(const char* error) { _error = (char*)os::strdup(error); } 408 409 // all I/O go through this function 410 void write_internal(void* s, size_t len); 411 412 public: 413 DumpWriter(const char* path); 414 ~DumpWriter(); 415 416 void close(); 417 bool is_open() const { return file_descriptor() >= 0; } 418 void flush(); 419 420 jlong dump_start() const { return _dump_start; } 421 void set_dump_start(jlong pos); 422 julong current_record_length(); 423 424 // total number of bytes written to the disk 425 julong bytes_written() const { return _bytes_written; } 426 427 // adjust the number of bytes written to disk (used to keep the count 428 // of the number of bytes written in case of rewrites) 429 void adjust_bytes_written(jlong n) { _bytes_written += n; } 430 431 // number of (buffered) bytes as yet unwritten to the dump file 432 size_t bytes_unwritten() const { return position(); } 433 434 char* error() const { return _error; } 435 436 jlong current_offset(); 437 void seek_to_offset(jlong pos); 438 439 // writer functions 440 void write_raw(void* s, size_t len); 441 void write_u1(u1 x) { write_raw((void*)&x, 1); } 442 void write_u2(u2 x); 443 void write_u4(u4 x); 444 void write_u8(u8 x); 445 void write_objectID(oop o); 446 void write_symbolID(Symbol* o); 447 void write_classID(Klass* k); 448 void write_id(u4 x); 449 }; 450 451 DumpWriter::DumpWriter(const char* path) { 452 // try to allocate an I/O buffer of io_buffer_size. If there isn't 453 // sufficient memory then reduce size until we can allocate something. 454 _size = io_buffer_size; 455 do { 456 _buffer = (char*)os::malloc(_size, mtInternal); 457 if (_buffer == NULL) { 458 _size = _size >> 1; 459 } 460 } while (_buffer == NULL && _size > 0); 461 assert((_size > 0 && _buffer != NULL) || (_size == 0 && _buffer == NULL), "sanity check"); 462 _pos = 0; 463 _error = NULL; 464 _bytes_written = 0L; 465 _dump_start = (jlong)-1; 466 _fd = os::create_binary_file(path, false); // don't replace existing file 467 468 // if the open failed we record the error 469 if (_fd < 0) { 470 _error = (char*)os::strdup(os::strerror(errno)); 471 } 472 } 473 474 DumpWriter::~DumpWriter() { 475 // flush and close dump file 476 if (is_open()) { 477 close(); 478 } 479 if (_buffer != NULL) os::free(_buffer); 480 if (_error != NULL) os::free(_error); 481 } 482 483 // closes dump file (if open) 484 void DumpWriter::close() { 485 // flush and close dump file 486 if (is_open()) { 487 flush(); 488 os::close(file_descriptor()); 489 set_file_descriptor(-1); 490 } 491 } 492 493 // sets the dump starting position 494 void DumpWriter::set_dump_start(jlong pos) { 495 _dump_start = pos; 496 } 497 498 julong DumpWriter::current_record_length() { 499 if (is_open()) { 500 // calculate the size of the dump record 501 julong dump_end = bytes_written() + bytes_unwritten(); 502 assert(dump_end == (size_t)current_offset(), "checking"); 503 julong dump_len = dump_end - dump_start() - 4; 504 return dump_len; 505 } 506 return 0; 507 } 508 509 // write directly to the file 510 void DumpWriter::write_internal(void* s, size_t len) { 511 if (is_open()) { 512 const char* pos = (char*)s; 513 ssize_t n = 0; 514 while (len > 0) { 515 uint tmp = (uint)MIN2(len, (size_t)UINT_MAX); 516 n = os::write(file_descriptor(), pos, tmp); 517 518 if (n < 0) { 519 // EINTR cannot happen here, os::write will take care of that 520 set_error(os::strerror(errno)); 521 os::close(file_descriptor()); 522 set_file_descriptor(-1); 523 return; 524 } 525 526 _bytes_written += n; 527 pos += n; 528 len -= n; 529 } 530 } 531 } 532 533 // write raw bytes 534 void DumpWriter::write_raw(void* s, size_t len) { 535 if (is_open()) { 536 // flush buffer to make room 537 if ((position() + len) >= buffer_size()) { 538 flush(); 539 } 540 541 // buffer not available or too big to buffer it 542 if ((buffer() == NULL) || (len >= buffer_size())) { 543 write_internal(s, len); 544 } else { 545 // Should optimize this for u1/u2/u4/u8 sizes. 546 memcpy(buffer() + position(), s, len); 547 set_position(position() + len); 548 } 549 } 550 } 551 552 // flush any buffered bytes to the file 553 void DumpWriter::flush() { 554 if (is_open() && position() > 0) { 555 write_internal(buffer(), position()); 556 set_position(0); 557 } 558 } 559 560 jlong DumpWriter::current_offset() { 561 if (is_open()) { 562 // the offset is the file offset plus whatever we have buffered 563 jlong offset = os::current_file_offset(file_descriptor()); 564 assert(offset >= 0, "lseek failed"); 565 return offset + position(); 566 } else { 567 return (jlong)-1; 568 } 569 } 570 571 void DumpWriter::seek_to_offset(jlong off) { 572 assert(off >= 0, "bad offset"); 573 574 // need to flush before seeking 575 flush(); 576 577 // may be closed due to I/O error 578 if (is_open()) { 579 jlong n = os::seek_to_file_offset(file_descriptor(), off); 580 assert(n >= 0, "lseek failed"); 581 } 582 } 583 584 void DumpWriter::write_u2(u2 x) { 585 u2 v; 586 Bytes::put_Java_u2((address)&v, x); 587 write_raw((void*)&v, 2); 588 } 589 590 void DumpWriter::write_u4(u4 x) { 591 u4 v; 592 Bytes::put_Java_u4((address)&v, x); 593 write_raw((void*)&v, 4); 594 } 595 596 void DumpWriter::write_u8(u8 x) { 597 u8 v; 598 Bytes::put_Java_u8((address)&v, x); 599 write_raw((void*)&v, 8); 600 } 601 602 void DumpWriter::write_objectID(oop o) { 603 address a = (address)o; 604 #ifdef _LP64 605 write_u8((u8)a); 606 #else 607 write_u4((u4)a); 608 #endif 609 } 610 611 void DumpWriter::write_symbolID(Symbol* s) { 612 address a = (address)((uintptr_t)s); 613 #ifdef _LP64 614 write_u8((u8)a); 615 #else 616 write_u4((u4)a); 617 #endif 618 } 619 620 void DumpWriter::write_id(u4 x) { 621 #ifdef _LP64 622 write_u8((u8) x); 623 #else 624 write_u4(x); 625 #endif 626 } 627 628 // We use java mirror as the class ID 629 void DumpWriter::write_classID(Klass* k) { 630 write_objectID(k->java_mirror()); 631 } 632 633 634 635 // Support class with a collection of functions used when dumping the heap 636 637 class DumperSupport : AllStatic { 638 public: 639 640 // write a header of the given type 641 static void write_header(DumpWriter* writer, hprofTag tag, u4 len); 642 643 // returns hprof tag for the given type signature 644 static hprofTag sig2tag(Symbol* sig); 645 // returns hprof tag for the given basic type 646 static hprofTag type2tag(BasicType type); 647 648 // returns the size of the instance of the given class 649 static u4 instance_size(Klass* k); 650 651 // dump a jfloat 652 static void dump_float(DumpWriter* writer, jfloat f); 653 // dump a jdouble 654 static void dump_double(DumpWriter* writer, jdouble d); 655 // dumps the raw value of the given field 656 static void dump_field_value(DumpWriter* writer, char type, oop obj, int offset); 657 // dumps static fields of the given class 658 static void dump_static_fields(DumpWriter* writer, Klass* k); 659 // dump the raw values of the instance fields of the given object 660 static void dump_instance_fields(DumpWriter* writer, oop o); 661 // dumps the definition of the instance fields for a given class 662 static void dump_instance_field_descriptors(DumpWriter* writer, Klass* k); 663 // creates HPROF_GC_INSTANCE_DUMP record for the given object 664 static void dump_instance(DumpWriter* writer, oop o); 665 // creates HPROF_GC_CLASS_DUMP record for the given class and each of its 666 // array classes 667 static void dump_class_and_array_classes(DumpWriter* writer, Klass* k); 668 // creates HPROF_GC_CLASS_DUMP record for a given primitive array 669 // class (and each multi-dimensional array class too) 670 static void dump_basic_type_array_class(DumpWriter* writer, Klass* k); 671 672 // creates HPROF_GC_OBJ_ARRAY_DUMP record for the given object array 673 static void dump_object_array(DumpWriter* writer, objArrayOop array); 674 // creates HPROF_GC_PRIM_ARRAY_DUMP record for the given type array 675 static void dump_prim_array(DumpWriter* writer, typeArrayOop array); 676 // create HPROF_FRAME record for the given method and bci 677 static void dump_stack_frame(DumpWriter* writer, int frame_serial_num, int class_serial_num, Method* m, int bci); 678 679 // check if we need to truncate an array 680 static int calculate_array_max_length(DumpWriter* writer, arrayOop array, short header_size); 681 682 // writes a HPROF_HEAP_DUMP_SEGMENT record 683 static void write_dump_header(DumpWriter* writer); 684 685 // fixes up the length of the current dump record 686 static void write_current_dump_record_length(DumpWriter* writer); 687 688 // fixes up the current dump record and writes HPROF_HEAP_DUMP_END record 689 static void end_of_dump(DumpWriter* writer); 690 }; 691 692 // write a header of the given type 693 void DumperSupport:: write_header(DumpWriter* writer, hprofTag tag, u4 len) { 694 writer->write_u1((u1)tag); 695 writer->write_u4(0); // current ticks 696 writer->write_u4(len); 697 } 698 699 // returns hprof tag for the given type signature 700 hprofTag DumperSupport::sig2tag(Symbol* sig) { 701 switch (sig->byte_at(0)) { 702 case JVM_SIGNATURE_CLASS : return HPROF_NORMAL_OBJECT; 703 case JVM_SIGNATURE_ARRAY : return HPROF_NORMAL_OBJECT; 704 case JVM_SIGNATURE_BYTE : return HPROF_BYTE; 705 case JVM_SIGNATURE_CHAR : return HPROF_CHAR; 706 case JVM_SIGNATURE_FLOAT : return HPROF_FLOAT; 707 case JVM_SIGNATURE_DOUBLE : return HPROF_DOUBLE; 708 case JVM_SIGNATURE_INT : return HPROF_INT; 709 case JVM_SIGNATURE_LONG : return HPROF_LONG; 710 case JVM_SIGNATURE_SHORT : return HPROF_SHORT; 711 case JVM_SIGNATURE_BOOLEAN : return HPROF_BOOLEAN; 712 default : ShouldNotReachHere(); /* to shut up compiler */ return HPROF_BYTE; 713 } 714 } 715 716 hprofTag DumperSupport::type2tag(BasicType type) { 717 switch (type) { 718 case T_BYTE : return HPROF_BYTE; 719 case T_CHAR : return HPROF_CHAR; 720 case T_FLOAT : return HPROF_FLOAT; 721 case T_DOUBLE : return HPROF_DOUBLE; 722 case T_INT : return HPROF_INT; 723 case T_LONG : return HPROF_LONG; 724 case T_SHORT : return HPROF_SHORT; 725 case T_BOOLEAN : return HPROF_BOOLEAN; 726 default : ShouldNotReachHere(); /* to shut up compiler */ return HPROF_BYTE; 727 } 728 } 729 730 // dump a jfloat 731 void DumperSupport::dump_float(DumpWriter* writer, jfloat f) { 732 if (g_isnan(f)) { 733 writer->write_u4(0x7fc00000); // collapsing NaNs 734 } else { 735 union { 736 int i; 737 float f; 738 } u; 739 u.f = (float)f; 740 writer->write_u4((u4)u.i); 741 } 742 } 743 744 // dump a jdouble 745 void DumperSupport::dump_double(DumpWriter* writer, jdouble d) { 746 union { 747 jlong l; 748 double d; 749 } u; 750 if (g_isnan(d)) { // collapsing NaNs 751 u.l = (jlong)(0x7ff80000); 752 u.l = (u.l << 32); 753 } else { 754 u.d = (double)d; 755 } 756 writer->write_u8((u8)u.l); 757 } 758 759 // dumps the raw value of the given field 760 void DumperSupport::dump_field_value(DumpWriter* writer, char type, oop obj, int offset) { 761 switch (type) { 762 case JVM_SIGNATURE_CLASS : 763 case JVM_SIGNATURE_ARRAY : { 764 oop o = obj->obj_field_access<ON_UNKNOWN_OOP_REF>(offset); 765 assert(oopDesc::is_oop_or_null(o), "Expected an oop or NULL at " PTR_FORMAT, p2i(o)); 766 writer->write_objectID(o); 767 break; 768 } 769 case JVM_SIGNATURE_BYTE : { 770 jbyte b = obj->byte_field(offset); 771 writer->write_u1((u1)b); 772 break; 773 } 774 case JVM_SIGNATURE_CHAR : { 775 jchar c = obj->char_field(offset); 776 writer->write_u2((u2)c); 777 break; 778 } 779 case JVM_SIGNATURE_SHORT : { 780 jshort s = obj->short_field(offset); 781 writer->write_u2((u2)s); 782 break; 783 } 784 case JVM_SIGNATURE_FLOAT : { 785 jfloat f = obj->float_field(offset); 786 dump_float(writer, f); 787 break; 788 } 789 case JVM_SIGNATURE_DOUBLE : { 790 jdouble d = obj->double_field(offset); 791 dump_double(writer, d); 792 break; 793 } 794 case JVM_SIGNATURE_INT : { 795 jint i = obj->int_field(offset); 796 writer->write_u4((u4)i); 797 break; 798 } 799 case JVM_SIGNATURE_LONG : { 800 jlong l = obj->long_field(offset); 801 writer->write_u8((u8)l); 802 break; 803 } 804 case JVM_SIGNATURE_BOOLEAN : { 805 jboolean b = obj->bool_field(offset); 806 writer->write_u1((u1)b); 807 break; 808 } 809 default : { 810 ShouldNotReachHere(); 811 break; 812 } 813 } 814 } 815 816 // returns the size of the instance of the given class 817 u4 DumperSupport::instance_size(Klass* k) { 818 HandleMark hm; 819 InstanceKlass* ik = InstanceKlass::cast(k); 820 821 u4 size = 0; 822 823 for (FieldStream fld(ik, false, false); !fld.eos(); fld.next()) { 824 if (!fld.access_flags().is_static()) { 825 Symbol* sig = fld.signature(); 826 switch (sig->byte_at(0)) { 827 case JVM_SIGNATURE_CLASS : 828 case JVM_SIGNATURE_ARRAY : size += oopSize; break; 829 830 case JVM_SIGNATURE_BYTE : 831 case JVM_SIGNATURE_BOOLEAN : size += 1; break; 832 833 case JVM_SIGNATURE_CHAR : 834 case JVM_SIGNATURE_SHORT : size += 2; break; 835 836 case JVM_SIGNATURE_INT : 837 case JVM_SIGNATURE_FLOAT : size += 4; break; 838 839 case JVM_SIGNATURE_LONG : 840 case JVM_SIGNATURE_DOUBLE : size += 8; break; 841 842 default : ShouldNotReachHere(); 843 } 844 } 845 } 846 return size; 847 } 848 849 // dumps static fields of the given class 850 void DumperSupport::dump_static_fields(DumpWriter* writer, Klass* k) { 851 HandleMark hm; 852 InstanceKlass* ik = InstanceKlass::cast(k); 853 854 // pass 1 - count the static fields 855 u2 field_count = 0; 856 for (FieldStream fldc(ik, true, true); !fldc.eos(); fldc.next()) { 857 if (fldc.access_flags().is_static()) field_count++; 858 } 859 860 // Add in resolved_references which is referenced by the cpCache 861 // The resolved_references is an array per InstanceKlass holding the 862 // strings and other oops resolved from the constant pool. 863 oop resolved_references = ik->constants()->resolved_references_or_null(); 864 if (resolved_references != NULL) { 865 field_count++; 866 867 // Add in the resolved_references of the used previous versions of the class 868 // in the case of RedefineClasses 869 InstanceKlass* prev = ik->previous_versions(); 870 while (prev != NULL && prev->constants()->resolved_references_or_null() != NULL) { 871 field_count++; 872 prev = prev->previous_versions(); 873 } 874 } 875 876 // Also provide a pointer to the init_lock if present, so there aren't unreferenced int[0] 877 // arrays. 878 oop init_lock = ik->init_lock(); 879 if (init_lock != NULL) { 880 field_count++; 881 } 882 883 writer->write_u2(field_count); 884 885 // pass 2 - dump the field descriptors and raw values 886 for (FieldStream fld(ik, true, true); !fld.eos(); fld.next()) { 887 if (fld.access_flags().is_static()) { 888 Symbol* sig = fld.signature(); 889 890 writer->write_symbolID(fld.name()); // name 891 writer->write_u1(sig2tag(sig)); // type 892 893 // value 894 dump_field_value(writer, sig->byte_at(0), ik->java_mirror(), fld.offset()); 895 } 896 } 897 898 // Add resolved_references for each class that has them 899 if (resolved_references != NULL) { 900 writer->write_symbolID(vmSymbols::resolved_references_name()); // name 901 writer->write_u1(sig2tag(vmSymbols::object_array_signature())); // type 902 writer->write_objectID(resolved_references); 903 904 // Also write any previous versions 905 InstanceKlass* prev = ik->previous_versions(); 906 while (prev != NULL && prev->constants()->resolved_references_or_null() != NULL) { 907 writer->write_symbolID(vmSymbols::resolved_references_name()); // name 908 writer->write_u1(sig2tag(vmSymbols::object_array_signature())); // type 909 writer->write_objectID(prev->constants()->resolved_references()); 910 prev = prev->previous_versions(); 911 } 912 } 913 914 // Add init lock to the end if the class is not yet initialized 915 if (init_lock != NULL) { 916 writer->write_symbolID(vmSymbols::init_lock_name()); // name 917 writer->write_u1(sig2tag(vmSymbols::int_array_signature())); // type 918 writer->write_objectID(init_lock); 919 } 920 } 921 922 // dump the raw values of the instance fields of the given object 923 void DumperSupport::dump_instance_fields(DumpWriter* writer, oop o) { 924 HandleMark hm; 925 InstanceKlass* ik = InstanceKlass::cast(o->klass()); 926 927 for (FieldStream fld(ik, false, false); !fld.eos(); fld.next()) { 928 if (!fld.access_flags().is_static()) { 929 Symbol* sig = fld.signature(); 930 dump_field_value(writer, sig->byte_at(0), o, fld.offset()); 931 } 932 } 933 } 934 935 // dumps the definition of the instance fields for a given class 936 void DumperSupport::dump_instance_field_descriptors(DumpWriter* writer, Klass* k) { 937 HandleMark hm; 938 InstanceKlass* ik = InstanceKlass::cast(k); 939 940 // pass 1 - count the instance fields 941 u2 field_count = 0; 942 for (FieldStream fldc(ik, true, true); !fldc.eos(); fldc.next()) { 943 if (!fldc.access_flags().is_static()) field_count++; 944 } 945 946 writer->write_u2(field_count); 947 948 // pass 2 - dump the field descriptors 949 for (FieldStream fld(ik, true, true); !fld.eos(); fld.next()) { 950 if (!fld.access_flags().is_static()) { 951 Symbol* sig = fld.signature(); 952 953 writer->write_symbolID(fld.name()); // name 954 writer->write_u1(sig2tag(sig)); // type 955 } 956 } 957 } 958 959 // creates HPROF_GC_INSTANCE_DUMP record for the given object 960 void DumperSupport::dump_instance(DumpWriter* writer, oop o) { 961 Klass* k = o->klass(); 962 963 writer->write_u1(HPROF_GC_INSTANCE_DUMP); 964 writer->write_objectID(o); 965 writer->write_u4(STACK_TRACE_ID); 966 967 // class ID 968 writer->write_classID(k); 969 970 // number of bytes that follow 971 writer->write_u4(instance_size(k) ); 972 973 // field values 974 dump_instance_fields(writer, o); 975 } 976 977 // creates HPROF_GC_CLASS_DUMP record for the given class and each of 978 // its array classes 979 void DumperSupport::dump_class_and_array_classes(DumpWriter* writer, Klass* k) { 980 InstanceKlass* ik = InstanceKlass::cast(k); 981 982 // We can safepoint and do a heap dump at a point where we have a Klass, 983 // but no java mirror class has been setup for it. So we need to check 984 // that the class is at least loaded, to avoid crash from a null mirror. 985 if (!ik->is_loaded()) { 986 return; 987 } 988 989 writer->write_u1(HPROF_GC_CLASS_DUMP); 990 991 // class ID 992 writer->write_classID(ik); 993 writer->write_u4(STACK_TRACE_ID); 994 995 // super class ID 996 Klass* java_super = ik->java_super(); 997 if (java_super == NULL) { 998 writer->write_objectID(oop(NULL)); 999 } else { 1000 writer->write_classID(java_super); 1001 } 1002 1003 writer->write_objectID(ik->class_loader()); 1004 writer->write_objectID(ik->signers()); 1005 writer->write_objectID(ik->protection_domain()); 1006 1007 // reserved 1008 writer->write_objectID(oop(NULL)); 1009 writer->write_objectID(oop(NULL)); 1010 1011 // instance size 1012 writer->write_u4(DumperSupport::instance_size(k)); 1013 1014 // size of constant pool - ignored by HAT 1.1 1015 writer->write_u2(0); 1016 1017 // number of static fields 1018 dump_static_fields(writer, k); 1019 1020 // description of instance fields 1021 dump_instance_field_descriptors(writer, k); 1022 1023 // array classes 1024 k = k->array_klass_or_null(); 1025 while (k != NULL) { 1026 Klass* klass = k; 1027 assert(klass->is_objArray_klass(), "not an ObjArrayKlass"); 1028 1029 writer->write_u1(HPROF_GC_CLASS_DUMP); 1030 writer->write_classID(klass); 1031 writer->write_u4(STACK_TRACE_ID); 1032 1033 // super class of array classes is java.lang.Object 1034 java_super = klass->java_super(); 1035 assert(java_super != NULL, "checking"); 1036 writer->write_classID(java_super); 1037 1038 writer->write_objectID(ik->class_loader()); 1039 writer->write_objectID(ik->signers()); 1040 writer->write_objectID(ik->protection_domain()); 1041 1042 writer->write_objectID(oop(NULL)); // reserved 1043 writer->write_objectID(oop(NULL)); 1044 writer->write_u4(0); // instance size 1045 writer->write_u2(0); // constant pool 1046 writer->write_u2(0); // static fields 1047 writer->write_u2(0); // instance fields 1048 1049 // get the array class for the next rank 1050 k = klass->array_klass_or_null(); 1051 } 1052 } 1053 1054 // creates HPROF_GC_CLASS_DUMP record for a given primitive array 1055 // class (and each multi-dimensional array class too) 1056 void DumperSupport::dump_basic_type_array_class(DumpWriter* writer, Klass* k) { 1057 // array classes 1058 while (k != NULL) { 1059 Klass* klass = k; 1060 1061 writer->write_u1(HPROF_GC_CLASS_DUMP); 1062 writer->write_classID(klass); 1063 writer->write_u4(STACK_TRACE_ID); 1064 1065 // super class of array classes is java.lang.Object 1066 Klass* java_super = klass->java_super(); 1067 assert(java_super != NULL, "checking"); 1068 writer->write_classID(java_super); 1069 1070 writer->write_objectID(oop(NULL)); // loader 1071 writer->write_objectID(oop(NULL)); // signers 1072 writer->write_objectID(oop(NULL)); // protection domain 1073 1074 writer->write_objectID(oop(NULL)); // reserved 1075 writer->write_objectID(oop(NULL)); 1076 writer->write_u4(0); // instance size 1077 writer->write_u2(0); // constant pool 1078 writer->write_u2(0); // static fields 1079 writer->write_u2(0); // instance fields 1080 1081 // get the array class for the next rank 1082 k = klass->array_klass_or_null(); 1083 } 1084 } 1085 1086 // Hprof uses an u4 as record length field, 1087 // which means we need to truncate arrays that are too long. 1088 int DumperSupport::calculate_array_max_length(DumpWriter* writer, arrayOop array, short header_size) { 1089 BasicType type = ArrayKlass::cast(array->klass())->element_type(); 1090 assert(type >= T_BOOLEAN && type <= T_OBJECT, "invalid array element type"); 1091 1092 int length = array->length(); 1093 1094 int type_size; 1095 if (type == T_OBJECT) { 1096 type_size = sizeof(address); 1097 } else { 1098 type_size = type2aelembytes(type); 1099 } 1100 1101 size_t length_in_bytes = (size_t)length * type_size; 1102 1103 // Create a new record if the current record is non-empty and the array can't fit. 1104 julong current_record_length = writer->current_record_length(); 1105 if (current_record_length > 0 && 1106 (current_record_length + header_size + length_in_bytes) > max_juint) { 1107 write_current_dump_record_length(writer); 1108 write_dump_header(writer); 1109 1110 // We now have an empty record. 1111 current_record_length = 0; 1112 } 1113 1114 // Calculate max bytes we can use. 1115 uint max_bytes = max_juint - (header_size + current_record_length); 1116 1117 // Array too long for the record? 1118 // Calculate max length and return it. 1119 if (length_in_bytes > max_bytes) { 1120 length = max_bytes / type_size; 1121 length_in_bytes = (size_t)length * type_size; 1122 1123 warning("cannot dump array of type %s[] with length %d; truncating to length %d", 1124 type2name_tab[type], array->length(), length); 1125 } 1126 return length; 1127 } 1128 1129 // creates HPROF_GC_OBJ_ARRAY_DUMP record for the given object array 1130 void DumperSupport::dump_object_array(DumpWriter* writer, objArrayOop array) { 1131 // sizeof(u1) + 2 * sizeof(u4) + sizeof(objectID) + sizeof(classID) 1132 short header_size = 1 + 2 * 4 + 2 * sizeof(address); 1133 1134 int length = calculate_array_max_length(writer, array, header_size); 1135 1136 writer->write_u1(HPROF_GC_OBJ_ARRAY_DUMP); 1137 writer->write_objectID(array); 1138 writer->write_u4(STACK_TRACE_ID); 1139 writer->write_u4(length); 1140 1141 // array class ID 1142 writer->write_classID(array->klass()); 1143 1144 // [id]* elements 1145 for (int index = 0; index < length; index++) { 1146 oop o = array->obj_at(index); 1147 writer->write_objectID(o); 1148 } 1149 } 1150 1151 #define WRITE_ARRAY(Array, Type, Size, Length) \ 1152 for (int i = 0; i < Length; i++) { writer->write_##Size((Size)Array->Type##_at(i)); } 1153 1154 // creates HPROF_GC_PRIM_ARRAY_DUMP record for the given type array 1155 void DumperSupport::dump_prim_array(DumpWriter* writer, typeArrayOop array) { 1156 BasicType type = TypeArrayKlass::cast(array->klass())->element_type(); 1157 1158 // 2 * sizeof(u1) + 2 * sizeof(u4) + sizeof(objectID) 1159 short header_size = 2 * 1 + 2 * 4 + sizeof(address); 1160 1161 int length = calculate_array_max_length(writer, array, header_size); 1162 int type_size = type2aelembytes(type); 1163 u4 length_in_bytes = (u4)length * type_size; 1164 1165 writer->write_u1(HPROF_GC_PRIM_ARRAY_DUMP); 1166 writer->write_objectID(array); 1167 writer->write_u4(STACK_TRACE_ID); 1168 writer->write_u4(length); 1169 writer->write_u1(type2tag(type)); 1170 1171 // nothing to copy 1172 if (length == 0) { 1173 return; 1174 } 1175 1176 // If the byte ordering is big endian then we can copy most types directly 1177 1178 switch (type) { 1179 case T_INT : { 1180 if (Endian::is_Java_byte_ordering_different()) { 1181 WRITE_ARRAY(array, int, u4, length); 1182 } else { 1183 writer->write_raw((void*)(array->int_at_addr(0)), length_in_bytes); 1184 } 1185 break; 1186 } 1187 case T_BYTE : { 1188 writer->write_raw((void*)(array->byte_at_addr(0)), length_in_bytes); 1189 break; 1190 } 1191 case T_CHAR : { 1192 if (Endian::is_Java_byte_ordering_different()) { 1193 WRITE_ARRAY(array, char, u2, length); 1194 } else { 1195 writer->write_raw((void*)(array->char_at_addr(0)), length_in_bytes); 1196 } 1197 break; 1198 } 1199 case T_SHORT : { 1200 if (Endian::is_Java_byte_ordering_different()) { 1201 WRITE_ARRAY(array, short, u2, length); 1202 } else { 1203 writer->write_raw((void*)(array->short_at_addr(0)), length_in_bytes); 1204 } 1205 break; 1206 } 1207 case T_BOOLEAN : { 1208 if (Endian::is_Java_byte_ordering_different()) { 1209 WRITE_ARRAY(array, bool, u1, length); 1210 } else { 1211 writer->write_raw((void*)(array->bool_at_addr(0)), length_in_bytes); 1212 } 1213 break; 1214 } 1215 case T_LONG : { 1216 if (Endian::is_Java_byte_ordering_different()) { 1217 WRITE_ARRAY(array, long, u8, length); 1218 } else { 1219 writer->write_raw((void*)(array->long_at_addr(0)), length_in_bytes); 1220 } 1221 break; 1222 } 1223 1224 // handle float/doubles in a special value to ensure than NaNs are 1225 // written correctly. TO DO: Check if we can avoid this on processors that 1226 // use IEEE 754. 1227 1228 case T_FLOAT : { 1229 for (int i = 0; i < length; i++) { 1230 dump_float(writer, array->float_at(i)); 1231 } 1232 break; 1233 } 1234 case T_DOUBLE : { 1235 for (int i = 0; i < length; i++) { 1236 dump_double(writer, array->double_at(i)); 1237 } 1238 break; 1239 } 1240 default : ShouldNotReachHere(); 1241 } 1242 } 1243 1244 // create a HPROF_FRAME record of the given Method* and bci 1245 void DumperSupport::dump_stack_frame(DumpWriter* writer, 1246 int frame_serial_num, 1247 int class_serial_num, 1248 Method* m, 1249 int bci) { 1250 int line_number; 1251 if (m->is_native()) { 1252 line_number = -3; // native frame 1253 } else { 1254 line_number = m->line_number_from_bci(bci); 1255 } 1256 1257 write_header(writer, HPROF_FRAME, 4*oopSize + 2*sizeof(u4)); 1258 writer->write_id(frame_serial_num); // frame serial number 1259 writer->write_symbolID(m->name()); // method's name 1260 writer->write_symbolID(m->signature()); // method's signature 1261 1262 assert(m->method_holder()->is_instance_klass(), "not InstanceKlass"); 1263 writer->write_symbolID(m->method_holder()->source_file_name()); // source file name 1264 writer->write_u4(class_serial_num); // class serial number 1265 writer->write_u4((u4) line_number); // line number 1266 } 1267 1268 1269 // Support class used to generate HPROF_UTF8 records from the entries in the 1270 // SymbolTable. 1271 1272 class SymbolTableDumper : public SymbolClosure { 1273 private: 1274 DumpWriter* _writer; 1275 DumpWriter* writer() const { return _writer; } 1276 public: 1277 SymbolTableDumper(DumpWriter* writer) { _writer = writer; } 1278 void do_symbol(Symbol** p); 1279 }; 1280 1281 void SymbolTableDumper::do_symbol(Symbol** p) { 1282 ResourceMark rm; 1283 Symbol* sym = load_symbol(p); 1284 int len = sym->utf8_length(); 1285 if (len > 0) { 1286 char* s = sym->as_utf8(); 1287 DumperSupport::write_header(writer(), HPROF_UTF8, oopSize + len); 1288 writer()->write_symbolID(sym); 1289 writer()->write_raw(s, len); 1290 } 1291 } 1292 1293 // Support class used to generate HPROF_GC_ROOT_JNI_LOCAL records 1294 1295 class JNILocalsDumper : public OopClosure { 1296 private: 1297 DumpWriter* _writer; 1298 u4 _thread_serial_num; 1299 int _frame_num; 1300 DumpWriter* writer() const { return _writer; } 1301 public: 1302 JNILocalsDumper(DumpWriter* writer, u4 thread_serial_num) { 1303 _writer = writer; 1304 _thread_serial_num = thread_serial_num; 1305 _frame_num = -1; // default - empty stack 1306 } 1307 void set_frame_number(int n) { _frame_num = n; } 1308 void do_oop(oop* obj_p); 1309 void do_oop(narrowOop* obj_p) { ShouldNotReachHere(); } 1310 }; 1311 1312 1313 void JNILocalsDumper::do_oop(oop* obj_p) { 1314 // ignore null handles 1315 oop o = *obj_p; 1316 if (o != NULL) { 1317 writer()->write_u1(HPROF_GC_ROOT_JNI_LOCAL); 1318 writer()->write_objectID(o); 1319 writer()->write_u4(_thread_serial_num); 1320 writer()->write_u4((u4)_frame_num); 1321 } 1322 } 1323 1324 1325 // Support class used to generate HPROF_GC_ROOT_JNI_GLOBAL records 1326 1327 class JNIGlobalsDumper : public OopClosure { 1328 private: 1329 DumpWriter* _writer; 1330 DumpWriter* writer() const { return _writer; } 1331 1332 public: 1333 JNIGlobalsDumper(DumpWriter* writer) { 1334 _writer = writer; 1335 } 1336 void do_oop(oop* obj_p); 1337 void do_oop(narrowOop* obj_p) { ShouldNotReachHere(); } 1338 }; 1339 1340 void JNIGlobalsDumper::do_oop(oop* obj_p) { 1341 oop o = *obj_p; 1342 1343 // ignore these 1344 if (o == NULL) return; 1345 1346 // we ignore global ref to symbols and other internal objects 1347 if (o->is_instance() || o->is_objArray() || o->is_typeArray()) { 1348 writer()->write_u1(HPROF_GC_ROOT_JNI_GLOBAL); 1349 writer()->write_objectID(o); 1350 writer()->write_objectID((oopDesc*)obj_p); // global ref ID 1351 } 1352 }; 1353 1354 1355 // Support class used to generate HPROF_GC_ROOT_MONITOR_USED records 1356 1357 class MonitorUsedDumper : public OopClosure { 1358 private: 1359 DumpWriter* _writer; 1360 DumpWriter* writer() const { return _writer; } 1361 public: 1362 MonitorUsedDumper(DumpWriter* writer) { 1363 _writer = writer; 1364 } 1365 void do_oop(oop* obj_p) { 1366 writer()->write_u1(HPROF_GC_ROOT_MONITOR_USED); 1367 writer()->write_objectID(*obj_p); 1368 } 1369 void do_oop(narrowOop* obj_p) { ShouldNotReachHere(); } 1370 }; 1371 1372 1373 // Support class used to generate HPROF_GC_ROOT_STICKY_CLASS records 1374 1375 class StickyClassDumper : public KlassClosure { 1376 private: 1377 DumpWriter* _writer; 1378 DumpWriter* writer() const { return _writer; } 1379 public: 1380 StickyClassDumper(DumpWriter* writer) { 1381 _writer = writer; 1382 } 1383 void do_klass(Klass* k) { 1384 if (k->is_instance_klass()) { 1385 InstanceKlass* ik = InstanceKlass::cast(k); 1386 writer()->write_u1(HPROF_GC_ROOT_STICKY_CLASS); 1387 writer()->write_classID(ik); 1388 } 1389 } 1390 }; 1391 1392 1393 class VM_HeapDumper; 1394 1395 // Support class using when iterating over the heap. 1396 1397 class HeapObjectDumper : public ObjectClosure { 1398 private: 1399 VM_HeapDumper* _dumper; 1400 DumpWriter* _writer; 1401 1402 VM_HeapDumper* dumper() { return _dumper; } 1403 DumpWriter* writer() { return _writer; } 1404 1405 // used to indicate that a record has been writen 1406 void mark_end_of_record(); 1407 1408 public: 1409 HeapObjectDumper(VM_HeapDumper* dumper, DumpWriter* writer) { 1410 _dumper = dumper; 1411 _writer = writer; 1412 } 1413 1414 // called for each object in the heap 1415 void do_object(oop o); 1416 }; 1417 1418 void HeapObjectDumper::do_object(oop o) { 1419 // skip classes as these emitted as HPROF_GC_CLASS_DUMP records 1420 if (o->klass() == SystemDictionary::Class_klass()) { 1421 if (!java_lang_Class::is_primitive(o)) { 1422 return; 1423 } 1424 } 1425 1426 if (o->is_instance()) { 1427 // create a HPROF_GC_INSTANCE record for each object 1428 DumperSupport::dump_instance(writer(), o); 1429 mark_end_of_record(); 1430 } else if (o->is_objArray()) { 1431 // create a HPROF_GC_OBJ_ARRAY_DUMP record for each object array 1432 DumperSupport::dump_object_array(writer(), objArrayOop(o)); 1433 mark_end_of_record(); 1434 } else if (o->is_typeArray()) { 1435 // create a HPROF_GC_PRIM_ARRAY_DUMP record for each type array 1436 DumperSupport::dump_prim_array(writer(), typeArrayOop(o)); 1437 mark_end_of_record(); 1438 } 1439 } 1440 1441 // The VM operation that performs the heap dump 1442 class VM_HeapDumper : public VM_GC_Operation { 1443 private: 1444 static VM_HeapDumper* _global_dumper; 1445 static DumpWriter* _global_writer; 1446 DumpWriter* _local_writer; 1447 JavaThread* _oome_thread; 1448 Method* _oome_constructor; 1449 bool _gc_before_heap_dump; 1450 GrowableArray<Klass*>* _klass_map; 1451 ThreadStackTrace** _stack_traces; 1452 int _num_threads; 1453 1454 // accessors and setters 1455 static VM_HeapDumper* dumper() { assert(_global_dumper != NULL, "Error"); return _global_dumper; } 1456 static DumpWriter* writer() { assert(_global_writer != NULL, "Error"); return _global_writer; } 1457 void set_global_dumper() { 1458 assert(_global_dumper == NULL, "Error"); 1459 _global_dumper = this; 1460 } 1461 void set_global_writer() { 1462 assert(_global_writer == NULL, "Error"); 1463 _global_writer = _local_writer; 1464 } 1465 void clear_global_dumper() { _global_dumper = NULL; } 1466 void clear_global_writer() { _global_writer = NULL; } 1467 1468 bool skip_operation() const; 1469 1470 // writes a HPROF_LOAD_CLASS record 1471 static void do_load_class(Klass* k); 1472 1473 // writes a HPROF_GC_CLASS_DUMP record for the given class 1474 // (and each array class too) 1475 static void do_class_dump(Klass* k); 1476 1477 // writes a HPROF_GC_CLASS_DUMP records for a given basic type 1478 // array (and each multi-dimensional array too) 1479 static void do_basic_type_array_class_dump(Klass* k); 1480 1481 // HPROF_GC_ROOT_THREAD_OBJ records 1482 int do_thread(JavaThread* thread, u4 thread_serial_num); 1483 void do_threads(); 1484 1485 void add_class_serial_number(Klass* k, int serial_num) { 1486 _klass_map->at_put_grow(serial_num, k); 1487 } 1488 1489 // HPROF_TRACE and HPROF_FRAME records 1490 void dump_stack_traces(); 1491 1492 public: 1493 VM_HeapDumper(DumpWriter* writer, bool gc_before_heap_dump, bool oome) : 1494 VM_GC_Operation(0 /* total collections, dummy, ignored */, 1495 GCCause::_heap_dump /* GC Cause */, 1496 0 /* total full collections, dummy, ignored */, 1497 gc_before_heap_dump) { 1498 _local_writer = writer; 1499 _gc_before_heap_dump = gc_before_heap_dump; 1500 _klass_map = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<Klass*>(INITIAL_CLASS_COUNT, true); 1501 _stack_traces = NULL; 1502 _num_threads = 0; 1503 if (oome) { 1504 assert(!Thread::current()->is_VM_thread(), "Dump from OutOfMemoryError cannot be called by the VMThread"); 1505 // get OutOfMemoryError zero-parameter constructor 1506 InstanceKlass* oome_ik = SystemDictionary::OutOfMemoryError_klass(); 1507 _oome_constructor = oome_ik->find_method(vmSymbols::object_initializer_name(), 1508 vmSymbols::void_method_signature()); 1509 // get thread throwing OOME when generating the heap dump at OOME 1510 _oome_thread = JavaThread::current(); 1511 } else { 1512 _oome_thread = NULL; 1513 _oome_constructor = NULL; 1514 } 1515 } 1516 ~VM_HeapDumper() { 1517 if (_stack_traces != NULL) { 1518 for (int i=0; i < _num_threads; i++) { 1519 delete _stack_traces[i]; 1520 } 1521 FREE_C_HEAP_ARRAY(ThreadStackTrace*, _stack_traces); 1522 } 1523 delete _klass_map; 1524 } 1525 1526 VMOp_Type type() const { return VMOp_HeapDumper; } 1527 // used to mark sub-record boundary 1528 void check_segment_length(); 1529 void doit(); 1530 }; 1531 1532 VM_HeapDumper* VM_HeapDumper::_global_dumper = NULL; 1533 DumpWriter* VM_HeapDumper::_global_writer = NULL; 1534 1535 bool VM_HeapDumper::skip_operation() const { 1536 return false; 1537 } 1538 1539 // writes a HPROF_HEAP_DUMP_SEGMENT record 1540 void DumperSupport::write_dump_header(DumpWriter* writer) { 1541 if (writer->is_open()) { 1542 writer->write_u1(HPROF_HEAP_DUMP_SEGMENT); 1543 writer->write_u4(0); // current ticks 1544 1545 // record the starting position for the dump (its length will be fixed up later) 1546 writer->set_dump_start(writer->current_offset()); 1547 writer->write_u4(0); 1548 } 1549 } 1550 1551 // fixes up the length of the current dump record 1552 void DumperSupport::write_current_dump_record_length(DumpWriter* writer) { 1553 if (writer->is_open()) { 1554 julong dump_end = writer->bytes_written() + writer->bytes_unwritten(); 1555 julong dump_len = writer->current_record_length(); 1556 1557 // record length must fit in a u4 1558 if (dump_len > max_juint) { 1559 warning("record is too large"); 1560 } 1561 1562 // seek to the dump start and fix-up the length 1563 assert(writer->dump_start() >= 0, "no dump start recorded"); 1564 writer->seek_to_offset(writer->dump_start()); 1565 writer->write_u4((u4)dump_len); 1566 1567 // adjust the total size written to keep the bytes written correct. 1568 writer->adjust_bytes_written(-((jlong) sizeof(u4))); 1569 1570 // seek to dump end so we can continue 1571 writer->seek_to_offset(dump_end); 1572 1573 // no current dump record 1574 writer->set_dump_start((jlong)-1); 1575 } 1576 } 1577 1578 // used on a sub-record boundary to check if we need to start a 1579 // new segment. 1580 void VM_HeapDumper::check_segment_length() { 1581 if (writer()->is_open()) { 1582 julong dump_len = writer()->current_record_length(); 1583 1584 if (dump_len > 2UL*G) { 1585 DumperSupport::write_current_dump_record_length(writer()); 1586 DumperSupport::write_dump_header(writer()); 1587 } 1588 } 1589 } 1590 1591 // fixes up the current dump record and writes HPROF_HEAP_DUMP_END record 1592 void DumperSupport::end_of_dump(DumpWriter* writer) { 1593 if (writer->is_open()) { 1594 write_current_dump_record_length(writer); 1595 1596 writer->write_u1(HPROF_HEAP_DUMP_END); 1597 writer->write_u4(0); 1598 writer->write_u4(0); 1599 } 1600 } 1601 1602 // marks sub-record boundary 1603 void HeapObjectDumper::mark_end_of_record() { 1604 dumper()->check_segment_length(); 1605 } 1606 1607 // writes a HPROF_LOAD_CLASS record for the class (and each of its 1608 // array classes) 1609 void VM_HeapDumper::do_load_class(Klass* k) { 1610 static u4 class_serial_num = 0; 1611 1612 // len of HPROF_LOAD_CLASS record 1613 u4 remaining = 2*oopSize + 2*sizeof(u4); 1614 1615 // write a HPROF_LOAD_CLASS for the class and each array class 1616 do { 1617 DumperSupport::write_header(writer(), HPROF_LOAD_CLASS, remaining); 1618 1619 // class serial number is just a number 1620 writer()->write_u4(++class_serial_num); 1621 1622 // class ID 1623 Klass* klass = k; 1624 writer()->write_classID(klass); 1625 1626 // add the Klass* and class serial number pair 1627 dumper()->add_class_serial_number(klass, class_serial_num); 1628 1629 writer()->write_u4(STACK_TRACE_ID); 1630 1631 // class name ID 1632 Symbol* name = klass->name(); 1633 writer()->write_symbolID(name); 1634 1635 // write a LOAD_CLASS record for the array type (if it exists) 1636 k = klass->array_klass_or_null(); 1637 } while (k != NULL); 1638 } 1639 1640 // writes a HPROF_GC_CLASS_DUMP record for the given class 1641 void VM_HeapDumper::do_class_dump(Klass* k) { 1642 if (k->is_instance_klass()) { 1643 DumperSupport::dump_class_and_array_classes(writer(), k); 1644 } 1645 } 1646 1647 // writes a HPROF_GC_CLASS_DUMP records for a given basic type 1648 // array (and each multi-dimensional array too) 1649 void VM_HeapDumper::do_basic_type_array_class_dump(Klass* k) { 1650 DumperSupport::dump_basic_type_array_class(writer(), k); 1651 } 1652 1653 // Walk the stack of the given thread. 1654 // Dumps a HPROF_GC_ROOT_JAVA_FRAME record for each local 1655 // Dumps a HPROF_GC_ROOT_JNI_LOCAL record for each JNI local 1656 // 1657 // It returns the number of Java frames in this thread stack 1658 int VM_HeapDumper::do_thread(JavaThread* java_thread, u4 thread_serial_num) { 1659 JNILocalsDumper blk(writer(), thread_serial_num); 1660 1661 oop threadObj = java_thread->threadObj(); 1662 assert(threadObj != NULL, "sanity check"); 1663 1664 int stack_depth = 0; 1665 if (java_thread->has_last_Java_frame()) { 1666 1667 // vframes are resource allocated 1668 Thread* current_thread = Thread::current(); 1669 ResourceMark rm(current_thread); 1670 HandleMark hm(current_thread); 1671 1672 RegisterMap reg_map(java_thread); 1673 frame f = java_thread->last_frame(); 1674 vframe* vf = vframe::new_vframe(&f, ®_map, java_thread); 1675 frame* last_entry_frame = NULL; 1676 int extra_frames = 0; 1677 1678 if (java_thread == _oome_thread && _oome_constructor != NULL) { 1679 extra_frames++; 1680 } 1681 while (vf != NULL) { 1682 blk.set_frame_number(stack_depth); 1683 if (vf->is_java_frame()) { 1684 1685 // java frame (interpreted, compiled, ...) 1686 javaVFrame *jvf = javaVFrame::cast(vf); 1687 if (!(jvf->method()->is_native())) { 1688 StackValueCollection* locals = jvf->locals(); 1689 for (int slot=0; slot<locals->size(); slot++) { 1690 if (locals->at(slot)->type() == T_OBJECT) { 1691 oop o = locals->obj_at(slot)(); 1692 1693 if (o != NULL) { 1694 writer()->write_u1(HPROF_GC_ROOT_JAVA_FRAME); 1695 writer()->write_objectID(o); 1696 writer()->write_u4(thread_serial_num); 1697 writer()->write_u4((u4) (stack_depth + extra_frames)); 1698 } 1699 } 1700 } 1701 StackValueCollection *exprs = jvf->expressions(); 1702 for(int index = 0; index < exprs->size(); index++) { 1703 if (exprs->at(index)->type() == T_OBJECT) { 1704 oop o = exprs->obj_at(index)(); 1705 if (o != NULL) { 1706 writer()->write_u1(HPROF_GC_ROOT_JAVA_FRAME); 1707 writer()->write_objectID(o); 1708 writer()->write_u4(thread_serial_num); 1709 writer()->write_u4((u4) (stack_depth + extra_frames)); 1710 } 1711 } 1712 } 1713 } else { 1714 // native frame 1715 if (stack_depth == 0) { 1716 // JNI locals for the top frame. 1717 java_thread->active_handles()->oops_do(&blk); 1718 } else { 1719 if (last_entry_frame != NULL) { 1720 // JNI locals for the entry frame 1721 assert(last_entry_frame->is_entry_frame(), "checking"); 1722 last_entry_frame->entry_frame_call_wrapper()->handles()->oops_do(&blk); 1723 } 1724 } 1725 } 1726 // increment only for Java frames 1727 stack_depth++; 1728 last_entry_frame = NULL; 1729 1730 } else { 1731 // externalVFrame - if it's an entry frame then report any JNI locals 1732 // as roots when we find the corresponding native javaVFrame 1733 frame* fr = vf->frame_pointer(); 1734 assert(fr != NULL, "sanity check"); 1735 if (fr->is_entry_frame()) { 1736 last_entry_frame = fr; 1737 } 1738 } 1739 vf = vf->sender(); 1740 } 1741 } else { 1742 // no last java frame but there may be JNI locals 1743 java_thread->active_handles()->oops_do(&blk); 1744 } 1745 return stack_depth; 1746 } 1747 1748 1749 // write a HPROF_GC_ROOT_THREAD_OBJ record for each java thread. Then walk 1750 // the stack so that locals and JNI locals are dumped. 1751 void VM_HeapDumper::do_threads() { 1752 for (int i=0; i < _num_threads; i++) { 1753 JavaThread* thread = _stack_traces[i]->thread(); 1754 oop threadObj = thread->threadObj(); 1755 u4 thread_serial_num = i+1; 1756 u4 stack_serial_num = thread_serial_num + STACK_TRACE_ID; 1757 writer()->write_u1(HPROF_GC_ROOT_THREAD_OBJ); 1758 writer()->write_objectID(threadObj); 1759 writer()->write_u4(thread_serial_num); // thread number 1760 writer()->write_u4(stack_serial_num); // stack trace serial number 1761 int num_frames = do_thread(thread, thread_serial_num); 1762 assert(num_frames == _stack_traces[i]->get_stack_depth(), 1763 "total number of Java frames not matched"); 1764 } 1765 } 1766 1767 1768 // The VM operation that dumps the heap. The dump consists of the following 1769 // records: 1770 // 1771 // HPROF_HEADER 1772 // [HPROF_UTF8]* 1773 // [HPROF_LOAD_CLASS]* 1774 // [[HPROF_FRAME]*|HPROF_TRACE]* 1775 // [HPROF_GC_CLASS_DUMP]* 1776 // [HPROF_HEAP_DUMP_SEGMENT]* 1777 // HPROF_HEAP_DUMP_END 1778 // 1779 // The HPROF_TRACE records represent the stack traces where the heap dump 1780 // is generated and a "dummy trace" record which does not include 1781 // any frames. The dummy trace record is used to be referenced as the 1782 // unknown object alloc site. 1783 // 1784 // Each HPROF_HEAP_DUMP_SEGMENT record has a length followed by sub-records. 1785 // To allow the heap dump be generated in a single pass we remember the position 1786 // of the dump length and fix it up after all sub-records have been written. 1787 // To generate the sub-records we iterate over the heap, writing 1788 // HPROF_GC_INSTANCE_DUMP, HPROF_GC_OBJ_ARRAY_DUMP, and HPROF_GC_PRIM_ARRAY_DUMP 1789 // records as we go. Once that is done we write records for some of the GC 1790 // roots. 1791 1792 void VM_HeapDumper::doit() { 1793 1794 HandleMark hm; 1795 CollectedHeap* ch = Universe::heap(); 1796 1797 ch->ensure_parsability(false); // must happen, even if collection does 1798 // not happen (e.g. due to GCLocker) 1799 1800 if (_gc_before_heap_dump) { 1801 if (GCLocker::is_active()) { 1802 warning("GC locker is held; pre-heapdump GC was skipped"); 1803 } else { 1804 ch->collect_as_vm_thread(GCCause::_heap_dump); 1805 } 1806 } 1807 1808 // At this point we should be the only dumper active, so 1809 // the following should be safe. 1810 set_global_dumper(); 1811 set_global_writer(); 1812 1813 // Write the file header - we always use 1.0.2 1814 size_t used = ch->used(); 1815 const char* header = "JAVA PROFILE 1.0.2"; 1816 1817 // header is few bytes long - no chance to overflow int 1818 writer()->write_raw((void*)header, (int)strlen(header)); 1819 writer()->write_u1(0); // terminator 1820 writer()->write_u4(oopSize); 1821 writer()->write_u8(os::javaTimeMillis()); 1822 1823 // HPROF_UTF8 records 1824 SymbolTableDumper sym_dumper(writer()); 1825 SymbolTable::symbols_do(&sym_dumper); 1826 1827 // write HPROF_LOAD_CLASS records 1828 ClassLoaderDataGraph::classes_do(&do_load_class); 1829 Universe::basic_type_classes_do(&do_load_class); 1830 1831 // write HPROF_FRAME and HPROF_TRACE records 1832 // this must be called after _klass_map is built when iterating the classes above. 1833 dump_stack_traces(); 1834 1835 // write HPROF_HEAP_DUMP_SEGMENT 1836 DumperSupport::write_dump_header(writer()); 1837 1838 // Writes HPROF_GC_CLASS_DUMP records 1839 ClassLoaderDataGraph::classes_do(&do_class_dump); 1840 Universe::basic_type_classes_do(&do_basic_type_array_class_dump); 1841 check_segment_length(); 1842 1843 // writes HPROF_GC_INSTANCE_DUMP records. 1844 // After each sub-record is written check_segment_length will be invoked 1845 // to check if the current segment exceeds a threshold. If so, a new 1846 // segment is started. 1847 // The HPROF_GC_CLASS_DUMP and HPROF_GC_INSTANCE_DUMP are the vast bulk 1848 // of the heap dump. 1849 HeapObjectDumper obj_dumper(this, writer()); 1850 Universe::heap()->safe_object_iterate(&obj_dumper); 1851 1852 // HPROF_GC_ROOT_THREAD_OBJ + frames + jni locals 1853 do_threads(); 1854 check_segment_length(); 1855 1856 // HPROF_GC_ROOT_MONITOR_USED 1857 MonitorUsedDumper mon_dumper(writer()); 1858 ObjectSynchronizer::oops_do(&mon_dumper); 1859 check_segment_length(); 1860 1861 // HPROF_GC_ROOT_JNI_GLOBAL 1862 JNIGlobalsDumper jni_dumper(writer()); 1863 JNIHandles::oops_do(&jni_dumper); 1864 Universe::oops_do(&jni_dumper); // technically not jni roots, but global roots 1865 // for things like preallocated throwable backtraces 1866 check_segment_length(); 1867 1868 // HPROF_GC_ROOT_STICKY_CLASS 1869 // These should be classes in the NULL class loader data, and not all classes 1870 // if !ClassUnloading 1871 StickyClassDumper class_dumper(writer()); 1872 ClassLoaderData::the_null_class_loader_data()->classes_do(&class_dumper); 1873 1874 // fixes up the length of the dump record and writes the HPROF_HEAP_DUMP_END record. 1875 DumperSupport::end_of_dump(writer()); 1876 1877 // Now we clear the global variables, so that a future dumper might run. 1878 clear_global_dumper(); 1879 clear_global_writer(); 1880 } 1881 1882 void VM_HeapDumper::dump_stack_traces() { 1883 // write a HPROF_TRACE record without any frames to be referenced as object alloc sites 1884 DumperSupport::write_header(writer(), HPROF_TRACE, 3*sizeof(u4)); 1885 writer()->write_u4((u4) STACK_TRACE_ID); 1886 writer()->write_u4(0); // thread number 1887 writer()->write_u4(0); // frame count 1888 1889 _stack_traces = NEW_C_HEAP_ARRAY(ThreadStackTrace*, Threads::number_of_threads(), mtInternal); 1890 int frame_serial_num = 0; 1891 for (JavaThreadIteratorWithHandle jtiwh; JavaThread *thread = jtiwh.next(); ) { 1892 oop threadObj = thread->threadObj(); 1893 if (threadObj != NULL && !thread->is_exiting() && !thread->is_hidden_from_external_view()) { 1894 // dump thread stack trace 1895 ThreadStackTrace* stack_trace = new ThreadStackTrace(thread, false); 1896 stack_trace->dump_stack_at_safepoint(-1); 1897 _stack_traces[_num_threads++] = stack_trace; 1898 1899 // write HPROF_FRAME records for this thread's stack trace 1900 int depth = stack_trace->get_stack_depth(); 1901 int thread_frame_start = frame_serial_num; 1902 int extra_frames = 0; 1903 // write fake frame that makes it look like the thread, which caused OOME, 1904 // is in the OutOfMemoryError zero-parameter constructor 1905 if (thread == _oome_thread && _oome_constructor != NULL) { 1906 int oome_serial_num = _klass_map->find(_oome_constructor->method_holder()); 1907 // the class serial number starts from 1 1908 assert(oome_serial_num > 0, "OutOfMemoryError class not found"); 1909 DumperSupport::dump_stack_frame(writer(), ++frame_serial_num, oome_serial_num, 1910 _oome_constructor, 0); 1911 extra_frames++; 1912 } 1913 for (int j=0; j < depth; j++) { 1914 StackFrameInfo* frame = stack_trace->stack_frame_at(j); 1915 Method* m = frame->method(); 1916 int class_serial_num = _klass_map->find(m->method_holder()); 1917 // the class serial number starts from 1 1918 assert(class_serial_num > 0, "class not found"); 1919 DumperSupport::dump_stack_frame(writer(), ++frame_serial_num, class_serial_num, m, frame->bci()); 1920 } 1921 depth += extra_frames; 1922 1923 // write HPROF_TRACE record for one thread 1924 DumperSupport::write_header(writer(), HPROF_TRACE, 3*sizeof(u4) + depth*oopSize); 1925 int stack_serial_num = _num_threads + STACK_TRACE_ID; 1926 writer()->write_u4(stack_serial_num); // stack trace serial number 1927 writer()->write_u4((u4) _num_threads); // thread serial number 1928 writer()->write_u4(depth); // frame count 1929 for (int j=1; j <= depth; j++) { 1930 writer()->write_id(thread_frame_start + j); 1931 } 1932 } 1933 } 1934 } 1935 1936 // dump the heap to given path. 1937 int HeapDumper::dump(const char* path) { 1938 assert(path != NULL && strlen(path) > 0, "path missing"); 1939 1940 // print message in interactive case 1941 if (print_to_tty()) { 1942 tty->print_cr("Dumping heap to %s ...", path); 1943 timer()->start(); 1944 } 1945 1946 // create the dump writer. If the file can be opened then bail 1947 DumpWriter writer(path); 1948 if (!writer.is_open()) { 1949 set_error(writer.error()); 1950 if (print_to_tty()) { 1951 tty->print_cr("Unable to create %s: %s", path, 1952 (error() != NULL) ? error() : "reason unknown"); 1953 } 1954 return -1; 1955 } 1956 1957 // generate the dump 1958 VM_HeapDumper dumper(&writer, _gc_before_heap_dump, _oome); 1959 if (Thread::current()->is_VM_thread()) { 1960 assert(SafepointSynchronize::is_at_safepoint(), "Expected to be called at a safepoint"); 1961 dumper.doit(); 1962 } else { 1963 VMThread::execute(&dumper); 1964 } 1965 1966 // close dump file and record any error that the writer may have encountered 1967 writer.close(); 1968 set_error(writer.error()); 1969 1970 // print message in interactive case 1971 if (print_to_tty()) { 1972 timer()->stop(); 1973 if (error() == NULL) { 1974 tty->print_cr("Heap dump file created [" JULONG_FORMAT " bytes in %3.3f secs]", 1975 writer.bytes_written(), timer()->seconds()); 1976 } else { 1977 tty->print_cr("Dump file is incomplete: %s", writer.error()); 1978 } 1979 } 1980 1981 return (writer.error() == NULL) ? 0 : -1; 1982 } 1983 1984 // stop timer (if still active), and free any error string we might be holding 1985 HeapDumper::~HeapDumper() { 1986 if (timer()->is_active()) { 1987 timer()->stop(); 1988 } 1989 set_error(NULL); 1990 } 1991 1992 1993 // returns the error string (resource allocated), or NULL 1994 char* HeapDumper::error_as_C_string() const { 1995 if (error() != NULL) { 1996 char* str = NEW_RESOURCE_ARRAY(char, strlen(error())+1); 1997 strcpy(str, error()); 1998 return str; 1999 } else { 2000 return NULL; 2001 } 2002 } 2003 2004 // set the error string 2005 void HeapDumper::set_error(char* error) { 2006 if (_error != NULL) { 2007 os::free(_error); 2008 } 2009 if (error == NULL) { 2010 _error = NULL; 2011 } else { 2012 _error = os::strdup(error); 2013 assert(_error != NULL, "allocation failure"); 2014 } 2015 } 2016 2017 // Called by out-of-memory error reporting by a single Java thread 2018 // outside of a JVM safepoint 2019 void HeapDumper::dump_heap_from_oome() { 2020 HeapDumper::dump_heap(true); 2021 } 2022 2023 // Called by error reporting by a single Java thread outside of a JVM safepoint, 2024 // or by heap dumping by the VM thread during a (GC) safepoint. Thus, these various 2025 // callers are strictly serialized and guaranteed not to interfere below. For more 2026 // general use, however, this method will need modification to prevent 2027 // inteference when updating the static variables base_path and dump_file_seq below. 2028 void HeapDumper::dump_heap() { 2029 HeapDumper::dump_heap(false); 2030 } 2031 2032 void HeapDumper::dump_heap(bool oome) { 2033 static char base_path[JVM_MAXPATHLEN] = {'\0'}; 2034 static uint dump_file_seq = 0; 2035 char* my_path; 2036 const int max_digit_chars = 20; 2037 2038 const char* dump_file_name = "java_pid"; 2039 const char* dump_file_ext = ".hprof"; 2040 2041 // The dump file defaults to java_pid<pid>.hprof in the current working 2042 // directory. HeapDumpPath=<file> can be used to specify an alternative 2043 // dump file name or a directory where dump file is created. 2044 if (dump_file_seq == 0) { // first time in, we initialize base_path 2045 // Calculate potentially longest base path and check if we have enough 2046 // allocated statically. 2047 const size_t total_length = 2048 (HeapDumpPath == NULL ? 0 : strlen(HeapDumpPath)) + 2049 strlen(os::file_separator()) + max_digit_chars + 2050 strlen(dump_file_name) + strlen(dump_file_ext) + 1; 2051 if (total_length > sizeof(base_path)) { 2052 warning("Cannot create heap dump file. HeapDumpPath is too long."); 2053 return; 2054 } 2055 2056 bool use_default_filename = true; 2057 if (HeapDumpPath == NULL || HeapDumpPath[0] == '\0') { 2058 // HeapDumpPath=<file> not specified 2059 } else { 2060 strcpy(base_path, HeapDumpPath); 2061 // check if the path is a directory (must exist) 2062 DIR* dir = os::opendir(base_path); 2063 if (dir == NULL) { 2064 use_default_filename = false; 2065 } else { 2066 // HeapDumpPath specified a directory. We append a file separator 2067 // (if needed). 2068 os::closedir(dir); 2069 size_t fs_len = strlen(os::file_separator()); 2070 if (strlen(base_path) >= fs_len) { 2071 char* end = base_path; 2072 end += (strlen(base_path) - fs_len); 2073 if (strcmp(end, os::file_separator()) != 0) { 2074 strcat(base_path, os::file_separator()); 2075 } 2076 } 2077 } 2078 } 2079 // If HeapDumpPath wasn't a file name then we append the default name 2080 if (use_default_filename) { 2081 const size_t dlen = strlen(base_path); // if heap dump dir specified 2082 jio_snprintf(&base_path[dlen], sizeof(base_path)-dlen, "%s%d%s", 2083 dump_file_name, os::current_process_id(), dump_file_ext); 2084 } 2085 const size_t len = strlen(base_path) + 1; 2086 my_path = (char*)os::malloc(len, mtInternal); 2087 if (my_path == NULL) { 2088 warning("Cannot create heap dump file. Out of system memory."); 2089 return; 2090 } 2091 strncpy(my_path, base_path, len); 2092 } else { 2093 // Append a sequence number id for dumps following the first 2094 const size_t len = strlen(base_path) + max_digit_chars + 2; // for '.' and \0 2095 my_path = (char*)os::malloc(len, mtInternal); 2096 if (my_path == NULL) { 2097 warning("Cannot create heap dump file. Out of system memory."); 2098 return; 2099 } 2100 jio_snprintf(my_path, len, "%s.%d", base_path, dump_file_seq); 2101 } 2102 dump_file_seq++; // increment seq number for next time we dump 2103 2104 HeapDumper dumper(false /* no GC before heap dump */, 2105 true /* send to tty */, 2106 oome /* pass along out-of-memory-error flag */); 2107 dumper.dump(my_path); 2108 os::free(my_path); 2109 }