heapDumper.cpp 64.7 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
19 20 21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
22 23 24
 *
 */

25 26 27 28 29
#include "precompiled.hpp"
#include "classfile/symbolTable.hpp"
#include "classfile/systemDictionary.hpp"
#include "classfile/vmSymbols.hpp"
#include "gc_implementation/shared/vmGCOperations.hpp"
P
poonam 已提交
30
#include "memory/gcLocker.inline.hpp"
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
#include "memory/genCollectedHeap.hpp"
#include "memory/universe.hpp"
#include "oops/objArrayKlass.hpp"
#include "runtime/javaCalls.hpp"
#include "runtime/jniHandles.hpp"
#include "runtime/reflectionUtils.hpp"
#include "runtime/vframe.hpp"
#include "runtime/vmThread.hpp"
#include "runtime/vm_operations.hpp"
#include "services/heapDumper.hpp"
#include "services/threadService.hpp"
#include "utilities/ostream.hpp"
#ifndef SERIALGC
#include "gc_implementation/parallelScavenge/parallelScavengeHeap.hpp"
#endif
D
duke 已提交
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364

/*
 * HPROF binary format - description copied from:
 *   src/share/demo/jvmti/hprof/hprof_io.c
 *
 *
 *  header    "JAVA PROFILE 1.0.1" or "JAVA PROFILE 1.0.2"
 *            (0-terminated)
 *
 *  u4        size of identifiers. Identifiers are used to represent
 *            UTF8 strings, objects, stack traces, etc. They usually
 *            have the same size as host pointers. For example, on
 *            Solaris and Win32, the size is 4.
 * u4         high word
 * u4         low word    number of milliseconds since 0:00 GMT, 1/1/70
 * [record]*  a sequence of records.
 *
 *
 * Record format:
 *
 * u1         a TAG denoting the type of the record
 * u4         number of *microseconds* since the time stamp in the
 *            header. (wraps around in a little more than an hour)
 * u4         number of bytes *remaining* in the record. Note that
 *            this number excludes the tag and the length field itself.
 * [u1]*      BODY of the record (a sequence of bytes)
 *
 *
 * The following TAGs are supported:
 *
 * TAG           BODY       notes
 *----------------------------------------------------------
 * HPROF_UTF8               a UTF8-encoded name
 *
 *               id         name ID
 *               [u1]*      UTF8 characters (no trailing zero)
 *
 * HPROF_LOAD_CLASS         a newly loaded class
 *
 *                u4        class serial number (> 0)
 *                id        class object ID
 *                u4        stack trace serial number
 *                id        class name ID
 *
 * HPROF_UNLOAD_CLASS       an unloading class
 *
 *                u4        class serial_number
 *
 * HPROF_FRAME              a Java stack frame
 *
 *                id        stack frame ID
 *                id        method name ID
 *                id        method signature ID
 *                id        source file name ID
 *                u4        class serial number
 *                i4        line number. >0: normal
 *                                       -1: unknown
 *                                       -2: compiled method
 *                                       -3: native method
 *
 * HPROF_TRACE              a Java stack trace
 *
 *               u4         stack trace serial number
 *               u4         thread serial number
 *               u4         number of frames
 *               [id]*      stack frame IDs
 *
 *
 * HPROF_ALLOC_SITES        a set of heap allocation sites, obtained after GC
 *
 *               u2         flags 0x0001: incremental vs. complete
 *                                0x0002: sorted by allocation vs. live
 *                                0x0004: whether to force a GC
 *               u4         cutoff ratio
 *               u4         total live bytes
 *               u4         total live instances
 *               u8         total bytes allocated
 *               u8         total instances allocated
 *               u4         number of sites that follow
 *               [u1        is_array: 0:  normal object
 *                                    2:  object array
 *                                    4:  boolean array
 *                                    5:  char array
 *                                    6:  float array
 *                                    7:  double array
 *                                    8:  byte array
 *                                    9:  short array
 *                                    10: int array
 *                                    11: long array
 *                u4        class serial number (may be zero during startup)
 *                u4        stack trace serial number
 *                u4        number of bytes alive
 *                u4        number of instances alive
 *                u4        number of bytes allocated
 *                u4]*      number of instance allocated
 *
 * HPROF_START_THREAD       a newly started thread.
 *
 *               u4         thread serial number (> 0)
 *               id         thread object ID
 *               u4         stack trace serial number
 *               id         thread name ID
 *               id         thread group name ID
 *               id         thread group parent name ID
 *
 * HPROF_END_THREAD         a terminating thread.
 *
 *               u4         thread serial number
 *
 * HPROF_HEAP_SUMMARY       heap summary
 *
 *               u4         total live bytes
 *               u4         total live instances
 *               u8         total bytes allocated
 *               u8         total instances allocated
 *
 * HPROF_HEAP_DUMP          denote a heap dump
 *
 *               [heap dump sub-records]*
 *
 *                          There are four kinds of heap dump sub-records:
 *
 *               u1         sub-record type
 *
 *               HPROF_GC_ROOT_UNKNOWN         unknown root
 *
 *                          id         object ID
 *
 *               HPROF_GC_ROOT_THREAD_OBJ      thread object
 *
 *                          id         thread object ID  (may be 0 for a
 *                                     thread newly attached through JNI)
 *                          u4         thread sequence number
 *                          u4         stack trace sequence number
 *
 *               HPROF_GC_ROOT_JNI_GLOBAL      JNI global ref root
 *
 *                          id         object ID
 *                          id         JNI global ref ID
 *
 *               HPROF_GC_ROOT_JNI_LOCAL       JNI local ref
 *
 *                          id         object ID
 *                          u4         thread serial number
 *                          u4         frame # in stack trace (-1 for empty)
 *
 *               HPROF_GC_ROOT_JAVA_FRAME      Java stack frame
 *
 *                          id         object ID
 *                          u4         thread serial number
 *                          u4         frame # in stack trace (-1 for empty)
 *
 *               HPROF_GC_ROOT_NATIVE_STACK    Native stack
 *
 *                          id         object ID
 *                          u4         thread serial number
 *
 *               HPROF_GC_ROOT_STICKY_CLASS    System class
 *
 *                          id         object ID
 *
 *               HPROF_GC_ROOT_THREAD_BLOCK    Reference from thread block
 *
 *                          id         object ID
 *                          u4         thread serial number
 *
 *               HPROF_GC_ROOT_MONITOR_USED    Busy monitor
 *
 *                          id         object ID
 *
 *               HPROF_GC_CLASS_DUMP           dump of a class object
 *
 *                          id         class object ID
 *                          u4         stack trace serial number
 *                          id         super class object ID
 *                          id         class loader object ID
 *                          id         signers object ID
 *                          id         protection domain object ID
 *                          id         reserved
 *                          id         reserved
 *
 *                          u4         instance size (in bytes)
 *
 *                          u2         size of constant pool
 *                          [u2,       constant pool index,
 *                           ty,       type
 *                                     2:  object
 *                                     4:  boolean
 *                                     5:  char
 *                                     6:  float
 *                                     7:  double
 *                                     8:  byte
 *                                     9:  short
 *                                     10: int
 *                                     11: long
 *                           vl]*      and value
 *
 *                          u2         number of static fields
 *                          [id,       static field name,
 *                           ty,       type,
 *                           vl]*      and value
 *
 *                          u2         number of inst. fields (not inc. super)
 *                          [id,       instance field name,
 *                           ty]*      type
 *
 *               HPROF_GC_INSTANCE_DUMP        dump of a normal object
 *
 *                          id         object ID
 *                          u4         stack trace serial number
 *                          id         class object ID
 *                          u4         number of bytes that follow
 *                          [vl]*      instance field values (class, followed
 *                                     by super, super's super ...)
 *
 *               HPROF_GC_OBJ_ARRAY_DUMP       dump of an object array
 *
 *                          id         array object ID
 *                          u4         stack trace serial number
 *                          u4         number of elements
 *                          id         array class ID
 *                          [id]*      elements
 *
 *               HPROF_GC_PRIM_ARRAY_DUMP      dump of a primitive array
 *
 *                          id         array object ID
 *                          u4         stack trace serial number
 *                          u4         number of elements
 *                          u1         element type
 *                                     4:  boolean array
 *                                     5:  char array
 *                                     6:  float array
 *                                     7:  double array
 *                                     8:  byte array
 *                                     9:  short array
 *                                     10: int array
 *                                     11: long array
 *                          [u1]*      elements
 *
 * HPROF_CPU_SAMPLES        a set of sample traces of running threads
 *
 *                u4        total number of samples
 *                u4        # of traces
 *               [u4        # of samples
 *                u4]*      stack trace serial number
 *
 * HPROF_CONTROL_SETTINGS   the settings of on/off switches
 *
 *                u4        0x00000001: alloc traces on/off
 *                          0x00000002: cpu sampling on/off
 *                u2        stack trace depth
 *
 *
 * When the header is "JAVA PROFILE 1.0.2" a heap dump can optionally
 * be generated as a sequence of heap dump segments. This sequence is
 * terminated by an end record. The additional tags allowed by format
 * "JAVA PROFILE 1.0.2" are:
 *
 * HPROF_HEAP_DUMP_SEGMENT  denote a heap dump segment
 *
 *               [heap dump sub-records]*
 *               The same sub-record types allowed by HPROF_HEAP_DUMP
 *
 * HPROF_HEAP_DUMP_END      denotes the end of a heap dump
 *
 */


// HPROF tags

typedef enum {
  // top-level records
  HPROF_UTF8                    = 0x01,
  HPROF_LOAD_CLASS              = 0x02,
  HPROF_UNLOAD_CLASS            = 0x03,
  HPROF_FRAME                   = 0x04,
  HPROF_TRACE                   = 0x05,
  HPROF_ALLOC_SITES             = 0x06,
  HPROF_HEAP_SUMMARY            = 0x07,
  HPROF_START_THREAD            = 0x0A,
  HPROF_END_THREAD              = 0x0B,
  HPROF_HEAP_DUMP               = 0x0C,
  HPROF_CPU_SAMPLES             = 0x0D,
  HPROF_CONTROL_SETTINGS        = 0x0E,

  // 1.0.2 record types
  HPROF_HEAP_DUMP_SEGMENT       = 0x1C,
  HPROF_HEAP_DUMP_END           = 0x2C,

  // field types
  HPROF_ARRAY_OBJECT            = 0x01,
  HPROF_NORMAL_OBJECT           = 0x02,
  HPROF_BOOLEAN                 = 0x04,
  HPROF_CHAR                    = 0x05,
  HPROF_FLOAT                   = 0x06,
  HPROF_DOUBLE                  = 0x07,
  HPROF_BYTE                    = 0x08,
  HPROF_SHORT                   = 0x09,
  HPROF_INT                     = 0x0A,
  HPROF_LONG                    = 0x0B,

  // data-dump sub-records
  HPROF_GC_ROOT_UNKNOWN         = 0xFF,
  HPROF_GC_ROOT_JNI_GLOBAL      = 0x01,
  HPROF_GC_ROOT_JNI_LOCAL       = 0x02,
  HPROF_GC_ROOT_JAVA_FRAME      = 0x03,
  HPROF_GC_ROOT_NATIVE_STACK    = 0x04,
  HPROF_GC_ROOT_STICKY_CLASS    = 0x05,
  HPROF_GC_ROOT_THREAD_BLOCK    = 0x06,
  HPROF_GC_ROOT_MONITOR_USED    = 0x07,
  HPROF_GC_ROOT_THREAD_OBJ      = 0x08,
  HPROF_GC_CLASS_DUMP           = 0x20,
  HPROF_GC_INSTANCE_DUMP        = 0x21,
  HPROF_GC_OBJ_ARRAY_DUMP       = 0x22,
  HPROF_GC_PRIM_ARRAY_DUMP      = 0x23
} hprofTag;

// Default stack trace ID (used for dummy HPROF_TRACE record)
enum {
365 366
  STACK_TRACE_ID = 1,
  INITIAL_CLASS_COUNT = 200
D
duke 已提交
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
};

// Supports I/O operations on a dump file

class DumpWriter : public StackObj {
 private:
  enum {
    io_buffer_size  = 8*M
  };

  int _fd;              // file descriptor (-1 if dump file not open)
  jlong _bytes_written; // number of byte written to dump file

  char* _buffer;    // internal buffer
  int _size;
  int _pos;

  char* _error;   // error message when I/O fails

  void set_file_descriptor(int fd)              { _fd = fd; }
  int file_descriptor() const                   { return _fd; }

  char* buffer() const                          { return _buffer; }
  int buffer_size() const                       { return _size; }
  int position() const                          { return _pos; }
  void set_position(int pos)                    { _pos = pos; }

  void set_error(const char* error)             { _error = (char*)os::strdup(error); }

  // all I/O go through this function
  void write_internal(void* s, int len);

 public:
  DumpWriter(const char* path);
  ~DumpWriter();

  void close();
  bool is_open() const                  { return file_descriptor() >= 0; }
  void flush();

  // total number of bytes written to the disk
  jlong bytes_written() const           { return _bytes_written; }

  // adjust the number of bytes written to disk (used to keep the count
  // of the number of bytes written in case of rewrites)
  void adjust_bytes_written(jlong n)     { _bytes_written += n; }

  // number of (buffered) bytes as yet unwritten to the dump file
  jlong bytes_unwritten() const          { return (jlong)position(); }

  char* error() const                   { return _error; }

  jlong current_offset();
  void seek_to_offset(jlong pos);

  // writer functions
  void write_raw(void* s, int len);
  void write_u1(u1 x)                   { write_raw((void*)&x, 1); }
  void write_u2(u2 x);
  void write_u4(u4 x);
  void write_u8(u8 x);
  void write_objectID(oop o);
429
  void write_symbolID(Symbol* o);
D
duke 已提交
430
  void write_classID(Klass* k);
431
  void write_id(u4 x);
D
duke 已提交
432 433 434 435 436 437 438
};

DumpWriter::DumpWriter(const char* path) {
  // try to allocate an I/O buffer of io_buffer_size. If there isn't
  // sufficient memory then reduce size until we can allocate something.
  _size = io_buffer_size;
  do {
Z
zgu 已提交
439
    _buffer = (char*)os::malloc(_size, mtInternal);
D
duke 已提交
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
    if (_buffer == NULL) {
      _size = _size >> 1;
    }
  } while (_buffer == NULL && _size > 0);
  assert((_size > 0 && _buffer != NULL) || (_size == 0 && _buffer == NULL), "sanity check");
  _pos = 0;
  _error = NULL;
  _bytes_written = 0L;
  _fd = os::create_binary_file(path, false);    // don't replace existing file

  // if the open failed we record the error
  if (_fd < 0) {
    _error = (char*)os::strdup(strerror(errno));
  }
}

DumpWriter::~DumpWriter() {
  // flush and close dump file
458
  if (is_open()) {
D
duke 已提交
459 460 461 462 463 464 465 466 467
    close();
  }
  if (_buffer != NULL) os::free(_buffer);
  if (_error != NULL) os::free(_error);
}

// closes dump file (if open)
void DumpWriter::close() {
  // flush and close dump file
468
  if (is_open()) {
D
duke 已提交
469 470
    flush();
    ::close(file_descriptor());
471
    set_file_descriptor(-1);
D
duke 已提交
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572
  }
}

// write directly to the file
void DumpWriter::write_internal(void* s, int len) {
  if (is_open()) {
    int n = ::write(file_descriptor(), s, len);
    if (n > 0) {
      _bytes_written += n;
    }
    if (n != len) {
      if (n < 0) {
        set_error(strerror(errno));
      } else {
        set_error("file size limit");
      }
      ::close(file_descriptor());
      set_file_descriptor(-1);
    }
  }
}

// write raw bytes
void DumpWriter::write_raw(void* s, int len) {
  if (is_open()) {
    // flush buffer to make toom
    if ((position()+ len) >= buffer_size()) {
      flush();
    }

    // buffer not available or too big to buffer it
    if ((buffer() == NULL) || (len >= buffer_size())) {
      write_internal(s, len);
    } else {
      // Should optimize this for u1/u2/u4/u8 sizes.
      memcpy(buffer() + position(), s, len);
      set_position(position() + len);
    }
  }
}

// flush any buffered bytes to the file
void DumpWriter::flush() {
  if (is_open() && position() > 0) {
    write_internal(buffer(), position());
    set_position(0);
  }
}


jlong DumpWriter::current_offset() {
  if (is_open()) {
    // the offset is the file offset plus whatever we have buffered
    jlong offset = os::current_file_offset(file_descriptor());
    assert(offset >= 0, "lseek failed");
    return offset + (jlong)position();
  } else {
    return (jlong)-1;
  }
}

void DumpWriter::seek_to_offset(jlong off) {
  assert(off >= 0, "bad offset");

  // need to flush before seeking
  flush();

  // may be closed due to I/O error
  if (is_open()) {
    jlong n = os::seek_to_file_offset(file_descriptor(), off);
    assert(n >= 0, "lseek failed");
  }
}

void DumpWriter::write_u2(u2 x) {
  u2 v;
  Bytes::put_Java_u2((address)&v, x);
  write_raw((void*)&v, 2);
}

void DumpWriter::write_u4(u4 x) {
  u4 v;
  Bytes::put_Java_u4((address)&v, x);
  write_raw((void*)&v, 4);
}

void DumpWriter::write_u8(u8 x) {
  u8 v;
  Bytes::put_Java_u8((address)&v, x);
  write_raw((void*)&v, 8);
}

void DumpWriter::write_objectID(oop o) {
  address a = (address)((uintptr_t)o);
#ifdef _LP64
  write_u8((u8)a);
#else
  write_u4((u4)a);
#endif
}

573 574 575 576 577 578 579 580 581
void DumpWriter::write_symbolID(Symbol* s) {
  address a = (address)((uintptr_t)s);
#ifdef _LP64
  write_u8((u8)a);
#else
  write_u4((u4)a);
#endif
}

582 583 584 585 586 587 588 589
void DumpWriter::write_id(u4 x) {
#ifdef _LP64
  write_u8((u8) x);
#else
  write_u4(x);
#endif
}

D
duke 已提交
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
// We use java mirror as the class ID
void DumpWriter::write_classID(Klass* k) {
  write_objectID(k->java_mirror());
}



// Support class with a collection of functions used when dumping the heap

class DumperSupport : AllStatic {
 public:

  // write a header of the given type
  static void write_header(DumpWriter* writer, hprofTag tag, u4 len);

  // returns hprof tag for the given type signature
606
  static hprofTag sig2tag(Symbol* sig);
D
duke 已提交
607 608 609 610
  // returns hprof tag for the given basic type
  static hprofTag type2tag(BasicType type);

  // returns the size of the instance of the given class
611
  static u4 instance_size(Klass* k);
D
duke 已提交
612 613 614 615 616 617 618 619

  // dump a jfloat
  static void dump_float(DumpWriter* writer, jfloat f);
  // dump a jdouble
  static void dump_double(DumpWriter* writer, jdouble d);
  // dumps the raw value of the given field
  static void dump_field_value(DumpWriter* writer, char type, address addr);
  // dumps static fields of the given class
620
  static void dump_static_fields(DumpWriter* writer, Klass* k);
D
duke 已提交
621 622 623
  // dump the raw values of the instance fields of the given object
  static void dump_instance_fields(DumpWriter* writer, oop o);
  // dumps the definition of the instance fields for a given class
624
  static void dump_instance_field_descriptors(DumpWriter* writer, Klass* k);
D
duke 已提交
625 626 627 628
  // creates HPROF_GC_INSTANCE_DUMP record for the given object
  static void dump_instance(DumpWriter* writer, oop o);
  // creates HPROF_GC_CLASS_DUMP record for the given class and each of its
  // array classes
629
  static void dump_class_and_array_classes(DumpWriter* writer, Klass* k);
D
duke 已提交
630 631
  // creates HPROF_GC_CLASS_DUMP record for a given primitive array
  // class (and each multi-dimensional array class too)
632
  static void dump_basic_type_array_class(DumpWriter* writer, Klass* k);
D
duke 已提交
633 634 635 636 637

  // creates HPROF_GC_OBJ_ARRAY_DUMP record for the given object array
  static void dump_object_array(DumpWriter* writer, objArrayOop array);
  // creates HPROF_GC_PRIM_ARRAY_DUMP record for the given type array
  static void dump_prim_array(DumpWriter* writer, typeArrayOop array);
638
  // create HPROF_FRAME record for the given method and bci
639
  static void dump_stack_frame(DumpWriter* writer, int frame_serial_num, int class_serial_num, Method* m, int bci);
D
duke 已提交
640 641 642 643 644 645 646 647 648 649
};

// write a header of the given type
void DumperSupport:: write_header(DumpWriter* writer, hprofTag tag, u4 len) {
  writer->write_u1((u1)tag);
  writer->write_u4(0);                  // current ticks
  writer->write_u4(len);
}

// returns hprof tag for the given type signature
650
hprofTag DumperSupport::sig2tag(Symbol* sig) {
D
duke 已提交
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713
  switch (sig->byte_at(0)) {
    case JVM_SIGNATURE_CLASS    : return HPROF_NORMAL_OBJECT;
    case JVM_SIGNATURE_ARRAY    : return HPROF_NORMAL_OBJECT;
    case JVM_SIGNATURE_BYTE     : return HPROF_BYTE;
    case JVM_SIGNATURE_CHAR     : return HPROF_CHAR;
    case JVM_SIGNATURE_FLOAT    : return HPROF_FLOAT;
    case JVM_SIGNATURE_DOUBLE   : return HPROF_DOUBLE;
    case JVM_SIGNATURE_INT      : return HPROF_INT;
    case JVM_SIGNATURE_LONG     : return HPROF_LONG;
    case JVM_SIGNATURE_SHORT    : return HPROF_SHORT;
    case JVM_SIGNATURE_BOOLEAN  : return HPROF_BOOLEAN;
    default : ShouldNotReachHere(); /* to shut up compiler */ return HPROF_BYTE;
  }
}

hprofTag DumperSupport::type2tag(BasicType type) {
  switch (type) {
    case T_BYTE     : return HPROF_BYTE;
    case T_CHAR     : return HPROF_CHAR;
    case T_FLOAT    : return HPROF_FLOAT;
    case T_DOUBLE   : return HPROF_DOUBLE;
    case T_INT      : return HPROF_INT;
    case T_LONG     : return HPROF_LONG;
    case T_SHORT    : return HPROF_SHORT;
    case T_BOOLEAN  : return HPROF_BOOLEAN;
    default : ShouldNotReachHere(); /* to shut up compiler */ return HPROF_BYTE;
  }
}

// dump a jfloat
void DumperSupport::dump_float(DumpWriter* writer, jfloat f) {
  if (g_isnan(f)) {
    writer->write_u4(0x7fc00000);    // collapsing NaNs
  } else {
    union {
      int i;
      float f;
    } u;
    u.f = (float)f;
    writer->write_u4((u4)u.i);
  }
}

// dump a jdouble
void DumperSupport::dump_double(DumpWriter* writer, jdouble d) {
  union {
    jlong l;
    double d;
  } u;
  if (g_isnan(d)) {                 // collapsing NaNs
    u.l = (jlong)(0x7ff80000);
    u.l = (u.l << 32);
  } else {
    u.d = (double)d;
  }
  writer->write_u8((u8)u.l);
}

// dumps the raw value of the given field
void DumperSupport::dump_field_value(DumpWriter* writer, char type, address addr) {
  switch (type) {
    case JVM_SIGNATURE_CLASS :
    case JVM_SIGNATURE_ARRAY : {
714 715 716 717 718 719
      oop o;
      if (UseCompressedOops) {
        o = oopDesc::load_decode_heap_oop((narrowOop*)addr);
      } else {
        o = oopDesc::load_decode_heap_oop((oop*)addr);
      }
D
duke 已提交
720 721

      // reflection and sun.misc.Unsafe classes may have a reference to a
722 723
      // Klass* so filter it out.
      assert(o->is_oop_or_null(), "should always be an oop");
D
duke 已提交
724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771
      writer->write_objectID(o);
      break;
    }
    case JVM_SIGNATURE_BYTE     : {
      jbyte* b = (jbyte*)addr;
      writer->write_u1((u1)*b);
      break;
    }
    case JVM_SIGNATURE_CHAR     : {
      jchar* c = (jchar*)addr;
      writer->write_u2((u2)*c);
      break;
    }
    case JVM_SIGNATURE_SHORT : {
      jshort* s = (jshort*)addr;
      writer->write_u2((u2)*s);
      break;
    }
    case JVM_SIGNATURE_FLOAT : {
      jfloat* f = (jfloat*)addr;
      dump_float(writer, *f);
      break;
    }
    case JVM_SIGNATURE_DOUBLE : {
      jdouble* f = (jdouble*)addr;
      dump_double(writer, *f);
      break;
    }
    case JVM_SIGNATURE_INT : {
      jint* i = (jint*)addr;
      writer->write_u4((u4)*i);
      break;
    }
    case JVM_SIGNATURE_LONG     : {
      jlong* l = (jlong*)addr;
      writer->write_u8((u8)*l);
      break;
    }
    case JVM_SIGNATURE_BOOLEAN : {
      jboolean* b = (jboolean*)addr;
      writer->write_u1((u1)*b);
      break;
    }
    default : ShouldNotReachHere();
  }
}

// returns the size of the instance of the given class
772
u4 DumperSupport::instance_size(Klass* k) {
D
duke 已提交
773 774 775 776 777 778 779
  HandleMark hm;
  instanceKlassHandle ikh = instanceKlassHandle(Thread::current(), k);

  int size = 0;

  for (FieldStream fld(ikh, false, false); !fld.eos(); fld.next()) {
    if (!fld.access_flags().is_static()) {
780
      Symbol* sig = fld.signature();
D
duke 已提交
781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804
      switch (sig->byte_at(0)) {
        case JVM_SIGNATURE_CLASS   :
        case JVM_SIGNATURE_ARRAY   : size += oopSize; break;

        case JVM_SIGNATURE_BYTE    :
        case JVM_SIGNATURE_BOOLEAN : size += 1; break;

        case JVM_SIGNATURE_CHAR    :
        case JVM_SIGNATURE_SHORT   : size += 2; break;

        case JVM_SIGNATURE_INT     :
        case JVM_SIGNATURE_FLOAT   : size += 4; break;

        case JVM_SIGNATURE_LONG    :
        case JVM_SIGNATURE_DOUBLE  : size += 8; break;

        default : ShouldNotReachHere();
      }
    }
  }
  return (u4)size;
}

// dumps static fields of the given class
805
void DumperSupport::dump_static_fields(DumpWriter* writer, Klass* k) {
D
duke 已提交
806 807 808 809 810 811 812 813 814 815 816 817 818 819
  HandleMark hm;
  instanceKlassHandle ikh = instanceKlassHandle(Thread::current(), k);

  // pass 1 - count the static fields
  u2 field_count = 0;
  for (FieldStream fldc(ikh, true, true); !fldc.eos(); fldc.next()) {
    if (fldc.access_flags().is_static()) field_count++;
  }

  writer->write_u2(field_count);

  // pass 2 - dump the field descriptors and raw values
  for (FieldStream fld(ikh, true, true); !fld.eos(); fld.next()) {
    if (fld.access_flags().is_static()) {
820
      Symbol* sig = fld.signature();
D
duke 已提交
821

822
      writer->write_symbolID(fld.name());   // name
D
duke 已提交
823 824 825 826
      writer->write_u1(sig2tag(sig));       // type

      // value
      int offset = fld.offset();
827
      address addr = (address)ikh->java_mirror() + offset;
D
duke 已提交
828 829 830 831 832 833 834 835 836 837 838 839 840

      dump_field_value(writer, sig->byte_at(0), addr);
    }
  }
}

// dump the raw values of the instance fields of the given object
void DumperSupport::dump_instance_fields(DumpWriter* writer, oop o) {
  HandleMark hm;
  instanceKlassHandle ikh = instanceKlassHandle(Thread::current(), o->klass());

  for (FieldStream fld(ikh, false, false); !fld.eos(); fld.next()) {
    if (!fld.access_flags().is_static()) {
841
      Symbol* sig = fld.signature();
D
duke 已提交
842 843 844 845 846 847 848 849
      address addr = (address)o + fld.offset();

      dump_field_value(writer, sig->byte_at(0), addr);
    }
  }
}

// dumps the definition of the instance fields for a given class
850
void DumperSupport::dump_instance_field_descriptors(DumpWriter* writer, Klass* k) {
D
duke 已提交
851 852 853 854 855 856 857 858 859 860 861 862 863 864
  HandleMark hm;
  instanceKlassHandle ikh = instanceKlassHandle(Thread::current(), k);

  // pass 1 - count the instance fields
  u2 field_count = 0;
  for (FieldStream fldc(ikh, true, true); !fldc.eos(); fldc.next()) {
    if (!fldc.access_flags().is_static()) field_count++;
  }

  writer->write_u2(field_count);

  // pass 2 - dump the field descriptors
  for (FieldStream fld(ikh, true, true); !fld.eos(); fld.next()) {
    if (!fld.access_flags().is_static()) {
865
      Symbol* sig = fld.signature();
D
duke 已提交
866

867
      writer->write_symbolID(fld.name());                   // name
D
duke 已提交
868 869 870 871 872 873 874
      writer->write_u1(sig2tag(sig));       // type
    }
  }
}

// creates HPROF_GC_INSTANCE_DUMP record for the given object
void DumperSupport::dump_instance(DumpWriter* writer, oop o) {
875
  Klass* k = o->klass();
D
duke 已提交
876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892

  writer->write_u1(HPROF_GC_INSTANCE_DUMP);
  writer->write_objectID(o);
  writer->write_u4(STACK_TRACE_ID);

  // class ID
  writer->write_classID(Klass::cast(k));

  // number of bytes that follow
  writer->write_u4(instance_size(k) );

  // field values
  dump_instance_fields(writer, o);
}

// creates HPROF_GC_CLASS_DUMP record for the given class and each of
// its array classes
893
void DumperSupport::dump_class_and_array_classes(DumpWriter* writer, Klass* k) {
D
duke 已提交
894
  Klass* klass = Klass::cast(k);
895 896
  assert(klass->oop_is_instance(), "not an InstanceKlass");
  InstanceKlass* ik = (InstanceKlass*)klass;
D
duke 已提交
897 898 899 900 901 902 903 904

  writer->write_u1(HPROF_GC_CLASS_DUMP);

  // class ID
  writer->write_classID(ik);
  writer->write_u4(STACK_TRACE_ID);

  // super class ID
905
  Klass* java_super = ik->java_super();
D
duke 已提交
906
  if (java_super == NULL) {
907
    writer->write_objectID(oop(NULL));
D
duke 已提交
908 909 910 911 912 913 914 915 916
  } else {
    writer->write_classID(Klass::cast(java_super));
  }

  writer->write_objectID(ik->class_loader());
  writer->write_objectID(ik->signers());
  writer->write_objectID(ik->protection_domain());

  // reserved
917 918
  writer->write_objectID(oop(NULL));
  writer->write_objectID(oop(NULL));
D
duke 已提交
919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950

  // instance size
  writer->write_u4(DumperSupport::instance_size(k));

  // size of constant pool - ignored by HAT 1.1
  writer->write_u2(0);

  // number of static fields
  dump_static_fields(writer, k);

  // description of instance fields
  dump_instance_field_descriptors(writer, k);

  // array classes
  k = klass->array_klass_or_null();
  while (k != NULL) {
    Klass* klass = Klass::cast(k);
    assert(klass->oop_is_objArray(), "not an objArrayKlass");

    writer->write_u1(HPROF_GC_CLASS_DUMP);
    writer->write_classID(klass);
    writer->write_u4(STACK_TRACE_ID);

    // super class of array classes is java.lang.Object
    java_super = klass->java_super();
    assert(java_super != NULL, "checking");
    writer->write_classID(Klass::cast(java_super));

    writer->write_objectID(ik->class_loader());
    writer->write_objectID(ik->signers());
    writer->write_objectID(ik->protection_domain());

951 952
    writer->write_objectID(oop(NULL));    // reserved
    writer->write_objectID(oop(NULL));
D
duke 已提交
953 954 955 956 957 958 959 960 961 962 963 964
    writer->write_u4(0);             // instance size
    writer->write_u2(0);             // constant pool
    writer->write_u2(0);             // static fields
    writer->write_u2(0);             // instance fields

    // get the array class for the next rank
    k = klass->array_klass_or_null();
  }
}

// creates HPROF_GC_CLASS_DUMP record for a given primitive array
// class (and each multi-dimensional array class too)
965
void DumperSupport::dump_basic_type_array_class(DumpWriter* writer, Klass* k) {
D
duke 已提交
966 967 968 969 970 971 972 973 974
 // array classes
 while (k != NULL) {
    Klass* klass = Klass::cast(k);

    writer->write_u1(HPROF_GC_CLASS_DUMP);
    writer->write_classID(klass);
    writer->write_u4(STACK_TRACE_ID);

    // super class of array classes is java.lang.Object
975
    Klass* java_super = klass->java_super();
D
duke 已提交
976 977 978
    assert(java_super != NULL, "checking");
    writer->write_classID(Klass::cast(java_super));

979 980 981
    writer->write_objectID(oop(NULL));    // loader
    writer->write_objectID(oop(NULL));    // signers
    writer->write_objectID(oop(NULL));    // protection domain
D
duke 已提交
982

983 984
    writer->write_objectID(oop(NULL));    // reserved
    writer->write_objectID(oop(NULL));
D
duke 已提交
985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
    writer->write_u4(0);             // instance size
    writer->write_u2(0);             // constant pool
    writer->write_u2(0);             // static fields
    writer->write_u2(0);             // instance fields

    // get the array class for the next rank
    k = klass->array_klass_or_null();
  }
}

// creates HPROF_GC_OBJ_ARRAY_DUMP record for the given object array
void DumperSupport::dump_object_array(DumpWriter* writer, objArrayOop array) {

  writer->write_u1(HPROF_GC_OBJ_ARRAY_DUMP);
  writer->write_objectID(array);
  writer->write_u4(STACK_TRACE_ID);
  writer->write_u4((u4)array->length());

  // array class ID
  writer->write_classID(Klass::cast(array->klass()));

  // [id]* elements
  for (int index=0; index<array->length(); index++) {
    oop o = array->obj_at(index);
    writer->write_objectID(o);
  }
}

#define WRITE_ARRAY(Array, Type, Size) \
  for (int i=0; i<Array->length(); i++) { writer->write_##Size((Size)array->Type##_at(i)); }


// creates HPROF_GC_PRIM_ARRAY_DUMP record for the given type array
void DumperSupport::dump_prim_array(DumpWriter* writer, typeArrayOop array) {
  BasicType type = typeArrayKlass::cast(array->klass())->element_type();

  writer->write_u1(HPROF_GC_PRIM_ARRAY_DUMP);
  writer->write_objectID(array);
  writer->write_u4(STACK_TRACE_ID);
  writer->write_u4((u4)array->length());
  writer->write_u1(type2tag(type));

  // nothing to copy
  if (array->length() == 0) {
    return;
  }

  // If the byte ordering is big endian then we can copy most types directly
1033
  int length_in_bytes = array->length() * type2aelembytes(type);
D
duke 已提交
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
  assert(length_in_bytes > 0, "nothing to copy");

  switch (type) {
    case T_INT : {
      if (Bytes::is_Java_byte_ordering_different()) {
        WRITE_ARRAY(array, int, u4);
      } else {
        writer->write_raw((void*)(array->int_at_addr(0)), length_in_bytes);
      }
      break;
    }
    case T_BYTE : {
      writer->write_raw((void*)(array->byte_at_addr(0)), length_in_bytes);
      break;
    }
    case T_CHAR : {
      if (Bytes::is_Java_byte_ordering_different()) {
        WRITE_ARRAY(array, char, u2);
      } else {
        writer->write_raw((void*)(array->char_at_addr(0)), length_in_bytes);
      }
      break;
    }
    case T_SHORT : {
      if (Bytes::is_Java_byte_ordering_different()) {
        WRITE_ARRAY(array, short, u2);
      } else {
        writer->write_raw((void*)(array->short_at_addr(0)), length_in_bytes);
      }
      break;
    }
    case T_BOOLEAN : {
      if (Bytes::is_Java_byte_ordering_different()) {
        WRITE_ARRAY(array, bool, u1);
      } else {
        writer->write_raw((void*)(array->bool_at_addr(0)), length_in_bytes);
      }
      break;
    }
    case T_LONG : {
      if (Bytes::is_Java_byte_ordering_different()) {
        WRITE_ARRAY(array, long, u8);
      } else {
        writer->write_raw((void*)(array->long_at_addr(0)), length_in_bytes);
      }
      break;
    }

    // handle float/doubles in a special value to ensure than NaNs are
    // written correctly. TO DO: Check if we can avoid this on processors that
    // use IEEE 754.

    case T_FLOAT : {
      for (int i=0; i<array->length(); i++) {
        dump_float( writer, array->float_at(i) );
      }
      break;
    }
    case T_DOUBLE : {
      for (int i=0; i<array->length(); i++) {
        dump_double( writer, array->double_at(i) );
      }
      break;
    }
    default : ShouldNotReachHere();
  }
}

1102
// create a HPROF_FRAME record of the given Method* and bci
1103 1104 1105
void DumperSupport::dump_stack_frame(DumpWriter* writer,
                                     int frame_serial_num,
                                     int class_serial_num,
1106
                                     Method* m,
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
                                     int bci) {
  int line_number;
  if (m->is_native()) {
    line_number = -3;  // native frame
  } else {
    line_number = m->line_number_from_bci(bci);
  }

  write_header(writer, HPROF_FRAME, 4*oopSize + 2*sizeof(u4));
  writer->write_id(frame_serial_num);               // frame serial number
1117 1118
  writer->write_symbolID(m->name());                // method's name
  writer->write_symbolID(m->signature());           // method's signature
1119

1120 1121
  assert(Klass::cast(m->method_holder())->oop_is_instance(), "not InstanceKlass");
  writer->write_symbolID(InstanceKlass::cast(m->method_holder())->source_file_name());  // source file name
1122 1123 1124
  writer->write_u4(class_serial_num);               // class serial number
  writer->write_u4((u4) line_number);               // line number
}
D
duke 已提交
1125

1126

D
duke 已提交
1127 1128 1129
// Support class used to generate HPROF_UTF8 records from the entries in the
// SymbolTable.

1130
class SymbolTableDumper : public SymbolClosure {
D
duke 已提交
1131 1132 1133 1134 1135
 private:
  DumpWriter* _writer;
  DumpWriter* writer() const                { return _writer; }
 public:
  SymbolTableDumper(DumpWriter* writer)     { _writer = writer; }
1136
  void do_symbol(Symbol** p);
D
duke 已提交
1137 1138
};

1139
void SymbolTableDumper::do_symbol(Symbol** p) {
D
duke 已提交
1140
  ResourceMark rm;
1141
  Symbol* sym = load_symbol(p);
D
duke 已提交
1142 1143 1144 1145
  int len = sym->utf8_length();
  if (len > 0) {
    char* s = sym->as_utf8();
    DumperSupport::write_header(writer(), HPROF_UTF8, oopSize + len);
1146
    writer()->write_symbolID(sym);
D
duke 已提交
1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
    writer()->write_raw(s, len);
  }
}

// Support class used to generate HPROF_GC_ROOT_JNI_LOCAL records

class JNILocalsDumper : public OopClosure {
 private:
  DumpWriter* _writer;
  u4 _thread_serial_num;
1157
  int _frame_num;
D
duke 已提交
1158 1159 1160 1161 1162
  DumpWriter* writer() const                { return _writer; }
 public:
  JNILocalsDumper(DumpWriter* writer, u4 thread_serial_num) {
    _writer = writer;
    _thread_serial_num = thread_serial_num;
1163
    _frame_num = -1;  // default - empty stack
D
duke 已提交
1164
  }
1165
  void set_frame_number(int n) { _frame_num = n; }
D
duke 已提交
1166
  void do_oop(oop* obj_p);
1167
  void do_oop(narrowOop* obj_p) { ShouldNotReachHere(); }
D
duke 已提交
1168 1169 1170 1171 1172 1173 1174 1175 1176 1177
};


void JNILocalsDumper::do_oop(oop* obj_p) {
  // ignore null or deleted handles
  oop o = *obj_p;
  if (o != NULL && o != JNIHandles::deleted_handle()) {
    writer()->write_u1(HPROF_GC_ROOT_JNI_LOCAL);
    writer()->write_objectID(o);
    writer()->write_u4(_thread_serial_num);
1178
    writer()->write_u4((u4)_frame_num);
D
duke 已提交
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194
  }
}


// Support class used to generate HPROF_GC_ROOT_JNI_GLOBAL records

class JNIGlobalsDumper : public OopClosure {
 private:
  DumpWriter* _writer;
  DumpWriter* writer() const                { return _writer; }

 public:
  JNIGlobalsDumper(DumpWriter* writer) {
    _writer = writer;
  }
  void do_oop(oop* obj_p);
1195
  void do_oop(narrowOop* obj_p) { ShouldNotReachHere(); }
D
duke 已提交
1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
};

void JNIGlobalsDumper::do_oop(oop* obj_p) {
  oop o = *obj_p;

  // ignore these
  if (o == NULL || o == JNIHandles::deleted_handle()) return;

  // we ignore global ref to symbols and other internal objects
  if (o->is_instance() || o->is_objArray() || o->is_typeArray()) {
    writer()->write_u1(HPROF_GC_ROOT_JNI_GLOBAL);
    writer()->write_objectID(o);
    writer()->write_objectID((oopDesc*)obj_p);      // global ref ID
  }
};


// Support class used to generate HPROF_GC_ROOT_MONITOR_USED records

class MonitorUsedDumper : public OopClosure {
 private:
  DumpWriter* _writer;
  DumpWriter* writer() const                { return _writer; }
 public:
  MonitorUsedDumper(DumpWriter* writer) {
    _writer = writer;
  }
  void do_oop(oop* obj_p) {
    writer()->write_u1(HPROF_GC_ROOT_MONITOR_USED);
    writer()->write_objectID(*obj_p);
  }
1227
  void do_oop(narrowOop* obj_p) { ShouldNotReachHere(); }
D
duke 已提交
1228 1229 1230 1231 1232
};


// Support class used to generate HPROF_GC_ROOT_STICKY_CLASS records

1233
class StickyClassDumper : public KlassClosure {
D
duke 已提交
1234 1235 1236 1237 1238 1239 1240
 private:
  DumpWriter* _writer;
  DumpWriter* writer() const                { return _writer; }
 public:
  StickyClassDumper(DumpWriter* writer) {
    _writer = writer;
  }
1241 1242 1243
  void do_klass(Klass* k) {
    if (k->oop_is_instance()) {
      InstanceKlass* ik = InstanceKlass::cast(k);
D
duke 已提交
1244 1245 1246 1247
        writer()->write_u1(HPROF_GC_ROOT_STICKY_CLASS);
        writer()->write_classID(ik);
      }
    }
1248
};
D
duke 已提交
1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280


class VM_HeapDumper;

// Support class using when iterating over the heap.

class HeapObjectDumper : public ObjectClosure {
 private:
  VM_HeapDumper* _dumper;
  DumpWriter* _writer;

  VM_HeapDumper* dumper()               { return _dumper; }
  DumpWriter* writer()                  { return _writer; }

  // used to indicate that a record has been writen
  void mark_end_of_record();

 public:
  HeapObjectDumper(VM_HeapDumper* dumper, DumpWriter* writer) {
    _dumper = dumper;
    _writer = writer;
  }

  // called for each object in the heap
  void do_object(oop o);
};

void HeapObjectDumper::do_object(oop o) {
  // hide the sentinel for deleted handles
  if (o == JNIHandles::deleted_handle()) return;

  // skip classes as these emitted as HPROF_GC_CLASS_DUMP records
1281
  if (o->klass() == SystemDictionary::Class_klass()) {
D
duke 已提交
1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308
    if (!java_lang_Class::is_primitive(o)) {
      return;
    }
  }

  // create a HPROF_GC_INSTANCE record for each object
  if (o->is_instance()) {
    DumperSupport::dump_instance(writer(), o);
    mark_end_of_record();
  } else {
    // create a HPROF_GC_OBJ_ARRAY_DUMP record for each object array
    if (o->is_objArray()) {
      DumperSupport::dump_object_array(writer(), objArrayOop(o));
      mark_end_of_record();
    } else {
      // create a HPROF_GC_PRIM_ARRAY_DUMP record for each type array
      if (o->is_typeArray()) {
        DumperSupport::dump_prim_array(writer(), typeArrayOop(o));
        mark_end_of_record();
      }
    }
  }
}

// The VM operation that performs the heap dump
class VM_HeapDumper : public VM_GC_Operation {
 private:
1309 1310 1311
  static VM_HeapDumper* _global_dumper;
  static DumpWriter*    _global_writer;
  DumpWriter*           _local_writer;
1312
  JavaThread*           _oome_thread;
1313
  Method*               _oome_constructor;
D
duke 已提交
1314 1315 1316
  bool _gc_before_heap_dump;
  bool _is_segmented_dump;
  jlong _dump_start;
1317 1318 1319
  GrowableArray<Klass*>* _klass_map;
  ThreadStackTrace** _stack_traces;
  int _num_threads;
D
duke 已提交
1320

1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334
  // accessors and setters
  static VM_HeapDumper* dumper()         {  assert(_global_dumper != NULL, "Error"); return _global_dumper; }
  static DumpWriter* writer()            {  assert(_global_writer != NULL, "Error"); return _global_writer; }
  void set_global_dumper() {
    assert(_global_dumper == NULL, "Error");
    _global_dumper = this;
  }
  void set_global_writer() {
    assert(_global_writer == NULL, "Error");
    _global_writer = _local_writer;
  }
  void clear_global_dumper() { _global_dumper = NULL; }
  void clear_global_writer() { _global_writer = NULL; }

D
duke 已提交
1335 1336 1337 1338 1339 1340 1341 1342
  bool is_segmented_dump() const                { return _is_segmented_dump; }
  void set_segmented_dump()                     { _is_segmented_dump = true; }
  jlong dump_start() const                      { return _dump_start; }
  void set_dump_start(jlong pos);

  bool skip_operation() const;

  // writes a HPROF_LOAD_CLASS record
1343
  static void do_load_class(Klass* k);
D
duke 已提交
1344 1345 1346

  // writes a HPROF_GC_CLASS_DUMP record for the given class
  // (and each array class too)
1347
  static void do_class_dump(Klass* k);
D
duke 已提交
1348 1349 1350

  // writes a HPROF_GC_CLASS_DUMP records for a given basic type
  // array (and each multi-dimensional array too)
1351
  static void do_basic_type_array_class_dump(Klass* k);
D
duke 已提交
1352 1353

  // HPROF_GC_ROOT_THREAD_OBJ records
1354
  int do_thread(JavaThread* thread, u4 thread_serial_num);
D
duke 已提交
1355 1356
  void do_threads();

1357 1358 1359 1360 1361 1362 1363
  void add_class_serial_number(Klass* k, int serial_num) {
    _klass_map->at_put_grow(serial_num, k);
  }

  // HPROF_TRACE and HPROF_FRAME records
  void dump_stack_traces();

D
duke 已提交
1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374
  // writes a HPROF_HEAP_DUMP or HPROF_HEAP_DUMP_SEGMENT record
  void write_dump_header();

  // fixes up the length of the current dump record
  void write_current_dump_record_length();

  // fixes up the current dump record )and writes HPROF_HEAP_DUMP_END
  // record in the case of a segmented heap dump)
  void end_of_dump();

 public:
1375
  VM_HeapDumper(DumpWriter* writer, bool gc_before_heap_dump, bool oome) :
D
duke 已提交
1376
    VM_GC_Operation(0 /* total collections,      dummy, ignored */,
B
brutisso 已提交
1377
                    GCCause::_heap_dump /* GC Cause */,
D
duke 已提交
1378 1379
                    0 /* total full collections, dummy, ignored */,
                    gc_before_heap_dump) {
1380
    _local_writer = writer;
D
duke 已提交
1381 1382 1383
    _gc_before_heap_dump = gc_before_heap_dump;
    _is_segmented_dump = false;
    _dump_start = (jlong)-1;
Z
zgu 已提交
1384
    _klass_map = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<Klass*>(INITIAL_CLASS_COUNT, true);
1385 1386
    _stack_traces = NULL;
    _num_threads = 0;
1387 1388 1389
    if (oome) {
      assert(!Thread::current()->is_VM_thread(), "Dump from OutOfMemoryError cannot be called by the VMThread");
      // get OutOfMemoryError zero-parameter constructor
1390
      InstanceKlass* oome_ik = InstanceKlass::cast(SystemDictionary::OutOfMemoryError_klass());
1391 1392 1393 1394 1395 1396 1397 1398
      _oome_constructor = oome_ik->find_method(vmSymbols::object_initializer_name(),
                                                          vmSymbols::void_method_signature());
      // get thread throwing OOME when generating the heap dump at OOME
      _oome_thread = JavaThread::current();
    } else {
      _oome_thread = NULL;
      _oome_constructor = NULL;
    }
1399 1400 1401 1402 1403 1404
  }
  ~VM_HeapDumper() {
    if (_stack_traces != NULL) {
      for (int i=0; i < _num_threads; i++) {
        delete _stack_traces[i];
      }
Z
zgu 已提交
1405
      FREE_C_HEAP_ARRAY(ThreadStackTrace*, _stack_traces, mtInternal);
1406 1407
    }
    delete _klass_map;
D
duke 已提交
1408 1409 1410 1411 1412 1413 1414 1415
  }

  VMOp_Type type() const { return VMOp_HeapDumper; }
  // used to mark sub-record boundary
  void check_segment_length();
  void doit();
};

1416 1417 1418
VM_HeapDumper* VM_HeapDumper::_global_dumper = NULL;
DumpWriter*    VM_HeapDumper::_global_writer = NULL;

D
duke 已提交
1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513
bool VM_HeapDumper::skip_operation() const {
  return false;
}

// sets the dump starting position
void VM_HeapDumper::set_dump_start(jlong pos) {
  _dump_start = pos;
}

 // writes a HPROF_HEAP_DUMP or HPROF_HEAP_DUMP_SEGMENT record
void VM_HeapDumper::write_dump_header() {
  if (writer()->is_open()) {
    if (is_segmented_dump()) {
      writer()->write_u1(HPROF_HEAP_DUMP_SEGMENT);
    } else {
      writer()->write_u1(HPROF_HEAP_DUMP);
    }
    writer()->write_u4(0); // current ticks

    // record the starting position for the dump (its length will be fixed up later)
    set_dump_start(writer()->current_offset());
    writer()->write_u4(0);
  }
}

// fixes up the length of the current dump record
void VM_HeapDumper::write_current_dump_record_length() {
  if (writer()->is_open()) {
    assert(dump_start() >= 0, "no dump start recorded");

    // calculate the size of the dump record
    jlong dump_end = writer()->current_offset();
    jlong dump_len = (dump_end - dump_start() - 4);

    // record length must fit in a u4
    if (dump_len > (jlong)(4L*(jlong)G)) {
      warning("record is too large");
    }

    // seek to the dump start and fix-up the length
    writer()->seek_to_offset(dump_start());
    writer()->write_u4((u4)dump_len);

    // adjust the total size written to keep the bytes written correct.
    writer()->adjust_bytes_written(-((long) sizeof(u4)));

    // seek to dump end so we can continue
    writer()->seek_to_offset(dump_end);

    // no current dump record
    set_dump_start((jlong)-1);
  }
}

// used on a sub-record boundary to check if we need to start a
// new segment.
void VM_HeapDumper::check_segment_length() {
  if (writer()->is_open()) {
    if (is_segmented_dump()) {
      // don't use current_offset that would be too expensive on a per record basis
      jlong dump_end = writer()->bytes_written() + writer()->bytes_unwritten();
      assert(dump_end == writer()->current_offset(), "checking");
      jlong dump_len = (dump_end - dump_start() - 4);
      assert(dump_len >= 0 && dump_len <= max_juint, "bad dump length");

      if (dump_len > (jlong)HeapDumpSegmentSize) {
        write_current_dump_record_length();
        write_dump_header();
      }
    }
  }
}

// fixes up the current dump record )and writes HPROF_HEAP_DUMP_END
// record in the case of a segmented heap dump)
void VM_HeapDumper::end_of_dump() {
  if (writer()->is_open()) {
    write_current_dump_record_length();

    // for segmented dump we write the end record
    if (is_segmented_dump()) {
      writer()->write_u1(HPROF_HEAP_DUMP_END);
      writer()->write_u4(0);
      writer()->write_u4(0);
    }
  }
}

// marks sub-record boundary
void HeapObjectDumper::mark_end_of_record() {
  dumper()->check_segment_length();
}

// writes a HPROF_LOAD_CLASS record for the class (and each of its
// array classes)
1514
void VM_HeapDumper::do_load_class(Klass* k) {
D
duke 已提交
1515 1516 1517 1518 1519 1520 1521
  static u4 class_serial_num = 0;

  // len of HPROF_LOAD_CLASS record
  u4 remaining = 2*oopSize + 2*sizeof(u4);

  // write a HPROF_LOAD_CLASS for the class and each array class
  do {
1522
    DumperSupport::write_header(writer(), HPROF_LOAD_CLASS, remaining);
D
duke 已提交
1523 1524

    // class serial number is just a number
1525
    writer()->write_u4(++class_serial_num);
D
duke 已提交
1526 1527 1528

    // class ID
    Klass* klass = Klass::cast(k);
1529
    writer()->write_classID(klass);
D
duke 已提交
1530

1531
    // add the Klass* and class serial number pair
1532
    dumper()->add_class_serial_number(klass, class_serial_num);
1533

1534
    writer()->write_u4(STACK_TRACE_ID);
D
duke 已提交
1535 1536

    // class name ID
1537 1538
    Symbol* name = klass->name();
    writer()->write_symbolID(name);
D
duke 已提交
1539 1540 1541 1542 1543 1544 1545

    // write a LOAD_CLASS record for the array type (if it exists)
    k = klass->array_klass_or_null();
  } while (k != NULL);
}

// writes a HPROF_GC_CLASS_DUMP record for the given class
1546
void VM_HeapDumper::do_class_dump(Klass* k) {
1547
  DumperSupport::dump_class_and_array_classes(writer(), k);
D
duke 已提交
1548 1549 1550 1551
}

// writes a HPROF_GC_CLASS_DUMP records for a given basic type
// array (and each multi-dimensional array too)
1552
void VM_HeapDumper::do_basic_type_array_class_dump(Klass* k) {
1553
  DumperSupport::dump_basic_type_array_class(writer(), k);
D
duke 已提交
1554 1555 1556 1557 1558
}

// Walk the stack of the given thread.
// Dumps a HPROF_GC_ROOT_JAVA_FRAME record for each local
// Dumps a HPROF_GC_ROOT_JNI_LOCAL record for each JNI local
1559 1560 1561
//
// It returns the number of Java frames in this thread stack
int VM_HeapDumper::do_thread(JavaThread* java_thread, u4 thread_serial_num) {
D
duke 已提交
1562 1563 1564 1565 1566
  JNILocalsDumper blk(writer(), thread_serial_num);

  oop threadObj = java_thread->threadObj();
  assert(threadObj != NULL, "sanity check");

1567
  int stack_depth = 0;
D
duke 已提交
1568 1569 1570 1571 1572 1573 1574 1575 1576 1577
  if (java_thread->has_last_Java_frame()) {

    // vframes are resource allocated
    Thread* current_thread = Thread::current();
    ResourceMark rm(current_thread);
    HandleMark hm(current_thread);

    RegisterMap reg_map(java_thread);
    frame f = java_thread->last_frame();
    vframe* vf = vframe::new_vframe(&f, &reg_map, java_thread);
1578
    frame* last_entry_frame = NULL;
1579
    int extra_frames = 0;
D
duke 已提交
1580

1581 1582 1583
    if (java_thread == _oome_thread && _oome_constructor != NULL) {
      extra_frames++;
    }
D
duke 已提交
1584
    while (vf != NULL) {
1585
      blk.set_frame_number(stack_depth);
D
duke 已提交
1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599
      if (vf->is_java_frame()) {

        // java frame (interpreted, compiled, ...)
        javaVFrame *jvf = javaVFrame::cast(vf);
        if (!(jvf->method()->is_native())) {
          StackValueCollection* locals = jvf->locals();
          for (int slot=0; slot<locals->size(); slot++) {
            if (locals->at(slot)->type() == T_OBJECT) {
              oop o = locals->obj_at(slot)();

              if (o != NULL) {
                writer()->write_u1(HPROF_GC_ROOT_JAVA_FRAME);
                writer()->write_objectID(o);
                writer()->write_u4(thread_serial_num);
1600
                writer()->write_u4((u4) (stack_depth + extra_frames));
D
duke 已提交
1601 1602 1603
              }
            }
          }
1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615
        } else {
          // native frame
          if (stack_depth == 0) {
            // JNI locals for the top frame.
            java_thread->active_handles()->oops_do(&blk);
          } else {
            if (last_entry_frame != NULL) {
              // JNI locals for the entry frame
              assert(last_entry_frame->is_entry_frame(), "checking");
              last_entry_frame->entry_frame_call_wrapper()->handles()->oops_do(&blk);
            }
          }
D
duke 已提交
1616
        }
1617 1618 1619
        // increment only for Java frames
        stack_depth++;
        last_entry_frame = NULL;
D
duke 已提交
1620

1621
      } else {
D
duke 已提交
1622
        // externalVFrame - if it's an entry frame then report any JNI locals
1623
        // as roots when we find the corresponding native javaVFrame
D
duke 已提交
1624 1625 1626
        frame* fr = vf->frame_pointer();
        assert(fr != NULL, "sanity check");
        if (fr->is_entry_frame()) {
1627
          last_entry_frame = fr;
D
duke 已提交
1628 1629 1630 1631
        }
      }
      vf = vf->sender();
    }
1632 1633 1634
  } else {
    // no last java frame but there may be JNI locals
    java_thread->active_handles()->oops_do(&blk);
D
duke 已提交
1635
  }
1636
  return stack_depth;
D
duke 已提交
1637 1638 1639 1640 1641 1642
}


// write a HPROF_GC_ROOT_THREAD_OBJ record for each java thread. Then walk
// the stack so that locals and JNI locals are dumped.
void VM_HeapDumper::do_threads() {
1643 1644
  for (int i=0; i < _num_threads; i++) {
    JavaThread* thread = _stack_traces[i]->thread();
D
duke 已提交
1645
    oop threadObj = thread->threadObj();
1646 1647 1648 1649 1650 1651 1652 1653 1654
    u4 thread_serial_num = i+1;
    u4 stack_serial_num = thread_serial_num + STACK_TRACE_ID;
    writer()->write_u1(HPROF_GC_ROOT_THREAD_OBJ);
    writer()->write_objectID(threadObj);
    writer()->write_u4(thread_serial_num);  // thread number
    writer()->write_u4(stack_serial_num);   // stack trace serial number
    int num_frames = do_thread(thread, thread_serial_num);
    assert(num_frames == _stack_traces[i]->get_stack_depth(),
           "total number of Java frames not matched");
D
duke 已提交
1655 1656 1657 1658 1659 1660 1661 1662 1663 1664
  }
}


// The VM operation that dumps the heap. The dump consists of the following
// records:
//
//  HPROF_HEADER
//  [HPROF_UTF8]*
//  [HPROF_LOAD_CLASS]*
1665
//  [[HPROF_FRAME]*|HPROF_TRACE]*
D
duke 已提交
1666 1667 1668
//  [HPROF_GC_CLASS_DUMP]*
//  HPROF_HEAP_DUMP
//
1669 1670 1671 1672
// The HPROF_TRACE records represent the stack traces where the heap dump
// is generated and a "dummy trace" record which does not include
// any frames. The dummy trace record is used to be referenced as the
// unknown object alloc site.
D
duke 已提交
1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685
//
// The HPROF_HEAP_DUMP record has a length following by sub-records. To allow
// the heap dump be generated in a single pass we remember the position of
// the dump length and fix it up after all sub-records have been written.
// To generate the sub-records we iterate over the heap, writing
// HPROF_GC_INSTANCE_DUMP, HPROF_GC_OBJ_ARRAY_DUMP, and HPROF_GC_PRIM_ARRAY_DUMP
// records as we go. Once that is done we write records for some of the GC
// roots.

void VM_HeapDumper::doit() {

  HandleMark hm;
  CollectedHeap* ch = Universe::heap();
P
poonam 已提交
1686 1687 1688 1689

  ch->ensure_parsability(false); // must happen, even if collection does
                                 // not happen (e.g. due to GC_locker)

D
duke 已提交
1690
  if (_gc_before_heap_dump) {
P
poonam 已提交
1691 1692 1693 1694 1695
    if (GC_locker::is_active()) {
      warning("GC locker is held; pre-heapdump GC was skipped");
    } else {
      ch->collect_as_vm_thread(GCCause::_heap_dump);
    }
D
duke 已提交
1696 1697
  }

1698 1699 1700 1701 1702
  // At this point we should be the only dumper active, so
  // the following should be safe.
  set_global_dumper();
  set_global_writer();

D
duke 已提交
1703
  // Write the file header - use 1.0.2 for large heaps, otherwise 1.0.1
1704
  size_t used = ch->used();
D
duke 已提交
1705 1706 1707 1708 1709 1710 1711
  const char* header;
  if (used > (size_t)SegmentedHeapDumpThreshold) {
    set_segmented_dump();
    header = "JAVA PROFILE 1.0.2";
  } else {
    header = "JAVA PROFILE 1.0.1";
  }
1712

D
duke 已提交
1713 1714 1715 1716 1717 1718 1719 1720
  // header is few bytes long - no chance to overflow int
  writer()->write_raw((void*)header, (int)strlen(header));
  writer()->write_u1(0); // terminator
  writer()->write_u4(oopSize);
  writer()->write_u8(os::javaTimeMillis());

  // HPROF_UTF8 records
  SymbolTableDumper sym_dumper(writer());
1721
  SymbolTable::symbols_do(&sym_dumper);
D
duke 已提交
1722 1723 1724 1725 1726

  // write HPROF_LOAD_CLASS records
  SystemDictionary::classes_do(&do_load_class);
  Universe::basic_type_classes_do(&do_load_class);

1727 1728 1729 1730
  // write HPROF_FRAME and HPROF_TRACE records
  // this must be called after _klass_map is built when iterating the classes above.
  dump_stack_traces();

D
duke 已提交
1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745
  // write HPROF_HEAP_DUMP or HPROF_HEAP_DUMP_SEGMENT
  write_dump_header();

  // Writes HPROF_GC_CLASS_DUMP records
  SystemDictionary::classes_do(&do_class_dump);
  Universe::basic_type_classes_do(&do_basic_type_array_class_dump);
  check_segment_length();

  // writes HPROF_GC_INSTANCE_DUMP records.
  // After each sub-record is written check_segment_length will be invoked. When
  // generated a segmented heap dump this allows us to check if the current
  // segment exceeds a threshold and if so, then a new segment is started.
  // The HPROF_GC_CLASS_DUMP and HPROF_GC_INSTANCE_DUMP are the vast bulk
  // of the heap dump.
  HeapObjectDumper obj_dumper(this, writer());
1746
  Universe::heap()->safe_object_iterate(&obj_dumper);
D
duke 已提交
1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763

  // HPROF_GC_ROOT_THREAD_OBJ + frames + jni locals
  do_threads();
  check_segment_length();

  // HPROF_GC_ROOT_MONITOR_USED
  MonitorUsedDumper mon_dumper(writer());
  ObjectSynchronizer::oops_do(&mon_dumper);
  check_segment_length();

  // HPROF_GC_ROOT_JNI_GLOBAL
  JNIGlobalsDumper jni_dumper(writer());
  JNIHandles::oops_do(&jni_dumper);
  check_segment_length();

  // HPROF_GC_ROOT_STICKY_CLASS
  StickyClassDumper class_dumper(writer());
1764
  SystemDictionary::always_strong_classes_do(&class_dumper);
D
duke 已提交
1765 1766 1767 1768

  // fixes up the length of the dump record. In the case of a segmented
  // heap then the HPROF_HEAP_DUMP_END record is also written.
  end_of_dump();
1769 1770 1771 1772

  // Now we clear the global variables, so that a future dumper might run.
  clear_global_dumper();
  clear_global_writer();
D
duke 已提交
1773 1774
}

1775 1776 1777 1778 1779 1780 1781
void VM_HeapDumper::dump_stack_traces() {
  // write a HPROF_TRACE record without any frames to be referenced as object alloc sites
  DumperSupport::write_header(writer(), HPROF_TRACE, 3*sizeof(u4));
  writer()->write_u4((u4) STACK_TRACE_ID);
  writer()->write_u4(0);                    // thread number
  writer()->write_u4(0);                    // frame count

Z
zgu 已提交
1782
  _stack_traces = NEW_C_HEAP_ARRAY(ThreadStackTrace*, Threads::number_of_threads(), mtInternal);
1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794
  int frame_serial_num = 0;
  for (JavaThread* thread = Threads::first(); thread != NULL ; thread = thread->next()) {
    oop threadObj = thread->threadObj();
    if (threadObj != NULL && !thread->is_exiting() && !thread->is_hidden_from_external_view()) {
      // dump thread stack trace
      ThreadStackTrace* stack_trace = new ThreadStackTrace(thread, false);
      stack_trace->dump_stack_at_safepoint(-1);
      _stack_traces[_num_threads++] = stack_trace;

      // write HPROF_FRAME records for this thread's stack trace
      int depth = stack_trace->get_stack_depth();
      int thread_frame_start = frame_serial_num;
1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805
      int extra_frames = 0;
      // write fake frame that makes it look like the thread, which caused OOME,
      // is in the OutOfMemoryError zero-parameter constructor
      if (thread == _oome_thread && _oome_constructor != NULL) {
        int oome_serial_num = _klass_map->find(Klass::cast(_oome_constructor->method_holder()));
        // the class serial number starts from 1
        assert(oome_serial_num > 0, "OutOfMemoryError class not found");
        DumperSupport::dump_stack_frame(writer(), ++frame_serial_num, oome_serial_num,
                                        _oome_constructor, 0);
        extra_frames++;
      }
1806 1807
      for (int j=0; j < depth; j++) {
        StackFrameInfo* frame = stack_trace->stack_frame_at(j);
1808
        Method* m = frame->method();
1809 1810 1811 1812 1813
        int class_serial_num = _klass_map->find(Klass::cast(m->method_holder()));
        // the class serial number starts from 1
        assert(class_serial_num > 0, "class not found");
        DumperSupport::dump_stack_frame(writer(), ++frame_serial_num, class_serial_num, m, frame->bci());
      }
1814
      depth += extra_frames;
1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827

      // write HPROF_TRACE record for one thread
      DumperSupport::write_header(writer(), HPROF_TRACE, 3*sizeof(u4) + depth*oopSize);
      int stack_serial_num = _num_threads + STACK_TRACE_ID;
      writer()->write_u4(stack_serial_num);      // stack trace serial number
      writer()->write_u4((u4) _num_threads);     // thread serial number
      writer()->write_u4(depth);                 // frame count
      for (int j=1; j <= depth; j++) {
        writer()->write_id(thread_frame_start + j);
      }
    }
  }
}
D
duke 已提交
1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850

// dump the heap to given path.
int HeapDumper::dump(const char* path) {
  assert(path != NULL && strlen(path) > 0, "path missing");

  // print message in interactive case
  if (print_to_tty()) {
    tty->print_cr("Dumping heap to %s ...", path);
    timer()->start();
  }

  // create the dump writer. If the file can be opened then bail
  DumpWriter writer(path);
  if (!writer.is_open()) {
    set_error(writer.error());
    if (print_to_tty()) {
      tty->print_cr("Unable to create %s: %s", path,
        (error() != NULL) ? error() : "reason unknown");
    }
    return -1;
  }

  // generate the dump
1851
  VM_HeapDumper dumper(&writer, _gc_before_heap_dump, _oome);
1852 1853 1854 1855 1856 1857
  if (Thread::current()->is_VM_thread()) {
    assert(SafepointSynchronize::is_at_safepoint(), "Expected to be called at a safepoint");
    dumper.doit();
  } else {
    VMThread::execute(&dumper);
  }
D
duke 已提交
1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911

  // close dump file and record any error that the writer may have encountered
  writer.close();
  set_error(writer.error());

  // print message in interactive case
  if (print_to_tty()) {
    timer()->stop();
    if (error() == NULL) {
      char msg[256];
      sprintf(msg, "Heap dump file created [%s bytes in %3.3f secs]",
        os::jlong_format_specifier(), timer()->seconds());
      tty->print_cr(msg, writer.bytes_written());
    } else {
      tty->print_cr("Dump file is incomplete: %s", writer.error());
    }
  }

  return (writer.error() == NULL) ? 0 : -1;
}

// stop timer (if still active), and free any error string we might be holding
HeapDumper::~HeapDumper() {
  if (timer()->is_active()) {
    timer()->stop();
  }
  set_error(NULL);
}


// returns the error string (resource allocated), or NULL
char* HeapDumper::error_as_C_string() const {
  if (error() != NULL) {
    char* str = NEW_RESOURCE_ARRAY(char, strlen(error())+1);
    strcpy(str, error());
    return str;
  } else {
    return NULL;
  }
}

// set the error string
void HeapDumper::set_error(char* error) {
  if (_error != NULL) {
    os::free(_error);
  }
  if (error == NULL) {
    _error = NULL;
  } else {
    _error = os::strdup(error);
    assert(_error != NULL, "allocation failure");
  }
}

1912 1913 1914 1915 1916 1917
// Called by out-of-memory error reporting by a single Java thread
// outside of a JVM safepoint
void HeapDumper::dump_heap_from_oome() {
  HeapDumper::dump_heap(true);
}

1918 1919 1920 1921 1922
// Called by error reporting by a single Java thread outside of a JVM safepoint,
// or by heap dumping by the VM thread during a (GC) safepoint. Thus, these various
// callers are strictly serialized and guaranteed not to interfere below. For more
// general use, however, this method will need modification to prevent
// inteference when updating the static variables base_path and dump_file_seq below.
D
duke 已提交
1923
void HeapDumper::dump_heap() {
1924 1925 1926 1927
  HeapDumper::dump_heap(false);
}

void HeapDumper::dump_heap(bool oome) {
1928 1929
  static char base_path[JVM_MAXPATHLEN] = {'\0'};
  static uint dump_file_seq = 0;
1930 1931 1932 1933 1934
  char* my_path;
  const int max_digit_chars = 20;

  const char* dump_file_name = "java_pid";
  const char* dump_file_ext  = ".hprof";
D
duke 已提交
1935 1936 1937 1938

  // The dump file defaults to java_pid<pid>.hprof in the current working
  // directory. HeapDumpPath=<file> can be used to specify an alternative
  // dump file name or a directory where dump file is created.
1939
  if (dump_file_seq == 0) { // first time in, we initialize base_path
1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950
    // Calculate potentially longest base path and check if we have enough
    // allocated statically.
    const size_t total_length =
                      (HeapDumpPath == NULL ? 0 : strlen(HeapDumpPath)) +
                      strlen(os::file_separator()) + max_digit_chars +
                      strlen(dump_file_name) + strlen(dump_file_ext) + 1;
    if (total_length > sizeof(base_path)) {
      warning("Cannot create heap dump file.  HeapDumpPath is too long.");
      return;
    }

1951 1952 1953
    bool use_default_filename = true;
    if (HeapDumpPath == NULL || HeapDumpPath[0] == '\0') {
      // HeapDumpPath=<file> not specified
D
duke 已提交
1954
    } else {
1955
      strncpy(base_path, HeapDumpPath, sizeof(base_path));
1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970
      // check if the path is a directory (must exist)
      DIR* dir = os::opendir(base_path);
      if (dir == NULL) {
        use_default_filename = false;
      } else {
        // HeapDumpPath specified a directory. We append a file separator
        // (if needed).
        os::closedir(dir);
        size_t fs_len = strlen(os::file_separator());
        if (strlen(base_path) >= fs_len) {
          char* end = base_path;
          end += (strlen(base_path) - fs_len);
          if (strcmp(end, os::file_separator()) != 0) {
            strcat(base_path, os::file_separator());
          }
D
duke 已提交
1971 1972 1973
        }
      }
    }
1974 1975
    // If HeapDumpPath wasn't a file name then we append the default name
    if (use_default_filename) {
1976 1977 1978 1979 1980
      const size_t dlen = strlen(base_path);  // if heap dump dir specified
      jio_snprintf(&base_path[dlen], sizeof(base_path)-dlen, "%s%d%s",
                   dump_file_name, os::current_process_id(), dump_file_ext);
    }
    const size_t len = strlen(base_path) + 1;
Z
zgu 已提交
1981
    my_path = (char*)os::malloc(len, mtInternal);
1982 1983 1984
    if (my_path == NULL) {
      warning("Cannot create heap dump file.  Out of system memory.");
      return;
1985
    }
1986
    strncpy(my_path, base_path, len);
1987 1988
  } else {
    // Append a sequence number id for dumps following the first
1989
    const size_t len = strlen(base_path) + max_digit_chars + 2; // for '.' and \0
Z
zgu 已提交
1990
    my_path = (char*)os::malloc(len, mtInternal);
1991 1992 1993 1994 1995
    if (my_path == NULL) {
      warning("Cannot create heap dump file.  Out of system memory.");
      return;
    }
    jio_snprintf(my_path, len, "%s.%d", base_path, dump_file_seq);
D
duke 已提交
1996
  }
1997
  dump_file_seq++;   // increment seq number for next time we dump
D
duke 已提交
1998 1999

  HeapDumper dumper(false /* no GC before heap dump */,
2000 2001
                    true  /* send to tty */,
                    oome  /* pass along out-of-memory-error flag */);
2002
  dumper.dump(my_path);
2003
  os::free(my_path);
D
duke 已提交
2004
}