1 /*
2 * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "precompiled.hpp"
26 #include "jvm.h"
27 #include "code/codeCache.hpp"
28 #include "compiler/compileBroker.hpp"
29 #include "compiler/disassembler.hpp"
30 #include "gc/shared/gcConfig.hpp"
31 #include "logging/logConfiguration.hpp"
32 #include "jfr/jfrEvents.hpp"
33 #include "memory/resourceArea.hpp"
34 #include "memory/universe.hpp"
35 #include "oops/compressedOops.hpp"
36 #include "prims/whitebox.hpp"
37 #include "runtime/arguments.hpp"
38 #include "runtime/atomic.hpp"
39 #include "runtime/frame.inline.hpp"
40 #include "runtime/init.hpp"
41 #include "runtime/os.hpp"
42 #include "runtime/thread.inline.hpp"
43 #include "runtime/threadSMR.hpp"
44 #include "runtime/vmThread.hpp"
45 #include "runtime/vmOperations.hpp"
46 #include "runtime/vm_version.hpp"
47 #include "runtime/flags/jvmFlag.hpp"
48 #include "services/memTracker.hpp"
49 #include "utilities/debug.hpp"
50 #include "utilities/decoder.hpp"
51 #include "utilities/defaultStream.hpp"
52 #include "utilities/events.hpp"
53 #include "utilities/vmError.hpp"
54 #include "utilities/macros.hpp"
55 #if INCLUDE_JFR
56 #include "jfr/jfr.hpp"
57 #endif
58
59 #ifndef PRODUCT
60 #include <signal.h>
61 #endif // PRODUCT
62
63 bool VMError::_error_reported = false;
64
65 // call this when the VM is dying--it might loosen some asserts
is_error_reported()66 bool VMError::is_error_reported() { return _error_reported; }
67
68 // returns an address which is guaranteed to generate a SIGSEGV on read,
69 // for test purposes, which is not NULL and contains bits in every word
get_segfault_address()70 void* VMError::get_segfault_address() {
71 return (void*)
72 #ifdef _LP64
73 0xABC0000000000ABCULL;
74 #else
75 0x00000ABC;
76 #endif
77 }
78
79 // List of environment variables that should be reported in error log file.
80 const char *env_list[] = {
81 // All platforms
82 "JAVA_HOME", "JRE_HOME", "JAVA_TOOL_OPTIONS", "_JAVA_OPTIONS", "CLASSPATH",
83 "JAVA_COMPILER", "PATH", "USERNAME",
84
85 // Env variables that are defined on Solaris/Linux/BSD
86 "LD_LIBRARY_PATH", "LD_PRELOAD", "SHELL", "DISPLAY",
87 "HOSTTYPE", "OSTYPE", "ARCH", "MACHTYPE",
88 "LANG", "LC_ALL", "LC_CTYPE", "TZ",
89
90 // defined on AIX
91 "LIBPATH", "LDR_PRELOAD", "LDR_PRELOAD64",
92
93 // defined on Linux
94 "LD_ASSUME_KERNEL", "_JAVA_SR_SIGNUM",
95
96 // defined on Darwin
97 "DYLD_LIBRARY_PATH", "DYLD_FALLBACK_LIBRARY_PATH",
98 "DYLD_FRAMEWORK_PATH", "DYLD_FALLBACK_FRAMEWORK_PATH",
99 "DYLD_INSERT_LIBRARIES",
100
101 // defined on Windows
102 "OS", "PROCESSOR_IDENTIFIER", "_ALT_JAVA_HOME_DIR",
103
104 (const char *)0
105 };
106
107 // A simple parser for -XX:OnError, usage:
108 // ptr = OnError;
109 // while ((cmd = next_OnError_command(buffer, sizeof(buffer), &ptr) != NULL)
110 // ... ...
next_OnError_command(char * buf,int buflen,const char ** ptr)111 static char* next_OnError_command(char* buf, int buflen, const char** ptr) {
112 if (ptr == NULL || *ptr == NULL) return NULL;
113
114 const char* cmd = *ptr;
115
116 // skip leading blanks or ';'
117 while (*cmd == ' ' || *cmd == ';') cmd++;
118
119 if (*cmd == '\0') return NULL;
120
121 const char * cmdend = cmd;
122 while (*cmdend != '\0' && *cmdend != ';') cmdend++;
123
124 Arguments::copy_expand_pid(cmd, cmdend - cmd, buf, buflen);
125
126 *ptr = (*cmdend == '\0' ? cmdend : cmdend + 1);
127 return buf;
128 }
129
print_bug_submit_message(outputStream * out,Thread * thread)130 static void print_bug_submit_message(outputStream *out, Thread *thread) {
131 if (out == NULL) return;
132 const char *url = Arguments::java_vendor_url_bug();
133 if (url == NULL || *url == '\0')
134 url = JDK_Version::runtime_vendor_vm_bug_url();
135 if (url != NULL && *url != '\0') {
136 out->print_raw_cr("# If you would like to submit a bug report, please visit:");
137 out->print_raw ("# ");
138 out->print_raw_cr(url);
139 }
140 // If the crash is in native code, encourage user to submit a bug to the
141 // provider of that code.
142 if (thread && thread->is_Java_thread() &&
143 !thread->is_hidden_from_external_view()) {
144 JavaThread* jt = (JavaThread*)thread;
145 if (jt->thread_state() == _thread_in_native) {
146 out->print_cr("# The crash happened outside the Java Virtual Machine in native code.\n# See problematic frame for where to report the bug.");
147 }
148 }
149 out->print_raw_cr("#");
150 }
151
152 bool VMError::coredump_status;
153 char VMError::coredump_message[O_BUFLEN];
154
record_coredump_status(const char * message,bool status)155 void VMError::record_coredump_status(const char* message, bool status) {
156 coredump_status = status;
157 strncpy(coredump_message, message, sizeof(coredump_message));
158 coredump_message[sizeof(coredump_message)-1] = 0;
159 }
160
161 // Return a string to describe the error
error_string(char * buf,int buflen)162 char* VMError::error_string(char* buf, int buflen) {
163 char signame_buf[64];
164 const char *signame = os::exception_name(_id, signame_buf, sizeof(signame_buf));
165
166 if (signame) {
167 jio_snprintf(buf, buflen,
168 "%s (0x%x) at pc=" PTR_FORMAT ", pid=%d, tid=" UINTX_FORMAT,
169 signame, _id, _pc,
170 os::current_process_id(), os::current_thread_id());
171 } else if (_filename != NULL && _lineno > 0) {
172 // skip directory names
173 char separator = os::file_separator()[0];
174 const char *p = strrchr(_filename, separator);
175 int n = jio_snprintf(buf, buflen,
176 "Internal Error at %s:%d, pid=%d, tid=" UINTX_FORMAT,
177 p ? p + 1 : _filename, _lineno,
178 os::current_process_id(), os::current_thread_id());
179 if (n >= 0 && n < buflen && _message) {
180 if (strlen(_detail_msg) > 0) {
181 jio_snprintf(buf + n, buflen - n, "%s%s: %s",
182 os::line_separator(), _message, _detail_msg);
183 } else {
184 jio_snprintf(buf + n, buflen - n, "%sError: %s",
185 os::line_separator(), _message);
186 }
187 }
188 } else {
189 jio_snprintf(buf, buflen,
190 "Internal Error (0x%x), pid=%d, tid=" UINTX_FORMAT,
191 _id, os::current_process_id(), os::current_thread_id());
192 }
193
194 return buf;
195 }
196
print_stack_trace(outputStream * st,JavaThread * jt,char * buf,int buflen,bool verbose)197 void VMError::print_stack_trace(outputStream* st, JavaThread* jt,
198 char* buf, int buflen, bool verbose) {
199 #ifdef ZERO
200 if (jt->zero_stack()->sp() && jt->top_zero_frame()) {
201 // StackFrameStream uses the frame anchor, which may not have
202 // been set up. This can be done at any time in Zero, however,
203 // so if it hasn't been set up then we just set it up now and
204 // clear it again when we're done.
205 bool has_last_Java_frame = jt->has_last_Java_frame();
206 if (!has_last_Java_frame)
207 jt->set_last_Java_frame();
208 st->print("Java frames:");
209 st->cr();
210
211 // Print the frames
212 StackFrameStream sfs(jt);
213 for(int i = 0; !sfs.is_done(); sfs.next(), i++) {
214 sfs.current()->zero_print_on_error(i, st, buf, buflen);
215 st->cr();
216 }
217
218 // Reset the frame anchor if necessary
219 if (!has_last_Java_frame)
220 jt->reset_last_Java_frame();
221 }
222 #else
223 if (jt->has_last_Java_frame()) {
224 st->print_cr("Java frames: (J=compiled Java code, j=interpreted, Vv=VM code)");
225 for(StackFrameStream sfs(jt); !sfs.is_done(); sfs.next()) {
226 sfs.current()->print_on_error(st, buf, buflen, verbose);
227 st->cr();
228 }
229 }
230 #endif // ZERO
231 }
232
print_native_stack(outputStream * st,frame fr,Thread * t,char * buf,int buf_size)233 void VMError::print_native_stack(outputStream* st, frame fr, Thread* t, char* buf, int buf_size) {
234
235 // see if it's a valid frame
236 if (fr.pc()) {
237 st->print_cr("Native frames: (J=compiled Java code, A=aot compiled Java code, j=interpreted, Vv=VM code, C=native code)");
238
239 int count = 0;
240 while (count++ < StackPrintLimit) {
241 fr.print_on_error(st, buf, buf_size);
242 if (fr.pc()) { // print source file and line, if available
243 char buf[128];
244 int line_no;
245 if (Decoder::get_source_info(fr.pc(), buf, sizeof(buf), &line_no)) {
246 st->print(" (%s:%d)", buf, line_no);
247 }
248 }
249 st->cr();
250 // Compiled code may use EBP register on x86 so it looks like
251 // non-walkable C frame. Use frame.sender() for java frames.
252 if (t && t->is_Java_thread()) {
253 // Catch very first native frame by using stack address.
254 // For JavaThread stack_base and stack_size should be set.
255 if (!t->on_local_stack((address)(fr.real_fp() + 1))) {
256 break;
257 }
258 if (fr.is_java_frame() || fr.is_native_frame() || fr.is_runtime_frame()) {
259 RegisterMap map((JavaThread*)t, false); // No update
260 fr = fr.sender(&map);
261 } else {
262 // is_first_C_frame() does only simple checks for frame pointer,
263 // it will pass if java compiled code has a pointer in EBP.
264 if (os::is_first_C_frame(&fr)) break;
265 fr = os::get_sender_for_C_frame(&fr);
266 }
267 } else {
268 if (os::is_first_C_frame(&fr)) break;
269 fr = os::get_sender_for_C_frame(&fr);
270 }
271 }
272
273 if (count > StackPrintLimit) {
274 st->print_cr("...<more frames>...");
275 }
276
277 st->cr();
278 }
279 }
280
print_oom_reasons(outputStream * st)281 static void print_oom_reasons(outputStream* st) {
282 st->print_cr("# Possible reasons:");
283 st->print_cr("# The system is out of physical RAM or swap space");
284 if (UseCompressedOops) {
285 st->print_cr("# The process is running with CompressedOops enabled, and the Java Heap may be blocking the growth of the native heap");
286 }
287 if (LogBytesPerWord == 2) {
288 st->print_cr("# In 32 bit mode, the process size limit was hit");
289 }
290 st->print_cr("# Possible solutions:");
291 st->print_cr("# Reduce memory load on the system");
292 st->print_cr("# Increase physical memory or swap space");
293 st->print_cr("# Check if swap backing store is full");
294 if (LogBytesPerWord == 2) {
295 st->print_cr("# Use 64 bit Java on a 64 bit OS");
296 }
297 st->print_cr("# Decrease Java heap size (-Xmx/-Xms)");
298 st->print_cr("# Decrease number of Java threads");
299 st->print_cr("# Decrease Java thread stack sizes (-Xss)");
300 st->print_cr("# Set larger code cache with -XX:ReservedCodeCacheSize=");
301 if (UseCompressedOops) {
302 switch (CompressedOops::mode()) {
303 case CompressedOops::UnscaledNarrowOop:
304 st->print_cr("# JVM is running with Unscaled Compressed Oops mode in which the Java heap is");
305 st->print_cr("# placed in the first 4GB address space. The Java Heap base address is the");
306 st->print_cr("# maximum limit for the native heap growth. Please use -XX:HeapBaseMinAddress");
307 st->print_cr("# to set the Java Heap base and to place the Java Heap above 4GB virtual address.");
308 break;
309 case CompressedOops::ZeroBasedNarrowOop:
310 st->print_cr("# JVM is running with Zero Based Compressed Oops mode in which the Java heap is");
311 st->print_cr("# placed in the first 32GB address space. The Java Heap base address is the");
312 st->print_cr("# maximum limit for the native heap growth. Please use -XX:HeapBaseMinAddress");
313 st->print_cr("# to set the Java Heap base and to place the Java Heap above 32GB virtual address.");
314 break;
315 default:
316 break;
317 }
318 }
319 st->print_cr("# This output file may be truncated or incomplete.");
320 }
321
report_vm_version(outputStream * st,char * buf,int buflen)322 static void report_vm_version(outputStream* st, char* buf, int buflen) {
323 // VM version
324 st->print_cr("#");
325 JDK_Version::current().to_string(buf, buflen);
326 const char* runtime_name = JDK_Version::runtime_name() != NULL ?
327 JDK_Version::runtime_name() : "";
328 const char* runtime_version = JDK_Version::runtime_version() != NULL ?
329 JDK_Version::runtime_version() : "";
330 const char* vendor_version = JDK_Version::runtime_vendor_version() != NULL ?
331 JDK_Version::runtime_vendor_version() : "";
332 const char* jdk_debug_level = VM_Version::printable_jdk_debug_level() != NULL ?
333 VM_Version::printable_jdk_debug_level() : "";
334
335 st->print_cr("# JRE version: %s%s%s (%s) (%sbuild %s)", runtime_name,
336 (*vendor_version != '\0') ? " " : "", vendor_version,
337 buf, jdk_debug_level, runtime_version);
338
339 // This is the long version with some default settings added
340 st->print_cr("# Java VM: %s%s%s (%s%s, %s%s%s%s%s, %s, %s)",
341 VM_Version::vm_name(),
342 (*vendor_version != '\0') ? " " : "", vendor_version,
343 jdk_debug_level,
344 VM_Version::vm_release(),
345 VM_Version::vm_info_string(),
346 TieredCompilation ? ", tiered" : "",
347 #if INCLUDE_JVMCI
348 EnableJVMCI ? ", jvmci" : "",
349 UseJVMCICompiler ? ", jvmci compiler" : "",
350 #else
351 "", "",
352 #endif
353 UseCompressedOops ? ", compressed oops" : "",
354 GCConfig::hs_err_name(),
355 VM_Version::vm_platform_string()
356 );
357 }
358
359 // This is the main function to report a fatal error. Only one thread can
360 // call this function, so we don't need to worry about MT-safety. But it's
361 // possible that the error handler itself may crash or die on an internal
362 // error, for example, when the stack/heap is badly damaged. We must be
363 // able to handle recursive errors that happen inside error handler.
364 //
365 // Error reporting is done in several steps. If a crash or internal error
366 // occurred when reporting an error, the nested signal/exception handler
367 // can skip steps that are already (or partially) done. Error reporting will
368 // continue from the next step. This allows us to retrieve and print
369 // information that may be unsafe to get after a fatal error. If it happens,
370 // you may find nested report_and_die() frames when you look at the stack
371 // in a debugger.
372 //
373 // In general, a hang in error handler is much worse than a crash or internal
374 // error, as it's harder to recover from a hang. Deadlock can happen if we
375 // try to grab a lock that is already owned by current thread, or if the
376 // owner is blocked forever (e.g. in os::infinite_sleep()). If possible, the
377 // error handler and all the functions it called should avoid grabbing any
378 // lock. An important thing to notice is that memory allocation needs a lock.
379 //
380 // We should avoid using large stack allocated buffers. Many errors happen
381 // when stack space is already low. Making things even worse is that there
382 // could be nested report_and_die() calls on stack (see above). Only one
383 // thread can report error, so large buffers are statically allocated in data
384 // segment.
385
386 int VMError::_current_step;
387 const char* VMError::_current_step_info;
388
389 volatile jlong VMError::_reporting_start_time = -1;
390 volatile bool VMError::_reporting_did_timeout = false;
391 volatile jlong VMError::_step_start_time = -1;
392 volatile bool VMError::_step_did_timeout = false;
393
394 // Helper, return current timestamp for timeout handling.
get_current_timestamp()395 jlong VMError::get_current_timestamp() {
396 return os::javaTimeNanos();
397 }
398 // Factor to translate the timestamp to seconds.
399 #define TIMESTAMP_TO_SECONDS_FACTOR (1000 * 1000 * 1000)
400
record_reporting_start_time()401 void VMError::record_reporting_start_time() {
402 const jlong now = get_current_timestamp();
403 Atomic::store(now, &_reporting_start_time);
404 }
405
get_reporting_start_time()406 jlong VMError::get_reporting_start_time() {
407 return Atomic::load(&_reporting_start_time);
408 }
409
record_step_start_time()410 void VMError::record_step_start_time() {
411 const jlong now = get_current_timestamp();
412 Atomic::store(now, &_step_start_time);
413 }
414
get_step_start_time()415 jlong VMError::get_step_start_time() {
416 return Atomic::load(&_step_start_time);
417 }
418
clear_step_start_time()419 void VMError::clear_step_start_time() {
420 return Atomic::store((jlong)0, &_step_start_time);
421 }
422
report(outputStream * st,bool _verbose)423 void VMError::report(outputStream* st, bool _verbose) {
424
425 # define BEGIN if (_current_step == 0) { _current_step = __LINE__;
426 # define STEP(s) } if (_current_step < __LINE__) { _current_step = __LINE__; _current_step_info = s; \
427 record_step_start_time(); _step_did_timeout = false;
428 # define END clear_step_start_time(); }
429
430 // don't allocate large buffer on stack
431 static char buf[O_BUFLEN];
432
433 BEGIN
434
435 STEP("printing fatal error message")
436
437 st->print_cr("#");
438 if (should_report_bug(_id)) {
439 st->print_cr("# A fatal error has been detected by the Java Runtime Environment:");
440 } else {
441 st->print_cr("# There is insufficient memory for the Java "
442 "Runtime Environment to continue.");
443 }
444
445 #ifndef PRODUCT
446 // Error handler self tests
447
448 // test secondary error handling. Test it twice, to test that resetting
449 // error handler after a secondary crash works.
450 STEP("test secondary crash 1")
451 if (_verbose && TestCrashInErrorHandler != 0) {
452 st->print_cr("Will crash now (TestCrashInErrorHandler=" UINTX_FORMAT ")...",
453 TestCrashInErrorHandler);
454 controlled_crash(TestCrashInErrorHandler);
455 }
456
457 STEP("test secondary crash 2")
458 if (_verbose && TestCrashInErrorHandler != 0) {
459 st->print_cr("Will crash now (TestCrashInErrorHandler=" UINTX_FORMAT ")...",
460 TestCrashInErrorHandler);
461 controlled_crash(TestCrashInErrorHandler);
462 }
463
464 // TestUnresponsiveErrorHandler: We want to test both step timeouts and global timeout.
465 // Step to global timeout ratio is 4:1, so in order to be absolutely sure we hit the
466 // global timeout, let's execute the timeout step five times.
467 // See corresponding test in test/runtime/ErrorHandling/TimeoutInErrorHandlingTest.java
468 STEP("setup for test unresponsive error reporting step")
469 if (_verbose && TestUnresponsiveErrorHandler) {
470 // We record reporting_start_time for this test here because we
471 // care about the time spent executing TIMEOUT_TEST_STEP and not
472 // about the time it took us to get here.
473 tty->print_cr("Recording reporting_start_time for TestUnresponsiveErrorHandler.");
474 record_reporting_start_time();
475 }
476
477 #define TIMEOUT_TEST_STEP STEP("test unresponsive error reporting step") \
478 if (_verbose && TestUnresponsiveErrorHandler) { os::infinite_sleep(); }
479 TIMEOUT_TEST_STEP
480 TIMEOUT_TEST_STEP
481 TIMEOUT_TEST_STEP
482 TIMEOUT_TEST_STEP
483 TIMEOUT_TEST_STEP
484
485 STEP("test safefetch in error handler")
486 // test whether it is safe to use SafeFetch32 in Crash Handler. Test twice
487 // to test that resetting the signal handler works correctly.
488 if (_verbose && TestSafeFetchInErrorHandler) {
489 st->print_cr("Will test SafeFetch...");
490 if (CanUseSafeFetch32()) {
491 int* const invalid_pointer = (int*) get_segfault_address();
492 const int x = 0x76543210;
493 int i1 = SafeFetch32(invalid_pointer, x);
494 int i2 = SafeFetch32(invalid_pointer, x);
495 if (i1 == x && i2 == x) {
496 st->print_cr("SafeFetch OK."); // Correctly deflected and returned default pattern
497 } else {
498 st->print_cr("??");
499 }
500 } else {
501 st->print_cr("not possible; skipped.");
502 }
503 }
504 #endif // PRODUCT
505
506 STEP("printing type of error")
507
508 switch(static_cast<unsigned int>(_id)) {
509 case OOM_MALLOC_ERROR:
510 case OOM_MMAP_ERROR:
511 if (_size) {
512 st->print("# Native memory allocation ");
513 st->print((_id == (int)OOM_MALLOC_ERROR) ? "(malloc) failed to allocate " :
514 "(mmap) failed to map ");
515 jio_snprintf(buf, sizeof(buf), SIZE_FORMAT, _size);
516 st->print("%s", buf);
517 st->print(" bytes");
518 if (strlen(_detail_msg) > 0) {
519 st->print(" for ");
520 st->print("%s", _detail_msg);
521 }
522 st->cr();
523 } else {
524 if (strlen(_detail_msg) > 0) {
525 st->print("# ");
526 st->print_cr("%s", _detail_msg);
527 }
528 }
529 // In error file give some solutions
530 if (_verbose) {
531 print_oom_reasons(st);
532 } else {
533 return; // that's enough for the screen
534 }
535 break;
536 case INTERNAL_ERROR:
537 default:
538 break;
539 }
540
541 STEP("printing exception/signal name")
542
543 st->print_cr("#");
544 st->print("# ");
545 // Is it an OS exception/signal?
546 if (os::exception_name(_id, buf, sizeof(buf))) {
547 st->print("%s", buf);
548 st->print(" (0x%x)", _id); // signal number
549 st->print(" at pc=" PTR_FORMAT, p2i(_pc));
550 if (_siginfo != NULL && os::signal_sent_by_kill(_siginfo)) {
551 st->print(" (sent by kill)");
552 }
553 } else {
554 if (should_report_bug(_id)) {
555 st->print("Internal Error");
556 } else {
557 st->print("Out of Memory Error");
558 }
559 if (_filename != NULL && _lineno > 0) {
560 #ifdef PRODUCT
561 // In product mode chop off pathname?
562 char separator = os::file_separator()[0];
563 const char *p = strrchr(_filename, separator);
564 const char *file = p ? p+1 : _filename;
565 #else
566 const char *file = _filename;
567 #endif
568 st->print(" (%s:%d)", file, _lineno);
569 } else {
570 st->print(" (0x%x)", _id);
571 }
572 }
573
574 STEP("printing current thread and pid")
575
576 // process id, thread id
577 st->print(", pid=%d", os::current_process_id());
578 st->print(", tid=" UINTX_FORMAT, os::current_thread_id());
579 st->cr();
580
581 STEP("printing error message")
582
583 if (should_report_bug(_id)) { // already printed the message.
584 // error message
585 if (strlen(_detail_msg) > 0) {
586 st->print_cr("# %s: %s", _message ? _message : "Error", _detail_msg);
587 } else if (_message) {
588 st->print_cr("# Error: %s", _message);
589 }
590 }
591
592 STEP("printing Java version string")
593
594 report_vm_version(st, buf, sizeof(buf));
595
596 STEP("printing problematic frame")
597
598 // Print current frame if we have a context (i.e. it's a crash)
599 if (_context) {
600 st->print_cr("# Problematic frame:");
601 st->print("# ");
602 frame fr = os::fetch_frame_from_context(_context);
603 fr.print_on_error(st, buf, sizeof(buf));
604 st->cr();
605 st->print_cr("#");
606 }
607
608 STEP("printing core file information")
609 st->print("# ");
610 if (CreateCoredumpOnCrash) {
611 if (coredump_status) {
612 st->print("Core dump will be written. Default location: %s", coredump_message);
613 } else {
614 st->print("No core dump will be written. %s", coredump_message);
615 }
616 } else {
617 st->print("CreateCoredumpOnCrash turned off, no core file dumped");
618 }
619 st->cr();
620 st->print_cr("#");
621
622 STEP("printing bug submit message")
623
624 if (should_report_bug(_id) && _verbose) {
625 print_bug_submit_message(st, _thread);
626 }
627
628 STEP("printing summary")
629
630 if (_verbose) {
631 st->cr();
632 st->print_cr("--------------- S U M M A R Y ------------");
633 st->cr();
634 }
635
636 STEP("printing VM option summary")
637
638 if (_verbose) {
639 // VM options
640 Arguments::print_summary_on(st);
641 st->cr();
642 }
643
644 STEP("printing summary machine and OS info")
645
646 if (_verbose) {
647 os::print_summary_info(st, buf, sizeof(buf));
648 }
649
650
651 STEP("printing date and time")
652
653 if (_verbose) {
654 os::print_date_and_time(st, buf, sizeof(buf));
655 }
656
657 STEP("printing thread")
658
659 if (_verbose) {
660 st->cr();
661 st->print_cr("--------------- T H R E A D ---------------");
662 st->cr();
663 }
664
665 STEP("printing current thread")
666
667 // current thread
668 if (_verbose) {
669 if (_thread) {
670 st->print("Current thread (" PTR_FORMAT "): ", p2i(_thread));
671 _thread->print_on_error(st, buf, sizeof(buf));
672 st->cr();
673 } else {
674 st->print_cr("Current thread is native thread");
675 }
676 st->cr();
677 }
678
679 STEP("printing current compile task")
680
681 if (_verbose && _thread && _thread->is_Compiler_thread()) {
682 CompilerThread* t = (CompilerThread*)_thread;
683 if (t->task()) {
684 st->cr();
685 st->print_cr("Current CompileTask:");
686 t->task()->print_line_on_error(st, buf, sizeof(buf));
687 st->cr();
688 }
689 }
690
691
692 STEP("printing stack bounds")
693
694 if (_verbose) {
695 st->print("Stack: ");
696
697 address stack_top;
698 size_t stack_size;
699
700 if (_thread) {
701 stack_top = _thread->stack_base();
702 stack_size = _thread->stack_size();
703 } else {
704 stack_top = os::current_stack_base();
705 stack_size = os::current_stack_size();
706 }
707
708 address stack_bottom = stack_top - stack_size;
709 st->print("[" PTR_FORMAT "," PTR_FORMAT "]", p2i(stack_bottom), p2i(stack_top));
710
711 frame fr = _context ? os::fetch_frame_from_context(_context)
712 : os::current_frame();
713
714 if (fr.sp()) {
715 st->print(", sp=" PTR_FORMAT, p2i(fr.sp()));
716 size_t free_stack_size = pointer_delta(fr.sp(), stack_bottom, 1024);
717 st->print(", free space=" SIZE_FORMAT "k", free_stack_size);
718 }
719
720 st->cr();
721 }
722
723 STEP("printing native stack")
724
725 if (_verbose) {
726 if (os::platform_print_native_stack(st, _context, buf, sizeof(buf))) {
727 // We have printed the native stack in platform-specific code
728 // Windows/x64 needs special handling.
729 } else {
730 frame fr = _context ? os::fetch_frame_from_context(_context)
731 : os::current_frame();
732
733 print_native_stack(st, fr, _thread, buf, sizeof(buf));
734 }
735 }
736
737 STEP("printing Java stack")
738
739 if (_verbose && _thread && _thread->is_Java_thread()) {
740 print_stack_trace(st, (JavaThread*)_thread, buf, sizeof(buf));
741 }
742
743 STEP("printing target Java thread stack")
744
745 // printing Java thread stack trace if it is involved in GC crash
746 if (_verbose && _thread && (_thread->is_Named_thread())) {
747 JavaThread* jt = ((NamedThread *)_thread)->processed_thread();
748 if (jt != NULL) {
749 st->print_cr("JavaThread " PTR_FORMAT " (nid = %d) was being processed", p2i(jt), jt->osthread()->thread_id());
750 print_stack_trace(st, jt, buf, sizeof(buf), true);
751 }
752 }
753
754 STEP("printing siginfo")
755
756 // signal no, signal code, address that caused the fault
757 if (_verbose && _siginfo) {
758 st->cr();
759 os::print_siginfo(st, _siginfo);
760 st->cr();
761 }
762
763 STEP("CDS archive access warning")
764
765 // Print an explicit hint if we crashed on access to the CDS archive.
766 if (_verbose && _siginfo) {
767 check_failing_cds_access(st, _siginfo);
768 st->cr();
769 }
770
771 STEP("printing register info")
772
773 // decode register contents if possible
774 if (_verbose && _context && Universe::is_fully_initialized()) {
775 os::print_register_info(st, _context);
776 st->cr();
777 }
778
779 STEP("printing registers, top of stack, instructions near pc")
780
781 // registers, top of stack, instructions near pc
782 if (_verbose && _context) {
783 os::print_context(st, _context);
784 st->cr();
785 }
786
787 STEP("inspecting top of stack")
788
789 // decode stack contents if possible
790 if (_verbose && _context && Universe::is_fully_initialized()) {
791 frame fr = os::fetch_frame_from_context(_context);
792 const int slots = 8;
793 const intptr_t *start = fr.sp();
794 const intptr_t *end = start + slots;
795 if (is_aligned(start, sizeof(intptr_t)) && os::is_readable_range(start, end)) {
796 st->print_cr("Stack slot to memory mapping:");
797 for (int i = 0; i < slots; ++i) {
798 st->print("stack at sp + %d slots: ", i);
799 os::print_location(st, *(start + i));
800 }
801 }
802 st->cr();
803 }
804
805 STEP("printing code blob if possible")
806
807 if (_verbose && _context) {
808 CodeBlob* cb = CodeCache::find_blob(_pc);
809 if (cb != NULL) {
810 if (Interpreter::contains(_pc)) {
811 // The interpreter CodeBlob is very large so try to print the codelet instead.
812 InterpreterCodelet* codelet = Interpreter::codelet_containing(_pc);
813 if (codelet != NULL) {
814 codelet->print_on(st);
815 Disassembler::decode(codelet->code_begin(), codelet->code_end(), st);
816 }
817 } else {
818 StubCodeDesc* desc = StubCodeDesc::desc_for(_pc);
819 if (desc != NULL) {
820 desc->print_on(st);
821 Disassembler::decode(desc->begin(), desc->end(), st);
822 } else if (_thread != NULL) {
823 // Disassembling nmethod will incur resource memory allocation,
824 // only do so when thread is valid.
825 ResourceMark rm(_thread);
826 Disassembler::decode(cb, st);
827 st->cr();
828 }
829 }
830 }
831 }
832
833 STEP("printing VM operation")
834
835 if (_verbose && _thread && _thread->is_VM_thread()) {
836 VMThread* t = (VMThread*)_thread;
837 VM_Operation* op = t->vm_operation();
838 if (op) {
839 op->print_on_error(st);
840 st->cr();
841 st->cr();
842 }
843 }
844
845 STEP("printing process")
846
847 if (_verbose) {
848 st->cr();
849 st->print_cr("--------------- P R O C E S S ---------------");
850 st->cr();
851 }
852
853 #ifndef _WIN32
854 STEP("printing user info")
855
856 if (ExtensiveErrorReports && _verbose) {
857 os::Posix::print_user_info(st);
858 }
859 #endif
860
861 STEP("printing all threads")
862
863 // all threads
864 if (_verbose && _thread) {
865 Threads::print_on_error(st, _thread, buf, sizeof(buf));
866 st->cr();
867 }
868
869 STEP("printing VM state")
870
871 if (_verbose) {
872 // Safepoint state
873 st->print("VM state:");
874
875 if (SafepointSynchronize::is_synchronizing()) st->print("synchronizing");
876 else if (SafepointSynchronize::is_at_safepoint()) st->print("at safepoint");
877 else st->print("not at safepoint");
878
879 // Also see if error occurred during initialization or shutdown
880 if (!Universe::is_fully_initialized()) {
881 st->print(" (not fully initialized)");
882 } else if (VM_Exit::vm_exited()) {
883 st->print(" (shutting down)");
884 } else {
885 st->print(" (normal execution)");
886 }
887 st->cr();
888 st->cr();
889 }
890
891 STEP("printing owned locks on error")
892
893 // mutexes/monitors that currently have an owner
894 if (_verbose) {
895 print_owned_locks_on_error(st);
896 st->cr();
897 }
898
899 STEP("printing number of OutOfMemoryError and StackOverflow exceptions")
900
901 if (_verbose && Exceptions::has_exception_counts()) {
902 st->print_cr("OutOfMemory and StackOverflow Exception counts:");
903 Exceptions::print_exception_counts_on_error(st);
904 st->cr();
905 }
906
907 STEP("printing compressed oops mode")
908
909 if (_verbose && UseCompressedOops) {
910 CompressedOops::print_mode(st);
911 if (UseCompressedClassPointers) {
912 Metaspace::print_compressed_class_space(st);
913 }
914 st->cr();
915 }
916
917 STEP("printing heap information")
918
919 if (_verbose && Universe::is_fully_initialized()) {
920 Universe::heap()->print_on_error(st);
921 st->cr();
922 st->print_cr("Polling page: " INTPTR_FORMAT, p2i(os::get_polling_page()));
923 st->cr();
924 }
925
926 STEP("printing metaspace information")
927
928 if (_verbose && Universe::is_fully_initialized()) {
929 st->print_cr("Metaspace:");
930 MetaspaceUtils::print_basic_report(st, 0);
931 }
932
933 STEP("printing code cache information")
934
935 if (_verbose && Universe::is_fully_initialized()) {
936 // print code cache information before vm abort
937 CodeCache::print_summary(st);
938 st->cr();
939 }
940
941 STEP("printing ring buffers")
942
943 if (_verbose) {
944 Events::print_all(st);
945 st->cr();
946 }
947
948 STEP("printing dynamic libraries")
949
950 if (_verbose) {
951 // dynamic libraries, or memory map
952 os::print_dll_info(st);
953 st->cr();
954 }
955
956 STEP("printing native decoder state")
957
958 if (_verbose) {
959 Decoder::print_state_on(st);
960 st->cr();
961 }
962
963 STEP("printing VM options")
964
965 if (_verbose) {
966 // VM options
967 Arguments::print_on(st);
968 st->cr();
969 }
970
971 STEP("printing flags")
972
973 if (_verbose) {
974 JVMFlag::printFlags(
975 st,
976 true, // with comments
977 false, // no ranges
978 true); // skip defaults
979 st->cr();
980 }
981
982 STEP("printing warning if internal testing API used")
983
984 if (WhiteBox::used()) {
985 st->print_cr("Unsupported internal testing APIs have been used.");
986 st->cr();
987 }
988
989 STEP("printing log configuration")
990 if (_verbose){
991 st->print_cr("Logging:");
992 LogConfiguration::describe_current_configuration(st);
993 st->cr();
994 }
995
996 STEP("printing all environment variables")
997
998 if (_verbose) {
999 os::print_environment_variables(st, env_list);
1000 st->cr();
1001 }
1002
1003 STEP("printing signal handlers")
1004
1005 if (_verbose) {
1006 os::print_signal_handlers(st, buf, sizeof(buf));
1007 st->cr();
1008 }
1009
1010 STEP("Native Memory Tracking")
1011 if (_verbose) {
1012 MemTracker::error_report(st);
1013 }
1014
1015 STEP("printing system")
1016
1017 if (_verbose) {
1018 st->cr();
1019 st->print_cr("--------------- S Y S T E M ---------------");
1020 st->cr();
1021 }
1022
1023 STEP("printing OS information")
1024
1025 if (_verbose) {
1026 os::print_os_info(st);
1027 st->cr();
1028 }
1029
1030 STEP("printing CPU info")
1031 if (_verbose) {
1032 os::print_cpu_info(st, buf, sizeof(buf));
1033 st->cr();
1034 }
1035
1036 STEP("printing memory info")
1037
1038 if (_verbose) {
1039 os::print_memory_info(st);
1040 st->cr();
1041 }
1042
1043 STEP("printing internal vm info")
1044
1045 if (_verbose) {
1046 st->print_cr("vm_info: %s", VM_Version::internal_vm_info_string());
1047 st->cr();
1048 }
1049
1050 // print a defined marker to show that error handling finished correctly.
1051 STEP("printing end marker")
1052
1053 if (_verbose) {
1054 st->print_cr("END.");
1055 }
1056
1057 END
1058
1059 # undef BEGIN
1060 # undef STEP
1061 # undef END
1062 }
1063
1064 // Report for the vm_info_cmd. This prints out the information above omitting
1065 // crash and thread specific information. If output is added above, it should be added
1066 // here also, if it is safe to call during a running process.
print_vm_info(outputStream * st)1067 void VMError::print_vm_info(outputStream* st) {
1068
1069 char buf[O_BUFLEN];
1070 report_vm_version(st, buf, sizeof(buf));
1071
1072 // STEP("printing summary")
1073
1074 st->cr();
1075 st->print_cr("--------------- S U M M A R Y ------------");
1076 st->cr();
1077
1078 // STEP("printing VM option summary")
1079
1080 // VM options
1081 Arguments::print_summary_on(st);
1082 st->cr();
1083
1084 // STEP("printing summary machine and OS info")
1085
1086 os::print_summary_info(st, buf, sizeof(buf));
1087
1088 // STEP("printing date and time")
1089
1090 os::print_date_and_time(st, buf, sizeof(buf));
1091
1092 // Skip: STEP("printing thread")
1093
1094 // STEP("printing process")
1095
1096 st->cr();
1097 st->print_cr("--------------- P R O C E S S ---------------");
1098 st->cr();
1099
1100 // STEP("printing number of OutOfMemoryError and StackOverflow exceptions")
1101
1102 if (Exceptions::has_exception_counts()) {
1103 st->print_cr("OutOfMemory and StackOverflow Exception counts:");
1104 Exceptions::print_exception_counts_on_error(st);
1105 st->cr();
1106 }
1107
1108 // STEP("printing compressed oops mode")
1109
1110 if (UseCompressedOops) {
1111 CompressedOops::print_mode(st);
1112 if (UseCompressedClassPointers) {
1113 Metaspace::print_compressed_class_space(st);
1114 }
1115 st->cr();
1116 }
1117
1118 // STEP("printing heap information")
1119
1120 if (Universe::is_fully_initialized()) {
1121 MutexLocker hl(Heap_lock);
1122 Universe::heap()->print_on_error(st);
1123 st->cr();
1124 st->print_cr("Polling page: " INTPTR_FORMAT, p2i(os::get_polling_page()));
1125 st->cr();
1126 }
1127
1128 // STEP("printing metaspace information")
1129
1130 if (Universe::is_fully_initialized()) {
1131 st->print_cr("Metaspace:");
1132 MetaspaceUtils::print_basic_report(st, 0);
1133 }
1134
1135 // STEP("printing code cache information")
1136
1137 if (Universe::is_fully_initialized()) {
1138 // print code cache information before vm abort
1139 CodeCache::print_summary(st);
1140 st->cr();
1141 }
1142
1143 // STEP("printing ring buffers")
1144
1145 Events::print_all(st);
1146 st->cr();
1147
1148 // STEP("printing dynamic libraries")
1149
1150 // dynamic libraries, or memory map
1151 os::print_dll_info(st);
1152 st->cr();
1153
1154 // STEP("printing VM options")
1155
1156 // VM options
1157 Arguments::print_on(st);
1158 st->cr();
1159
1160 // STEP("printing warning if internal testing API used")
1161
1162 if (WhiteBox::used()) {
1163 st->print_cr("Unsupported internal testing APIs have been used.");
1164 st->cr();
1165 }
1166
1167 // STEP("printing log configuration")
1168 st->print_cr("Logging:");
1169 LogConfiguration::describe(st);
1170 st->cr();
1171
1172 // STEP("printing all environment variables")
1173
1174 os::print_environment_variables(st, env_list);
1175 st->cr();
1176
1177 // STEP("printing signal handlers")
1178
1179 os::print_signal_handlers(st, buf, sizeof(buf));
1180 st->cr();
1181
1182 // STEP("Native Memory Tracking")
1183
1184 MemTracker::error_report(st);
1185
1186 // STEP("printing system")
1187
1188 st->cr();
1189 st->print_cr("--------------- S Y S T E M ---------------");
1190 st->cr();
1191
1192 // STEP("printing OS information")
1193
1194 os::print_os_info(st);
1195 st->cr();
1196
1197 // STEP("printing CPU info")
1198
1199 os::print_cpu_info(st, buf, sizeof(buf));
1200 st->cr();
1201
1202 // STEP("printing memory info")
1203
1204 os::print_memory_info(st);
1205 st->cr();
1206
1207 // STEP("printing internal vm info")
1208
1209 st->print_cr("vm_info: %s", VM_Version::internal_vm_info_string());
1210 st->cr();
1211
1212 // print a defined marker to show that error handling finished correctly.
1213 // STEP("printing end marker")
1214
1215 st->print_cr("END.");
1216 }
1217
1218 volatile intptr_t VMError::first_error_tid = -1;
1219
1220 /** Expand a pattern into a buffer starting at pos and open a file using constructed path */
expand_and_open(const char * pattern,bool overwrite_existing,char * buf,size_t buflen,size_t pos)1221 static int expand_and_open(const char* pattern, bool overwrite_existing, char* buf, size_t buflen, size_t pos) {
1222 int fd = -1;
1223 int mode = O_RDWR | O_CREAT;
1224 if (overwrite_existing) {
1225 mode |= O_TRUNC;
1226 } else {
1227 mode |= O_EXCL;
1228 }
1229 if (Arguments::copy_expand_pid(pattern, strlen(pattern), &buf[pos], buflen - pos)) {
1230 fd = open(buf, mode, 0666);
1231 }
1232 return fd;
1233 }
1234
1235 /**
1236 * Construct file name for a log file and return it's file descriptor.
1237 * Name and location depends on pattern, default_pattern params and access
1238 * permissions.
1239 */
prepare_log_file(const char * pattern,const char * default_pattern,bool overwrite_existing,char * buf,size_t buflen)1240 static int prepare_log_file(const char* pattern, const char* default_pattern, bool overwrite_existing, char* buf, size_t buflen) {
1241 int fd = -1;
1242
1243 // If possible, use specified pattern to construct log file name
1244 if (pattern != NULL) {
1245 fd = expand_and_open(pattern, overwrite_existing, buf, buflen, 0);
1246 }
1247
1248 // Either user didn't specify, or the user's location failed,
1249 // so use the default name in the current directory
1250 if (fd == -1) {
1251 const char* cwd = os::get_current_directory(buf, buflen);
1252 if (cwd != NULL) {
1253 size_t pos = strlen(cwd);
1254 int fsep_len = jio_snprintf(&buf[pos], buflen-pos, "%s", os::file_separator());
1255 pos += fsep_len;
1256 if (fsep_len > 0) {
1257 fd = expand_and_open(default_pattern, overwrite_existing, buf, buflen, pos);
1258 }
1259 }
1260 }
1261
1262 // try temp directory if it exists.
1263 if (fd == -1) {
1264 const char* tmpdir = os::get_temp_directory();
1265 if (tmpdir != NULL && strlen(tmpdir) > 0) {
1266 int pos = jio_snprintf(buf, buflen, "%s%s", tmpdir, os::file_separator());
1267 if (pos > 0) {
1268 fd = expand_and_open(default_pattern, overwrite_existing, buf, buflen, pos);
1269 }
1270 }
1271 }
1272
1273 return fd;
1274 }
1275
1276 int VMError::_id;
1277 const char* VMError::_message;
1278 char VMError::_detail_msg[1024];
1279 Thread* VMError::_thread;
1280 address VMError::_pc;
1281 void* VMError::_siginfo;
1282 void* VMError::_context;
1283 const char* VMError::_filename;
1284 int VMError::_lineno;
1285 size_t VMError::_size;
1286
report_and_die(Thread * thread,unsigned int sig,address pc,void * siginfo,void * context,const char * detail_fmt,...)1287 void VMError::report_and_die(Thread* thread, unsigned int sig, address pc, void* siginfo,
1288 void* context, const char* detail_fmt, ...)
1289 {
1290 va_list detail_args;
1291 va_start(detail_args, detail_fmt);
1292 report_and_die(sig, NULL, detail_fmt, detail_args, thread, pc, siginfo, context, NULL, 0, 0);
1293 va_end(detail_args);
1294 }
1295
report_and_die(Thread * thread,unsigned int sig,address pc,void * siginfo,void * context)1296 void VMError::report_and_die(Thread* thread, unsigned int sig, address pc, void* siginfo, void* context)
1297 {
1298 report_and_die(thread, sig, pc, siginfo, context, "%s", "");
1299 }
1300
report_and_die(const char * message,const char * detail_fmt,...)1301 void VMError::report_and_die(const char* message, const char* detail_fmt, ...)
1302 {
1303 va_list detail_args;
1304 va_start(detail_args, detail_fmt);
1305 report_and_die(INTERNAL_ERROR, message, detail_fmt, detail_args, NULL, NULL, NULL, NULL, NULL, 0, 0);
1306 va_end(detail_args);
1307 }
1308
report_and_die(const char * message)1309 void VMError::report_and_die(const char* message)
1310 {
1311 report_and_die(message, "%s", "");
1312 }
1313
report_and_die(Thread * thread,void * context,const char * filename,int lineno,const char * message,const char * detail_fmt,va_list detail_args)1314 void VMError::report_and_die(Thread* thread, void* context, const char* filename, int lineno, const char* message,
1315 const char* detail_fmt, va_list detail_args)
1316 {
1317 report_and_die(INTERNAL_ERROR, message, detail_fmt, detail_args, thread, NULL, NULL, context, filename, lineno, 0);
1318 }
1319
report_and_die(Thread * thread,const char * filename,int lineno,size_t size,VMErrorType vm_err_type,const char * detail_fmt,va_list detail_args)1320 void VMError::report_and_die(Thread* thread, const char* filename, int lineno, size_t size,
1321 VMErrorType vm_err_type, const char* detail_fmt, va_list detail_args) {
1322 report_and_die(vm_err_type, NULL, detail_fmt, detail_args, thread, NULL, NULL, NULL, filename, lineno, size);
1323 }
1324
report_and_die(int id,const char * message,const char * detail_fmt,va_list detail_args,Thread * thread,address pc,void * siginfo,void * context,const char * filename,int lineno,size_t size)1325 void VMError::report_and_die(int id, const char* message, const char* detail_fmt, va_list detail_args,
1326 Thread* thread, address pc, void* siginfo, void* context, const char* filename,
1327 int lineno, size_t size)
1328 {
1329 // A single scratch buffer to be used from here on.
1330 // Do not rely on it being preserved across function calls.
1331 static char buffer[O_BUFLEN];
1332
1333 // File descriptor to tty to print an error summary to.
1334 // Hard wired to stdout; see JDK-8215004 (compatibility concerns).
1335 static const int fd_out = 1; // stdout
1336
1337 // File descriptor to the error log file.
1338 static int fd_log = -1;
1339
1340 #ifdef CAN_SHOW_REGISTERS_ON_ASSERT
1341 // Disarm assertion poison page, since from this point on we do not need this mechanism anymore and it may
1342 // cause problems in error handling during native OOM, see JDK-8227275.
1343 disarm_assert_poison();
1344 #endif
1345
1346 // Use local fdStream objects only. Do not use global instances whose initialization
1347 // relies on dynamic initialization (see JDK-8214975). Do not rely on these instances
1348 // to carry over into recursions or invocations from other threads.
1349 fdStream out(fd_out);
1350 out.set_scratch_buffer(buffer, sizeof(buffer));
1351
1352 // Depending on the re-entrance depth at this point, fd_log may be -1 or point to an open hs-err file.
1353 fdStream log(fd_log);
1354 log.set_scratch_buffer(buffer, sizeof(buffer));
1355
1356 // How many errors occurred in error handler when reporting first_error.
1357 static int recursive_error_count;
1358
1359 // We will first print a brief message to standard out (verbose = false),
1360 // then save detailed information in log file (verbose = true).
1361 static bool out_done = false; // done printing to standard out
1362 static bool log_done = false; // done saving error log
1363
1364 if (SuppressFatalErrorMessage) {
1365 os::abort(CreateCoredumpOnCrash);
1366 }
1367 intptr_t mytid = os::current_thread_id();
1368 if (first_error_tid == -1 &&
1369 Atomic::cmpxchg(mytid, &first_error_tid, (intptr_t)-1) == -1) {
1370
1371 // Initialize time stamps to use the same base.
1372 out.time_stamp().update_to(1);
1373 log.time_stamp().update_to(1);
1374
1375 _id = id;
1376 _message = message;
1377 _thread = thread;
1378 _pc = pc;
1379 _siginfo = siginfo;
1380 _context = context;
1381 _filename = filename;
1382 _lineno = lineno;
1383 _size = size;
1384 jio_vsnprintf(_detail_msg, sizeof(_detail_msg), detail_fmt, detail_args);
1385
1386 // first time
1387 _error_reported = true;
1388
1389 reporting_started();
1390 if (!TestUnresponsiveErrorHandler) {
1391 // Record reporting_start_time unless we're running the
1392 // TestUnresponsiveErrorHandler test. For that test we record
1393 // reporting_start_time at the beginning of the test.
1394 record_reporting_start_time();
1395 } else {
1396 out.print_raw_cr("Delaying recording reporting_start_time for TestUnresponsiveErrorHandler.");
1397 }
1398
1399 if (ShowMessageBoxOnError || PauseAtExit) {
1400 show_message_box(buffer, sizeof(buffer));
1401
1402 // User has asked JVM to abort. Reset ShowMessageBoxOnError so the
1403 // WatcherThread can kill JVM if the error handler hangs.
1404 ShowMessageBoxOnError = false;
1405 }
1406
1407 os::check_dump_limit(buffer, sizeof(buffer));
1408
1409 // reset signal handlers or exception filter; make sure recursive crashes
1410 // are handled properly.
1411 reset_signal_handlers();
1412
1413 EventShutdown e;
1414 if (e.should_commit()) {
1415 e.set_reason("VM Error");
1416 e.commit();
1417 }
1418
1419 JFR_ONLY(Jfr::on_vm_shutdown(true);)
1420
1421 } else {
1422 // If UseOsErrorReporting we call this for each level of the call stack
1423 // while searching for the exception handler. Only the first level needs
1424 // to be reported.
1425 if (UseOSErrorReporting && log_done) return;
1426
1427 // This is not the first error, see if it happened in a different thread
1428 // or in the same thread during error reporting.
1429 if (first_error_tid != mytid) {
1430 char msgbuf[64];
1431 jio_snprintf(msgbuf, sizeof(msgbuf),
1432 "[thread " INTX_FORMAT " also had an error]",
1433 mytid);
1434 out.print_raw_cr(msgbuf);
1435
1436 // error reporting is not MT-safe, block current thread
1437 os::infinite_sleep();
1438
1439 } else {
1440 if (recursive_error_count++ > 30) {
1441 out.print_raw_cr("[Too many errors, abort]");
1442 os::die();
1443 }
1444
1445 outputStream* const st = log.is_open() ? &log : &out;
1446 st->cr();
1447
1448 // Timeout handling.
1449 if (_step_did_timeout) {
1450 // The current step had a timeout. Lets continue reporting with the next step.
1451 st->print_raw("[timeout occurred during error reporting in step \"");
1452 st->print_raw(_current_step_info);
1453 st->print_cr("\"] after " INT64_FORMAT " s.",
1454 (int64_t)
1455 ((get_current_timestamp() - _step_start_time) / TIMESTAMP_TO_SECONDS_FACTOR));
1456 } else if (_reporting_did_timeout) {
1457 // We hit ErrorLogTimeout. Reporting will stop altogether. Let's wrap things
1458 // up, the process is about to be stopped by the WatcherThread.
1459 st->print_cr("------ Timeout during error reporting after " INT64_FORMAT " s. ------",
1460 (int64_t)
1461 ((get_current_timestamp() - _reporting_start_time) / TIMESTAMP_TO_SECONDS_FACTOR));
1462 st->flush();
1463 // Watcherthread is about to call os::die. Lets just wait.
1464 os::infinite_sleep();
1465 } else {
1466 // Crash or assert during error reporting. Lets continue reporting with the next step.
1467 stringStream ss(buffer, sizeof(buffer));
1468 // Note: this string does get parsed by a number of jtreg tests,
1469 // see hotspot/jtreg/runtime/ErrorHandling.
1470 ss.print("[error occurred during error reporting (%s), id 0x%x",
1471 _current_step_info, id);
1472 char signal_name[64];
1473 if (os::exception_name(id, signal_name, sizeof(signal_name))) {
1474 ss.print(", %s (0x%x) at pc=" PTR_FORMAT, signal_name, id, p2i(pc));
1475 } else {
1476 if (should_report_bug(id)) {
1477 ss.print(", Internal Error (%s:%d)",
1478 filename == NULL ? "??" : filename, lineno);
1479 } else {
1480 ss.print(", Out of Memory Error (%s:%d)",
1481 filename == NULL ? "??" : filename, lineno);
1482 }
1483 }
1484 ss.print("]");
1485 st->print_raw_cr(buffer);
1486 st->cr();
1487 }
1488 }
1489 }
1490
1491 // Part 1: print an abbreviated version (the '#' section) to stdout.
1492 if (!out_done) {
1493 // Suppress this output if we plan to print Part 2 to stdout too.
1494 // No need to have the "#" section twice.
1495 if (!(ErrorFileToStdout && out.fd() == 1)) {
1496 report(&out, false);
1497 }
1498
1499 out_done = true;
1500
1501 _current_step = 0;
1502 _current_step_info = "";
1503 }
1504
1505 // Part 2: print a full error log file (optionally to stdout or stderr).
1506 // print to error log file
1507 if (!log_done) {
1508 // see if log file is already open
1509 if (!log.is_open()) {
1510 // open log file
1511 if (ErrorFileToStdout) {
1512 fd_log = 1;
1513 } else if (ErrorFileToStderr) {
1514 fd_log = 2;
1515 } else {
1516 fd_log = prepare_log_file(ErrorFile, "hs_err_pid%p.log", true,
1517 buffer, sizeof(buffer));
1518 if (fd_log != -1) {
1519 out.print_raw("# An error report file with more information is saved as:\n# ");
1520 out.print_raw_cr(buffer);
1521 } else {
1522 out.print_raw_cr("# Can not save log file, dump to screen..");
1523 fd_log = 1;
1524 }
1525 }
1526 log.set_fd(fd_log);
1527 }
1528
1529 report(&log, true);
1530 log_done = true;
1531 _current_step = 0;
1532 _current_step_info = "";
1533
1534 if (fd_log > 3) {
1535 close(fd_log);
1536 fd_log = -1;
1537 }
1538
1539 log.set_fd(-1);
1540 }
1541
1542 if (PrintNMTStatistics) {
1543 fdStream fds(fd_out);
1544 MemTracker::final_report(&fds);
1545 }
1546
1547 static bool skip_replay = ReplayCompiles; // Do not overwrite file during replay
1548 if (DumpReplayDataOnError && _thread && _thread->is_Compiler_thread() && !skip_replay) {
1549 skip_replay = true;
1550 ciEnv* env = ciEnv::current();
1551 if (env != NULL) {
1552 const bool overwrite = false; // We do not overwrite an existing replay file.
1553 int fd = prepare_log_file(ReplayDataFile, "replay_pid%p.log", overwrite, buffer, sizeof(buffer));
1554 if (fd != -1) {
1555 FILE* replay_data_file = os::open(fd, "w");
1556 if (replay_data_file != NULL) {
1557 fileStream replay_data_stream(replay_data_file, /*need_close=*/true);
1558 env->dump_replay_data_unsafe(&replay_data_stream);
1559 out.print_raw("#\n# Compiler replay data is saved as:\n# ");
1560 out.print_raw_cr(buffer);
1561 } else {
1562 int e = errno;
1563 out.print_raw("#\n# Can't open file to dump replay data. Error: ");
1564 out.print_raw_cr(os::strerror(e));
1565 }
1566 }
1567 }
1568 }
1569
1570 static bool skip_bug_url = !should_report_bug(_id);
1571 if (!skip_bug_url) {
1572 skip_bug_url = true;
1573
1574 out.print_raw_cr("#");
1575 print_bug_submit_message(&out, _thread);
1576 }
1577
1578 static bool skip_OnError = false;
1579 if (!skip_OnError && OnError && OnError[0]) {
1580 skip_OnError = true;
1581
1582 // Flush output and finish logs before running OnError commands.
1583 ostream_abort();
1584
1585 out.print_raw_cr("#");
1586 out.print_raw ("# -XX:OnError=\"");
1587 out.print_raw (OnError);
1588 out.print_raw_cr("\"");
1589
1590 char* cmd;
1591 const char* ptr = OnError;
1592 while ((cmd = next_OnError_command(buffer, sizeof(buffer), &ptr)) != NULL){
1593 out.print_raw ("# Executing ");
1594 #if defined(LINUX) || defined(_ALLBSD_SOURCE)
1595 out.print_raw ("/bin/sh -c ");
1596 #elif defined(SOLARIS)
1597 out.print_raw ("/usr/bin/sh -c ");
1598 #elif defined(_WINDOWS)
1599 out.print_raw ("cmd /C ");
1600 #endif
1601 out.print_raw ("\"");
1602 out.print_raw (cmd);
1603 out.print_raw_cr("\" ...");
1604
1605 if (os::fork_and_exec(cmd) < 0) {
1606 out.print_cr("os::fork_and_exec failed: %s (%s=%d)",
1607 os::strerror(errno), os::errno_name(errno), errno);
1608 }
1609 }
1610
1611 // done with OnError
1612 OnError = NULL;
1613 }
1614
1615 if (!UseOSErrorReporting) {
1616 // os::abort() will call abort hooks, try it first.
1617 static bool skip_os_abort = false;
1618 if (!skip_os_abort) {
1619 skip_os_abort = true;
1620 bool dump_core = should_report_bug(_id);
1621 os::abort(dump_core && CreateCoredumpOnCrash, _siginfo, _context);
1622 }
1623
1624 // if os::abort() doesn't abort, try os::die();
1625 os::die();
1626 }
1627 }
1628
1629 /*
1630 * OnOutOfMemoryError scripts/commands executed while VM is a safepoint - this
1631 * ensures utilities such as jmap can observe the process is a consistent state.
1632 */
1633 class VM_ReportJavaOutOfMemory : public VM_Operation {
1634 private:
1635 const char* _message;
1636 public:
VM_ReportJavaOutOfMemory(const char * message)1637 VM_ReportJavaOutOfMemory(const char* message) { _message = message; }
type() const1638 VMOp_Type type() const { return VMOp_ReportJavaOutOfMemory; }
1639 void doit();
1640 };
1641
doit()1642 void VM_ReportJavaOutOfMemory::doit() {
1643 // Don't allocate large buffer on stack
1644 static char buffer[O_BUFLEN];
1645
1646 tty->print_cr("#");
1647 tty->print_cr("# java.lang.OutOfMemoryError: %s", _message);
1648 tty->print_cr("# -XX:OnOutOfMemoryError=\"%s\"", OnOutOfMemoryError);
1649
1650 // make heap parsability
1651 Universe::heap()->ensure_parsability(false); // no need to retire TLABs
1652
1653 char* cmd;
1654 const char* ptr = OnOutOfMemoryError;
1655 while ((cmd = next_OnError_command(buffer, sizeof(buffer), &ptr)) != NULL){
1656 tty->print("# Executing ");
1657 #if defined(LINUX)
1658 tty->print ("/bin/sh -c ");
1659 #elif defined(SOLARIS)
1660 tty->print ("/usr/bin/sh -c ");
1661 #endif
1662 tty->print_cr("\"%s\"...", cmd);
1663
1664 if (os::fork_and_exec(cmd, true) < 0) {
1665 tty->print_cr("os::fork_and_exec failed: %s (%s=%d)",
1666 os::strerror(errno), os::errno_name(errno), errno);
1667 }
1668 }
1669 }
1670
report_java_out_of_memory(const char * message)1671 void VMError::report_java_out_of_memory(const char* message) {
1672 if (OnOutOfMemoryError && OnOutOfMemoryError[0]) {
1673 MutexLocker ml(Heap_lock);
1674 VM_ReportJavaOutOfMemory op(message);
1675 VMThread::execute(&op);
1676 }
1677 }
1678
show_message_box(char * buf,int buflen)1679 void VMError::show_message_box(char *buf, int buflen) {
1680 bool yes;
1681 do {
1682 error_string(buf, buflen);
1683 yes = os::start_debugging(buf,buflen);
1684 } while (yes);
1685 }
1686
1687 // Timeout handling: check if a timeout happened (either a single step did
1688 // timeout or the whole of error reporting hit ErrorLogTimeout). Interrupt
1689 // the reporting thread if that is the case.
check_timeout()1690 bool VMError::check_timeout() {
1691
1692 if (ErrorLogTimeout == 0) {
1693 return false;
1694 }
1695
1696 // Do not check for timeouts if we still have a message box to show to the
1697 // user or if there are OnError handlers to be run.
1698 if (ShowMessageBoxOnError
1699 || (OnError != NULL && OnError[0] != '\0')
1700 || Arguments::abort_hook() != NULL) {
1701 return false;
1702 }
1703
1704 const jlong reporting_start_time_l = get_reporting_start_time();
1705 const jlong now = get_current_timestamp();
1706 // Timestamp is stored in nanos.
1707 if (reporting_start_time_l > 0) {
1708 const jlong end = reporting_start_time_l + (jlong)ErrorLogTimeout * TIMESTAMP_TO_SECONDS_FACTOR;
1709 if (end <= now && !_reporting_did_timeout) {
1710 // We hit ErrorLogTimeout and we haven't interrupted the reporting
1711 // thread yet.
1712 _reporting_did_timeout = true;
1713 interrupt_reporting_thread();
1714 return true; // global timeout
1715 }
1716 }
1717
1718 const jlong step_start_time_l = get_step_start_time();
1719 if (step_start_time_l > 0) {
1720 // A step times out after a quarter of the total timeout. Steps are mostly fast unless they
1721 // hang for some reason, so this simple rule allows for three hanging step and still
1722 // hopefully leaves time enough for the rest of the steps to finish.
1723 const jlong end = step_start_time_l + (jlong)ErrorLogTimeout * TIMESTAMP_TO_SECONDS_FACTOR / 4;
1724 if (end <= now && !_step_did_timeout) {
1725 // The step timed out and we haven't interrupted the reporting
1726 // thread yet.
1727 _step_did_timeout = true;
1728 interrupt_reporting_thread();
1729 return false; // (Not a global timeout)
1730 }
1731 }
1732
1733 return false;
1734
1735 }
1736
1737 #ifndef PRODUCT
1738 #if defined(__SUNPRO_CC) && __SUNPRO_CC >= 0x5140
1739 #pragma error_messages(off, SEC_NULL_PTR_DEREF)
1740 #endif
1741 typedef void (*voidfun_t)();
1742 // Crash with an authentic sigfpe
crash_with_sigfpe()1743 static void crash_with_sigfpe() {
1744 // generate a native synchronous SIGFPE where possible;
1745 // if that did not cause a signal (e.g. on ppc), just
1746 // raise the signal.
1747 volatile int x = 0;
1748 volatile int y = 1/x;
1749 #ifndef _WIN32
1750 // OSX implements raise(sig) incorrectly so we need to
1751 // explicitly target the current thread
1752 pthread_kill(pthread_self(), SIGFPE);
1753 #endif
1754 } // end: crash_with_sigfpe
1755
1756 // crash with sigsegv at non-null address.
crash_with_segfault()1757 static void crash_with_segfault() {
1758
1759 char* const crash_addr = (char*) VMError::get_segfault_address();
1760 *crash_addr = 'X';
1761
1762 } // end: crash_with_segfault
1763
test_error_handler()1764 void VMError::test_error_handler() {
1765 controlled_crash(ErrorHandlerTest);
1766 }
1767
1768 // crash in a controlled way:
1769 // how can be one of:
1770 // 1,2 - asserts
1771 // 3,4 - guarantee
1772 // 5-7 - fatal
1773 // 8 - vm_exit_out_of_memory
1774 // 9 - ShouldNotCallThis
1775 // 10 - ShouldNotReachHere
1776 // 11 - Unimplemented
1777 // 12,13 - (not guaranteed) crashes
1778 // 14 - SIGSEGV
1779 // 15 - SIGFPE
controlled_crash(int how)1780 void VMError::controlled_crash(int how) {
1781 if (how == 0) return;
1782
1783 // If asserts are disabled, use the corresponding guarantee instead.
1784 NOT_DEBUG(if (how <= 2) how += 2);
1785
1786 const char* const str = "hello";
1787 const size_t num = (size_t)os::vm_page_size();
1788
1789 const char* const eol = os::line_separator();
1790 const char* const msg = "this message should be truncated during formatting";
1791 char * const dataPtr = NULL; // bad data pointer
1792 const void (*funcPtr)(void); // bad function pointer
1793
1794 #if defined(PPC64) && !defined(ABI_ELFv2)
1795 struct FunctionDescriptor functionDescriptor;
1796
1797 functionDescriptor.set_entry((address) 0xF);
1798 funcPtr = (const void(*)()) &functionDescriptor;
1799 #else
1800 funcPtr = (const void(*)()) 0xF;
1801 #endif
1802
1803 // Keep this in sync with test/hotspot/jtreg/runtime/ErrorHandling/ErrorHandler.java
1804 // which tests cases 1 thru 13.
1805 // Case 14 is tested by test/hotspot/jtreg/runtime/ErrorHandling/SafeFetchInErrorHandlingTest.java.
1806 // Case 15 is tested by test/hotspot/jtreg/runtime/ErrorHandling/SecondaryErrorTest.java.
1807 // Case 16 is tested by test/hotspot/jtreg/runtime/ErrorHandling/ThreadsListHandleInErrorHandlingTest.java.
1808 // Case 17 is tested by test/hotspot/jtreg/runtime/ErrorHandling/NestedThreadsListHandleInErrorHandlingTest.java.
1809
1810 // We grab Threads_lock to keep ThreadsSMRSupport::print_info_on()
1811 // from racing with Threads::add() or Threads::remove() as we
1812 // generate the hs_err_pid file. This makes our ErrorHandling tests
1813 // more stable.
1814 MutexLocker ml(Threads_lock->owned_by_self() ? NULL : Threads_lock, Mutex::_no_safepoint_check_flag);
1815
1816 switch (how) {
1817 case 1: vmassert(str == NULL, "expected null"); break;
1818 case 2: vmassert(num == 1023 && *str == 'X',
1819 "num=" SIZE_FORMAT " str=\"%s\"", num, str); break;
1820 case 3: guarantee(str == NULL, "expected null"); break;
1821 case 4: guarantee(num == 1023 && *str == 'X',
1822 "num=" SIZE_FORMAT " str=\"%s\"", num, str); break;
1823 case 5: fatal("expected null"); break;
1824 case 6: fatal("num=" SIZE_FORMAT " str=\"%s\"", num, str); break;
1825 case 7: fatal("%s%s# %s%s# %s%s# %s%s# %s%s# "
1826 "%s%s# %s%s# %s%s# %s%s# %s%s# "
1827 "%s%s# %s%s# %s%s# %s%s# %s",
1828 msg, eol, msg, eol, msg, eol, msg, eol, msg, eol,
1829 msg, eol, msg, eol, msg, eol, msg, eol, msg, eol,
1830 msg, eol, msg, eol, msg, eol, msg, eol, msg); break;
1831 case 8: vm_exit_out_of_memory(num, OOM_MALLOC_ERROR, "ChunkPool::allocate"); break;
1832 case 9: ShouldNotCallThis(); break;
1833 case 10: ShouldNotReachHere(); break;
1834 case 11: Unimplemented(); break;
1835 // There's no guarantee the bad data pointer will crash us
1836 // so "break" out to the ShouldNotReachHere().
1837 case 12: *dataPtr = '\0'; break;
1838 // There's no guarantee the bad function pointer will crash us
1839 // so "break" out to the ShouldNotReachHere().
1840 case 13: (*funcPtr)(); break;
1841 case 14: crash_with_segfault(); break;
1842 case 15: crash_with_sigfpe(); break;
1843 case 16: {
1844 ThreadsListHandle tlh;
1845 fatal("Force crash with an active ThreadsListHandle.");
1846 }
1847 case 17: {
1848 ThreadsListHandle tlh;
1849 {
1850 ThreadsListHandle tlh2;
1851 fatal("Force crash with a nested ThreadsListHandle.");
1852 }
1853 }
1854
1855 default: tty->print_cr("ERROR: %d: unexpected test_num value.", how);
1856 }
1857 tty->print_cr("VMError::controlled_crash: survived intentional crash. Did you suppress the assert?");
1858 ShouldNotReachHere();
1859 }
1860 #endif // !PRODUCT
1861