1 /*
   2  * Copyright (c) 2005, 2015, 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 "classfile/symbolTable.hpp"
  27 #include "classfile/systemDictionary.hpp"
  28 #include "classfile/vmSymbols.hpp"
  29 #include "gc/shared/gcLocker.inline.hpp"
  30 #include "gc/shared/genCollectedHeap.hpp"
  31 #include "gc/shared/vmGCOperations.hpp"
  32 #include "memory/universe.hpp"
  33 #include "oops/objArrayKlass.hpp"
  34 #include "oops/objArrayOop.inline.hpp"
  35 #include "oops/oop.inline.hpp"
  36 #include "runtime/javaCalls.hpp"
  37 #include "runtime/jniHandles.hpp"
  38 #include "runtime/os.hpp"
  39 #include "runtime/reflectionUtils.hpp"
  40 #include "runtime/vframe.hpp"
  41 #include "runtime/vmThread.hpp"
  42 #include "runtime/vm_operations.hpp"
  43 #include "services/heapDumper.hpp"
  44 #include "services/threadService.hpp"
  45 #include "utilities/macros.hpp"
  46 #include "utilities/ostream.hpp"
  47 #if INCLUDE_ALL_GCS
  48 #include "gc/parallel/parallelScavengeHeap.hpp"
  49 #endif // INCLUDE_ALL_GCS
  50 
  51 /*
  52  * HPROF binary format - description copied from:
  53  *   src/share/demo/jvmti/hprof/hprof_io.c
  54  *
  55  *
  56  *  header    "JAVA PROFILE 1.0.1" or "JAVA PROFILE 1.0.2"
  57  *            (0-terminated)
  58  *
  59  *  u4        size of identifiers. Identifiers are used to represent
  60  *            UTF8 strings, objects, stack traces, etc. They usually
  61  *            have the same size as host pointers. For example, on
  62  *            Solaris and Win32, the size is 4.
  63  * u4         high word
  64  * u4         low word    number of milliseconds since 0:00 GMT, 1/1/70
  65  * [record]*  a sequence of records.
  66  *
  67  *
  68  * Record format:
  69  *
  70  * u1         a TAG denoting the type of the record
  71  * u4         number of *microseconds* since the time stamp in the
  72  *            header. (wraps around in a little more than an hour)
  73  * u4         number of bytes *remaining* in the record. Note that
  74  *            this number excludes the tag and the length field itself.
  75  * [u1]*      BODY of the record (a sequence of bytes)
  76  *
  77  *
  78  * The following TAGs are supported:
  79  *
  80  * TAG           BODY       notes
  81  *----------------------------------------------------------
  82  * HPROF_UTF8               a UTF8-encoded name
  83  *
  84  *               id         name ID
  85  *               [u1]*      UTF8 characters (no trailing zero)
  86  *
  87  * HPROF_LOAD_CLASS         a newly loaded class
  88  *
  89  *                u4        class serial number (> 0)
  90  *                id        class object ID
  91  *                u4        stack trace serial number
  92  *                id        class name ID
  93  *
  94  * HPROF_UNLOAD_CLASS       an unloading class
  95  *
  96  *                u4        class serial_number
  97  *
  98  * HPROF_FRAME              a Java stack frame
  99  *
 100  *                id        stack frame ID
 101  *                id        method name ID
 102  *                id        method signature ID
 103  *                id        source file name ID
 104  *                u4        class serial number
 105  *                i4        line number. >0: normal
 106  *                                       -1: unknown
 107  *                                       -2: compiled method
 108  *                                       -3: native method
 109  *
 110  * HPROF_TRACE              a Java stack trace
 111  *
 112  *               u4         stack trace serial number
 113  *               u4         thread serial number
 114  *               u4         number of frames
 115  *               [id]*      stack frame IDs
 116  *
 117  *
 118  * HPROF_ALLOC_SITES        a set of heap allocation sites, obtained after GC
 119  *
 120  *               u2         flags 0x0001: incremental vs. complete
 121  *                                0x0002: sorted by allocation vs. live
 122  *                                0x0004: whether to force a GC
 123  *               u4         cutoff ratio
 124  *               u4         total live bytes
 125  *               u4         total live instances
 126  *               u8         total bytes allocated
 127  *               u8         total instances allocated
 128  *               u4         number of sites that follow
 129  *               [u1        is_array: 0:  normal object
 130  *                                    2:  object array
 131  *                                    4:  boolean array
 132  *                                    5:  char array
 133  *                                    6:  float array
 134  *                                    7:  double array
 135  *                                    8:  byte array
 136  *                                    9:  short array
 137  *                                    10: int array
 138  *                                    11: long array
 139  *                u4        class serial number (may be zero during startup)
 140  *                u4        stack trace serial number
 141  *                u4        number of bytes alive
 142  *                u4        number of instances alive
 143  *                u4        number of bytes allocated
 144  *                u4]*      number of instance allocated
 145  *
 146  * HPROF_START_THREAD       a newly started thread.
 147  *
 148  *               u4         thread serial number (> 0)
 149  *               id         thread object ID
 150  *               u4         stack trace serial number
 151  *               id         thread name ID
 152  *               id         thread group name ID
 153  *               id         thread group parent name ID
 154  *
 155  * HPROF_END_THREAD         a terminating thread.
 156  *
 157  *               u4         thread serial number
 158  *
 159  * HPROF_HEAP_SUMMARY       heap summary
 160  *
 161  *               u4         total live bytes
 162  *               u4         total live instances
 163  *               u8         total bytes allocated
 164  *               u8         total instances allocated
 165  *
 166  * HPROF_HEAP_DUMP          denote a heap dump
 167  *
 168  *               [heap dump sub-records]*
 169  *
 170  *                          There are four kinds of heap dump sub-records:
 171  *
 172  *               u1         sub-record type
 173  *
 174  *               HPROF_GC_ROOT_UNKNOWN         unknown root
 175  *
 176  *                          id         object ID
 177  *
 178  *               HPROF_GC_ROOT_THREAD_OBJ      thread object
 179  *
 180  *                          id         thread object ID  (may be 0 for a
 181  *                                     thread newly attached through JNI)
 182  *                          u4         thread sequence number
 183  *                          u4         stack trace sequence number
 184  *
 185  *               HPROF_GC_ROOT_JNI_GLOBAL      JNI global ref root
 186  *
 187  *                          id         object ID
 188  *                          id         JNI global ref ID
 189  *
 190  *               HPROF_GC_ROOT_JNI_LOCAL       JNI local ref
 191  *
 192  *                          id         object ID
 193  *                          u4         thread serial number
 194  *                          u4         frame # in stack trace (-1 for empty)
 195  *
 196  *               HPROF_GC_ROOT_JAVA_FRAME      Java stack frame
 197  *
 198  *                          id         object ID
 199  *                          u4         thread serial number
 200  *                          u4         frame # in stack trace (-1 for empty)
 201  *
 202  *               HPROF_GC_ROOT_NATIVE_STACK    Native stack
 203  *
 204  *                          id         object ID
 205  *                          u4         thread serial number
 206  *
 207  *               HPROF_GC_ROOT_STICKY_CLASS    System class
 208  *
 209  *                          id         object ID
 210  *
 211  *               HPROF_GC_ROOT_THREAD_BLOCK    Reference from thread block
 212  *
 213  *                          id         object ID
 214  *                          u4         thread serial number
 215  *
 216  *               HPROF_GC_ROOT_MONITOR_USED    Busy monitor
 217  *
 218  *                          id         object ID
 219  *
 220  *               HPROF_GC_CLASS_DUMP           dump of a class object
 221  *
 222  *                          id         class object ID
 223  *                          u4         stack trace serial number
 224  *                          id         super class object ID
 225  *                          id         class loader object ID
 226  *                          id         signers object ID
 227  *                          id         protection domain object ID
 228  *                          id         reserved
 229  *                          id         reserved
 230  *
 231  *                          u4         instance size (in bytes)
 232  *
 233  *                          u2         size of constant pool
 234  *                          [u2,       constant pool index,
 235  *                           ty,       type
 236  *                                     2:  object
 237  *                                     4:  boolean
 238  *                                     5:  char
 239  *                                     6:  float
 240  *                                     7:  double
 241  *                                     8:  byte
 242  *                                     9:  short
 243  *                                     10: int
 244  *                                     11: long
 245  *                           vl]*      and value
 246  *
 247  *                          u2         number of static fields
 248  *                          [id,       static field name,
 249  *                           ty,       type,
 250  *                           vl]*      and value
 251  *
 252  *                          u2         number of inst. fields (not inc. super)
 253  *                          [id,       instance field name,
 254  *                           ty]*      type
 255  *
 256  *               HPROF_GC_INSTANCE_DUMP        dump of a normal object
 257  *
 258  *                          id         object ID
 259  *                          u4         stack trace serial number
 260  *                          id         class object ID
 261  *                          u4         number of bytes that follow
 262  *                          [vl]*      instance field values (class, followed
 263  *                                     by super, super's super ...)
 264  *
 265  *               HPROF_GC_OBJ_ARRAY_DUMP       dump of an object array
 266  *
 267  *                          id         array object ID
 268  *                          u4         stack trace serial number
 269  *                          u4         number of elements
 270  *                          id         array class ID
 271  *                          [id]*      elements
 272  *
 273  *               HPROF_GC_PRIM_ARRAY_DUMP      dump of a primitive array
 274  *
 275  *                          id         array object ID
 276  *                          u4         stack trace serial number
 277  *                          u4         number of elements
 278  *                          u1         element type
 279  *                                     4:  boolean array
 280  *                                     5:  char array
 281  *                                     6:  float array
 282  *                                     7:  double array
 283  *                                     8:  byte array
 284  *                                     9:  short array
 285  *                                     10: int array
 286  *                                     11: long array
 287  *                          [u1]*      elements
 288  *
 289  * HPROF_CPU_SAMPLES        a set of sample traces of running threads
 290  *
 291  *                u4        total number of samples
 292  *                u4        # of traces
 293  *               [u4        # of samples
 294  *                u4]*      stack trace serial number
 295  *
 296  * HPROF_CONTROL_SETTINGS   the settings of on/off switches
 297  *
 298  *                u4        0x00000001: alloc traces on/off
 299  *                          0x00000002: cpu sampling on/off
 300  *                u2        stack trace depth
 301  *
 302  *
 303  * When the header is "JAVA PROFILE 1.0.2" a heap dump can optionally
 304  * be generated as a sequence of heap dump segments. This sequence is
 305  * terminated by an end record. The additional tags allowed by format
 306  * "JAVA PROFILE 1.0.2" are:
 307  *
 308  * HPROF_HEAP_DUMP_SEGMENT  denote a heap dump segment
 309  *
 310  *               [heap dump sub-records]*
 311  *               The same sub-record types allowed by HPROF_HEAP_DUMP
 312  *
 313  * HPROF_HEAP_DUMP_END      denotes the end of a heap dump
 314  *
 315  */
 316 
 317 
 318 // HPROF tags
 319 
 320 typedef enum {
 321   // top-level records
 322   HPROF_UTF8                    = 0x01,
 323   HPROF_LOAD_CLASS              = 0x02,
 324   HPROF_UNLOAD_CLASS            = 0x03,
 325   HPROF_FRAME                   = 0x04,
 326   HPROF_TRACE                   = 0x05,
 327   HPROF_ALLOC_SITES             = 0x06,
 328   HPROF_HEAP_SUMMARY            = 0x07,
 329   HPROF_START_THREAD            = 0x0A,
 330   HPROF_END_THREAD              = 0x0B,
 331   HPROF_HEAP_DUMP               = 0x0C,
 332   HPROF_CPU_SAMPLES             = 0x0D,
 333   HPROF_CONTROL_SETTINGS        = 0x0E,
 334 
 335   // 1.0.2 record types
 336   HPROF_HEAP_DUMP_SEGMENT       = 0x1C,
 337   HPROF_HEAP_DUMP_END           = 0x2C,
 338 
 339   // field types
 340   HPROF_ARRAY_OBJECT            = 0x01,
 341   HPROF_NORMAL_OBJECT           = 0x02,
 342   HPROF_BOOLEAN                 = 0x04,
 343   HPROF_CHAR                    = 0x05,
 344   HPROF_FLOAT                   = 0x06,
 345   HPROF_DOUBLE                  = 0x07,
 346   HPROF_BYTE                    = 0x08,
 347   HPROF_SHORT                   = 0x09,
 348   HPROF_INT                     = 0x0A,
 349   HPROF_LONG                    = 0x0B,
 350 
 351   // data-dump sub-records
 352   HPROF_GC_ROOT_UNKNOWN         = 0xFF,
 353   HPROF_GC_ROOT_JNI_GLOBAL      = 0x01,
 354   HPROF_GC_ROOT_JNI_LOCAL       = 0x02,
 355   HPROF_GC_ROOT_JAVA_FRAME      = 0x03,
 356   HPROF_GC_ROOT_NATIVE_STACK    = 0x04,
 357   HPROF_GC_ROOT_STICKY_CLASS    = 0x05,
 358   HPROF_GC_ROOT_THREAD_BLOCK    = 0x06,
 359   HPROF_GC_ROOT_MONITOR_USED    = 0x07,
 360   HPROF_GC_ROOT_THREAD_OBJ      = 0x08,
 361   HPROF_GC_CLASS_DUMP           = 0x20,
 362   HPROF_GC_INSTANCE_DUMP        = 0x21,
 363   HPROF_GC_OBJ_ARRAY_DUMP       = 0x22,
 364   HPROF_GC_PRIM_ARRAY_DUMP      = 0x23
 365 } hprofTag;
 366 
 367 // Default stack trace ID (used for dummy HPROF_TRACE record)
 368 enum {
 369   STACK_TRACE_ID = 1,
 370   INITIAL_CLASS_COUNT = 200
 371 };
 372 
 373 // Supports I/O operations on a dump file
 374 
 375 class DumpWriter : public StackObj {
 376  private:
 377   enum {
 378     io_buffer_size  = 8*M
 379   };
 380 
 381   int _fd;              // file descriptor (-1 if dump file not open)
 382   jlong _bytes_written; // number of byte written to dump file
 383 
 384   char* _buffer;    // internal buffer
 385   int _size;
 386   int _pos;
 387 
 388   char* _error;   // error message when I/O fails
 389 
 390   void set_file_descriptor(int fd)              { _fd = fd; }
 391   int file_descriptor() const                   { return _fd; }
 392 
 393   char* buffer() const                          { return _buffer; }
 394   int buffer_size() const                       { return _size; }
 395   int position() const                          { return _pos; }
 396   void set_position(int pos)                    { _pos = pos; }
 397 
 398   void set_error(const char* error)             { _error = (char*)os::strdup(error); }
 399 
 400   // all I/O go through this function
 401   void write_internal(void* s, int len);
 402 
 403  public:
 404   DumpWriter(const char* path);
 405   ~DumpWriter();
 406 
 407   void close();
 408   bool is_open() const                  { return file_descriptor() >= 0; }
 409   void flush();
 410 
 411   // total number of bytes written to the disk
 412   jlong bytes_written() const           { return _bytes_written; }
 413 
 414   // adjust the number of bytes written to disk (used to keep the count
 415   // of the number of bytes written in case of rewrites)
 416   void adjust_bytes_written(jlong n)     { _bytes_written += n; }
 417 
 418   // number of (buffered) bytes as yet unwritten to the dump file
 419   jlong bytes_unwritten() const          { return (jlong)position(); }
 420 
 421   char* error() const                   { return _error; }
 422 
 423   jlong current_offset();
 424   void seek_to_offset(jlong pos);
 425 
 426   // writer functions
 427   void write_raw(void* s, int len);
 428   void write_u1(u1 x)                   { write_raw((void*)&x, 1); }
 429   void write_u2(u2 x);
 430   void write_u4(u4 x);
 431   void write_u8(u8 x);
 432   void write_objectID(oop o);
 433   void write_symbolID(Symbol* o);
 434   void write_classID(Klass* k);
 435   void write_id(u4 x);
 436 };
 437 
 438 DumpWriter::DumpWriter(const char* path) {
 439   // try to allocate an I/O buffer of io_buffer_size. If there isn't
 440   // sufficient memory then reduce size until we can allocate something.
 441   _size = io_buffer_size;
 442   do {
 443     _buffer = (char*)os::malloc(_size, mtInternal);
 444     if (_buffer == NULL) {
 445       _size = _size >> 1;
 446     }
 447   } while (_buffer == NULL && _size > 0);
 448   assert((_size > 0 && _buffer != NULL) || (_size == 0 && _buffer == NULL), "sanity check");
 449   _pos = 0;
 450   _error = NULL;
 451   _bytes_written = 0L;
 452   _fd = os::create_binary_file(path, false);    // don't replace existing file
 453 
 454   // if the open failed we record the error
 455   if (_fd < 0) {
 456     _error = (char*)os::strdup(strerror(errno));
 457   }
 458 }
 459 
 460 DumpWriter::~DumpWriter() {
 461   // flush and close dump file
 462   if (is_open()) {
 463     close();
 464   }
 465   if (_buffer != NULL) os::free(_buffer);
 466   if (_error != NULL) os::free(_error);
 467 }
 468 
 469 // closes dump file (if open)
 470 void DumpWriter::close() {
 471   // flush and close dump file
 472   if (is_open()) {
 473     flush();
 474     ::close(file_descriptor());
 475     set_file_descriptor(-1);
 476   }
 477 }
 478 
 479 // write directly to the file
 480 void DumpWriter::write_internal(void* s, int len) {
 481   if (is_open()) {
 482     int n = ::write(file_descriptor(), s, len);
 483     if (n > 0) {
 484       _bytes_written += n;
 485     }
 486     if (n != len) {
 487       if (n < 0) {
 488         set_error(strerror(errno));
 489       } else {
 490         set_error("file size limit");
 491       }
 492       ::close(file_descriptor());
 493       set_file_descriptor(-1);
 494     }
 495   }
 496 }
 497 
 498 // write raw bytes
 499 void DumpWriter::write_raw(void* s, int len) {
 500   if (is_open()) {
 501     // flush buffer to make toom
 502     if ((position()+ len) >= buffer_size()) {
 503       flush();
 504     }
 505 
 506     // buffer not available or too big to buffer it
 507     if ((buffer() == NULL) || (len >= buffer_size())) {
 508       write_internal(s, len);
 509     } else {
 510       // Should optimize this for u1/u2/u4/u8 sizes.
 511       memcpy(buffer() + position(), s, len);
 512       set_position(position() + len);
 513     }
 514   }
 515 }
 516 
 517 // flush any buffered bytes to the file
 518 void DumpWriter::flush() {
 519   if (is_open() && position() > 0) {
 520     write_internal(buffer(), position());
 521     set_position(0);
 522   }
 523 }
 524 
 525 
 526 jlong DumpWriter::current_offset() {
 527   if (is_open()) {
 528     // the offset is the file offset plus whatever we have buffered
 529     jlong offset = os::current_file_offset(file_descriptor());
 530     assert(offset >= 0, "lseek failed");
 531     return offset + (jlong)position();
 532   } else {
 533     return (jlong)-1;
 534   }
 535 }
 536 
 537 void DumpWriter::seek_to_offset(jlong off) {
 538   assert(off >= 0, "bad offset");
 539 
 540   // need to flush before seeking
 541   flush();
 542 
 543   // may be closed due to I/O error
 544   if (is_open()) {
 545     jlong n = os::seek_to_file_offset(file_descriptor(), off);
 546     assert(n >= 0, "lseek failed");
 547   }
 548 }
 549 
 550 void DumpWriter::write_u2(u2 x) {
 551   u2 v;
 552   Bytes::put_Java_u2((address)&v, x);
 553   write_raw((void*)&v, 2);
 554 }
 555 
 556 void DumpWriter::write_u4(u4 x) {
 557   u4 v;
 558   Bytes::put_Java_u4((address)&v, x);
 559   write_raw((void*)&v, 4);
 560 }
 561 
 562 void DumpWriter::write_u8(u8 x) {
 563   u8 v;
 564   Bytes::put_Java_u8((address)&v, x);
 565   write_raw((void*)&v, 8);
 566 }
 567 
 568 void DumpWriter::write_objectID(oop o) {
 569   address a = (address)o;
 570 #ifdef _LP64
 571   write_u8((u8)a);
 572 #else
 573   write_u4((u4)a);
 574 #endif
 575 }
 576 
 577 void DumpWriter::write_symbolID(Symbol* s) {
 578   address a = (address)((uintptr_t)s);
 579 #ifdef _LP64
 580   write_u8((u8)a);
 581 #else
 582   write_u4((u4)a);
 583 #endif
 584 }
 585 
 586 void DumpWriter::write_id(u4 x) {
 587 #ifdef _LP64
 588   write_u8((u8) x);
 589 #else
 590   write_u4(x);
 591 #endif
 592 }
 593 
 594 // We use java mirror as the class ID
 595 void DumpWriter::write_classID(Klass* k) {
 596   write_objectID(k->java_mirror());
 597 }
 598 
 599 
 600 
 601 // Support class with a collection of functions used when dumping the heap
 602 
 603 class DumperSupport : AllStatic {
 604  public:
 605 
 606   // write a header of the given type
 607   static void write_header(DumpWriter* writer, hprofTag tag, u4 len);
 608 
 609   // returns hprof tag for the given type signature
 610   static hprofTag sig2tag(Symbol* sig);
 611   // returns hprof tag for the given basic type
 612   static hprofTag type2tag(BasicType type);
 613 
 614   // returns the size of the instance of the given class
 615   static u4 instance_size(Klass* k);
 616 
 617   // dump a jfloat
 618   static void dump_float(DumpWriter* writer, jfloat f);
 619   // dump a jdouble
 620   static void dump_double(DumpWriter* writer, jdouble d);
 621   // dumps the raw value of the given field
 622   static void dump_field_value(DumpWriter* writer, char type, address addr);
 623   // dumps static fields of the given class
 624   static void dump_static_fields(DumpWriter* writer, Klass* k);
 625   // dump the raw values of the instance fields of the given object
 626   static void dump_instance_fields(DumpWriter* writer, oop o);
 627   // dumps the definition of the instance fields for a given class
 628   static void dump_instance_field_descriptors(DumpWriter* writer, Klass* k);
 629   // creates HPROF_GC_INSTANCE_DUMP record for the given object
 630   static void dump_instance(DumpWriter* writer, oop o);
 631   // creates HPROF_GC_CLASS_DUMP record for the given class and each of its
 632   // array classes
 633   static void dump_class_and_array_classes(DumpWriter* writer, Klass* k);
 634   // creates HPROF_GC_CLASS_DUMP record for a given primitive array
 635   // class (and each multi-dimensional array class too)
 636   static void dump_basic_type_array_class(DumpWriter* writer, Klass* k);
 637 
 638   // creates HPROF_GC_OBJ_ARRAY_DUMP record for the given object array
 639   static void dump_object_array(DumpWriter* writer, objArrayOop array);
 640   // creates HPROF_GC_PRIM_ARRAY_DUMP record for the given type array
 641   static void dump_prim_array(DumpWriter* writer, typeArrayOop array);
 642   // create HPROF_FRAME record for the given method and bci
 643   static void dump_stack_frame(DumpWriter* writer, int frame_serial_num, int class_serial_num, Method* m, int bci);
 644 };
 645 
 646 // write a header of the given type
 647 void DumperSupport:: write_header(DumpWriter* writer, hprofTag tag, u4 len) {
 648   writer->write_u1((u1)tag);
 649   writer->write_u4(0);                  // current ticks
 650   writer->write_u4(len);
 651 }
 652 
 653 // returns hprof tag for the given type signature
 654 hprofTag DumperSupport::sig2tag(Symbol* sig) {
 655   switch (sig->byte_at(0)) {
 656     case JVM_SIGNATURE_CLASS    : return HPROF_NORMAL_OBJECT;
 657     case JVM_SIGNATURE_ARRAY    : return HPROF_NORMAL_OBJECT;
 658     case JVM_SIGNATURE_BYTE     : return HPROF_BYTE;
 659     case JVM_SIGNATURE_CHAR     : return HPROF_CHAR;
 660     case JVM_SIGNATURE_FLOAT    : return HPROF_FLOAT;
 661     case JVM_SIGNATURE_DOUBLE   : return HPROF_DOUBLE;
 662     case JVM_SIGNATURE_INT      : return HPROF_INT;
 663     case JVM_SIGNATURE_LONG     : return HPROF_LONG;
 664     case JVM_SIGNATURE_SHORT    : return HPROF_SHORT;
 665     case JVM_SIGNATURE_BOOLEAN  : return HPROF_BOOLEAN;
 666     default : ShouldNotReachHere(); /* to shut up compiler */ return HPROF_BYTE;
 667   }
 668 }
 669 
 670 hprofTag DumperSupport::type2tag(BasicType type) {
 671   switch (type) {
 672     case T_BYTE     : return HPROF_BYTE;
 673     case T_CHAR     : return HPROF_CHAR;
 674     case T_FLOAT    : return HPROF_FLOAT;
 675     case T_DOUBLE   : return HPROF_DOUBLE;
 676     case T_INT      : return HPROF_INT;
 677     case T_LONG     : return HPROF_LONG;
 678     case T_SHORT    : return HPROF_SHORT;
 679     case T_BOOLEAN  : return HPROF_BOOLEAN;
 680     default : ShouldNotReachHere(); /* to shut up compiler */ return HPROF_BYTE;
 681   }
 682 }
 683 
 684 // dump a jfloat
 685 void DumperSupport::dump_float(DumpWriter* writer, jfloat f) {
 686   if (g_isnan(f)) {
 687     writer->write_u4(0x7fc00000);    // collapsing NaNs
 688   } else {
 689     union {
 690       int i;
 691       float f;
 692     } u;
 693     u.f = (float)f;
 694     writer->write_u4((u4)u.i);
 695   }
 696 }
 697 
 698 // dump a jdouble
 699 void DumperSupport::dump_double(DumpWriter* writer, jdouble d) {
 700   union {
 701     jlong l;
 702     double d;
 703   } u;
 704   if (g_isnan(d)) {                 // collapsing NaNs
 705     u.l = (jlong)(0x7ff80000);
 706     u.l = (u.l << 32);
 707   } else {
 708     u.d = (double)d;
 709   }
 710   writer->write_u8((u8)u.l);
 711 }
 712 
 713 // dumps the raw value of the given field
 714 void DumperSupport::dump_field_value(DumpWriter* writer, char type, address addr) {
 715   switch (type) {
 716     case JVM_SIGNATURE_CLASS :
 717     case JVM_SIGNATURE_ARRAY : {
 718       oop o;
 719       if (UseCompressedOops) {
 720         o = oopDesc::load_decode_heap_oop((narrowOop*)addr);
 721       } else {
 722         o = oopDesc::load_decode_heap_oop((oop*)addr);
 723       }
 724 
 725       // reflection and sun.misc.Unsafe classes may have a reference to a
 726       // Klass* so filter it out.
 727       assert(o->is_oop_or_null(), err_msg("Expected an oop or NULL at " PTR_FORMAT, p2i(o)));
 728       writer->write_objectID(o);
 729       break;
 730     }
 731     case JVM_SIGNATURE_BYTE     : {
 732       jbyte* b = (jbyte*)addr;
 733       writer->write_u1((u1)*b);
 734       break;
 735     }
 736     case JVM_SIGNATURE_CHAR     : {
 737       jchar* c = (jchar*)addr;
 738       writer->write_u2((u2)*c);
 739       break;
 740     }
 741     case JVM_SIGNATURE_SHORT : {
 742       jshort* s = (jshort*)addr;
 743       writer->write_u2((u2)*s);
 744       break;
 745     }
 746     case JVM_SIGNATURE_FLOAT : {
 747       jfloat* f = (jfloat*)addr;
 748       dump_float(writer, *f);
 749       break;
 750     }
 751     case JVM_SIGNATURE_DOUBLE : {
 752       jdouble* f = (jdouble*)addr;
 753       dump_double(writer, *f);
 754       break;
 755     }
 756     case JVM_SIGNATURE_INT : {
 757       jint* i = (jint*)addr;
 758       writer->write_u4((u4)*i);
 759       break;
 760     }
 761     case JVM_SIGNATURE_LONG     : {
 762       jlong* l = (jlong*)addr;
 763       writer->write_u8((u8)*l);
 764       break;
 765     }
 766     case JVM_SIGNATURE_BOOLEAN : {
 767       jboolean* b = (jboolean*)addr;
 768       writer->write_u1((u1)*b);
 769       break;
 770     }
 771     default : ShouldNotReachHere();
 772   }
 773 }
 774 
 775 // returns the size of the instance of the given class
 776 u4 DumperSupport::instance_size(Klass* k) {
 777   HandleMark hm;
 778   instanceKlassHandle ikh = instanceKlassHandle(Thread::current(), k);
 779 
 780   int size = 0;
 781 
 782   for (FieldStream fld(ikh, false, false); !fld.eos(); fld.next()) {
 783     if (!fld.access_flags().is_static()) {
 784       Symbol* sig = fld.signature();
 785       switch (sig->byte_at(0)) {
 786         case JVM_SIGNATURE_CLASS   :
 787         case JVM_SIGNATURE_ARRAY   : size += oopSize; break;
 788 
 789         case JVM_SIGNATURE_BYTE    :
 790         case JVM_SIGNATURE_BOOLEAN : size += 1; break;
 791 
 792         case JVM_SIGNATURE_CHAR    :
 793         case JVM_SIGNATURE_SHORT   : size += 2; break;
 794 
 795         case JVM_SIGNATURE_INT     :
 796         case JVM_SIGNATURE_FLOAT   : size += 4; break;
 797 
 798         case JVM_SIGNATURE_LONG    :
 799         case JVM_SIGNATURE_DOUBLE  : size += 8; break;
 800 
 801         default : ShouldNotReachHere();
 802       }
 803     }
 804   }
 805   return (u4)size;
 806 }
 807 
 808 // dumps static fields of the given class
 809 void DumperSupport::dump_static_fields(DumpWriter* writer, Klass* k) {
 810   HandleMark hm;
 811   instanceKlassHandle ikh = instanceKlassHandle(Thread::current(), k);
 812 
 813   // pass 1 - count the static fields
 814   u2 field_count = 0;
 815   for (FieldStream fldc(ikh, true, true); !fldc.eos(); fldc.next()) {
 816     if (fldc.access_flags().is_static()) field_count++;
 817   }
 818 
 819   writer->write_u2(field_count);
 820 
 821   // pass 2 - dump the field descriptors and raw values
 822   for (FieldStream fld(ikh, true, true); !fld.eos(); fld.next()) {
 823     if (fld.access_flags().is_static()) {
 824       Symbol* sig = fld.signature();
 825 
 826       writer->write_symbolID(fld.name());   // name
 827       writer->write_u1(sig2tag(sig));       // type
 828 
 829       // value
 830       int offset = fld.offset();
 831       address addr = (address)ikh->java_mirror() + offset;
 832 
 833       dump_field_value(writer, sig->byte_at(0), addr);
 834     }
 835   }
 836 }
 837 
 838 // dump the raw values of the instance fields of the given object
 839 void DumperSupport::dump_instance_fields(DumpWriter* writer, oop o) {
 840   HandleMark hm;
 841   instanceKlassHandle ikh = instanceKlassHandle(Thread::current(), o->klass());
 842 
 843   for (FieldStream fld(ikh, false, false); !fld.eos(); fld.next()) {
 844     if (!fld.access_flags().is_static()) {
 845       Symbol* sig = fld.signature();
 846       address addr = (address)o + fld.offset();
 847 
 848       dump_field_value(writer, sig->byte_at(0), addr);
 849     }
 850   }
 851 }
 852 
 853 // dumps the definition of the instance fields for a given class
 854 void DumperSupport::dump_instance_field_descriptors(DumpWriter* writer, Klass* k) {
 855   HandleMark hm;
 856   instanceKlassHandle ikh = instanceKlassHandle(Thread::current(), k);
 857 
 858   // pass 1 - count the instance fields
 859   u2 field_count = 0;
 860   for (FieldStream fldc(ikh, true, true); !fldc.eos(); fldc.next()) {
 861     if (!fldc.access_flags().is_static()) field_count++;
 862   }
 863 
 864   writer->write_u2(field_count);
 865 
 866   // pass 2 - dump the field descriptors
 867   for (FieldStream fld(ikh, true, true); !fld.eos(); fld.next()) {
 868     if (!fld.access_flags().is_static()) {
 869       Symbol* sig = fld.signature();
 870 
 871       writer->write_symbolID(fld.name());                   // name
 872       writer->write_u1(sig2tag(sig));       // type
 873     }
 874   }
 875 }
 876 
 877 // creates HPROF_GC_INSTANCE_DUMP record for the given object
 878 void DumperSupport::dump_instance(DumpWriter* writer, oop o) {
 879   Klass* k = o->klass();
 880 
 881   writer->write_u1(HPROF_GC_INSTANCE_DUMP);
 882   writer->write_objectID(o);
 883   writer->write_u4(STACK_TRACE_ID);
 884 
 885   // class ID
 886   writer->write_classID(k);
 887 
 888   // number of bytes that follow
 889   writer->write_u4(instance_size(k) );
 890 
 891   // field values
 892   dump_instance_fields(writer, o);
 893 }
 894 
 895 // creates HPROF_GC_CLASS_DUMP record for the given class and each of
 896 // its array classes
 897 void DumperSupport::dump_class_and_array_classes(DumpWriter* writer, Klass* k) {
 898   Klass* klass = k;
 899   assert(klass->oop_is_instance(), "not an InstanceKlass");
 900   InstanceKlass* ik = (InstanceKlass*)klass;
 901 





 902   writer->write_u1(HPROF_GC_CLASS_DUMP);
 903 
 904   // class ID
 905   writer->write_classID(ik);
 906   writer->write_u4(STACK_TRACE_ID);
 907 
 908   // super class ID
 909   Klass* java_super = ik->java_super();
 910   if (java_super == NULL) {
 911     writer->write_objectID(oop(NULL));
 912   } else {
 913     writer->write_classID(java_super);
 914   }
 915 
 916   writer->write_objectID(ik->class_loader());
 917   writer->write_objectID(ik->signers());
 918   writer->write_objectID(ik->protection_domain());
 919 
 920   // reserved
 921   writer->write_objectID(oop(NULL));
 922   writer->write_objectID(oop(NULL));
 923 
 924   // instance size
 925   writer->write_u4(DumperSupport::instance_size(k));
 926 
 927   // size of constant pool - ignored by HAT 1.1
 928   writer->write_u2(0);
 929 
 930   // number of static fields
 931   dump_static_fields(writer, k);
 932 
 933   // description of instance fields
 934   dump_instance_field_descriptors(writer, k);
 935 
 936   // array classes
 937   k = klass->array_klass_or_null();
 938   while (k != NULL) {

 939     Klass* klass = k;
 940     assert(klass->oop_is_objArray(), "not an ObjArrayKlass");
 941 
 942     writer->write_u1(HPROF_GC_CLASS_DUMP);
 943     writer->write_classID(klass);
 944     writer->write_u4(STACK_TRACE_ID);
 945 
 946     // super class of array classes is java.lang.Object
 947     java_super = klass->java_super();
 948     assert(java_super != NULL, "checking");
 949     writer->write_classID(java_super);
 950 
 951     writer->write_objectID(ik->class_loader());
 952     writer->write_objectID(ik->signers());
 953     writer->write_objectID(ik->protection_domain());
 954 
 955     writer->write_objectID(oop(NULL));    // reserved
 956     writer->write_objectID(oop(NULL));
 957     writer->write_u4(0);             // instance size
 958     writer->write_u2(0);             // constant pool
 959     writer->write_u2(0);             // static fields
 960     writer->write_u2(0);             // instance fields
 961 
 962     // get the array class for the next rank
 963     k = klass->array_klass_or_null();
 964   }
 965 }
 966 
 967 // creates HPROF_GC_CLASS_DUMP record for a given primitive array
 968 // class (and each multi-dimensional array class too)
 969 void DumperSupport::dump_basic_type_array_class(DumpWriter* writer, Klass* k) {
 970  // array classes
 971  while (k != NULL) {
 972     Klass* klass = k;
 973 
 974     writer->write_u1(HPROF_GC_CLASS_DUMP);
 975     writer->write_classID(klass);
 976     writer->write_u4(STACK_TRACE_ID);
 977 
 978     // super class of array classes is java.lang.Object
 979     Klass* java_super = klass->java_super();
 980     assert(java_super != NULL, "checking");
 981     writer->write_classID(java_super);
 982 
 983     writer->write_objectID(oop(NULL));    // loader
 984     writer->write_objectID(oop(NULL));    // signers
 985     writer->write_objectID(oop(NULL));    // protection domain
 986 
 987     writer->write_objectID(oop(NULL));    // reserved
 988     writer->write_objectID(oop(NULL));
 989     writer->write_u4(0);             // instance size
 990     writer->write_u2(0);             // constant pool
 991     writer->write_u2(0);             // static fields
 992     writer->write_u2(0);             // instance fields
 993 
 994     // get the array class for the next rank
 995     k = klass->array_klass_or_null();
 996   }
 997 }
 998 
 999 // creates HPROF_GC_OBJ_ARRAY_DUMP record for the given object array
1000 void DumperSupport::dump_object_array(DumpWriter* writer, objArrayOop array) {
1001 
1002   writer->write_u1(HPROF_GC_OBJ_ARRAY_DUMP);
1003   writer->write_objectID(array);
1004   writer->write_u4(STACK_TRACE_ID);
1005   writer->write_u4((u4)array->length());
1006 
1007   // array class ID
1008   writer->write_classID(array->klass());
1009 
1010   // [id]* elements
1011   for (int index=0; index<array->length(); index++) {
1012     oop o = array->obj_at(index);
1013     writer->write_objectID(o);
1014   }
1015 }
1016 
1017 #define WRITE_ARRAY(Array, Type, Size) \
1018   for (int i=0; i<Array->length(); i++) { writer->write_##Size((Size)array->Type##_at(i)); }
1019 
1020 
1021 // creates HPROF_GC_PRIM_ARRAY_DUMP record for the given type array
1022 void DumperSupport::dump_prim_array(DumpWriter* writer, typeArrayOop array) {
1023   BasicType type = TypeArrayKlass::cast(array->klass())->element_type();
1024 
1025   writer->write_u1(HPROF_GC_PRIM_ARRAY_DUMP);
1026   writer->write_objectID(array);
1027   writer->write_u4(STACK_TRACE_ID);
1028   writer->write_u4((u4)array->length());
1029   writer->write_u1(type2tag(type));
1030 
1031   // nothing to copy
1032   if (array->length() == 0) {
1033     return;
1034   }
1035 
1036   // If the byte ordering is big endian then we can copy most types directly
1037   int length_in_bytes = array->length() * type2aelembytes(type);
1038   assert(length_in_bytes > 0, "nothing to copy");
1039 
1040   switch (type) {
1041     case T_INT : {
1042       if (Bytes::is_Java_byte_ordering_different()) {
1043         WRITE_ARRAY(array, int, u4);
1044       } else {
1045         writer->write_raw((void*)(array->int_at_addr(0)), length_in_bytes);
1046       }
1047       break;
1048     }
1049     case T_BYTE : {
1050       writer->write_raw((void*)(array->byte_at_addr(0)), length_in_bytes);
1051       break;
1052     }
1053     case T_CHAR : {
1054       if (Bytes::is_Java_byte_ordering_different()) {
1055         WRITE_ARRAY(array, char, u2);
1056       } else {
1057         writer->write_raw((void*)(array->char_at_addr(0)), length_in_bytes);
1058       }
1059       break;
1060     }
1061     case T_SHORT : {
1062       if (Bytes::is_Java_byte_ordering_different()) {
1063         WRITE_ARRAY(array, short, u2);
1064       } else {
1065         writer->write_raw((void*)(array->short_at_addr(0)), length_in_bytes);
1066       }
1067       break;
1068     }
1069     case T_BOOLEAN : {
1070       if (Bytes::is_Java_byte_ordering_different()) {
1071         WRITE_ARRAY(array, bool, u1);
1072       } else {
1073         writer->write_raw((void*)(array->bool_at_addr(0)), length_in_bytes);
1074       }
1075       break;
1076     }
1077     case T_LONG : {
1078       if (Bytes::is_Java_byte_ordering_different()) {
1079         WRITE_ARRAY(array, long, u8);
1080       } else {
1081         writer->write_raw((void*)(array->long_at_addr(0)), length_in_bytes);
1082       }
1083       break;
1084     }
1085 
1086     // handle float/doubles in a special value to ensure than NaNs are
1087     // written correctly. TO DO: Check if we can avoid this on processors that
1088     // use IEEE 754.
1089 
1090     case T_FLOAT : {
1091       for (int i=0; i<array->length(); i++) {
1092         dump_float( writer, array->float_at(i) );
1093       }
1094       break;
1095     }
1096     case T_DOUBLE : {
1097       for (int i=0; i<array->length(); i++) {
1098         dump_double( writer, array->double_at(i) );
1099       }
1100       break;
1101     }
1102     default : ShouldNotReachHere();
1103   }
1104 }
1105 
1106 // create a HPROF_FRAME record of the given Method* and bci
1107 void DumperSupport::dump_stack_frame(DumpWriter* writer,
1108                                      int frame_serial_num,
1109                                      int class_serial_num,
1110                                      Method* m,
1111                                      int bci) {
1112   int line_number;
1113   if (m->is_native()) {
1114     line_number = -3;  // native frame
1115   } else {
1116     line_number = m->line_number_from_bci(bci);
1117   }
1118 
1119   write_header(writer, HPROF_FRAME, 4*oopSize + 2*sizeof(u4));
1120   writer->write_id(frame_serial_num);               // frame serial number
1121   writer->write_symbolID(m->name());                // method's name
1122   writer->write_symbolID(m->signature());           // method's signature
1123 
1124   assert(m->method_holder()->oop_is_instance(), "not InstanceKlass");
1125   writer->write_symbolID(m->method_holder()->source_file_name());  // source file name
1126   writer->write_u4(class_serial_num);               // class serial number
1127   writer->write_u4((u4) line_number);               // line number
1128 }
1129 
1130 
1131 // Support class used to generate HPROF_UTF8 records from the entries in the
1132 // SymbolTable.
1133 
1134 class SymbolTableDumper : public SymbolClosure {
1135  private:
1136   DumpWriter* _writer;
1137   DumpWriter* writer() const                { return _writer; }
1138  public:
1139   SymbolTableDumper(DumpWriter* writer)     { _writer = writer; }
1140   void do_symbol(Symbol** p);
1141 };
1142 
1143 void SymbolTableDumper::do_symbol(Symbol** p) {
1144   ResourceMark rm;
1145   Symbol* sym = load_symbol(p);
1146   int len = sym->utf8_length();
1147   if (len > 0) {
1148     char* s = sym->as_utf8();
1149     DumperSupport::write_header(writer(), HPROF_UTF8, oopSize + len);
1150     writer()->write_symbolID(sym);
1151     writer()->write_raw(s, len);
1152   }
1153 }
1154 
1155 // Support class used to generate HPROF_GC_ROOT_JNI_LOCAL records
1156 
1157 class JNILocalsDumper : public OopClosure {
1158  private:
1159   DumpWriter* _writer;
1160   u4 _thread_serial_num;
1161   int _frame_num;
1162   DumpWriter* writer() const                { return _writer; }
1163  public:
1164   JNILocalsDumper(DumpWriter* writer, u4 thread_serial_num) {
1165     _writer = writer;
1166     _thread_serial_num = thread_serial_num;
1167     _frame_num = -1;  // default - empty stack
1168   }
1169   void set_frame_number(int n) { _frame_num = n; }
1170   void do_oop(oop* obj_p);
1171   void do_oop(narrowOop* obj_p) { ShouldNotReachHere(); }
1172 };
1173 
1174 
1175 void JNILocalsDumper::do_oop(oop* obj_p) {
1176   // ignore null or deleted handles
1177   oop o = *obj_p;
1178   if (o != NULL && o != JNIHandles::deleted_handle()) {
1179     writer()->write_u1(HPROF_GC_ROOT_JNI_LOCAL);
1180     writer()->write_objectID(o);
1181     writer()->write_u4(_thread_serial_num);
1182     writer()->write_u4((u4)_frame_num);
1183   }
1184 }
1185 
1186 
1187 // Support class used to generate HPROF_GC_ROOT_JNI_GLOBAL records
1188 
1189 class JNIGlobalsDumper : public OopClosure {
1190  private:
1191   DumpWriter* _writer;
1192   DumpWriter* writer() const                { return _writer; }
1193 
1194  public:
1195   JNIGlobalsDumper(DumpWriter* writer) {
1196     _writer = writer;
1197   }
1198   void do_oop(oop* obj_p);
1199   void do_oop(narrowOop* obj_p) { ShouldNotReachHere(); }
1200 };
1201 
1202 void JNIGlobalsDumper::do_oop(oop* obj_p) {
1203   oop o = *obj_p;
1204 
1205   // ignore these
1206   if (o == NULL || o == JNIHandles::deleted_handle()) return;
1207 
1208   // we ignore global ref to symbols and other internal objects
1209   if (o->is_instance() || o->is_objArray() || o->is_typeArray()) {
1210     writer()->write_u1(HPROF_GC_ROOT_JNI_GLOBAL);
1211     writer()->write_objectID(o);
1212     writer()->write_objectID((oopDesc*)obj_p);      // global ref ID
1213   }
1214 };
1215 
1216 
1217 // Support class used to generate HPROF_GC_ROOT_MONITOR_USED records
1218 
1219 class MonitorUsedDumper : public OopClosure {
1220  private:
1221   DumpWriter* _writer;
1222   DumpWriter* writer() const                { return _writer; }
1223  public:
1224   MonitorUsedDumper(DumpWriter* writer) {
1225     _writer = writer;
1226   }
1227   void do_oop(oop* obj_p) {
1228     writer()->write_u1(HPROF_GC_ROOT_MONITOR_USED);
1229     writer()->write_objectID(*obj_p);
1230   }
1231   void do_oop(narrowOop* obj_p) { ShouldNotReachHere(); }
1232 };
1233 
1234 
1235 // Support class used to generate HPROF_GC_ROOT_STICKY_CLASS records
1236 
1237 class StickyClassDumper : public KlassClosure {
1238  private:
1239   DumpWriter* _writer;
1240   DumpWriter* writer() const                { return _writer; }
1241  public:
1242   StickyClassDumper(DumpWriter* writer) {
1243     _writer = writer;
1244   }
1245   void do_klass(Klass* k) {
1246     if (k->oop_is_instance()) {
1247       InstanceKlass* ik = InstanceKlass::cast(k);
1248         writer()->write_u1(HPROF_GC_ROOT_STICKY_CLASS);
1249         writer()->write_classID(ik);
1250       }
1251     }
1252 };
1253 
1254 
1255 class VM_HeapDumper;
1256 
1257 // Support class using when iterating over the heap.
1258 
1259 class HeapObjectDumper : public ObjectClosure {
1260  private:
1261   VM_HeapDumper* _dumper;
1262   DumpWriter* _writer;
1263 
1264   VM_HeapDumper* dumper()               { return _dumper; }
1265   DumpWriter* writer()                  { return _writer; }
1266 
1267   // used to indicate that a record has been writen
1268   void mark_end_of_record();
1269 
1270  public:
1271   HeapObjectDumper(VM_HeapDumper* dumper, DumpWriter* writer) {
1272     _dumper = dumper;
1273     _writer = writer;
1274   }
1275 
1276   // called for each object in the heap
1277   void do_object(oop o);
1278 };
1279 
1280 void HeapObjectDumper::do_object(oop o) {
1281   // hide the sentinel for deleted handles
1282   if (o == JNIHandles::deleted_handle()) return;
1283 
1284   // skip classes as these emitted as HPROF_GC_CLASS_DUMP records
1285   if (o->klass() == SystemDictionary::Class_klass()) {
1286     if (!java_lang_Class::is_primitive(o)) {
1287       return;
1288     }
1289   }
1290 
1291   // create a HPROF_GC_INSTANCE record for each object
1292   if (o->is_instance()) {
1293     DumperSupport::dump_instance(writer(), o);
1294     mark_end_of_record();
1295   } else {
1296     // create a HPROF_GC_OBJ_ARRAY_DUMP record for each object array
1297     if (o->is_objArray()) {
1298       DumperSupport::dump_object_array(writer(), objArrayOop(o));
1299       mark_end_of_record();
1300     } else {
1301       // create a HPROF_GC_PRIM_ARRAY_DUMP record for each type array
1302       if (o->is_typeArray()) {
1303         DumperSupport::dump_prim_array(writer(), typeArrayOop(o));
1304         mark_end_of_record();
1305       }
1306     }
1307   }
1308 }
1309 
1310 // The VM operation that performs the heap dump
1311 class VM_HeapDumper : public VM_GC_Operation {
1312  private:
1313   static VM_HeapDumper* _global_dumper;
1314   static DumpWriter*    _global_writer;
1315   DumpWriter*           _local_writer;
1316   JavaThread*           _oome_thread;
1317   Method*               _oome_constructor;
1318   bool _gc_before_heap_dump;
1319   bool _is_segmented_dump;
1320   jlong _dump_start;
1321   GrowableArray<Klass*>* _klass_map;
1322   ThreadStackTrace** _stack_traces;
1323   int _num_threads;
1324 
1325   // accessors and setters
1326   static VM_HeapDumper* dumper()         {  assert(_global_dumper != NULL, "Error"); return _global_dumper; }
1327   static DumpWriter* writer()            {  assert(_global_writer != NULL, "Error"); return _global_writer; }
1328   void set_global_dumper() {
1329     assert(_global_dumper == NULL, "Error");
1330     _global_dumper = this;
1331   }
1332   void set_global_writer() {
1333     assert(_global_writer == NULL, "Error");
1334     _global_writer = _local_writer;
1335   }
1336   void clear_global_dumper() { _global_dumper = NULL; }
1337   void clear_global_writer() { _global_writer = NULL; }
1338 
1339   bool is_segmented_dump() const                { return _is_segmented_dump; }
1340   void set_segmented_dump()                     { _is_segmented_dump = true; }
1341   jlong dump_start() const                      { return _dump_start; }
1342   void set_dump_start(jlong pos);
1343 
1344   bool skip_operation() const;
1345 
1346   // writes a HPROF_LOAD_CLASS record
1347   static void do_load_class(Klass* k);
1348 
1349   // writes a HPROF_GC_CLASS_DUMP record for the given class
1350   // (and each array class too)
1351   static void do_class_dump(Klass* k);
1352 
1353   // writes a HPROF_GC_CLASS_DUMP records for a given basic type
1354   // array (and each multi-dimensional array too)
1355   static void do_basic_type_array_class_dump(Klass* k);
1356 
1357   // HPROF_GC_ROOT_THREAD_OBJ records
1358   int do_thread(JavaThread* thread, u4 thread_serial_num);
1359   void do_threads();
1360 
1361   void add_class_serial_number(Klass* k, int serial_num) {
1362     _klass_map->at_put_grow(serial_num, k);
1363   }
1364 
1365   // HPROF_TRACE and HPROF_FRAME records
1366   void dump_stack_traces();
1367 
1368   // writes a HPROF_HEAP_DUMP or HPROF_HEAP_DUMP_SEGMENT record
1369   void write_dump_header();
1370 
1371   // fixes up the length of the current dump record
1372   void write_current_dump_record_length();
1373 
1374   // fixes up the current dump record )and writes HPROF_HEAP_DUMP_END
1375   // record in the case of a segmented heap dump)
1376   void end_of_dump();
1377 
1378  public:
1379   VM_HeapDumper(DumpWriter* writer, bool gc_before_heap_dump, bool oome) :
1380     VM_GC_Operation(0 /* total collections,      dummy, ignored */,
1381                     GCCause::_heap_dump /* GC Cause */,
1382                     0 /* total full collections, dummy, ignored */,
1383                     gc_before_heap_dump) {
1384     _local_writer = writer;
1385     _gc_before_heap_dump = gc_before_heap_dump;
1386     _is_segmented_dump = false;
1387     _dump_start = (jlong)-1;
1388     _klass_map = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<Klass*>(INITIAL_CLASS_COUNT, true);
1389     _stack_traces = NULL;
1390     _num_threads = 0;
1391     if (oome) {
1392       assert(!Thread::current()->is_VM_thread(), "Dump from OutOfMemoryError cannot be called by the VMThread");
1393       // get OutOfMemoryError zero-parameter constructor
1394       InstanceKlass* oome_ik = InstanceKlass::cast(SystemDictionary::OutOfMemoryError_klass());
1395       _oome_constructor = oome_ik->find_method(vmSymbols::object_initializer_name(),
1396                                                           vmSymbols::void_method_signature());
1397       // get thread throwing OOME when generating the heap dump at OOME
1398       _oome_thread = JavaThread::current();
1399     } else {
1400       _oome_thread = NULL;
1401       _oome_constructor = NULL;
1402     }
1403   }
1404   ~VM_HeapDumper() {
1405     if (_stack_traces != NULL) {
1406       for (int i=0; i < _num_threads; i++) {
1407         delete _stack_traces[i];
1408       }
1409       FREE_C_HEAP_ARRAY(ThreadStackTrace*, _stack_traces);
1410     }
1411     delete _klass_map;
1412   }
1413 
1414   VMOp_Type type() const { return VMOp_HeapDumper; }
1415   // used to mark sub-record boundary
1416   void check_segment_length();
1417   void doit();
1418 };
1419 
1420 VM_HeapDumper* VM_HeapDumper::_global_dumper = NULL;
1421 DumpWriter*    VM_HeapDumper::_global_writer = NULL;
1422 
1423 bool VM_HeapDumper::skip_operation() const {
1424   return false;
1425 }
1426 
1427 // sets the dump starting position
1428 void VM_HeapDumper::set_dump_start(jlong pos) {
1429   _dump_start = pos;
1430 }
1431 
1432  // writes a HPROF_HEAP_DUMP or HPROF_HEAP_DUMP_SEGMENT record
1433 void VM_HeapDumper::write_dump_header() {
1434   if (writer()->is_open()) {
1435     if (is_segmented_dump()) {
1436       writer()->write_u1(HPROF_HEAP_DUMP_SEGMENT);
1437     } else {
1438       writer()->write_u1(HPROF_HEAP_DUMP);
1439     }
1440     writer()->write_u4(0); // current ticks
1441 
1442     // record the starting position for the dump (its length will be fixed up later)
1443     set_dump_start(writer()->current_offset());
1444     writer()->write_u4(0);
1445   }
1446 }
1447 
1448 // fixes up the length of the current dump record
1449 void VM_HeapDumper::write_current_dump_record_length() {
1450   if (writer()->is_open()) {
1451     assert(dump_start() >= 0, "no dump start recorded");
1452 
1453     // calculate the size of the dump record
1454     jlong dump_end = writer()->current_offset();
1455     jlong dump_len = (dump_end - dump_start() - 4);
1456 
1457     // record length must fit in a u4
1458     if (dump_len > (jlong)(4L*(jlong)G)) {
1459       warning("record is too large");
1460     }
1461 
1462     // seek to the dump start and fix-up the length
1463     writer()->seek_to_offset(dump_start());
1464     writer()->write_u4((u4)dump_len);
1465 
1466     // adjust the total size written to keep the bytes written correct.
1467     writer()->adjust_bytes_written(-((long) sizeof(u4)));
1468 
1469     // seek to dump end so we can continue
1470     writer()->seek_to_offset(dump_end);
1471 
1472     // no current dump record
1473     set_dump_start((jlong)-1);
1474   }
1475 }
1476 
1477 // used on a sub-record boundary to check if we need to start a
1478 // new segment.
1479 void VM_HeapDumper::check_segment_length() {
1480   if (writer()->is_open()) {
1481     if (is_segmented_dump()) {
1482       // don't use current_offset that would be too expensive on a per record basis
1483       jlong dump_end = writer()->bytes_written() + writer()->bytes_unwritten();
1484       assert(dump_end == writer()->current_offset(), "checking");
1485       jlong dump_len = (dump_end - dump_start() - 4);
1486       assert(dump_len >= 0 && dump_len <= max_juint, "bad dump length");
1487 
1488       if (dump_len > (jlong)HeapDumpSegmentSize) {
1489         write_current_dump_record_length();
1490         write_dump_header();
1491       }
1492     }
1493   }
1494 }
1495 
1496 // fixes up the current dump record )and writes HPROF_HEAP_DUMP_END
1497 // record in the case of a segmented heap dump)
1498 void VM_HeapDumper::end_of_dump() {
1499   if (writer()->is_open()) {
1500     write_current_dump_record_length();
1501 
1502     // for segmented dump we write the end record
1503     if (is_segmented_dump()) {
1504       writer()->write_u1(HPROF_HEAP_DUMP_END);
1505       writer()->write_u4(0);
1506       writer()->write_u4(0);
1507     }
1508   }
1509 }
1510 
1511 // marks sub-record boundary
1512 void HeapObjectDumper::mark_end_of_record() {
1513   dumper()->check_segment_length();
1514 }
1515 
1516 // writes a HPROF_LOAD_CLASS record for the class (and each of its
1517 // array classes)
1518 void VM_HeapDumper::do_load_class(Klass* k) {
1519   static u4 class_serial_num = 0;
1520 
1521   // len of HPROF_LOAD_CLASS record
1522   u4 remaining = 2*oopSize + 2*sizeof(u4);
1523 
1524   // write a HPROF_LOAD_CLASS for the class and each array class
1525   do {
1526     DumperSupport::write_header(writer(), HPROF_LOAD_CLASS, remaining);
1527 
1528     // class serial number is just a number
1529     writer()->write_u4(++class_serial_num);
1530 
1531     // class ID
1532     Klass* klass = k;
1533     writer()->write_classID(klass);
1534 
1535     // add the Klass* and class serial number pair
1536     dumper()->add_class_serial_number(klass, class_serial_num);
1537 
1538     writer()->write_u4(STACK_TRACE_ID);
1539 
1540     // class name ID
1541     Symbol* name = klass->name();
1542     writer()->write_symbolID(name);
1543 
1544     // write a LOAD_CLASS record for the array type (if it exists)
1545     k = klass->array_klass_or_null();
1546   } while (k != NULL);
1547 }
1548 
1549 // writes a HPROF_GC_CLASS_DUMP record for the given class
1550 void VM_HeapDumper::do_class_dump(Klass* k) {
1551   if (k->oop_is_instance()) {
1552     DumperSupport::dump_class_and_array_classes(writer(), k);
1553   }
1554 }
1555 
1556 // writes a HPROF_GC_CLASS_DUMP records for a given basic type
1557 // array (and each multi-dimensional array too)
1558 void VM_HeapDumper::do_basic_type_array_class_dump(Klass* k) {
1559   DumperSupport::dump_basic_type_array_class(writer(), k);
1560 }
1561 
1562 // Walk the stack of the given thread.
1563 // Dumps a HPROF_GC_ROOT_JAVA_FRAME record for each local
1564 // Dumps a HPROF_GC_ROOT_JNI_LOCAL record for each JNI local
1565 //
1566 // It returns the number of Java frames in this thread stack
1567 int VM_HeapDumper::do_thread(JavaThread* java_thread, u4 thread_serial_num) {
1568   JNILocalsDumper blk(writer(), thread_serial_num);
1569 
1570   oop threadObj = java_thread->threadObj();
1571   assert(threadObj != NULL, "sanity check");
1572 
1573   int stack_depth = 0;
1574   if (java_thread->has_last_Java_frame()) {
1575 
1576     // vframes are resource allocated
1577     Thread* current_thread = Thread::current();
1578     ResourceMark rm(current_thread);
1579     HandleMark hm(current_thread);
1580 
1581     RegisterMap reg_map(java_thread);
1582     frame f = java_thread->last_frame();
1583     vframe* vf = vframe::new_vframe(&f, &reg_map, java_thread);
1584     frame* last_entry_frame = NULL;
1585     int extra_frames = 0;
1586 
1587     if (java_thread == _oome_thread && _oome_constructor != NULL) {
1588       extra_frames++;
1589     }
1590     while (vf != NULL) {
1591       blk.set_frame_number(stack_depth);
1592       if (vf->is_java_frame()) {
1593 
1594         // java frame (interpreted, compiled, ...)
1595         javaVFrame *jvf = javaVFrame::cast(vf);
1596         if (!(jvf->method()->is_native())) {
1597           StackValueCollection* locals = jvf->locals();
1598           for (int slot=0; slot<locals->size(); slot++) {
1599             if (locals->at(slot)->type() == T_OBJECT) {
1600               oop o = locals->obj_at(slot)();
1601 
1602               if (o != NULL) {
1603                 writer()->write_u1(HPROF_GC_ROOT_JAVA_FRAME);
1604                 writer()->write_objectID(o);
1605                 writer()->write_u4(thread_serial_num);
1606                 writer()->write_u4((u4) (stack_depth + extra_frames));
1607               }
1608             }
1609           }
1610           StackValueCollection *exprs = jvf->expressions();
1611           for(int index = 0; index < exprs->size(); index++) {
1612             if (exprs->at(index)->type() == T_OBJECT) {
1613                oop o = exprs->obj_at(index)();
1614                if (o != NULL) {
1615                  writer()->write_u1(HPROF_GC_ROOT_JAVA_FRAME);
1616                  writer()->write_objectID(o);
1617                  writer()->write_u4(thread_serial_num);
1618                  writer()->write_u4((u4) (stack_depth + extra_frames));
1619                }
1620              }
1621           }
1622         } else {
1623           // native frame
1624           if (stack_depth == 0) {
1625             // JNI locals for the top frame.
1626             java_thread->active_handles()->oops_do(&blk);
1627           } else {
1628             if (last_entry_frame != NULL) {
1629               // JNI locals for the entry frame
1630               assert(last_entry_frame->is_entry_frame(), "checking");
1631               last_entry_frame->entry_frame_call_wrapper()->handles()->oops_do(&blk);
1632             }
1633           }
1634         }
1635         // increment only for Java frames
1636         stack_depth++;
1637         last_entry_frame = NULL;
1638 
1639       } else {
1640         // externalVFrame - if it's an entry frame then report any JNI locals
1641         // as roots when we find the corresponding native javaVFrame
1642         frame* fr = vf->frame_pointer();
1643         assert(fr != NULL, "sanity check");
1644         if (fr->is_entry_frame()) {
1645           last_entry_frame = fr;
1646         }
1647       }
1648       vf = vf->sender();
1649     }
1650   } else {
1651     // no last java frame but there may be JNI locals
1652     java_thread->active_handles()->oops_do(&blk);
1653   }
1654   return stack_depth;
1655 }
1656 
1657 
1658 // write a HPROF_GC_ROOT_THREAD_OBJ record for each java thread. Then walk
1659 // the stack so that locals and JNI locals are dumped.
1660 void VM_HeapDumper::do_threads() {
1661   for (int i=0; i < _num_threads; i++) {
1662     JavaThread* thread = _stack_traces[i]->thread();
1663     oop threadObj = thread->threadObj();
1664     u4 thread_serial_num = i+1;
1665     u4 stack_serial_num = thread_serial_num + STACK_TRACE_ID;
1666     writer()->write_u1(HPROF_GC_ROOT_THREAD_OBJ);
1667     writer()->write_objectID(threadObj);
1668     writer()->write_u4(thread_serial_num);  // thread number
1669     writer()->write_u4(stack_serial_num);   // stack trace serial number
1670     int num_frames = do_thread(thread, thread_serial_num);
1671     assert(num_frames == _stack_traces[i]->get_stack_depth(),
1672            "total number of Java frames not matched");
1673   }
1674 }
1675 
1676 
1677 // The VM operation that dumps the heap. The dump consists of the following
1678 // records:
1679 //
1680 //  HPROF_HEADER
1681 //  [HPROF_UTF8]*
1682 //  [HPROF_LOAD_CLASS]*
1683 //  [[HPROF_FRAME]*|HPROF_TRACE]*
1684 //  [HPROF_GC_CLASS_DUMP]*
1685 //  HPROF_HEAP_DUMP
1686 //
1687 // The HPROF_TRACE records represent the stack traces where the heap dump
1688 // is generated and a "dummy trace" record which does not include
1689 // any frames. The dummy trace record is used to be referenced as the
1690 // unknown object alloc site.
1691 //
1692 // The HPROF_HEAP_DUMP record has a length following by sub-records. To allow
1693 // the heap dump be generated in a single pass we remember the position of
1694 // the dump length and fix it up after all sub-records have been written.
1695 // To generate the sub-records we iterate over the heap, writing
1696 // HPROF_GC_INSTANCE_DUMP, HPROF_GC_OBJ_ARRAY_DUMP, and HPROF_GC_PRIM_ARRAY_DUMP
1697 // records as we go. Once that is done we write records for some of the GC
1698 // roots.
1699 
1700 void VM_HeapDumper::doit() {
1701 
1702   HandleMark hm;
1703   CollectedHeap* ch = Universe::heap();
1704 
1705   ch->ensure_parsability(false); // must happen, even if collection does
1706                                  // not happen (e.g. due to GC_locker)
1707 
1708   if (_gc_before_heap_dump) {
1709     if (GC_locker::is_active()) {
1710       warning("GC locker is held; pre-heapdump GC was skipped");
1711     } else {
1712       ch->collect_as_vm_thread(GCCause::_heap_dump);
1713     }
1714   }
1715 
1716   // At this point we should be the only dumper active, so
1717   // the following should be safe.
1718   set_global_dumper();
1719   set_global_writer();
1720 
1721   // Write the file header - use 1.0.2 for large heaps, otherwise 1.0.1
1722   size_t used = ch->used();
1723   const char* header;
1724   if (used > SegmentedHeapDumpThreshold) {
1725     set_segmented_dump();
1726     header = "JAVA PROFILE 1.0.2";
1727   } else {
1728     header = "JAVA PROFILE 1.0.1";
1729   }
1730 
1731   // header is few bytes long - no chance to overflow int
1732   writer()->write_raw((void*)header, (int)strlen(header));
1733   writer()->write_u1(0); // terminator
1734   writer()->write_u4(oopSize);
1735   writer()->write_u8(os::javaTimeMillis());
1736 
1737   // HPROF_UTF8 records
1738   SymbolTableDumper sym_dumper(writer());
1739   SymbolTable::symbols_do(&sym_dumper);
1740 
1741   // write HPROF_LOAD_CLASS records
1742   ClassLoaderDataGraph::classes_do(&do_load_class);
1743   Universe::basic_type_classes_do(&do_load_class);
1744 
1745   // write HPROF_FRAME and HPROF_TRACE records
1746   // this must be called after _klass_map is built when iterating the classes above.
1747   dump_stack_traces();
1748 
1749   // write HPROF_HEAP_DUMP or HPROF_HEAP_DUMP_SEGMENT
1750   write_dump_header();
1751 
1752   // Writes HPROF_GC_CLASS_DUMP records
1753   ClassLoaderDataGraph::classes_do(&do_class_dump);
1754   Universe::basic_type_classes_do(&do_basic_type_array_class_dump);
1755   check_segment_length();
1756 
1757   // writes HPROF_GC_INSTANCE_DUMP records.
1758   // After each sub-record is written check_segment_length will be invoked. When
1759   // generated a segmented heap dump this allows us to check if the current
1760   // segment exceeds a threshold and if so, then a new segment is started.
1761   // The HPROF_GC_CLASS_DUMP and HPROF_GC_INSTANCE_DUMP are the vast bulk
1762   // of the heap dump.
1763   HeapObjectDumper obj_dumper(this, writer());
1764   Universe::heap()->safe_object_iterate(&obj_dumper);
1765 
1766   // HPROF_GC_ROOT_THREAD_OBJ + frames + jni locals
1767   do_threads();
1768   check_segment_length();
1769 
1770   // HPROF_GC_ROOT_MONITOR_USED
1771   MonitorUsedDumper mon_dumper(writer());
1772   ObjectSynchronizer::oops_do(&mon_dumper);
1773   check_segment_length();
1774 
1775   // HPROF_GC_ROOT_JNI_GLOBAL
1776   JNIGlobalsDumper jni_dumper(writer());
1777   JNIHandles::oops_do(&jni_dumper);
1778   check_segment_length();
1779 
1780   // HPROF_GC_ROOT_STICKY_CLASS
1781   StickyClassDumper class_dumper(writer());
1782   SystemDictionary::always_strong_classes_do(&class_dumper);
1783 
1784   // fixes up the length of the dump record. In the case of a segmented
1785   // heap then the HPROF_HEAP_DUMP_END record is also written.
1786   end_of_dump();
1787 
1788   // Now we clear the global variables, so that a future dumper might run.
1789   clear_global_dumper();
1790   clear_global_writer();
1791 }
1792 
1793 void VM_HeapDumper::dump_stack_traces() {
1794   // write a HPROF_TRACE record without any frames to be referenced as object alloc sites
1795   DumperSupport::write_header(writer(), HPROF_TRACE, 3*sizeof(u4));
1796   writer()->write_u4((u4) STACK_TRACE_ID);
1797   writer()->write_u4(0);                    // thread number
1798   writer()->write_u4(0);                    // frame count
1799 
1800   _stack_traces = NEW_C_HEAP_ARRAY(ThreadStackTrace*, Threads::number_of_threads(), mtInternal);
1801   int frame_serial_num = 0;
1802   for (JavaThread* thread = Threads::first(); thread != NULL ; thread = thread->next()) {
1803     oop threadObj = thread->threadObj();
1804     if (threadObj != NULL && !thread->is_exiting() && !thread->is_hidden_from_external_view()) {
1805       // dump thread stack trace
1806       ThreadStackTrace* stack_trace = new ThreadStackTrace(thread, false);
1807       stack_trace->dump_stack_at_safepoint(-1);
1808       _stack_traces[_num_threads++] = stack_trace;
1809 
1810       // write HPROF_FRAME records for this thread's stack trace
1811       int depth = stack_trace->get_stack_depth();
1812       int thread_frame_start = frame_serial_num;
1813       int extra_frames = 0;
1814       // write fake frame that makes it look like the thread, which caused OOME,
1815       // is in the OutOfMemoryError zero-parameter constructor
1816       if (thread == _oome_thread && _oome_constructor != NULL) {
1817         int oome_serial_num = _klass_map->find(_oome_constructor->method_holder());
1818         // the class serial number starts from 1
1819         assert(oome_serial_num > 0, "OutOfMemoryError class not found");
1820         DumperSupport::dump_stack_frame(writer(), ++frame_serial_num, oome_serial_num,
1821                                         _oome_constructor, 0);
1822         extra_frames++;
1823       }
1824       for (int j=0; j < depth; j++) {
1825         StackFrameInfo* frame = stack_trace->stack_frame_at(j);
1826         Method* m = frame->method();
1827         int class_serial_num = _klass_map->find(m->method_holder());
1828         // the class serial number starts from 1
1829         assert(class_serial_num > 0, "class not found");
1830         DumperSupport::dump_stack_frame(writer(), ++frame_serial_num, class_serial_num, m, frame->bci());
1831       }
1832       depth += extra_frames;
1833 
1834       // write HPROF_TRACE record for one thread
1835       DumperSupport::write_header(writer(), HPROF_TRACE, 3*sizeof(u4) + depth*oopSize);
1836       int stack_serial_num = _num_threads + STACK_TRACE_ID;
1837       writer()->write_u4(stack_serial_num);      // stack trace serial number
1838       writer()->write_u4((u4) _num_threads);     // thread serial number
1839       writer()->write_u4(depth);                 // frame count
1840       for (int j=1; j <= depth; j++) {
1841         writer()->write_id(thread_frame_start + j);
1842       }
1843     }
1844   }
1845 }
1846 
1847 // dump the heap to given path.
1848 PRAGMA_FORMAT_NONLITERAL_IGNORED_EXTERNAL
1849 int HeapDumper::dump(const char* path) {
1850   assert(path != NULL && strlen(path) > 0, "path missing");
1851 
1852   // print message in interactive case
1853   if (print_to_tty()) {
1854     tty->print_cr("Dumping heap to %s ...", path);
1855     timer()->start();
1856   }
1857 
1858   // create the dump writer. If the file can be opened then bail
1859   DumpWriter writer(path);
1860   if (!writer.is_open()) {
1861     set_error(writer.error());
1862     if (print_to_tty()) {
1863       tty->print_cr("Unable to create %s: %s", path,
1864         (error() != NULL) ? error() : "reason unknown");
1865     }
1866     return -1;
1867   }
1868 
1869   // generate the dump
1870   VM_HeapDumper dumper(&writer, _gc_before_heap_dump, _oome);
1871   if (Thread::current()->is_VM_thread()) {
1872     assert(SafepointSynchronize::is_at_safepoint(), "Expected to be called at a safepoint");
1873     dumper.doit();
1874   } else {
1875     VMThread::execute(&dumper);
1876   }
1877 
1878   // close dump file and record any error that the writer may have encountered
1879   writer.close();
1880   set_error(writer.error());
1881 
1882   // print message in interactive case
1883   if (print_to_tty()) {
1884     timer()->stop();
1885     if (error() == NULL) {
1886       char msg[256];
1887       sprintf(msg, "Heap dump file created [%s bytes in %3.3f secs]",
1888         JLONG_FORMAT, timer()->seconds());
1889 PRAGMA_DIAG_PUSH
1890 PRAGMA_FORMAT_NONLITERAL_IGNORED_INTERNAL
1891       tty->print_cr(msg, writer.bytes_written());
1892 PRAGMA_DIAG_POP
1893     } else {
1894       tty->print_cr("Dump file is incomplete: %s", writer.error());
1895     }
1896   }
1897 
1898   return (writer.error() == NULL) ? 0 : -1;
1899 }
1900 
1901 // stop timer (if still active), and free any error string we might be holding
1902 HeapDumper::~HeapDumper() {
1903   if (timer()->is_active()) {
1904     timer()->stop();
1905   }
1906   set_error(NULL);
1907 }
1908 
1909 
1910 // returns the error string (resource allocated), or NULL
1911 char* HeapDumper::error_as_C_string() const {
1912   if (error() != NULL) {
1913     char* str = NEW_RESOURCE_ARRAY(char, strlen(error())+1);
1914     strcpy(str, error());
1915     return str;
1916   } else {
1917     return NULL;
1918   }
1919 }
1920 
1921 // set the error string
1922 void HeapDumper::set_error(char* error) {
1923   if (_error != NULL) {
1924     os::free(_error);
1925   }
1926   if (error == NULL) {
1927     _error = NULL;
1928   } else {
1929     _error = os::strdup(error);
1930     assert(_error != NULL, "allocation failure");
1931   }
1932 }
1933 
1934 // Called by out-of-memory error reporting by a single Java thread
1935 // outside of a JVM safepoint
1936 void HeapDumper::dump_heap_from_oome() {
1937   HeapDumper::dump_heap(true);
1938 }
1939 
1940 // Called by error reporting by a single Java thread outside of a JVM safepoint,
1941 // or by heap dumping by the VM thread during a (GC) safepoint. Thus, these various
1942 // callers are strictly serialized and guaranteed not to interfere below. For more
1943 // general use, however, this method will need modification to prevent
1944 // inteference when updating the static variables base_path and dump_file_seq below.
1945 void HeapDumper::dump_heap() {
1946   HeapDumper::dump_heap(false);
1947 }
1948 
1949 void HeapDumper::dump_heap(bool oome) {
1950   static char base_path[JVM_MAXPATHLEN] = {'\0'};
1951   static uint dump_file_seq = 0;
1952   char* my_path;
1953   const int max_digit_chars = 20;
1954 
1955   const char* dump_file_name = "java_pid";
1956   const char* dump_file_ext  = ".hprof";
1957 
1958   // The dump file defaults to java_pid<pid>.hprof in the current working
1959   // directory. HeapDumpPath=<file> can be used to specify an alternative
1960   // dump file name or a directory where dump file is created.
1961   if (dump_file_seq == 0) { // first time in, we initialize base_path
1962     // Calculate potentially longest base path and check if we have enough
1963     // allocated statically.
1964     const size_t total_length =
1965                       (HeapDumpPath == NULL ? 0 : strlen(HeapDumpPath)) +
1966                       strlen(os::file_separator()) + max_digit_chars +
1967                       strlen(dump_file_name) + strlen(dump_file_ext) + 1;
1968     if (total_length > sizeof(base_path)) {
1969       warning("Cannot create heap dump file.  HeapDumpPath is too long.");
1970       return;
1971     }
1972 
1973     bool use_default_filename = true;
1974     if (HeapDumpPath == NULL || HeapDumpPath[0] == '\0') {
1975       // HeapDumpPath=<file> not specified
1976     } else {
1977       strncpy(base_path, HeapDumpPath, sizeof(base_path));
1978       // check if the path is a directory (must exist)
1979       DIR* dir = os::opendir(base_path);
1980       if (dir == NULL) {
1981         use_default_filename = false;
1982       } else {
1983         // HeapDumpPath specified a directory. We append a file separator
1984         // (if needed).
1985         os::closedir(dir);
1986         size_t fs_len = strlen(os::file_separator());
1987         if (strlen(base_path) >= fs_len) {
1988           char* end = base_path;
1989           end += (strlen(base_path) - fs_len);
1990           if (strcmp(end, os::file_separator()) != 0) {
1991             strcat(base_path, os::file_separator());
1992           }
1993         }
1994       }
1995     }
1996     // If HeapDumpPath wasn't a file name then we append the default name
1997     if (use_default_filename) {
1998       const size_t dlen = strlen(base_path);  // if heap dump dir specified
1999       jio_snprintf(&base_path[dlen], sizeof(base_path)-dlen, "%s%d%s",
2000                    dump_file_name, os::current_process_id(), dump_file_ext);
2001     }
2002     const size_t len = strlen(base_path) + 1;
2003     my_path = (char*)os::malloc(len, mtInternal);
2004     if (my_path == NULL) {
2005       warning("Cannot create heap dump file.  Out of system memory.");
2006       return;
2007     }
2008     strncpy(my_path, base_path, len);
2009   } else {
2010     // Append a sequence number id for dumps following the first
2011     const size_t len = strlen(base_path) + max_digit_chars + 2; // for '.' and \0
2012     my_path = (char*)os::malloc(len, mtInternal);
2013     if (my_path == NULL) {
2014       warning("Cannot create heap dump file.  Out of system memory.");
2015       return;
2016     }
2017     jio_snprintf(my_path, len, "%s.%d", base_path, dump_file_seq);
2018   }
2019   dump_file_seq++;   // increment seq number for next time we dump
2020 
2021   HeapDumper dumper(false /* no GC before heap dump */,
2022                     true  /* send to tty */,
2023                     oome  /* pass along out-of-memory-error flag */);
2024   dumper.dump(my_path);
2025   os::free(my_path);
2026 }
--- EOF ---