vmError.cpp revision 9593:ca793dd85e06
1/*
2 * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25#include <fcntl.h>
26#include "precompiled.hpp"
27#include "code/codeCache.hpp"
28#include "compiler/compileBroker.hpp"
29#include "compiler/disassembler.hpp"
30#include "gc/shared/collectedHeap.hpp"
31#include "prims/whitebox.hpp"
32#include "runtime/arguments.hpp"
33#include "runtime/atomic.inline.hpp"
34#include "runtime/frame.inline.hpp"
35#include "runtime/init.hpp"
36#include "runtime/os.hpp"
37#include "runtime/thread.inline.hpp"
38#include "runtime/vmThread.hpp"
39#include "runtime/vm_operations.hpp"
40#include "services/memTracker.hpp"
41#include "utilities/debug.hpp"
42#include "utilities/decoder.hpp"
43#include "utilities/defaultStream.hpp"
44#include "utilities/errorReporter.hpp"
45#include "utilities/events.hpp"
46#include "utilities/top.hpp"
47#include "utilities/vmError.hpp"
48
49// List of environment variables that should be reported in error log file.
50const char *env_list[] = {
51  // All platforms
52  "JAVA_HOME", "JRE_HOME", "JAVA_TOOL_OPTIONS", "_JAVA_OPTIONS", "CLASSPATH",
53  "JAVA_COMPILER", "PATH", "USERNAME",
54
55  // Env variables that are defined on Solaris/Linux/BSD
56  "LD_LIBRARY_PATH", "LD_PRELOAD", "SHELL", "DISPLAY",
57  "HOSTTYPE", "OSTYPE", "ARCH", "MACHTYPE",
58
59  // defined on Linux
60  "LD_ASSUME_KERNEL", "_JAVA_SR_SIGNUM",
61
62  // defined on Darwin
63  "DYLD_LIBRARY_PATH", "DYLD_FALLBACK_LIBRARY_PATH",
64  "DYLD_FRAMEWORK_PATH", "DYLD_FALLBACK_FRAMEWORK_PATH",
65  "DYLD_INSERT_LIBRARIES",
66
67  // defined on Windows
68  "OS", "PROCESSOR_IDENTIFIER", "_ALT_JAVA_HOME_DIR",
69
70  (const char *)0
71};
72
73// A simple parser for -XX:OnError, usage:
74//  ptr = OnError;
75//  while ((cmd = next_OnError_command(buffer, sizeof(buffer), &ptr) != NULL)
76//     ... ...
77static char* next_OnError_command(char* buf, int buflen, const char** ptr) {
78  if (ptr == NULL || *ptr == NULL) return NULL;
79
80  const char* cmd = *ptr;
81
82  // skip leading blanks or ';'
83  while (*cmd == ' ' || *cmd == ';') cmd++;
84
85  if (*cmd == '\0') return NULL;
86
87  const char * cmdend = cmd;
88  while (*cmdend != '\0' && *cmdend != ';') cmdend++;
89
90  Arguments::copy_expand_pid(cmd, cmdend - cmd, buf, buflen);
91
92  *ptr = (*cmdend == '\0' ? cmdend : cmdend + 1);
93  return buf;
94}
95
96static void print_bug_submit_message(outputStream *out, Thread *thread) {
97  if (out == NULL) return;
98  out->print_raw_cr("# If you would like to submit a bug report, please visit:");
99  out->print_raw   ("#   ");
100  out->print_raw_cr(Arguments::java_vendor_url_bug());
101  // If the crash is in native code, encourage user to submit a bug to the
102  // provider of that code.
103  if (thread && thread->is_Java_thread() &&
104      !thread->is_hidden_from_external_view()) {
105    JavaThread* jt = (JavaThread*)thread;
106    if (jt->thread_state() == _thread_in_native) {
107      out->print_cr("# The crash happened outside the Java Virtual Machine in native code.\n# See problematic frame for where to report the bug.");
108    }
109  }
110  out->print_raw_cr("#");
111}
112
113bool VMError::coredump_status;
114char VMError::coredump_message[O_BUFLEN];
115
116void VMError::record_coredump_status(const char* message, bool status) {
117  coredump_status = status;
118  strncpy(coredump_message, message, sizeof(coredump_message));
119  coredump_message[sizeof(coredump_message)-1] = 0;
120}
121
122// Return a string to describe the error
123char* VMError::error_string(char* buf, int buflen) {
124  char signame_buf[64];
125  const char *signame = os::exception_name(_id, signame_buf, sizeof(signame_buf));
126
127  if (signame) {
128    jio_snprintf(buf, buflen,
129                 "%s (0x%x) at pc=" PTR_FORMAT ", pid=%d, tid=" UINTX_FORMAT,
130                 signame, _id, _pc,
131                 os::current_process_id(), os::current_thread_id());
132  } else if (_filename != NULL && _lineno > 0) {
133    // skip directory names
134    char separator = os::file_separator()[0];
135    const char *p = strrchr(_filename, separator);
136    int n = jio_snprintf(buf, buflen,
137                         "Internal Error at %s:%d, pid=%d, tid=" UINTX_FORMAT,
138                         p ? p + 1 : _filename, _lineno,
139                         os::current_process_id(), os::current_thread_id());
140    if (n >= 0 && n < buflen && _message) {
141      if (strlen(_detail_msg) > 0) {
142        jio_snprintf(buf + n, buflen - n, "%s%s: %s",
143        os::line_separator(), _message, _detail_msg);
144      } else {
145        jio_snprintf(buf + n, buflen - n, "%sError: %s",
146                     os::line_separator(), _message);
147      }
148    }
149  } else {
150    jio_snprintf(buf, buflen,
151                 "Internal Error (0x%x), pid=%d, tid=" UINTX_FORMAT,
152                 _id, os::current_process_id(), os::current_thread_id());
153  }
154
155  return buf;
156}
157
158void VMError::print_stack_trace(outputStream* st, JavaThread* jt,
159                                char* buf, int buflen, bool verbose) {
160#ifdef ZERO
161  if (jt->zero_stack()->sp() && jt->top_zero_frame()) {
162    // StackFrameStream uses the frame anchor, which may not have
163    // been set up.  This can be done at any time in Zero, however,
164    // so if it hasn't been set up then we just set it up now and
165    // clear it again when we're done.
166    bool has_last_Java_frame = jt->has_last_Java_frame();
167    if (!has_last_Java_frame)
168      jt->set_last_Java_frame();
169    st->print("Java frames:");
170
171    // If the top frame is a Shark frame and the frame anchor isn't
172    // set up then it's possible that the information in the frame
173    // is garbage: it could be from a previous decache, or it could
174    // simply have never been written.  So we print a warning...
175    StackFrameStream sfs(jt);
176    if (!has_last_Java_frame && !sfs.is_done()) {
177      if (sfs.current()->zeroframe()->is_shark_frame()) {
178        st->print(" (TOP FRAME MAY BE JUNK)");
179      }
180    }
181    st->cr();
182
183    // Print the frames
184    for(int i = 0; !sfs.is_done(); sfs.next(), i++) {
185      sfs.current()->zero_print_on_error(i, st, buf, buflen);
186      st->cr();
187    }
188
189    // Reset the frame anchor if necessary
190    if (!has_last_Java_frame)
191      jt->reset_last_Java_frame();
192  }
193#else
194  if (jt->has_last_Java_frame()) {
195    st->print_cr("Java frames: (J=compiled Java code, j=interpreted, Vv=VM code)");
196    for(StackFrameStream sfs(jt); !sfs.is_done(); sfs.next()) {
197      sfs.current()->print_on_error(st, buf, buflen, verbose);
198      st->cr();
199    }
200  }
201#endif // ZERO
202}
203
204static void print_oom_reasons(outputStream* st) {
205  st->print_cr("# Possible reasons:");
206  st->print_cr("#   The system is out of physical RAM or swap space");
207  st->print_cr("#   In 32 bit mode, the process size limit was hit");
208  st->print_cr("# Possible solutions:");
209  st->print_cr("#   Reduce memory load on the system");
210  st->print_cr("#   Increase physical memory or swap space");
211  st->print_cr("#   Check if swap backing store is full");
212  st->print_cr("#   Use 64 bit Java on a 64 bit OS");
213  st->print_cr("#   Decrease Java heap size (-Xmx/-Xms)");
214  st->print_cr("#   Decrease number of Java threads");
215  st->print_cr("#   Decrease Java thread stack sizes (-Xss)");
216  st->print_cr("#   Set larger code cache with -XX:ReservedCodeCacheSize=");
217  st->print_cr("# This output file may be truncated or incomplete.");
218}
219
220static const char* gc_mode() {
221  if (UseG1GC)            return "g1 gc";
222  if (UseParallelGC)      return "parallel gc";
223  if (UseConcMarkSweepGC) return "concurrent mark sweep gc";
224  if (UseSerialGC)        return "serial gc";
225  return "ERROR in GC mode";
226}
227
228static void report_vm_version(outputStream* st, char* buf, int buflen) {
229   // VM version
230   st->print_cr("#");
231   JDK_Version::current().to_string(buf, buflen);
232   const char* runtime_name = JDK_Version::runtime_name() != NULL ?
233                                JDK_Version::runtime_name() : "";
234   const char* runtime_version = JDK_Version::runtime_version() != NULL ?
235                                JDK_Version::runtime_version() : "";
236   st->print_cr("# JRE version: %s (%s) (build %s)", runtime_name, buf, runtime_version);
237   // This is the long version with some default settings added
238   st->print_cr("# Java VM: %s (%s, %s%s%s%s%s, %s, %s)",
239                 Abstract_VM_Version::vm_name(),
240                 Abstract_VM_Version::vm_release(),
241                 Abstract_VM_Version::vm_info_string(),
242                 TieredCompilation ? ", tiered" : "",
243#if INCLUDE_JVMCI
244                 EnableJVMCI ? ", jvmci" : "",
245                 UseJVMCICompiler ? ", jvmci compiler" : "",
246#else
247                 "", "",
248#endif
249                 UseCompressedOops ? ", compressed oops" : "",
250                 gc_mode(),
251                 Abstract_VM_Version::vm_platform_string()
252               );
253}
254
255// This is the main function to report a fatal error. Only one thread can
256// call this function, so we don't need to worry about MT-safety. But it's
257// possible that the error handler itself may crash or die on an internal
258// error, for example, when the stack/heap is badly damaged. We must be
259// able to handle recursive errors that happen inside error handler.
260//
261// Error reporting is done in several steps. If a crash or internal error
262// occurred when reporting an error, the nested signal/exception handler
263// can skip steps that are already (or partially) done. Error reporting will
264// continue from the next step. This allows us to retrieve and print
265// information that may be unsafe to get after a fatal error. If it happens,
266// you may find nested report_and_die() frames when you look at the stack
267// in a debugger.
268//
269// In general, a hang in error handler is much worse than a crash or internal
270// error, as it's harder to recover from a hang. Deadlock can happen if we
271// try to grab a lock that is already owned by current thread, or if the
272// owner is blocked forever (e.g. in os::infinite_sleep()). If possible, the
273// error handler and all the functions it called should avoid grabbing any
274// lock. An important thing to notice is that memory allocation needs a lock.
275//
276// We should avoid using large stack allocated buffers. Many errors happen
277// when stack space is already low. Making things even worse is that there
278// could be nested report_and_die() calls on stack (see above). Only one
279// thread can report error, so large buffers are statically allocated in data
280// segment.
281
282int          VMError::_current_step;
283const char*  VMError::_current_step_info;
284
285void VMError::report(outputStream* st, bool _verbose) {
286
287# define BEGIN if (_current_step == 0) { _current_step = 1;
288# define STEP(n, s) } if (_current_step < n) { _current_step = n; _current_step_info = s;
289# define END }
290
291  // don't allocate large buffer on stack
292  static char buf[O_BUFLEN];
293
294  BEGIN
295
296  STEP(10, "(printing fatal error message)")
297
298    st->print_cr("#");
299    if (should_report_bug(_id)) {
300      st->print_cr("# A fatal error has been detected by the Java Runtime Environment:");
301    } else {
302      st->print_cr("# There is insufficient memory for the Java "
303                   "Runtime Environment to continue.");
304    }
305
306#ifndef PRODUCT
307  // Error handler self tests
308
309  // test secondary error handling. Test it twice, to test that resetting
310  // error handler after a secondary crash works.
311  STEP(20, "(test secondary crash 1)")
312    if (_verbose && TestCrashInErrorHandler != 0) {
313      st->print_cr("Will crash now (TestCrashInErrorHandler=" UINTX_FORMAT ")...",
314        TestCrashInErrorHandler);
315      controlled_crash(TestCrashInErrorHandler);
316    }
317
318  STEP(30, "(test secondary crash 2)")
319    if (_verbose && TestCrashInErrorHandler != 0) {
320      st->print_cr("Will crash now (TestCrashInErrorHandler=" UINTX_FORMAT ")...",
321        TestCrashInErrorHandler);
322      controlled_crash(TestCrashInErrorHandler);
323    }
324
325  STEP(40, "(test safefetch in error handler)")
326    // test whether it is safe to use SafeFetch32 in Crash Handler. Test twice
327    // to test that resetting the signal handler works correctly.
328    if (_verbose && TestSafeFetchInErrorHandler) {
329      st->print_cr("Will test SafeFetch...");
330      if (CanUseSafeFetch32()) {
331        int* const invalid_pointer = (int*) get_segfault_address();
332        const int x = 0x76543210;
333        int i1 = SafeFetch32(invalid_pointer, x);
334        int i2 = SafeFetch32(invalid_pointer, x);
335        if (i1 == x && i2 == x) {
336          st->print_cr("SafeFetch OK."); // Correctly deflected and returned default pattern
337        } else {
338          st->print_cr("??");
339        }
340      } else {
341        st->print_cr("not possible; skipped.");
342      }
343    }
344#endif // PRODUCT
345
346  STEP(50, "(printing type of error)")
347
348     switch(_id) {
349       case OOM_MALLOC_ERROR:
350       case OOM_MMAP_ERROR:
351         if (_size) {
352           st->print("# Native memory allocation ");
353           st->print((_id == (int)OOM_MALLOC_ERROR) ? "(malloc) failed to allocate " :
354                                                 "(mmap) failed to map ");
355           jio_snprintf(buf, sizeof(buf), SIZE_FORMAT, _size);
356           st->print("%s", buf);
357           st->print(" bytes");
358           if (strlen(_detail_msg) > 0) {
359             st->print(" for ");
360             st->print("%s", _detail_msg);
361           }
362           st->cr();
363         } else {
364           if (strlen(_detail_msg) > 0) {
365             st->print("# ");
366             st->print_cr("%s", _detail_msg);
367           }
368         }
369         // In error file give some solutions
370         if (_verbose) {
371           print_oom_reasons(st);
372         } else {
373           return;  // that's enough for the screen
374         }
375         break;
376       case INTERNAL_ERROR:
377       default:
378         break;
379     }
380
381  STEP(60, "(printing exception/signal name)")
382
383     st->print_cr("#");
384     st->print("#  ");
385     // Is it an OS exception/signal?
386     if (os::exception_name(_id, buf, sizeof(buf))) {
387       st->print("%s", buf);
388       st->print(" (0x%x)", _id);                // signal number
389       st->print(" at pc=" PTR_FORMAT, p2i(_pc));
390     } else {
391       if (should_report_bug(_id)) {
392         st->print("Internal Error");
393       } else {
394         st->print("Out of Memory Error");
395       }
396       if (_filename != NULL && _lineno > 0) {
397#ifdef PRODUCT
398         // In product mode chop off pathname?
399         char separator = os::file_separator()[0];
400         const char *p = strrchr(_filename, separator);
401         const char *file = p ? p+1 : _filename;
402#else
403         const char *file = _filename;
404#endif
405         st->print(" (%s:%d)", file, _lineno);
406       } else {
407         st->print(" (0x%x)", _id);
408       }
409     }
410
411  STEP(70, "(printing current thread and pid)")
412
413     // process id, thread id
414     st->print(", pid=%d", os::current_process_id());
415     st->print(", tid=" UINTX_FORMAT, os::current_thread_id());
416     st->cr();
417
418  STEP(80, "(printing error message)")
419
420     if (should_report_bug(_id)) {  // already printed the message.
421       // error message
422       if (strlen(_detail_msg) > 0) {
423         st->print_cr("#  %s: %s", _message ? _message : "Error", _detail_msg);
424       } else if (_message) {
425         st->print_cr("#  Error: %s", _message);
426       }
427     }
428
429  STEP(90, "(printing Java version string)")
430
431     report_vm_version(st, buf, sizeof(buf));
432
433  STEP(100, "(printing problematic frame)")
434
435     // Print current frame if we have a context (i.e. it's a crash)
436     if (_context) {
437       st->print_cr("# Problematic frame:");
438       st->print("# ");
439       frame fr = os::fetch_frame_from_context(_context);
440       fr.print_on_error(st, buf, sizeof(buf));
441       st->cr();
442       st->print_cr("#");
443     }
444
445  STEP(110, "(printing core file information)")
446    st->print("# ");
447    if (CreateCoredumpOnCrash) {
448      if (coredump_status) {
449        st->print("Core dump will be written. Default location: %s", coredump_message);
450      } else {
451        st->print("No core dump will be written. %s", coredump_message);
452      }
453    } else {
454      st->print("CreateCoredumpOnCrash turned off, no core file dumped");
455    }
456    st->cr();
457    st->print_cr("#");
458
459  STEP(120, "(printing bug submit message)")
460
461     if (should_report_bug(_id) && _verbose) {
462       print_bug_submit_message(st, _thread);
463     }
464
465  STEP(130, "(printing summary)" )
466
467     if (_verbose) {
468       st->cr();
469       st->print_cr("---------------  S U M M A R Y ------------");
470       st->cr();
471     }
472
473  STEP(140, "(printing VM option summary)" )
474
475     if (_verbose) {
476       // VM options
477       Arguments::print_summary_on(st);
478       st->cr();
479     }
480
481  STEP(150, "(printing summary machine and OS info)")
482
483     if (_verbose) {
484       os::print_summary_info(st, buf, sizeof(buf));
485     }
486
487
488  STEP(160, "(printing date and time)" )
489
490     if (_verbose) {
491       os::print_date_and_time(st, buf, sizeof(buf));
492     }
493
494  STEP(170, "(printing thread)" )
495
496     if (_verbose) {
497       st->cr();
498       st->print_cr("---------------  T H R E A D  ---------------");
499       st->cr();
500     }
501
502  STEP(180, "(printing current thread)" )
503
504     // current thread
505     if (_verbose) {
506       if (_thread) {
507         st->print("Current thread (" PTR_FORMAT "):  ", p2i(_thread));
508         _thread->print_on_error(st, buf, sizeof(buf));
509         st->cr();
510       } else {
511         st->print_cr("Current thread is native thread");
512       }
513       st->cr();
514     }
515
516  STEP(190, "(printing current compile task)" )
517
518     if (_verbose && _thread && _thread->is_Compiler_thread()) {
519        CompilerThread* t = (CompilerThread*)_thread;
520        if (t->task()) {
521           st->cr();
522           st->print_cr("Current CompileTask:");
523           t->task()->print_line_on_error(st, buf, sizeof(buf));
524           st->cr();
525        }
526     }
527
528
529  STEP(200, "(printing stack bounds)" )
530
531     if (_verbose) {
532       st->print("Stack: ");
533
534       address stack_top;
535       size_t stack_size;
536
537       if (_thread) {
538          stack_top = _thread->stack_base();
539          stack_size = _thread->stack_size();
540       } else {
541          stack_top = os::current_stack_base();
542          stack_size = os::current_stack_size();
543       }
544
545       address stack_bottom = stack_top - stack_size;
546       st->print("[" PTR_FORMAT "," PTR_FORMAT "]", p2i(stack_bottom), p2i(stack_top));
547
548       frame fr = _context ? os::fetch_frame_from_context(_context)
549                           : os::current_frame();
550
551       if (fr.sp()) {
552         st->print(",  sp=" PTR_FORMAT, p2i(fr.sp()));
553         size_t free_stack_size = pointer_delta(fr.sp(), stack_bottom, 1024);
554         st->print(",  free space=" SIZE_FORMAT "k", free_stack_size);
555       }
556
557       st->cr();
558     }
559
560  STEP(210, "(printing native stack)" )
561
562   if (_verbose) {
563     if (os::platform_print_native_stack(st, _context, buf, sizeof(buf))) {
564       // We have printed the native stack in platform-specific code
565       // Windows/x64 needs special handling.
566     } else {
567       frame fr = _context ? os::fetch_frame_from_context(_context)
568                           : os::current_frame();
569
570       print_native_stack(st, fr, _thread, buf, sizeof(buf));
571     }
572   }
573
574  STEP(220, "(printing Java stack)" )
575
576     if (_verbose && _thread && _thread->is_Java_thread()) {
577       print_stack_trace(st, (JavaThread*)_thread, buf, sizeof(buf));
578     }
579
580  STEP(230, "(printing target Java thread stack)" )
581
582     // printing Java thread stack trace if it is involved in GC crash
583     if (_verbose && _thread && (_thread->is_Named_thread())) {
584       JavaThread*  jt = ((NamedThread *)_thread)->processed_thread();
585       if (jt != NULL) {
586         st->print_cr("JavaThread " PTR_FORMAT " (nid = %d) was being processed", p2i(jt), jt->osthread()->thread_id());
587         print_stack_trace(st, jt, buf, sizeof(buf), true);
588       }
589     }
590
591  STEP(240, "(printing siginfo)" )
592
593     // signal no, signal code, address that caused the fault
594     if (_verbose && _siginfo) {
595       st->cr();
596       os::print_siginfo(st, _siginfo);
597       st->cr();
598     }
599
600  STEP(250, "(printing register info)")
601
602     // decode register contents if possible
603     if (_verbose && _context && Universe::is_fully_initialized()) {
604       os::print_register_info(st, _context);
605       st->cr();
606     }
607
608  STEP(260, "(printing registers, top of stack, instructions near pc)")
609
610     // registers, top of stack, instructions near pc
611     if (_verbose && _context) {
612       os::print_context(st, _context);
613       st->cr();
614     }
615
616  STEP(265, "(printing code blob if possible)")
617
618     if (_verbose && _context) {
619       CodeBlob* cb = CodeCache::find_blob(_pc);
620       if (cb != NULL) {
621         if (Interpreter::contains(_pc)) {
622           // The interpreter CodeBlob is very large so try to print the codelet instead.
623           InterpreterCodelet* codelet = Interpreter::codelet_containing(_pc);
624           if (codelet != NULL) {
625             codelet->print_on(st);
626             Disassembler::decode(codelet->code_begin(), codelet->code_end(), st);
627           }
628         } else {
629           StubCodeDesc* desc = StubCodeDesc::desc_for(_pc);
630           if (desc != NULL) {
631             desc->print_on(st);
632             Disassembler::decode(desc->begin(), desc->end(), st);
633           } else {
634             Disassembler::decode(cb, st);
635             st->cr();
636           }
637         }
638       }
639     }
640
641  STEP(270, "(printing VM operation)" )
642
643     if (_verbose && _thread && _thread->is_VM_thread()) {
644        VMThread* t = (VMThread*)_thread;
645        VM_Operation* op = t->vm_operation();
646        if (op) {
647          op->print_on_error(st);
648          st->cr();
649          st->cr();
650        }
651     }
652
653  STEP(280, "(printing process)" )
654
655     if (_verbose) {
656       st->cr();
657       st->print_cr("---------------  P R O C E S S  ---------------");
658       st->cr();
659     }
660
661  STEP(290, "(printing all threads)" )
662
663     // all threads
664     if (_verbose && _thread) {
665       Threads::print_on_error(st, _thread, buf, sizeof(buf));
666       st->cr();
667     }
668
669  STEP(300, "(printing VM state)" )
670
671     if (_verbose) {
672       // Safepoint state
673       st->print("VM state:");
674
675       if (SafepointSynchronize::is_synchronizing()) st->print("synchronizing");
676       else if (SafepointSynchronize::is_at_safepoint()) st->print("at safepoint");
677       else st->print("not at safepoint");
678
679       // Also see if error occurred during initialization or shutdown
680       if (!Universe::is_fully_initialized()) {
681         st->print(" (not fully initialized)");
682       } else if (VM_Exit::vm_exited()) {
683         st->print(" (shutting down)");
684       } else {
685         st->print(" (normal execution)");
686       }
687       st->cr();
688       st->cr();
689     }
690
691  STEP(310, "(printing owned locks on error)" )
692
693     // mutexes/monitors that currently have an owner
694     if (_verbose) {
695       print_owned_locks_on_error(st);
696       st->cr();
697     }
698
699  STEP(320, "(printing number of OutOfMemoryError and StackOverflow exceptions)")
700
701     if (_verbose && Exceptions::has_exception_counts()) {
702       st->print_cr("OutOfMemory and StackOverflow Exception counts:");
703       Exceptions::print_exception_counts_on_error(st);
704       st->cr();
705     }
706
707  STEP(330, "(printing compressed oops mode")
708
709     if (_verbose && UseCompressedOops) {
710       Universe::print_compressed_oops_mode(st);
711       if (UseCompressedClassPointers) {
712         Metaspace::print_compressed_class_space(st);
713       }
714       st->cr();
715     }
716
717  STEP(340, "(printing heap information)" )
718
719     if (_verbose && Universe::is_fully_initialized()) {
720       Universe::heap()->print_on_error(st);
721       st->cr();
722       st->print_cr("Polling page: " INTPTR_FORMAT, p2i(os::get_polling_page()));
723       st->cr();
724     }
725
726  STEP(350, "(printing code cache information)" )
727
728     if (_verbose && Universe::is_fully_initialized()) {
729       // print code cache information before vm abort
730       CodeCache::print_summary(st);
731       st->cr();
732     }
733
734  STEP(360, "(printing ring buffers)" )
735
736     if (_verbose) {
737       Events::print_all(st);
738       st->cr();
739     }
740
741  STEP(370, "(printing dynamic libraries)" )
742
743     if (_verbose) {
744       // dynamic libraries, or memory map
745       os::print_dll_info(st);
746       st->cr();
747     }
748
749  STEP(380, "(printing VM options)" )
750
751     if (_verbose) {
752       // VM options
753       Arguments::print_on(st);
754       st->cr();
755     }
756
757  STEP(390, "(printing warning if internal testing API used)" )
758
759     if (WhiteBox::used()) {
760       st->print_cr("Unsupported internal testing APIs have been used.");
761       st->cr();
762     }
763
764  STEP(400, "(printing all environment variables)" )
765
766     if (_verbose) {
767       os::print_environment_variables(st, env_list);
768       st->cr();
769     }
770
771  STEP(410, "(printing signal handlers)" )
772
773     if (_verbose) {
774       os::print_signal_handlers(st, buf, sizeof(buf));
775       st->cr();
776     }
777
778  STEP(420, "(Native Memory Tracking)" )
779     if (_verbose) {
780       MemTracker::error_report(st);
781     }
782
783  STEP(430, "(printing system)" )
784
785     if (_verbose) {
786       st->cr();
787       st->print_cr("---------------  S Y S T E M  ---------------");
788       st->cr();
789     }
790
791  STEP(440, "(printing OS information)" )
792
793     if (_verbose) {
794       os::print_os_info(st);
795       st->cr();
796     }
797
798  STEP(450, "(printing CPU info)" )
799     if (_verbose) {
800       os::print_cpu_info(st, buf, sizeof(buf));
801       st->cr();
802     }
803
804  STEP(460, "(printing memory info)" )
805
806     if (_verbose) {
807       os::print_memory_info(st);
808       st->cr();
809     }
810
811  STEP(470, "(printing internal vm info)" )
812
813     if (_verbose) {
814       st->print_cr("vm_info: %s", Abstract_VM_Version::internal_vm_info_string());
815       st->cr();
816     }
817
818  // print a defined marker to show that error handling finished correctly.
819  STEP(480, "(printing end marker)" )
820
821     if (_verbose) {
822       st->print_cr("END.");
823     }
824
825  END
826
827# undef BEGIN
828# undef STEP
829# undef END
830}
831
832// Report for the vm_info_cmd. This prints out the information above omitting
833// crash and thread specific information.  If output is added above, it should be added
834// here also, if it is safe to call during a running process.
835void VMError::print_vm_info(outputStream* st) {
836
837  char buf[O_BUFLEN];
838  report_vm_version(st, buf, sizeof(buf));
839
840  // STEP("(printing summary)")
841
842  st->cr();
843  st->print_cr("---------------  S U M M A R Y ------------");
844  st->cr();
845
846  // STEP("(printing VM option summary)")
847
848  // VM options
849  Arguments::print_summary_on(st);
850  st->cr();
851
852  // STEP("(printing summary machine and OS info)")
853
854  os::print_summary_info(st, buf, sizeof(buf));
855
856  // STEP("(printing date and time)")
857
858  os::print_date_and_time(st, buf, sizeof(buf));
859
860  // Skip: STEP("(printing thread)")
861
862  // STEP("(printing process)")
863
864  st->cr();
865  st->print_cr("---------------  P R O C E S S  ---------------");
866  st->cr();
867
868  // STEP("(printing number of OutOfMemoryError and StackOverflow exceptions)")
869
870  if (Exceptions::has_exception_counts()) {
871    st->print_cr("OutOfMemory and StackOverflow Exception counts:");
872    Exceptions::print_exception_counts_on_error(st);
873    st->cr();
874  }
875
876  // STEP("(printing compressed oops mode")
877
878  if (UseCompressedOops) {
879    Universe::print_compressed_oops_mode(st);
880    if (UseCompressedClassPointers) {
881      Metaspace::print_compressed_class_space(st);
882    }
883    st->cr();
884  }
885
886  // STEP("(printing heap information)")
887
888  if (Universe::is_fully_initialized()) {
889    Universe::heap()->print_on_error(st);
890    st->cr();
891    st->print_cr("Polling page: " INTPTR_FORMAT, p2i(os::get_polling_page()));
892    st->cr();
893  }
894
895  // STEP("(printing code cache information)")
896
897  if (Universe::is_fully_initialized()) {
898    // print code cache information before vm abort
899    CodeCache::print_summary(st);
900    st->cr();
901  }
902
903  // STEP("(printing ring buffers)")
904
905  Events::print_all(st);
906  st->cr();
907
908  // STEP("(printing dynamic libraries)")
909
910  // dynamic libraries, or memory map
911  os::print_dll_info(st);
912  st->cr();
913
914  // STEP("(printing VM options)")
915
916  // VM options
917  Arguments::print_on(st);
918  st->cr();
919
920  // STEP("(printing warning if internal testing API used)")
921
922  if (WhiteBox::used()) {
923    st->print_cr("Unsupported internal testing APIs have been used.");
924    st->cr();
925  }
926
927  // STEP("(printing all environment variables)")
928
929  os::print_environment_variables(st, env_list);
930  st->cr();
931
932  // STEP("(printing signal handlers)")
933
934  os::print_signal_handlers(st, buf, sizeof(buf));
935  st->cr();
936
937  // STEP("(Native Memory Tracking)")
938
939  MemTracker::error_report(st);
940
941  // STEP("(printing system)")
942
943  st->cr();
944  st->print_cr("---------------  S Y S T E M  ---------------");
945  st->cr();
946
947  // STEP("(printing OS information)")
948
949  os::print_os_info(st);
950  st->cr();
951
952  // STEP("(printing CPU info)")
953
954  os::print_cpu_info(st, buf, sizeof(buf));
955  st->cr();
956
957  // STEP("(printing memory info)")
958
959  os::print_memory_info(st);
960  st->cr();
961
962  // STEP("(printing internal vm info)")
963
964  st->print_cr("vm_info: %s", Abstract_VM_Version::internal_vm_info_string());
965  st->cr();
966
967  // print a defined marker to show that error handling finished correctly.
968  // STEP("(printing end marker)")
969
970  st->print_cr("END.");
971}
972
973volatile intptr_t VMError::first_error_tid = -1;
974
975// An error could happen before tty is initialized or after it has been
976// destroyed. Here we use a very simple unbuffered fdStream for printing.
977// Only out.print_raw() and out.print_raw_cr() should be used, as other
978// printing methods need to allocate large buffer on stack. To format a
979// string, use jio_snprintf() with a static buffer or use staticBufferStream.
980fdStream VMError::out(defaultStream::output_fd());
981fdStream VMError::log; // error log used by VMError::report_and_die()
982
983/** Expand a pattern into a buffer starting at pos and open a file using constructed path */
984static int expand_and_open(const char* pattern, char* buf, size_t buflen, size_t pos) {
985  int fd = -1;
986  if (Arguments::copy_expand_pid(pattern, strlen(pattern), &buf[pos], buflen - pos)) {
987    // the O_EXCL flag will cause the open to fail if the file exists
988    fd = open(buf, O_RDWR | O_CREAT | O_EXCL, 0666);
989  }
990  return fd;
991}
992
993/**
994 * Construct file name for a log file and return it's file descriptor.
995 * Name and location depends on pattern, default_pattern params and access
996 * permissions.
997 */
998static int prepare_log_file(const char* pattern, const char* default_pattern, char* buf, size_t buflen) {
999  int fd = -1;
1000
1001  // If possible, use specified pattern to construct log file name
1002  if (pattern != NULL) {
1003    fd = expand_and_open(pattern, buf, buflen, 0);
1004  }
1005
1006  // Either user didn't specify, or the user's location failed,
1007  // so use the default name in the current directory
1008  if (fd == -1) {
1009    const char* cwd = os::get_current_directory(buf, buflen);
1010    if (cwd != NULL) {
1011      size_t pos = strlen(cwd);
1012      int fsep_len = jio_snprintf(&buf[pos], buflen-pos, "%s", os::file_separator());
1013      pos += fsep_len;
1014      if (fsep_len > 0) {
1015        fd = expand_and_open(default_pattern, buf, buflen, pos);
1016      }
1017    }
1018  }
1019
1020   // try temp directory if it exists.
1021   if (fd == -1) {
1022     const char* tmpdir = os::get_temp_directory();
1023     if (tmpdir != NULL && strlen(tmpdir) > 0) {
1024       int pos = jio_snprintf(buf, buflen, "%s%s", tmpdir, os::file_separator());
1025       if (pos > 0) {
1026         fd = expand_and_open(default_pattern, buf, buflen, pos);
1027       }
1028     }
1029   }
1030
1031  return fd;
1032}
1033
1034int         VMError::_id;
1035const char* VMError::_message;
1036char        VMError::_detail_msg[1024];
1037Thread*     VMError::_thread;
1038address     VMError::_pc;
1039void*       VMError::_siginfo;
1040void*       VMError::_context;
1041const char* VMError::_filename;
1042int         VMError::_lineno;
1043size_t      VMError::_size;
1044
1045void VMError::report_and_die(Thread* thread, unsigned int sig, address pc, void* siginfo,
1046                             void* context, const char* detail_fmt, ...)
1047{
1048  va_list detail_args;
1049  va_start(detail_args, detail_fmt);
1050  report_and_die(sig, NULL, detail_fmt, detail_args, thread, pc, siginfo, context, NULL, 0, 0);
1051  va_end(detail_args);
1052}
1053
1054void VMError::report_and_die(Thread* thread, unsigned int sig, address pc, void* siginfo, void* context)
1055{
1056  report_and_die(thread, sig, pc, siginfo, context, "%s", "");
1057}
1058
1059void VMError::report_and_die(const char* message, const char* detail_fmt, ...)
1060{
1061  va_list detail_args;
1062  va_start(detail_args, detail_fmt);
1063  report_and_die(INTERNAL_ERROR, message, detail_fmt, detail_args, NULL, NULL, NULL, NULL, NULL, 0, 0);
1064  va_end(detail_args);
1065}
1066
1067void VMError::report_and_die(const char* message)
1068{
1069  report_and_die(message, "%s", "");
1070}
1071
1072void VMError::report_and_die(Thread* thread, const char* filename, int lineno, const char* message,
1073                             const char* detail_fmt, va_list detail_args)
1074{
1075  report_and_die(INTERNAL_ERROR, message, detail_fmt, detail_args, thread, NULL, NULL, NULL, filename, lineno, 0);
1076}
1077
1078void VMError::report_and_die(Thread* thread, const char* filename, int lineno, size_t size,
1079                             VMErrorType vm_err_type, const char* detail_fmt, va_list detail_args) {
1080  report_and_die(vm_err_type, NULL, detail_fmt, detail_args, thread, NULL, NULL, NULL, filename, lineno, size);
1081}
1082
1083void VMError::report_and_die(int id, const char* message, const char* detail_fmt, va_list detail_args,
1084                             Thread* thread, address pc, void* siginfo, void* context, const char* filename,
1085                             int lineno, size_t size)
1086{
1087  // Don't allocate large buffer on stack
1088  static char buffer[O_BUFLEN];
1089
1090  // How many errors occurred in error handler when reporting first_error.
1091  static int recursive_error_count;
1092
1093  // We will first print a brief message to standard out (verbose = false),
1094  // then save detailed information in log file (verbose = true).
1095  static bool out_done = false;         // done printing to standard out
1096  static bool log_done = false;         // done saving error log
1097  static bool transmit_report_done = false; // done error reporting
1098
1099  if (SuppressFatalErrorMessage) {
1100      os::abort(CreateCoredumpOnCrash);
1101  }
1102  intptr_t mytid = os::current_thread_id();
1103  if (first_error_tid == -1 &&
1104      Atomic::cmpxchg_ptr(mytid, &first_error_tid, -1) == -1) {
1105
1106    _id = id;
1107    _message = message;
1108    _thread = thread;
1109    _pc = pc;
1110    _siginfo = siginfo;
1111    _context = context;
1112    _filename = filename;
1113    _lineno = lineno;
1114    _size = size;
1115    jio_vsnprintf(_detail_msg, sizeof(_detail_msg), detail_fmt, detail_args);
1116
1117    // first time
1118    set_error_reported();
1119
1120    if (ShowMessageBoxOnError || PauseAtExit) {
1121      show_message_box(buffer, sizeof(buffer));
1122
1123      // User has asked JVM to abort. Reset ShowMessageBoxOnError so the
1124      // WatcherThread can kill JVM if the error handler hangs.
1125      ShowMessageBoxOnError = false;
1126    }
1127
1128    os::check_dump_limit(buffer, sizeof(buffer));
1129
1130    // reset signal handlers or exception filter; make sure recursive crashes
1131    // are handled properly.
1132    reset_signal_handlers();
1133
1134  } else {
1135    // If UseOsErrorReporting we call this for each level of the call stack
1136    // while searching for the exception handler.  Only the first level needs
1137    // to be reported.
1138    if (UseOSErrorReporting && log_done) return;
1139
1140    // This is not the first error, see if it happened in a different thread
1141    // or in the same thread during error reporting.
1142    if (first_error_tid != mytid) {
1143      char msgbuf[64];
1144      jio_snprintf(msgbuf, sizeof(msgbuf),
1145                   "[thread " INTX_FORMAT " also had an error]",
1146                   mytid);
1147      out.print_raw_cr(msgbuf);
1148
1149      // error reporting is not MT-safe, block current thread
1150      os::infinite_sleep();
1151
1152    } else {
1153      if (recursive_error_count++ > 30) {
1154        out.print_raw_cr("[Too many errors, abort]");
1155        os::die();
1156      }
1157
1158      jio_snprintf(buffer, sizeof(buffer),
1159                   "[error occurred during error reporting %s, id 0x%x]",
1160                   _current_step_info, _id);
1161      if (log.is_open()) {
1162        log.cr();
1163        log.print_raw_cr(buffer);
1164        log.cr();
1165      } else {
1166        out.cr();
1167        out.print_raw_cr(buffer);
1168        out.cr();
1169      }
1170    }
1171  }
1172
1173  // print to screen
1174  if (!out_done) {
1175    staticBufferStream sbs(buffer, sizeof(buffer), &out);
1176    report(&sbs, false);
1177
1178    out_done = true;
1179
1180    _current_step = 0;
1181    _current_step_info = "";
1182  }
1183
1184  // print to error log file
1185  if (!log_done) {
1186    // see if log file is already open
1187    if (!log.is_open()) {
1188      // open log file
1189      int fd = prepare_log_file(ErrorFile, "hs_err_pid%p.log", buffer, sizeof(buffer));
1190      if (fd != -1) {
1191        out.print_raw("# An error report file with more information is saved as:\n# ");
1192        out.print_raw_cr(buffer);
1193
1194        log.set_fd(fd);
1195      } else {
1196        out.print_raw_cr("# Can not save log file, dump to screen..");
1197        log.set_fd(defaultStream::output_fd());
1198        /* Error reporting currently needs dumpfile.
1199         * Maybe implement direct streaming in the future.*/
1200        transmit_report_done = true;
1201      }
1202    }
1203
1204    staticBufferStream sbs(buffer, O_BUFLEN, &log);
1205    report(&sbs, true);
1206    _current_step = 0;
1207    _current_step_info = "";
1208
1209    // Run error reporting to determine whether or not to report the crash.
1210    if (!transmit_report_done && should_report_bug(_id)) {
1211      transmit_report_done = true;
1212      const int fd2 = ::dup(log.fd());
1213      FILE* const hs_err = ::fdopen(fd2, "r");
1214      if (NULL != hs_err) {
1215        ErrorReporter er;
1216        er.call(hs_err, buffer, O_BUFLEN);
1217      }
1218      ::fclose(hs_err);
1219    }
1220
1221    if (log.fd() != defaultStream::output_fd()) {
1222      close(log.fd());
1223    }
1224
1225    log.set_fd(-1);
1226    log_done = true;
1227  }
1228
1229
1230  static bool skip_OnError = false;
1231  if (!skip_OnError && OnError && OnError[0]) {
1232    skip_OnError = true;
1233
1234    out.print_raw_cr("#");
1235    out.print_raw   ("# -XX:OnError=\"");
1236    out.print_raw   (OnError);
1237    out.print_raw_cr("\"");
1238
1239    char* cmd;
1240    const char* ptr = OnError;
1241    while ((cmd = next_OnError_command(buffer, sizeof(buffer), &ptr)) != NULL){
1242      out.print_raw   ("#   Executing ");
1243#if defined(LINUX) || defined(_ALLBSD_SOURCE)
1244      out.print_raw   ("/bin/sh -c ");
1245#elif defined(SOLARIS)
1246      out.print_raw   ("/usr/bin/sh -c ");
1247#endif
1248      out.print_raw   ("\"");
1249      out.print_raw   (cmd);
1250      out.print_raw_cr("\" ...");
1251
1252      if (os::fork_and_exec(cmd) < 0) {
1253        out.print_cr("os::fork_and_exec failed: %s (%d)", strerror(errno), errno);
1254      }
1255    }
1256
1257    // done with OnError
1258    OnError = NULL;
1259  }
1260
1261  static bool skip_replay = ReplayCompiles; // Do not overwrite file during replay
1262  if (DumpReplayDataOnError && _thread && _thread->is_Compiler_thread() && !skip_replay) {
1263    skip_replay = true;
1264    ciEnv* env = ciEnv::current();
1265    if (env != NULL) {
1266      int fd = prepare_log_file(ReplayDataFile, "replay_pid%p.log", buffer, sizeof(buffer));
1267      if (fd != -1) {
1268        FILE* replay_data_file = os::open(fd, "w");
1269        if (replay_data_file != NULL) {
1270          fileStream replay_data_stream(replay_data_file, /*need_close=*/true);
1271          env->dump_replay_data_unsafe(&replay_data_stream);
1272          out.print_raw("#\n# Compiler replay data is saved as:\n# ");
1273          out.print_raw_cr(buffer);
1274        } else {
1275          out.print_raw("#\n# Can't open file to dump replay data. Error: ");
1276          out.print_raw_cr(strerror(os::get_last_error()));
1277        }
1278      }
1279    }
1280  }
1281
1282  static bool skip_bug_url = !should_report_bug(_id);
1283  if (!skip_bug_url) {
1284    skip_bug_url = true;
1285
1286    out.print_raw_cr("#");
1287    print_bug_submit_message(&out, _thread);
1288  }
1289
1290  if (!UseOSErrorReporting) {
1291    // os::abort() will call abort hooks, try it first.
1292    static bool skip_os_abort = false;
1293    if (!skip_os_abort) {
1294      skip_os_abort = true;
1295      bool dump_core = should_report_bug(_id);
1296      os::abort(dump_core && CreateCoredumpOnCrash, _siginfo, _context);
1297    }
1298
1299    // if os::abort() doesn't abort, try os::die();
1300    os::die();
1301  }
1302}
1303
1304/*
1305 * OnOutOfMemoryError scripts/commands executed while VM is a safepoint - this
1306 * ensures utilities such as jmap can observe the process is a consistent state.
1307 */
1308class VM_ReportJavaOutOfMemory : public VM_Operation {
1309 private:
1310  const char* _message;
1311 public:
1312  VM_ReportJavaOutOfMemory(const char* message) { _message = message; }
1313  VMOp_Type type() const                        { return VMOp_ReportJavaOutOfMemory; }
1314  void doit();
1315};
1316
1317void VM_ReportJavaOutOfMemory::doit() {
1318  // Don't allocate large buffer on stack
1319  static char buffer[O_BUFLEN];
1320
1321  tty->print_cr("#");
1322  tty->print_cr("# java.lang.OutOfMemoryError: %s", _message);
1323  tty->print_cr("# -XX:OnOutOfMemoryError=\"%s\"", OnOutOfMemoryError);
1324
1325  // make heap parsability
1326  Universe::heap()->ensure_parsability(false);  // no need to retire TLABs
1327
1328  char* cmd;
1329  const char* ptr = OnOutOfMemoryError;
1330  while ((cmd = next_OnError_command(buffer, sizeof(buffer), &ptr)) != NULL){
1331    tty->print("#   Executing ");
1332#if defined(LINUX)
1333    tty->print  ("/bin/sh -c ");
1334#elif defined(SOLARIS)
1335    tty->print  ("/usr/bin/sh -c ");
1336#endif
1337    tty->print_cr("\"%s\"...", cmd);
1338
1339    if (os::fork_and_exec(cmd) < 0) {
1340      tty->print_cr("os::fork_and_exec failed: %s (%d)", strerror(errno), errno);
1341    }
1342  }
1343}
1344
1345void VMError::report_java_out_of_memory(const char* message) {
1346  if (OnOutOfMemoryError && OnOutOfMemoryError[0]) {
1347    MutexLocker ml(Heap_lock);
1348    VM_ReportJavaOutOfMemory op(message);
1349    VMThread::execute(&op);
1350  }
1351}
1352
1353void VMError::show_message_box(char *buf, int buflen) {
1354  bool yes;
1355  do {
1356    error_string(buf, buflen);
1357    yes = os::start_debugging(buf,buflen);
1358  } while (yes);
1359}
1360