vmError.cpp revision 10627:1537c752a7f5
1238106Sdes/*
2238106Sdes * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
3238106Sdes * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4238106Sdes *
5238106Sdes * This code is free software; you can redistribute it and/or modify it
6238106Sdes * under the terms of the GNU General Public License version 2 only, as
7238106Sdes * published by the Free Software Foundation.
8238106Sdes *
9238106Sdes * This code is distributed in the hope that it will be useful, but WITHOUT
10238106Sdes * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11238106Sdes * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12238106Sdes * version 2 for more details (a copy is included in the LICENSE file that
13238106Sdes * accompanied this code).
14238106Sdes *
15238106Sdes * You should have received a copy of the GNU General Public License version
16238106Sdes * 2 along with this work; if not, write to the Free Software Foundation,
17238106Sdes * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18238106Sdes *
19238106Sdes * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20238106Sdes * or visit www.oracle.com if you need additional information or have any
21238106Sdes * questions.
22238106Sdes *
23238106Sdes */
24238106Sdes
25238106Sdes#include <fcntl.h>
26238106Sdes#include "precompiled.hpp"
27238106Sdes#include "code/codeCache.hpp"
28238106Sdes#include "compiler/compileBroker.hpp"
29238106Sdes#include "compiler/disassembler.hpp"
30238106Sdes#include "gc/shared/collectedHeap.hpp"
31238106Sdes#include "prims/whitebox.hpp"
32238106Sdes#include "runtime/arguments.hpp"
33238106Sdes#include "runtime/atomic.inline.hpp"
34238106Sdes#include "runtime/frame.inline.hpp"
35238106Sdes#include "runtime/init.hpp"
36238106Sdes#include "runtime/os.hpp"
37238106Sdes#include "runtime/thread.inline.hpp"
38238106Sdes#include "runtime/vmThread.hpp"
39238106Sdes#include "runtime/vm_operations.hpp"
40238106Sdes#include "services/memTracker.hpp"
41238106Sdes#include "utilities/debug.hpp"
42238106Sdes#include "utilities/decoder.hpp"
43238106Sdes#include "utilities/defaultStream.hpp"
44238106Sdes#include "utilities/errorReporter.hpp"
45238106Sdes#include "utilities/events.hpp"
46238106Sdes#include "utilities/top.hpp"
47238106Sdes#include "utilities/vmError.hpp"
48238106Sdes
49238106Sdes// List of environment variables that should be reported in error log file.
50238106Sdesconst char *env_list[] = {
51238106Sdes  // All platforms
52238106Sdes  "JAVA_HOME", "JRE_HOME", "JAVA_TOOL_OPTIONS", "_JAVA_OPTIONS", "CLASSPATH",
53238106Sdes  "JAVA_COMPILER", "PATH", "USERNAME",
54238106Sdes
55238106Sdes  // Env variables that are defined on Solaris/Linux/BSD
56238106Sdes  "LD_LIBRARY_PATH", "LD_PRELOAD", "SHELL", "DISPLAY",
57238106Sdes  "HOSTTYPE", "OSTYPE", "ARCH", "MACHTYPE",
58238106Sdes
59238106Sdes  // defined on Linux
60238106Sdes  "LD_ASSUME_KERNEL", "_JAVA_SR_SIGNUM",
61238106Sdes
62238106Sdes  // defined on Darwin
63238106Sdes  "DYLD_LIBRARY_PATH", "DYLD_FALLBACK_LIBRARY_PATH",
64238106Sdes  "DYLD_FRAMEWORK_PATH", "DYLD_FALLBACK_FRAMEWORK_PATH",
65238106Sdes  "DYLD_INSERT_LIBRARIES",
66238106Sdes
67238106Sdes  // defined on Windows
68238106Sdes  "OS", "PROCESSOR_IDENTIFIER", "_ALT_JAVA_HOME_DIR",
69238106Sdes
70238106Sdes  (const char *)0
71238106Sdes};
72238106Sdes
73238106Sdes// A simple parser for -XX:OnError, usage:
74238106Sdes//  ptr = OnError;
75238106Sdes//  while ((cmd = next_OnError_command(buffer, sizeof(buffer), &ptr) != NULL)
76238106Sdes//     ... ...
77238106Sdesstatic char* next_OnError_command(char* buf, int buflen, const char** ptr) {
78238106Sdes  if (ptr == NULL || *ptr == NULL) return NULL;
79238106Sdes
80238106Sdes  const char* cmd = *ptr;
81238106Sdes
82238106Sdes  // skip leading blanks or ';'
83238106Sdes  while (*cmd == ' ' || *cmd == ';') cmd++;
84238106Sdes
85238106Sdes  if (*cmd == '\0') return NULL;
86238106Sdes
87238106Sdes  const char * cmdend = cmd;
88238106Sdes  while (*cmdend != '\0' && *cmdend != ';') cmdend++;
89238106Sdes
90238106Sdes  Arguments::copy_expand_pid(cmd, cmdend - cmd, buf, buflen);
91238106Sdes
92238106Sdes  *ptr = (*cmdend == '\0' ? cmdend : cmdend + 1);
93238106Sdes  return buf;
94238106Sdes}
95238106Sdes
96238106Sdesstatic void print_bug_submit_message(outputStream *out, Thread *thread) {
97238106Sdes  if (out == NULL) return;
98238106Sdes  out->print_raw_cr("# If you would like to submit a bug report, please visit:");
99238106Sdes  out->print_raw   ("#   ");
100238106Sdes  out->print_raw_cr(Arguments::java_vendor_url_bug());
101238106Sdes  // If the crash is in native code, encourage user to submit a bug to the
102238106Sdes  // provider of that code.
103238106Sdes  if (thread && thread->is_Java_thread() &&
104238106Sdes      !thread->is_hidden_from_external_view()) {
105238106Sdes    JavaThread* jt = (JavaThread*)thread;
106238106Sdes    if (jt->thread_state() == _thread_in_native) {
107238106Sdes      out->print_cr("# The crash happened outside the Java Virtual Machine in native code.\n# See problematic frame for where to report the bug.");
108238106Sdes    }
109238106Sdes  }
110238106Sdes  out->print_raw_cr("#");
111238106Sdes}
112238106Sdes
113238106Sdesbool VMError::coredump_status;
114238106Sdeschar VMError::coredump_message[O_BUFLEN];
115238106Sdes
116238106Sdesvoid VMError::record_coredump_status(const char* message, bool status) {
117238106Sdes  coredump_status = status;
118238106Sdes  strncpy(coredump_message, message, sizeof(coredump_message));
119238106Sdes  coredump_message[sizeof(coredump_message)-1] = 0;
120238106Sdes}
121238106Sdes
122238106Sdes// Return a string to describe the error
123238106Sdeschar* VMError::error_string(char* buf, int buflen) {
124238106Sdes  char signame_buf[64];
125238106Sdes  const char *signame = os::exception_name(_id, signame_buf, sizeof(signame_buf));
126238106Sdes
127238106Sdes  if (signame) {
128238106Sdes    jio_snprintf(buf, buflen,
129238106Sdes                 "%s (0x%x) at pc=" PTR_FORMAT ", pid=%d, tid=" UINTX_FORMAT,
130238106Sdes                 signame, _id, _pc,
131238106Sdes                 os::current_process_id(), os::current_thread_id());
132238106Sdes  } else if (_filename != NULL && _lineno > 0) {
133238106Sdes    // skip directory names
134238106Sdes    char separator = os::file_separator()[0];
135238106Sdes    const char *p = strrchr(_filename, separator);
136238106Sdes    int n = jio_snprintf(buf, buflen,
137238106Sdes                         "Internal Error at %s:%d, pid=%d, tid=" UINTX_FORMAT,
138238106Sdes                         p ? p + 1 : _filename, _lineno,
139238106Sdes                         os::current_process_id(), os::current_thread_id());
140238106Sdes    if (n >= 0 && n < buflen && _message) {
141238106Sdes      if (strlen(_detail_msg) > 0) {
142238106Sdes        jio_snprintf(buf + n, buflen - n, "%s%s: %s",
143238106Sdes        os::line_separator(), _message, _detail_msg);
144238106Sdes      } else {
145238106Sdes        jio_snprintf(buf + n, buflen - n, "%sError: %s",
146238106Sdes                     os::line_separator(), _message);
147238106Sdes      }
148238106Sdes    }
149238106Sdes  } else {
150238106Sdes    jio_snprintf(buf, buflen,
151238106Sdes                 "Internal Error (0x%x), pid=%d, tid=" UINTX_FORMAT,
152238106Sdes                 _id, os::current_process_id(), os::current_thread_id());
153238106Sdes  }
154238106Sdes
155238106Sdes  return buf;
156238106Sdes}
157238106Sdes
158238106Sdesvoid VMError::print_stack_trace(outputStream* st, JavaThread* jt,
159238106Sdes                                char* buf, int buflen, bool verbose) {
160238106Sdes#ifdef ZERO
161238106Sdes  if (jt->zero_stack()->sp() && jt->top_zero_frame()) {
162238106Sdes    // StackFrameStream uses the frame anchor, which may not have
163238106Sdes    // been set up.  This can be done at any time in Zero, however,
164238106Sdes    // so if it hasn't been set up then we just set it up now and
165238106Sdes    // clear it again when we're done.
166238106Sdes    bool has_last_Java_frame = jt->has_last_Java_frame();
167238106Sdes    if (!has_last_Java_frame)
168238106Sdes      jt->set_last_Java_frame();
169238106Sdes    st->print("Java frames:");
170238106Sdes
171238106Sdes    // If the top frame is a Shark frame and the frame anchor isn't
172238106Sdes    // set up then it's possible that the information in the frame
173238106Sdes    // is garbage: it could be from a previous decache, or it could
174238106Sdes    // simply have never been written.  So we print a warning...
175238106Sdes    StackFrameStream sfs(jt);
176238106Sdes    if (!has_last_Java_frame && !sfs.is_done()) {
177238106Sdes      if (sfs.current()->zeroframe()->is_shark_frame()) {
178238106Sdes        st->print(" (TOP FRAME MAY BE JUNK)");
179238106Sdes      }
180238106Sdes    }
181238106Sdes    st->cr();
182238106Sdes
183238106Sdes    // Print the frames
184238106Sdes    for(int i = 0; !sfs.is_done(); sfs.next(), i++) {
185238106Sdes      sfs.current()->zero_print_on_error(i, st, buf, buflen);
186238106Sdes      st->cr();
187238106Sdes    }
188238106Sdes
189238106Sdes    // Reset the frame anchor if necessary
190238106Sdes    if (!has_last_Java_frame)
191238106Sdes      jt->reset_last_Java_frame();
192238106Sdes  }
193238106Sdes#else
194238106Sdes  if (jt->has_last_Java_frame()) {
195238106Sdes    st->print_cr("Java frames: (J=compiled Java code, j=interpreted, Vv=VM code)");
196238106Sdes    for(StackFrameStream sfs(jt); !sfs.is_done(); sfs.next()) {
197238106Sdes      sfs.current()->print_on_error(st, buf, buflen, verbose);
198238106Sdes      st->cr();
199238106Sdes    }
200238106Sdes  }
201238106Sdes#endif // ZERO
202238106Sdes}
203238106Sdes
204238106Sdesstatic void print_oom_reasons(outputStream* st) {
205238106Sdes  st->print_cr("# Possible reasons:");
206238106Sdes  st->print_cr("#   The system is out of physical RAM or swap space");
207238106Sdes  st->print_cr("#   In 32 bit mode, the process size limit was hit");
208238106Sdes  st->print_cr("# Possible solutions:");
209238106Sdes  st->print_cr("#   Reduce memory load on the system");
210238106Sdes  st->print_cr("#   Increase physical memory or swap space");
211238106Sdes  st->print_cr("#   Check if swap backing store is full");
212238106Sdes  st->print_cr("#   Use 64 bit Java on a 64 bit OS");
213238106Sdes  st->print_cr("#   Decrease Java heap size (-Xmx/-Xms)");
214238106Sdes  st->print_cr("#   Decrease number of Java threads");
215238106Sdes  st->print_cr("#   Decrease Java thread stack sizes (-Xss)");
216238106Sdes  st->print_cr("#   Set larger code cache with -XX:ReservedCodeCacheSize=");
217238106Sdes  st->print_cr("# This output file may be truncated or incomplete.");
218238106Sdes}
219238106Sdes
220238106Sdesstatic const char* gc_mode() {
221238106Sdes  if (UseG1GC)            return "g1 gc";
222238106Sdes  if (UseParallelGC)      return "parallel gc";
223238106Sdes  if (UseConcMarkSweepGC) return "concurrent mark sweep gc";
224238106Sdes  if (UseSerialGC)        return "serial gc";
225238106Sdes  return "ERROR in GC mode";
226238106Sdes}
227238106Sdes
228238106Sdesstatic void report_vm_version(outputStream* st, char* buf, int buflen) {
229238106Sdes   // VM version
230238106Sdes   st->print_cr("#");
231238106Sdes   JDK_Version::current().to_string(buf, buflen);
232238106Sdes   const char* runtime_name = JDK_Version::runtime_name() != NULL ?
233238106Sdes                                JDK_Version::runtime_name() : "";
234238106Sdes   const char* runtime_version = JDK_Version::runtime_version() != NULL ?
235238106Sdes                                   JDK_Version::runtime_version() : "";
236238106Sdes   const char* jdk_debug_level = Abstract_VM_Version::printable_jdk_debug_level() != NULL ?
237238106Sdes                                   Abstract_VM_Version::printable_jdk_debug_level() : "";
238238106Sdes
239238106Sdes   st->print_cr("# JRE version: %s (%s) (%sbuild %s)", runtime_name, buf,
240238106Sdes                 jdk_debug_level, runtime_version);
241238106Sdes
242238106Sdes   // This is the long version with some default settings added
243238106Sdes   st->print_cr("# Java VM: %s (%s%s, %s%s%s%s%s, %s, %s)",
244238106Sdes                 Abstract_VM_Version::vm_name(),
245238106Sdes                 jdk_debug_level,
246238106Sdes                 Abstract_VM_Version::vm_release(),
247238106Sdes                 Abstract_VM_Version::vm_info_string(),
248238106Sdes                 TieredCompilation ? ", tiered" : "",
249238106Sdes#if INCLUDE_JVMCI
250238106Sdes                 EnableJVMCI ? ", jvmci" : "",
251238106Sdes                 UseJVMCICompiler ? ", jvmci compiler" : "",
252238106Sdes#else
253238106Sdes                 "", "",
254238106Sdes#endif
255238106Sdes                 UseCompressedOops ? ", compressed oops" : "",
256238106Sdes                 gc_mode(),
257238106Sdes                 Abstract_VM_Version::vm_platform_string()
258238106Sdes               );
259238106Sdes}
260238106Sdes
261238106Sdes// This is the main function to report a fatal error. Only one thread can
262238106Sdes// call this function, so we don't need to worry about MT-safety. But it's
263238106Sdes// possible that the error handler itself may crash or die on an internal
264238106Sdes// error, for example, when the stack/heap is badly damaged. We must be
265238106Sdes// able to handle recursive errors that happen inside error handler.
266238106Sdes//
267238106Sdes// Error reporting is done in several steps. If a crash or internal error
268238106Sdes// occurred when reporting an error, the nested signal/exception handler
269238106Sdes// can skip steps that are already (or partially) done. Error reporting will
270238106Sdes// continue from the next step. This allows us to retrieve and print
271238106Sdes// information that may be unsafe to get after a fatal error. If it happens,
272238106Sdes// you may find nested report_and_die() frames when you look at the stack
273238106Sdes// in a debugger.
274238106Sdes//
275238106Sdes// In general, a hang in error handler is much worse than a crash or internal
276238106Sdes// error, as it's harder to recover from a hang. Deadlock can happen if we
277238106Sdes// try to grab a lock that is already owned by current thread, or if the
278238106Sdes// owner is blocked forever (e.g. in os::infinite_sleep()). If possible, the
279238106Sdes// error handler and all the functions it called should avoid grabbing any
280238106Sdes// lock. An important thing to notice is that memory allocation needs a lock.
281238106Sdes//
282238106Sdes// We should avoid using large stack allocated buffers. Many errors happen
283238106Sdes// when stack space is already low. Making things even worse is that there
284238106Sdes// could be nested report_and_die() calls on stack (see above). Only one
285238106Sdes// thread can report error, so large buffers are statically allocated in data
286238106Sdes// segment.
287238106Sdes
288238106Sdesint          VMError::_current_step;
289238106Sdesconst char*  VMError::_current_step_info;
290238106Sdes
291238106Sdesvoid VMError::report(outputStream* st, bool _verbose) {
292238106Sdes
293238106Sdes# define BEGIN if (_current_step == 0) { _current_step = 1;
294238106Sdes# define STEP(n, s) } if (_current_step < n) { _current_step = n; _current_step_info = s;
295238106Sdes# define END }
296238106Sdes
297238106Sdes  // don't allocate large buffer on stack
298238106Sdes  static char buf[O_BUFLEN];
299238106Sdes
300238106Sdes  BEGIN
301238106Sdes
302238106Sdes  STEP(10, "(printing fatal error message)")
303238106Sdes
304238106Sdes    st->print_cr("#");
305238106Sdes    if (should_report_bug(_id)) {
306238106Sdes      st->print_cr("# A fatal error has been detected by the Java Runtime Environment:");
307238106Sdes    } else {
308238106Sdes      st->print_cr("# There is insufficient memory for the Java "
309238106Sdes                   "Runtime Environment to continue.");
310238106Sdes    }
311238106Sdes
312238106Sdes#ifndef PRODUCT
313238106Sdes  // Error handler self tests
314238106Sdes
315238106Sdes  // test secondary error handling. Test it twice, to test that resetting
316238106Sdes  // error handler after a secondary crash works.
317238106Sdes  STEP(20, "(test secondary crash 1)")
318238106Sdes    if (_verbose && TestCrashInErrorHandler != 0) {
319238106Sdes      st->print_cr("Will crash now (TestCrashInErrorHandler=" UINTX_FORMAT ")...",
320238106Sdes        TestCrashInErrorHandler);
321238106Sdes      controlled_crash(TestCrashInErrorHandler);
322238106Sdes    }
323238106Sdes
324238106Sdes  STEP(30, "(test secondary crash 2)")
325238106Sdes    if (_verbose && TestCrashInErrorHandler != 0) {
326238106Sdes      st->print_cr("Will crash now (TestCrashInErrorHandler=" UINTX_FORMAT ")...",
327238106Sdes        TestCrashInErrorHandler);
328238106Sdes      controlled_crash(TestCrashInErrorHandler);
329238106Sdes    }
330238106Sdes
331238106Sdes  STEP(40, "(test safefetch in error handler)")
332238106Sdes    // test whether it is safe to use SafeFetch32 in Crash Handler. Test twice
333238106Sdes    // to test that resetting the signal handler works correctly.
334238106Sdes    if (_verbose && TestSafeFetchInErrorHandler) {
335238106Sdes      st->print_cr("Will test SafeFetch...");
336238106Sdes      if (CanUseSafeFetch32()) {
337238106Sdes        int* const invalid_pointer = (int*) get_segfault_address();
338238106Sdes        const int x = 0x76543210;
339238106Sdes        int i1 = SafeFetch32(invalid_pointer, x);
340238106Sdes        int i2 = SafeFetch32(invalid_pointer, x);
341238106Sdes        if (i1 == x && i2 == x) {
342238106Sdes          st->print_cr("SafeFetch OK."); // Correctly deflected and returned default pattern
343238106Sdes        } else {
344238106Sdes          st->print_cr("??");
345238106Sdes        }
346238106Sdes      } else {
347238106Sdes        st->print_cr("not possible; skipped.");
348238106Sdes      }
349238106Sdes    }
350238106Sdes#endif // PRODUCT
351238106Sdes
352238106Sdes  STEP(50, "(printing type of error)")
353238106Sdes
354238106Sdes     switch(_id) {
355238106Sdes       case OOM_MALLOC_ERROR:
356238106Sdes       case OOM_MMAP_ERROR:
357238106Sdes         if (_size) {
358238106Sdes           st->print("# Native memory allocation ");
359238106Sdes           st->print((_id == (int)OOM_MALLOC_ERROR) ? "(malloc) failed to allocate " :
360238106Sdes                                                 "(mmap) failed to map ");
361238106Sdes           jio_snprintf(buf, sizeof(buf), SIZE_FORMAT, _size);
362238106Sdes           st->print("%s", buf);
363238106Sdes           st->print(" bytes");
364238106Sdes           if (strlen(_detail_msg) > 0) {
365238106Sdes             st->print(" for ");
366238106Sdes             st->print("%s", _detail_msg);
367238106Sdes           }
368238106Sdes           st->cr();
369238106Sdes         } else {
370238106Sdes           if (strlen(_detail_msg) > 0) {
371238106Sdes             st->print("# ");
372238106Sdes             st->print_cr("%s", _detail_msg);
373238106Sdes           }
374238106Sdes         }
375238106Sdes         // In error file give some solutions
376238106Sdes         if (_verbose) {
377238106Sdes           print_oom_reasons(st);
378238106Sdes         } else {
379238106Sdes           return;  // that's enough for the screen
380238106Sdes         }
381238106Sdes         break;
382238106Sdes       case INTERNAL_ERROR:
383238106Sdes       default:
384238106Sdes         break;
385238106Sdes     }
386238106Sdes
387238106Sdes  STEP(60, "(printing exception/signal name)")
388238106Sdes
389238106Sdes     st->print_cr("#");
390238106Sdes     st->print("#  ");
391238106Sdes     // Is it an OS exception/signal?
392238106Sdes     if (os::exception_name(_id, buf, sizeof(buf))) {
393238106Sdes       st->print("%s", buf);
394238106Sdes       st->print(" (0x%x)", _id);                // signal number
395238106Sdes       st->print(" at pc=" PTR_FORMAT, p2i(_pc));
396238106Sdes     } else {
397238106Sdes       if (should_report_bug(_id)) {
398238106Sdes         st->print("Internal Error");
399238106Sdes       } else {
400238106Sdes         st->print("Out of Memory Error");
401238106Sdes       }
402238106Sdes       if (_filename != NULL && _lineno > 0) {
403238106Sdes#ifdef PRODUCT
404238106Sdes         // In product mode chop off pathname?
405238106Sdes         char separator = os::file_separator()[0];
406238106Sdes         const char *p = strrchr(_filename, separator);
407238106Sdes         const char *file = p ? p+1 : _filename;
408238106Sdes#else
409238106Sdes         const char *file = _filename;
410238106Sdes#endif
411238106Sdes         st->print(" (%s:%d)", file, _lineno);
412238106Sdes       } else {
413238106Sdes         st->print(" (0x%x)", _id);
414238106Sdes       }
415238106Sdes     }
416238106Sdes
417238106Sdes  STEP(70, "(printing current thread and pid)")
418238106Sdes
419238106Sdes     // process id, thread id
420238106Sdes     st->print(", pid=%d", os::current_process_id());
421238106Sdes     st->print(", tid=" UINTX_FORMAT, os::current_thread_id());
422238106Sdes     st->cr();
423238106Sdes
424238106Sdes  STEP(80, "(printing error message)")
425238106Sdes
426238106Sdes     if (should_report_bug(_id)) {  // already printed the message.
427238106Sdes       // error message
428238106Sdes       if (strlen(_detail_msg) > 0) {
429238106Sdes         st->print_cr("#  %s: %s", _message ? _message : "Error", _detail_msg);
430238106Sdes       } else if (_message) {
431238106Sdes         st->print_cr("#  Error: %s", _message);
432238106Sdes       }
433238106Sdes     }
434238106Sdes
435238106Sdes  STEP(90, "(printing Java version string)")
436238106Sdes
437238106Sdes     report_vm_version(st, buf, sizeof(buf));
438238106Sdes
439238106Sdes  STEP(100, "(printing problematic frame)")
440238106Sdes
441238106Sdes     // Print current frame if we have a context (i.e. it's a crash)
442238106Sdes     if (_context) {
443238106Sdes       st->print_cr("# Problematic frame:");
444238106Sdes       st->print("# ");
445238106Sdes       frame fr = os::fetch_frame_from_context(_context);
446238106Sdes       fr.print_on_error(st, buf, sizeof(buf));
447238106Sdes       st->cr();
448238106Sdes       st->print_cr("#");
449238106Sdes     }
450238106Sdes
451238106Sdes  STEP(110, "(printing core file information)")
452238106Sdes    st->print("# ");
453238106Sdes    if (CreateCoredumpOnCrash) {
454238106Sdes      if (coredump_status) {
455238106Sdes        st->print("Core dump will be written. Default location: %s", coredump_message);
456238106Sdes      } else {
457238106Sdes        st->print("No core dump will be written. %s", coredump_message);
458238106Sdes      }
459238106Sdes    } else {
460238106Sdes      st->print("CreateCoredumpOnCrash turned off, no core file dumped");
461238106Sdes    }
462238106Sdes    st->cr();
463238106Sdes    st->print_cr("#");
464238106Sdes
465238106Sdes  STEP(120, "(printing bug submit message)")
466238106Sdes
467238106Sdes     if (should_report_bug(_id) && _verbose) {
468238106Sdes       print_bug_submit_message(st, _thread);
469238106Sdes     }
470238106Sdes
471238106Sdes  STEP(130, "(printing summary)" )
472238106Sdes
473238106Sdes     if (_verbose) {
474238106Sdes       st->cr();
475238106Sdes       st->print_cr("---------------  S U M M A R Y ------------");
476238106Sdes       st->cr();
477238106Sdes     }
478238106Sdes
479238106Sdes  STEP(140, "(printing VM option summary)" )
480238106Sdes
481238106Sdes     if (_verbose) {
482238106Sdes       // VM options
483238106Sdes       Arguments::print_summary_on(st);
484238106Sdes       st->cr();
485238106Sdes     }
486238106Sdes
487238106Sdes  STEP(150, "(printing summary machine and OS info)")
488238106Sdes
489238106Sdes     if (_verbose) {
490238106Sdes       os::print_summary_info(st, buf, sizeof(buf));
491238106Sdes     }
492238106Sdes
493238106Sdes
494238106Sdes  STEP(160, "(printing date and time)" )
495238106Sdes
496238106Sdes     if (_verbose) {
497238106Sdes       os::print_date_and_time(st, buf, sizeof(buf));
498238106Sdes     }
499238106Sdes
500238106Sdes  STEP(170, "(printing thread)" )
501238106Sdes
502238106Sdes     if (_verbose) {
503238106Sdes       st->cr();
504238106Sdes       st->print_cr("---------------  T H R E A D  ---------------");
505238106Sdes       st->cr();
506238106Sdes     }
507238106Sdes
508238106Sdes  STEP(180, "(printing current thread)" )
509238106Sdes
510238106Sdes     // current thread
511238106Sdes     if (_verbose) {
512238106Sdes       if (_thread) {
513238106Sdes         st->print("Current thread (" PTR_FORMAT "):  ", p2i(_thread));
514238106Sdes         _thread->print_on_error(st, buf, sizeof(buf));
515238106Sdes         st->cr();
516238106Sdes       } else {
517238106Sdes         st->print_cr("Current thread is native thread");
518238106Sdes       }
519238106Sdes       st->cr();
520238106Sdes     }
521238106Sdes
522238106Sdes  STEP(190, "(printing current compile task)" )
523238106Sdes
524238106Sdes     if (_verbose && _thread && _thread->is_Compiler_thread()) {
525238106Sdes        CompilerThread* t = (CompilerThread*)_thread;
526238106Sdes        if (t->task()) {
527238106Sdes           st->cr();
528238106Sdes           st->print_cr("Current CompileTask:");
529238106Sdes           t->task()->print_line_on_error(st, buf, sizeof(buf));
530238106Sdes           st->cr();
531238106Sdes        }
532238106Sdes     }
533238106Sdes
534238106Sdes
535238106Sdes  STEP(200, "(printing stack bounds)" )
536238106Sdes
537238106Sdes     if (_verbose) {
538238106Sdes       st->print("Stack: ");
539238106Sdes
540238106Sdes       address stack_top;
541238106Sdes       size_t stack_size;
542238106Sdes
543238106Sdes       if (_thread) {
544238106Sdes          stack_top = _thread->stack_base();
545238106Sdes          stack_size = _thread->stack_size();
546238106Sdes       } else {
547238106Sdes          stack_top = os::current_stack_base();
548238106Sdes          stack_size = os::current_stack_size();
549238106Sdes       }
550238106Sdes
551238106Sdes       address stack_bottom = stack_top - stack_size;
552238106Sdes       st->print("[" PTR_FORMAT "," PTR_FORMAT "]", p2i(stack_bottom), p2i(stack_top));
553238106Sdes
554238106Sdes       frame fr = _context ? os::fetch_frame_from_context(_context)
555238106Sdes                           : os::current_frame();
556238106Sdes
557238106Sdes       if (fr.sp()) {
558238106Sdes         st->print(",  sp=" PTR_FORMAT, p2i(fr.sp()));
559238106Sdes         size_t free_stack_size = pointer_delta(fr.sp(), stack_bottom, 1024);
560238106Sdes         st->print(",  free space=" SIZE_FORMAT "k", free_stack_size);
561238106Sdes       }
562238106Sdes
563238106Sdes       st->cr();
564238106Sdes     }
565238106Sdes
566238106Sdes  STEP(210, "(printing native stack)" )
567238106Sdes
568238106Sdes   if (_verbose) {
569238106Sdes     if (os::platform_print_native_stack(st, _context, buf, sizeof(buf))) {
570238106Sdes       // We have printed the native stack in platform-specific code
571238106Sdes       // Windows/x64 needs special handling.
572238106Sdes     } else {
573238106Sdes       frame fr = _context ? os::fetch_frame_from_context(_context)
574238106Sdes                           : os::current_frame();
575238106Sdes
576238106Sdes       print_native_stack(st, fr, _thread, buf, sizeof(buf));
577238106Sdes     }
578238106Sdes   }
579238106Sdes
580238106Sdes  STEP(220, "(printing Java stack)" )
581238106Sdes
582238106Sdes     if (_verbose && _thread && _thread->is_Java_thread()) {
583238106Sdes       print_stack_trace(st, (JavaThread*)_thread, buf, sizeof(buf));
584238106Sdes     }
585238106Sdes
586238106Sdes  STEP(230, "(printing target Java thread stack)" )
587238106Sdes
588238106Sdes     // printing Java thread stack trace if it is involved in GC crash
589238106Sdes     if (_verbose && _thread && (_thread->is_Named_thread())) {
590238106Sdes       JavaThread*  jt = ((NamedThread *)_thread)->processed_thread();
591238106Sdes       if (jt != NULL) {
592238106Sdes         st->print_cr("JavaThread " PTR_FORMAT " (nid = %d) was being processed", p2i(jt), jt->osthread()->thread_id());
593238106Sdes         print_stack_trace(st, jt, buf, sizeof(buf), true);
594238106Sdes       }
595238106Sdes     }
596238106Sdes
597238106Sdes  STEP(240, "(printing siginfo)" )
598238106Sdes
599238106Sdes     // signal no, signal code, address that caused the fault
600238106Sdes     if (_verbose && _siginfo) {
601238106Sdes       st->cr();
602238106Sdes       os::print_siginfo(st, _siginfo);
603238106Sdes       st->cr();
604     }
605
606  STEP(245, "(CDS archive access warning)" )
607
608     // Print an explicit hint if we crashed on access to the CDS archive.
609     if (_verbose && _siginfo) {
610       check_failing_cds_access(st, _siginfo);
611       st->cr();
612     }
613
614  STEP(250, "(printing register info)")
615
616     // decode register contents if possible
617     if (_verbose && _context && Universe::is_fully_initialized()) {
618       os::print_register_info(st, _context);
619       st->cr();
620     }
621
622  STEP(260, "(printing registers, top of stack, instructions near pc)")
623
624     // registers, top of stack, instructions near pc
625     if (_verbose && _context) {
626       os::print_context(st, _context);
627       st->cr();
628     }
629
630  STEP(265, "(printing code blob if possible)")
631
632     if (_verbose && _context) {
633       CodeBlob* cb = CodeCache::find_blob(_pc);
634       if (cb != NULL) {
635         if (Interpreter::contains(_pc)) {
636           // The interpreter CodeBlob is very large so try to print the codelet instead.
637           InterpreterCodelet* codelet = Interpreter::codelet_containing(_pc);
638           if (codelet != NULL) {
639             codelet->print_on(st);
640             Disassembler::decode(codelet->code_begin(), codelet->code_end(), st);
641           }
642         } else {
643           StubCodeDesc* desc = StubCodeDesc::desc_for(_pc);
644           if (desc != NULL) {
645             desc->print_on(st);
646             Disassembler::decode(desc->begin(), desc->end(), st);
647           } else {
648             Disassembler::decode(cb, st);
649             st->cr();
650           }
651         }
652       }
653     }
654
655  STEP(270, "(printing VM operation)" )
656
657     if (_verbose && _thread && _thread->is_VM_thread()) {
658        VMThread* t = (VMThread*)_thread;
659        VM_Operation* op = t->vm_operation();
660        if (op) {
661          op->print_on_error(st);
662          st->cr();
663          st->cr();
664        }
665     }
666
667  STEP(280, "(printing process)" )
668
669     if (_verbose) {
670       st->cr();
671       st->print_cr("---------------  P R O C E S S  ---------------");
672       st->cr();
673     }
674
675  STEP(290, "(printing all threads)" )
676
677     // all threads
678     if (_verbose && _thread) {
679       Threads::print_on_error(st, _thread, buf, sizeof(buf));
680       st->cr();
681     }
682
683  STEP(300, "(printing VM state)" )
684
685     if (_verbose) {
686       // Safepoint state
687       st->print("VM state:");
688
689       if (SafepointSynchronize::is_synchronizing()) st->print("synchronizing");
690       else if (SafepointSynchronize::is_at_safepoint()) st->print("at safepoint");
691       else st->print("not at safepoint");
692
693       // Also see if error occurred during initialization or shutdown
694       if (!Universe::is_fully_initialized()) {
695         st->print(" (not fully initialized)");
696       } else if (VM_Exit::vm_exited()) {
697         st->print(" (shutting down)");
698       } else {
699         st->print(" (normal execution)");
700       }
701       st->cr();
702       st->cr();
703     }
704
705  STEP(310, "(printing owned locks on error)" )
706
707     // mutexes/monitors that currently have an owner
708     if (_verbose) {
709       print_owned_locks_on_error(st);
710       st->cr();
711     }
712
713  STEP(320, "(printing number of OutOfMemoryError and StackOverflow exceptions)")
714
715     if (_verbose && Exceptions::has_exception_counts()) {
716       st->print_cr("OutOfMemory and StackOverflow Exception counts:");
717       Exceptions::print_exception_counts_on_error(st);
718       st->cr();
719     }
720
721  STEP(330, "(printing compressed oops mode")
722
723     if (_verbose && UseCompressedOops) {
724       Universe::print_compressed_oops_mode(st);
725       if (UseCompressedClassPointers) {
726         Metaspace::print_compressed_class_space(st);
727       }
728       st->cr();
729     }
730
731  STEP(340, "(printing heap information)" )
732
733     if (_verbose && Universe::is_fully_initialized()) {
734       Universe::heap()->print_on_error(st);
735       st->cr();
736       st->print_cr("Polling page: " INTPTR_FORMAT, p2i(os::get_polling_page()));
737       st->cr();
738     }
739
740  STEP(350, "(printing code cache information)" )
741
742     if (_verbose && Universe::is_fully_initialized()) {
743       // print code cache information before vm abort
744       CodeCache::print_summary(st);
745       st->cr();
746     }
747
748  STEP(360, "(printing ring buffers)" )
749
750     if (_verbose) {
751       Events::print_all(st);
752       st->cr();
753     }
754
755  STEP(370, "(printing dynamic libraries)" )
756
757     if (_verbose) {
758       // dynamic libraries, or memory map
759       os::print_dll_info(st);
760       st->cr();
761     }
762
763  STEP(380, "(printing VM options)" )
764
765     if (_verbose) {
766       // VM options
767       Arguments::print_on(st);
768       st->cr();
769     }
770
771  STEP(390, "(printing warning if internal testing API used)" )
772
773     if (WhiteBox::used()) {
774       st->print_cr("Unsupported internal testing APIs have been used.");
775       st->cr();
776     }
777
778  STEP(400, "(printing all environment variables)" )
779
780     if (_verbose) {
781       os::print_environment_variables(st, env_list);
782       st->cr();
783     }
784
785  STEP(410, "(printing signal handlers)" )
786
787     if (_verbose) {
788       os::print_signal_handlers(st, buf, sizeof(buf));
789       st->cr();
790     }
791
792  STEP(420, "(Native Memory Tracking)" )
793     if (_verbose) {
794       MemTracker::error_report(st);
795     }
796
797  STEP(430, "(printing system)" )
798
799     if (_verbose) {
800       st->cr();
801       st->print_cr("---------------  S Y S T E M  ---------------");
802       st->cr();
803     }
804
805  STEP(440, "(printing OS information)" )
806
807     if (_verbose) {
808       os::print_os_info(st);
809       st->cr();
810     }
811
812  STEP(450, "(printing CPU info)" )
813     if (_verbose) {
814       os::print_cpu_info(st, buf, sizeof(buf));
815       st->cr();
816     }
817
818  STEP(460, "(printing memory info)" )
819
820     if (_verbose) {
821       os::print_memory_info(st);
822       st->cr();
823     }
824
825  STEP(470, "(printing internal vm info)" )
826
827     if (_verbose) {
828       st->print_cr("vm_info: %s", Abstract_VM_Version::internal_vm_info_string());
829       st->cr();
830     }
831
832  // print a defined marker to show that error handling finished correctly.
833  STEP(480, "(printing end marker)" )
834
835     if (_verbose) {
836       st->print_cr("END.");
837     }
838
839  END
840
841# undef BEGIN
842# undef STEP
843# undef END
844}
845
846// Report for the vm_info_cmd. This prints out the information above omitting
847// crash and thread specific information.  If output is added above, it should be added
848// here also, if it is safe to call during a running process.
849void VMError::print_vm_info(outputStream* st) {
850
851  char buf[O_BUFLEN];
852  report_vm_version(st, buf, sizeof(buf));
853
854  // STEP("(printing summary)")
855
856  st->cr();
857  st->print_cr("---------------  S U M M A R Y ------------");
858  st->cr();
859
860  // STEP("(printing VM option summary)")
861
862  // VM options
863  Arguments::print_summary_on(st);
864  st->cr();
865
866  // STEP("(printing summary machine and OS info)")
867
868  os::print_summary_info(st, buf, sizeof(buf));
869
870  // STEP("(printing date and time)")
871
872  os::print_date_and_time(st, buf, sizeof(buf));
873
874  // Skip: STEP("(printing thread)")
875
876  // STEP("(printing process)")
877
878  st->cr();
879  st->print_cr("---------------  P R O C E S S  ---------------");
880  st->cr();
881
882  // STEP("(printing number of OutOfMemoryError and StackOverflow exceptions)")
883
884  if (Exceptions::has_exception_counts()) {
885    st->print_cr("OutOfMemory and StackOverflow Exception counts:");
886    Exceptions::print_exception_counts_on_error(st);
887    st->cr();
888  }
889
890  // STEP("(printing compressed oops mode")
891
892  if (UseCompressedOops) {
893    Universe::print_compressed_oops_mode(st);
894    if (UseCompressedClassPointers) {
895      Metaspace::print_compressed_class_space(st);
896    }
897    st->cr();
898  }
899
900  // STEP("(printing heap information)")
901
902  if (Universe::is_fully_initialized()) {
903    Universe::heap()->print_on_error(st);
904    st->cr();
905    st->print_cr("Polling page: " INTPTR_FORMAT, p2i(os::get_polling_page()));
906    st->cr();
907  }
908
909  // STEP("(printing code cache information)")
910
911  if (Universe::is_fully_initialized()) {
912    // print code cache information before vm abort
913    CodeCache::print_summary(st);
914    st->cr();
915  }
916
917  // STEP("(printing ring buffers)")
918
919  Events::print_all(st);
920  st->cr();
921
922  // STEP("(printing dynamic libraries)")
923
924  // dynamic libraries, or memory map
925  os::print_dll_info(st);
926  st->cr();
927
928  // STEP("(printing VM options)")
929
930  // VM options
931  Arguments::print_on(st);
932  st->cr();
933
934  // STEP("(printing warning if internal testing API used)")
935
936  if (WhiteBox::used()) {
937    st->print_cr("Unsupported internal testing APIs have been used.");
938    st->cr();
939  }
940
941  // STEP("(printing all environment variables)")
942
943  os::print_environment_variables(st, env_list);
944  st->cr();
945
946  // STEP("(printing signal handlers)")
947
948  os::print_signal_handlers(st, buf, sizeof(buf));
949  st->cr();
950
951  // STEP("(Native Memory Tracking)")
952
953  MemTracker::error_report(st);
954
955  // STEP("(printing system)")
956
957  st->cr();
958  st->print_cr("---------------  S Y S T E M  ---------------");
959  st->cr();
960
961  // STEP("(printing OS information)")
962
963  os::print_os_info(st);
964  st->cr();
965
966  // STEP("(printing CPU info)")
967
968  os::print_cpu_info(st, buf, sizeof(buf));
969  st->cr();
970
971  // STEP("(printing memory info)")
972
973  os::print_memory_info(st);
974  st->cr();
975
976  // STEP("(printing internal vm info)")
977
978  st->print_cr("vm_info: %s", Abstract_VM_Version::internal_vm_info_string());
979  st->cr();
980
981  // print a defined marker to show that error handling finished correctly.
982  // STEP("(printing end marker)")
983
984  st->print_cr("END.");
985}
986
987volatile intptr_t VMError::first_error_tid = -1;
988
989// An error could happen before tty is initialized or after it has been
990// destroyed.
991// Please note: to prevent large stack allocations, the log- and
992// output-stream use a global scratch buffer for format printing.
993// (see VmError::report_and_die(). Access to those streams is synchronized
994// in  VmError::report_and_die() - there is only one reporting thread at
995// any given time.
996fdStream VMError::out(defaultStream::output_fd());
997fdStream VMError::log; // error log used by VMError::report_and_die()
998
999/** Expand a pattern into a buffer starting at pos and open a file using constructed path */
1000static int expand_and_open(const char* pattern, char* buf, size_t buflen, size_t pos) {
1001  int fd = -1;
1002  if (Arguments::copy_expand_pid(pattern, strlen(pattern), &buf[pos], buflen - pos)) {
1003    // the O_EXCL flag will cause the open to fail if the file exists
1004    fd = open(buf, O_RDWR | O_CREAT | O_EXCL, 0666);
1005  }
1006  return fd;
1007}
1008
1009/**
1010 * Construct file name for a log file and return it's file descriptor.
1011 * Name and location depends on pattern, default_pattern params and access
1012 * permissions.
1013 */
1014static int prepare_log_file(const char* pattern, const char* default_pattern, char* buf, size_t buflen) {
1015  int fd = -1;
1016
1017  // If possible, use specified pattern to construct log file name
1018  if (pattern != NULL) {
1019    fd = expand_and_open(pattern, buf, buflen, 0);
1020  }
1021
1022  // Either user didn't specify, or the user's location failed,
1023  // so use the default name in the current directory
1024  if (fd == -1) {
1025    const char* cwd = os::get_current_directory(buf, buflen);
1026    if (cwd != NULL) {
1027      size_t pos = strlen(cwd);
1028      int fsep_len = jio_snprintf(&buf[pos], buflen-pos, "%s", os::file_separator());
1029      pos += fsep_len;
1030      if (fsep_len > 0) {
1031        fd = expand_and_open(default_pattern, buf, buflen, pos);
1032      }
1033    }
1034  }
1035
1036   // try temp directory if it exists.
1037   if (fd == -1) {
1038     const char* tmpdir = os::get_temp_directory();
1039     if (tmpdir != NULL && strlen(tmpdir) > 0) {
1040       int pos = jio_snprintf(buf, buflen, "%s%s", tmpdir, os::file_separator());
1041       if (pos > 0) {
1042         fd = expand_and_open(default_pattern, buf, buflen, pos);
1043       }
1044     }
1045   }
1046
1047  return fd;
1048}
1049
1050int         VMError::_id;
1051const char* VMError::_message;
1052char        VMError::_detail_msg[1024];
1053Thread*     VMError::_thread;
1054address     VMError::_pc;
1055void*       VMError::_siginfo;
1056void*       VMError::_context;
1057const char* VMError::_filename;
1058int         VMError::_lineno;
1059size_t      VMError::_size;
1060
1061void VMError::report_and_die(Thread* thread, unsigned int sig, address pc, void* siginfo,
1062                             void* context, const char* detail_fmt, ...)
1063{
1064  va_list detail_args;
1065  va_start(detail_args, detail_fmt);
1066  report_and_die(sig, NULL, detail_fmt, detail_args, thread, pc, siginfo, context, NULL, 0, 0);
1067  va_end(detail_args);
1068}
1069
1070void VMError::report_and_die(Thread* thread, unsigned int sig, address pc, void* siginfo, void* context)
1071{
1072  report_and_die(thread, sig, pc, siginfo, context, "%s", "");
1073}
1074
1075void VMError::report_and_die(const char* message, const char* detail_fmt, ...)
1076{
1077  va_list detail_args;
1078  va_start(detail_args, detail_fmt);
1079  report_and_die(INTERNAL_ERROR, message, detail_fmt, detail_args, NULL, NULL, NULL, NULL, NULL, 0, 0);
1080  va_end(detail_args);
1081}
1082
1083void VMError::report_and_die(const char* message)
1084{
1085  report_and_die(message, "%s", "");
1086}
1087
1088void VMError::report_and_die(Thread* thread, const char* filename, int lineno, const char* message,
1089                             const char* detail_fmt, va_list detail_args)
1090{
1091  report_and_die(INTERNAL_ERROR, message, detail_fmt, detail_args, thread, NULL, NULL, NULL, filename, lineno, 0);
1092}
1093
1094void VMError::report_and_die(Thread* thread, const char* filename, int lineno, size_t size,
1095                             VMErrorType vm_err_type, const char* detail_fmt, va_list detail_args) {
1096  report_and_die(vm_err_type, NULL, detail_fmt, detail_args, thread, NULL, NULL, NULL, filename, lineno, size);
1097}
1098
1099void VMError::report_and_die(int id, const char* message, const char* detail_fmt, va_list detail_args,
1100                             Thread* thread, address pc, void* siginfo, void* context, const char* filename,
1101                             int lineno, size_t size)
1102{
1103  // Don't allocate large buffer on stack
1104  static char buffer[O_BUFLEN];
1105  out.set_scratch_buffer(buffer, sizeof(buffer));
1106  log.set_scratch_buffer(buffer, sizeof(buffer));
1107
1108  // How many errors occurred in error handler when reporting first_error.
1109  static int recursive_error_count;
1110
1111  // We will first print a brief message to standard out (verbose = false),
1112  // then save detailed information in log file (verbose = true).
1113  static bool out_done = false;         // done printing to standard out
1114  static bool log_done = false;         // done saving error log
1115  static bool transmit_report_done = false; // done error reporting
1116
1117  if (SuppressFatalErrorMessage) {
1118      os::abort(CreateCoredumpOnCrash);
1119  }
1120  intptr_t mytid = os::current_thread_id();
1121  if (first_error_tid == -1 &&
1122      Atomic::cmpxchg_ptr(mytid, &first_error_tid, -1) == -1) {
1123
1124    // Initialize time stamps to use the same base.
1125    out.time_stamp().update_to(1);
1126    log.time_stamp().update_to(1);
1127
1128    _id = id;
1129    _message = message;
1130    _thread = thread;
1131    _pc = pc;
1132    _siginfo = siginfo;
1133    _context = context;
1134    _filename = filename;
1135    _lineno = lineno;
1136    _size = size;
1137    jio_vsnprintf(_detail_msg, sizeof(_detail_msg), detail_fmt, detail_args);
1138
1139    // first time
1140    set_error_reported();
1141
1142    if (ShowMessageBoxOnError || PauseAtExit) {
1143      show_message_box(buffer, sizeof(buffer));
1144
1145      // User has asked JVM to abort. Reset ShowMessageBoxOnError so the
1146      // WatcherThread can kill JVM if the error handler hangs.
1147      ShowMessageBoxOnError = false;
1148    }
1149
1150    os::check_dump_limit(buffer, sizeof(buffer));
1151
1152    // reset signal handlers or exception filter; make sure recursive crashes
1153    // are handled properly.
1154    reset_signal_handlers();
1155
1156  } else {
1157    // If UseOsErrorReporting we call this for each level of the call stack
1158    // while searching for the exception handler.  Only the first level needs
1159    // to be reported.
1160    if (UseOSErrorReporting && log_done) return;
1161
1162    // This is not the first error, see if it happened in a different thread
1163    // or in the same thread during error reporting.
1164    if (first_error_tid != mytid) {
1165      char msgbuf[64];
1166      jio_snprintf(msgbuf, sizeof(msgbuf),
1167                   "[thread " INTX_FORMAT " also had an error]",
1168                   mytid);
1169      out.print_raw_cr(msgbuf);
1170
1171      // error reporting is not MT-safe, block current thread
1172      os::infinite_sleep();
1173
1174    } else {
1175      if (recursive_error_count++ > 30) {
1176        out.print_raw_cr("[Too many errors, abort]");
1177        os::die();
1178      }
1179
1180      jio_snprintf(buffer, sizeof(buffer),
1181                   "[error occurred during error reporting %s, id 0x%x]",
1182                   _current_step_info, _id);
1183      if (log.is_open()) {
1184        log.cr();
1185        log.print_raw_cr(buffer);
1186        log.cr();
1187      } else {
1188        out.cr();
1189        out.print_raw_cr(buffer);
1190        out.cr();
1191      }
1192    }
1193  }
1194
1195  // print to screen
1196  if (!out_done) {
1197    report(&out, false);
1198
1199    out_done = true;
1200
1201    _current_step = 0;
1202    _current_step_info = "";
1203  }
1204
1205  // print to error log file
1206  if (!log_done) {
1207    // see if log file is already open
1208    if (!log.is_open()) {
1209      // open log file
1210      int fd = prepare_log_file(ErrorFile, "hs_err_pid%p.log", buffer, sizeof(buffer));
1211      if (fd != -1) {
1212        out.print_raw("# An error report file with more information is saved as:\n# ");
1213        out.print_raw_cr(buffer);
1214
1215        log.set_fd(fd);
1216      } else {
1217        out.print_raw_cr("# Can not save log file, dump to screen..");
1218        log.set_fd(defaultStream::output_fd());
1219        /* Error reporting currently needs dumpfile.
1220         * Maybe implement direct streaming in the future.*/
1221        transmit_report_done = true;
1222      }
1223    }
1224
1225    report(&log, true);
1226    _current_step = 0;
1227    _current_step_info = "";
1228
1229    // Run error reporting to determine whether or not to report the crash.
1230    if (!transmit_report_done && should_report_bug(_id)) {
1231      transmit_report_done = true;
1232      const int fd2 = ::dup(log.fd());
1233      FILE* const hs_err = ::fdopen(fd2, "r");
1234      if (NULL != hs_err) {
1235        ErrorReporter er;
1236        er.call(hs_err, buffer, O_BUFLEN);
1237      }
1238      ::fclose(hs_err);
1239    }
1240
1241    if (log.fd() != defaultStream::output_fd()) {
1242      close(log.fd());
1243    }
1244
1245    log.set_fd(-1);
1246    log_done = true;
1247  }
1248
1249  static bool skip_replay = ReplayCompiles; // Do not overwrite file during replay
1250  if (DumpReplayDataOnError && _thread && _thread->is_Compiler_thread() && !skip_replay) {
1251    skip_replay = true;
1252    ciEnv* env = ciEnv::current();
1253    if (env != NULL) {
1254      int fd = prepare_log_file(ReplayDataFile, "replay_pid%p.log", buffer, sizeof(buffer));
1255      if (fd != -1) {
1256        FILE* replay_data_file = os::open(fd, "w");
1257        if (replay_data_file != NULL) {
1258          fileStream replay_data_stream(replay_data_file, /*need_close=*/true);
1259          env->dump_replay_data_unsafe(&replay_data_stream);
1260          out.print_raw("#\n# Compiler replay data is saved as:\n# ");
1261          out.print_raw_cr(buffer);
1262        } else {
1263          int e = errno;
1264          out.print_raw("#\n# Can't open file to dump replay data. Error: ");
1265          out.print_raw_cr(os::strerror(e));
1266        }
1267      }
1268    }
1269  }
1270
1271  static bool skip_bug_url = !should_report_bug(_id);
1272  if (!skip_bug_url) {
1273    skip_bug_url = true;
1274
1275    out.print_raw_cr("#");
1276    print_bug_submit_message(&out, _thread);
1277  }
1278
1279  static bool skip_OnError = false;
1280  if (!skip_OnError && OnError && OnError[0]) {
1281    skip_OnError = true;
1282
1283    // Flush output and finish logs before running OnError commands.
1284    ostream_abort();
1285
1286    out.print_raw_cr("#");
1287    out.print_raw   ("# -XX:OnError=\"");
1288    out.print_raw   (OnError);
1289    out.print_raw_cr("\"");
1290
1291    char* cmd;
1292    const char* ptr = OnError;
1293    while ((cmd = next_OnError_command(buffer, sizeof(buffer), &ptr)) != NULL){
1294      out.print_raw   ("#   Executing ");
1295#if defined(LINUX) || defined(_ALLBSD_SOURCE)
1296      out.print_raw   ("/bin/sh -c ");
1297#elif defined(SOLARIS)
1298      out.print_raw   ("/usr/bin/sh -c ");
1299#endif
1300      out.print_raw   ("\"");
1301      out.print_raw   (cmd);
1302      out.print_raw_cr("\" ...");
1303
1304      if (os::fork_and_exec(cmd) < 0) {
1305        out.print_cr("os::fork_and_exec failed: %s (%s=%d)",
1306                     os::strerror(errno), os::errno_name(errno), errno);
1307      }
1308    }
1309
1310    // done with OnError
1311    OnError = NULL;
1312  }
1313
1314  if (!UseOSErrorReporting) {
1315    // os::abort() will call abort hooks, try it first.
1316    static bool skip_os_abort = false;
1317    if (!skip_os_abort) {
1318      skip_os_abort = true;
1319      bool dump_core = should_report_bug(_id);
1320      os::abort(dump_core && CreateCoredumpOnCrash, _siginfo, _context);
1321    }
1322
1323    // if os::abort() doesn't abort, try os::die();
1324    os::die();
1325  }
1326}
1327
1328/*
1329 * OnOutOfMemoryError scripts/commands executed while VM is a safepoint - this
1330 * ensures utilities such as jmap can observe the process is a consistent state.
1331 */
1332class VM_ReportJavaOutOfMemory : public VM_Operation {
1333 private:
1334  const char* _message;
1335 public:
1336  VM_ReportJavaOutOfMemory(const char* message) { _message = message; }
1337  VMOp_Type type() const                        { return VMOp_ReportJavaOutOfMemory; }
1338  void doit();
1339};
1340
1341void VM_ReportJavaOutOfMemory::doit() {
1342  // Don't allocate large buffer on stack
1343  static char buffer[O_BUFLEN];
1344
1345  tty->print_cr("#");
1346  tty->print_cr("# java.lang.OutOfMemoryError: %s", _message);
1347  tty->print_cr("# -XX:OnOutOfMemoryError=\"%s\"", OnOutOfMemoryError);
1348
1349  // make heap parsability
1350  Universe::heap()->ensure_parsability(false);  // no need to retire TLABs
1351
1352  char* cmd;
1353  const char* ptr = OnOutOfMemoryError;
1354  while ((cmd = next_OnError_command(buffer, sizeof(buffer), &ptr)) != NULL){
1355    tty->print("#   Executing ");
1356#if defined(LINUX)
1357    tty->print  ("/bin/sh -c ");
1358#elif defined(SOLARIS)
1359    tty->print  ("/usr/bin/sh -c ");
1360#endif
1361    tty->print_cr("\"%s\"...", cmd);
1362
1363    if (os::fork_and_exec(cmd) < 0) {
1364      tty->print_cr("os::fork_and_exec failed: %s (%s=%d)",
1365                     os::strerror(errno), os::errno_name(errno), errno);
1366    }
1367  }
1368}
1369
1370void VMError::report_java_out_of_memory(const char* message) {
1371  if (OnOutOfMemoryError && OnOutOfMemoryError[0]) {
1372    MutexLocker ml(Heap_lock);
1373    VM_ReportJavaOutOfMemory op(message);
1374    VMThread::execute(&op);
1375  }
1376}
1377
1378void VMError::show_message_box(char *buf, int buflen) {
1379  bool yes;
1380  do {
1381    error_string(buf, buflen);
1382    yes = os::start_debugging(buf,buflen);
1383  } while (yes);
1384}
1385