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