/* * Copyright (c) 2003, 2022, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2017, 2020 SAP SE. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. *
*/
// List of environment variables that should be reported in error log file. staticconstchar* env_list[] = { // All platforms "JAVA_HOME", "JAVA_TOOL_OPTIONS", "_JAVA_OPTIONS", "CLASSPATH", "PATH", "USERNAME",
// Env variables that are defined on Linux/BSD "LD_LIBRARY_PATH", "LD_PRELOAD", "SHELL", "DISPLAY", "HOSTTYPE", "OSTYPE", "ARCH", "MACHTYPE", "LANG", "LC_ALL", "LC_CTYPE", "LC_NUMERIC", "LC_TIME", "TERM", "TMPDIR", "TZ",
// defined on AIX "LIBPATH", "LDR_PRELOAD", "LDR_PRELOAD64",
// defined on Linux/AIX/BSD "_JAVA_SR_SIGNUM",
// defined on Darwin "DYLD_LIBRARY_PATH", "DYLD_FALLBACK_LIBRARY_PATH", "DYLD_FRAMEWORK_PATH", "DYLD_FALLBACK_FRAMEWORK_PATH", "DYLD_INSERT_LIBRARIES",
// defined on Windows "OS", "PROCESSOR_IDENTIFIER", "_ALT_JAVA_HOME_DIR", "TMP", "TEMP",
(constchar *)0
};
// A simple parser for -XX:OnError, usage: // ptr = OnError; // while ((cmd = next_OnError_command(buffer, sizeof(buffer), &ptr) != NULL) // ... ... staticchar* next_OnError_command(char* buf, int buflen, constchar** ptr) { if (ptr == NULL || *ptr == NULL) return NULL;
constchar* cmd = *ptr;
// skip leading blanks or ';' while (*cmd == ' ' || *cmd == ';') cmd++;
staticvoid print_bug_submit_message(outputStream *out, Thread *thread) { if (out == NULL) return; constchar *url = Arguments::java_vendor_url_bug(); if (url == NULL || *url == '\0')
url = JDK_Version::runtime_vendor_vm_bug_url(); if (url != NULL && *url != '\0') {
out->print_raw_cr("# If you would like to submit a bug report, please visit:");
out->print_raw ("# ");
out->print_raw_cr(url);
} // If the crash is in native code, encourage user to submit a bug to the // provider of that code. if (thread && thread->is_Java_thread() &&
!thread->is_hidden_from_external_view()) { if (JavaThread::cast(thread)->thread_state() == _thread_in_native) {
out->print_cr("# The crash happened outside the Java Virtual Machine in native code.\n# See problematic frame for where to report the bug.");
}
}
out->print_raw_cr("#");
}
// Return a string to describe the error char* VMError::error_string(char* buf, int buflen) { char signame_buf[64]; constchar *signame = os::exception_name(_id, signame_buf, sizeof(signame_buf));
if (signame) {
jio_snprintf(buf, buflen, "%s (0x%x) at pc=" PTR_FORMAT ", pid=%d, tid=" UINTX_FORMAT,
signame, _id, _pc,
os::current_process_id(), os::current_thread_id());
} elseif (_filename != NULL && _lineno > 0) { // skip directory names int n = jio_snprintf(buf, buflen, "Internal Error at %s:%d, pid=%d, tid=" UINTX_FORMAT,
get_filename_only(), _lineno,
os::current_process_id(), os::current_thread_id()); if (n >= 0 && n < buflen && _message) { if (strlen(_detail_msg) > 0) {
jio_snprintf(buf + n, buflen - n, "%s%s: %s",
os::line_separator(), _message, _detail_msg);
} else {
jio_snprintf(buf + n, buflen - n, "%sError: %s",
os::line_separator(), _message);
}
}
} else {
jio_snprintf(buf, buflen, "Internal Error (0x%x), pid=%d, tid=" UINTX_FORMAT,
_id, os::current_process_id(), os::current_thread_id());
}
return buf;
}
void VMError::print_stack_trace(outputStream* st, JavaThread* jt, char* buf, int buflen, bool verbose) { #ifdef ZERO if (jt->zero_stack()->sp() && jt->top_zero_frame()) { // StackFrameStream uses the frame anchor, which may not have // been set up. This can be done at any time in Zero, however, // so if it hasn't been set up then we just set it up now and // clear it again when we're done. bool has_last_Java_frame = jt->has_last_Java_frame(); if (!has_last_Java_frame)
jt->set_last_Java_frame();
st->print("Java frames:");
st->cr();
// Reset the frame anchor if necessary if (!has_last_Java_frame)
jt->reset_last_Java_frame();
} #else if (jt->has_last_Java_frame()) {
st->print_cr("Java frames: (J=compiled Java code, j=interpreted, Vv=VM code)"); for (StackFrameStream sfs(jt, true/* update */, true /* process_frames */); !sfs.is_done(); sfs.next()) {
sfs.current()->print_on_error(st, buf, buflen, verbose);
st->cr();
}
} #endif// ZERO
}
/** * Adds `value` to `list` iff it's not already present and there is sufficient * capacity (i.e. length(list) < `list_capacity`). The length of the list * is the index of the first nullptr entry or `list_capacity` if there are * no nullptr entries. * * @ return true if the value was added, false otherwise
*/ staticbool add_if_absent(address value, address* list, int list_capacity) { for (int i = 0; i < list_capacity; i++) { if (list[i] == value) { returnfalse;
} if (list[i] == nullptr) {
list[i] = value; if (i + 1 < list_capacity) {
list[i + 1] = nullptr;
} returntrue;
}
} returnfalse;
}
/** * Prints the VM generated code unit, if any, containing `pc` if it has not already * been printed. If the code unit is an InterpreterCodelet or StubCodeDesc, it is * only printed if `is_crash_pc` is true. * * @param printed array of code units that have already been printed (delimited by NULL entry) * @param printed_capacity the capacity of `printed` * @return true if the code unit was printed, false otherwise
*/ staticbool print_code(outputStream* st, Thread* thread, address pc, bool is_crash_pc,
address* printed, int printed_capacity) { if (Interpreter::contains(pc)) { if (is_crash_pc) { // The interpreter CodeBlob is very large so try to print the codelet instead.
InterpreterCodelet* codelet = Interpreter::codelet_containing(pc); if (codelet != nullptr) { if (add_if_absent((address) codelet, printed, printed_capacity)) {
codelet->print_on(st);
Disassembler::decode(codelet->code_begin(), codelet->code_end(), st); returntrue;
}
}
}
} else {
StubCodeDesc* desc = StubCodeDesc::desc_for(pc); if (desc != nullptr) { if (is_crash_pc) { if (add_if_absent((address) desc, printed, printed_capacity)) {
desc->print_on(st);
Disassembler::decode(desc->begin(), desc->end(), st); returntrue;
}
}
} elseif (thread != nullptr) {
CodeBlob* cb = CodeCache::find_blob(pc); if (cb != nullptr && add_if_absent((address) cb, printed, printed_capacity)) { // Disassembling nmethod will incur resource memory allocation, // only do so when thread is valid.
ResourceMark rm(thread);
Disassembler::decode(cb, st);
st->cr(); returntrue;
}
}
} returnfalse;
}
/** * Gets the caller frame of `fr`. * * @returns an invalid frame (i.e. fr.pc() === 0) if the caller cannot be obtained
*/ static frame next_frame(frame fr, Thread* t) { // Compiled code may use EBP register on x86 so it looks like // non-walkable C frame. Use frame.sender() for java frames.
frame invalid; if (t != nullptr && t->is_Java_thread()) { // Catch very first native frame by using stack address. // For JavaThread stack_base and stack_size should be set. if (!t->is_in_full_stack((address)(fr.real_fp() + 1))) { return invalid;
} if (fr.is_java_frame() || fr.is_native_frame() || fr.is_runtime_frame()) {
RegisterMap map(JavaThread::cast(t),
RegisterMap::UpdateMap::skip,
RegisterMap::ProcessFrames::include,
RegisterMap::WalkContinuation::skip); // No update return fr.sender(&map);
} else { // is_first_C_frame() does only simple checks for frame pointer, // it will pass if java compiled code has a pointer in EBP. if (os::is_first_C_frame(&fr)) return invalid; return os::get_sender_for_C_frame(&fr);
}
} else { if (os::is_first_C_frame(&fr)) return invalid; return os::get_sender_for_C_frame(&fr);
}
}
void VMError::print_native_stack(outputStream* st, frame fr, Thread* t, bool print_source_info, int max_frames, char* buf, int buf_size) {
// see if it's a valid frame if (fr.pc()) {
st->print_cr("Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code)"); constint limit = max_frames == -1 ? StackPrintLimit : MIN2(max_frames, (int)StackPrintLimit); int count = 0; while (count++ < limit) {
fr.print_on_error(st, buf, buf_size); if (fr.pc()) { // print source file and line, if available char filename[128]; int line_no; if (count == 1 && _lineno != 0) { // We have source information of the first frame for internal errors. There is no need to parse it from the symbols.
st->print(" (%s:%d)", get_filename_only(), _lineno);
} elseif (print_source_info &&
Decoder::get_source_info(fr.pc(), filename, sizeof(filename), &line_no, count != 1)) {
st->print(" (%s:%d)", filename, line_no);
}
}
st->cr();
fr = next_frame(fr, t); if (fr.pc() == nullptr) { break;
}
}
if (count > limit) {
st->print_cr("......");
}
}
}
staticvoid print_oom_reasons(outputStream* st) {
st->print_cr("# Possible reasons:");
st->print_cr("# The system is out of physical RAM or swap space"); if (UseCompressedOops) {
st->print_cr("# The process is running with CompressedOops enabled, and the Java Heap may be blocking the growth of the native heap");
} if (LogBytesPerWord == 2) {
st->print_cr("# In 32 bit mode, the process size limit was hit");
}
st->print_cr("# Possible solutions:");
st->print_cr("# Reduce memory load on the system");
st->print_cr("# Increase physical memory or swap space");
st->print_cr("# Check if swap backing store is full"); if (LogBytesPerWord == 2) {
st->print_cr("# Use 64 bit Java on a 64 bit OS");
}
st->print_cr("# Decrease Java heap size (-Xmx/-Xms)");
st->print_cr("# Decrease number of Java threads");
st->print_cr("# Decrease Java thread stack sizes (-Xss)");
st->print_cr("# Set larger code cache with -XX:ReservedCodeCacheSize="); if (UseCompressedOops) { switch (CompressedOops::mode()) { case CompressedOops::UnscaledNarrowOop:
st->print_cr("# JVM is running with Unscaled Compressed Oops mode in which the Java heap is");
st->print_cr("# placed in the first 4GB address space. The Java Heap base address is the");
st->print_cr("# maximum limit for the native heap growth. Please use -XX:HeapBaseMinAddress");
st->print_cr("# to set the Java Heap base and to place the Java Heap above 4GB virtual address."); break; case CompressedOops::ZeroBasedNarrowOop:
st->print_cr("# JVM is running with Zero Based Compressed Oops mode in which the Java heap is");
st->print_cr("# placed in the first 32GB address space. The Java Heap base address is the");
st->print_cr("# maximum limit for the native heap growth. Please use -XX:HeapBaseMinAddress");
st->print_cr("# to set the Java Heap base and to place the Java Heap above 32GB virtual address."); break; default: break;
}
}
st->print_cr("# This output file may be truncated or incomplete.");
}
// This is the long version with some default settings added
st->print_cr("# Java VM: %s%s%s (%s%s, %s%s%s%s%s%s, %s, %s)",
VM_Version::vm_name(),
(*vendor_version != '\0') ? " " : "", vendor_version,
jdk_debug_level,
VM_Version::vm_release(),
VM_Version::vm_info_string(),
TieredCompilation ? ", tiered" : "", #if INCLUDE_JVMCI
EnableJVMCI ? ", jvmci" : "",
UseJVMCICompiler ? ", jvmci compiler" : "", #else "", "", #endif
UseCompressedOops ? ", compressed oops" : "",
UseCompressedClassPointers ? ", compressed class ptrs" : "",
GCConfig::hs_err_name(),
VM_Version::vm_platform_string()
);
}
// Returns true if at least one thread reported a fatal error and fatal error handling is in process. bool VMError::is_error_reported() { return _first_error_tid != -1;
}
// Returns true if the current thread reported a fatal error. bool VMError::is_error_reported_in_current_thread() { return _first_error_tid == os::current_thread_id();
}
// Helper, return current timestamp for timeout handling.
jlong VMError::get_current_timestamp() { return os::javaTimeNanos();
} // Factor to translate the timestamp to seconds. #define TIMESTAMP_TO_SECONDS_FACTOR (1000 * 1000 * 1000)
// This is the main function to report a fatal error. Only one thread can // call this function, so we don't need to worry about MT-safety. But it's // possible that the error handler itself may crash or die on an internal // error, for example, when the stack/heap is badly damaged. We must be // able to handle recursive errors that happen inside error handler. // // Error reporting is done in several steps. If a crash or internal error // occurred when reporting an error, the nested signal/exception handler // can skip steps that are already (or partially) done. Error reporting will // continue from the next step. This allows us to retrieve and print // information that may be unsafe to get after a fatal error. If it happens, // you may find nested report_and_die() frames when you look at the stack // in a debugger. // // In general, a hang in error handler is much worse than a crash or internal // error, as it's harder to recover from a hang. Deadlock can happen if we // try to grab a lock that is already owned by current thread, or if the // owner is blocked forever (e.g. in os::infinite_sleep()). If possible, the // error handler and all the functions it called should avoid grabbing any // lock. An important thing to notice is that memory allocation needs a lock. // // We should avoid using large stack allocated buffers. Many errors happen // when stack space is already low. Making things even worse is that there // could be nested report_and_die() calls on stack (see above). Only one // thread can report error, so large buffers are statically allocated in data // segment. void VMError::report(outputStream* st, bool _verbose) {
# define BEGIN \ if (_current_step == 0) { \
_current_step = __LINE__; \
{ // [Begin logic]
// don't allocate large buffer on stack staticchar buf[O_BUFLEN];
staticbool print_native_stack_succeeded = false;
BEGIN
STEP("printing fatal error message")
st->print_cr("#"); if (should_report_bug(_id)) {
st->print_cr("# A fatal error has been detected by the Java Runtime Environment:");
} else {
st->print_cr("# There is insufficient memory for the Java " "Runtime Environment to continue.");
}
#ifdef ASSERT // Error handler self tests // Meaning of codes passed through in the tests. #define TEST_SECONDARY_CRASH 14 #define TEST_RESOURCE_MARK_CRASH 2
// test secondary error handling. Test it twice, to test that resetting // error handler after a secondary crash works.
STEP_IF("test secondary crash 1", _verbose && TestCrashInErrorHandler == TEST_SECONDARY_CRASH)
st->print_cr("Will crash now (TestCrashInErrorHandler=%u)...",
TestCrashInErrorHandler);
controlled_crash(TestCrashInErrorHandler);
STEP_IF("test missing ResourceMark does not crash",
_verbose && TestCrashInErrorHandler == TEST_RESOURCE_MARK_CRASH)
stringStream message;
message.print("This is a message with no ResourceMark");
tty->print_cr("%s", message.as_string());
// TestUnresponsiveErrorHandler: We want to test both step timeouts and global timeout. // Step to global timeout ratio is 4:1, so in order to be absolutely sure we hit the // global timeout, let's execute the timeout step five times. // See corresponding test in test/runtime/ErrorHandling/TimeoutInErrorHandlingTest.java
STEP_IF("setup for test unresponsive error reporting step",
_verbose && TestUnresponsiveErrorHandler) // We record reporting_start_time for this test here because we // care about the time spent executing TIMEOUT_TEST_STEP and not // about the time it took us to get here.
tty->print_cr("Recording reporting_start_time for TestUnresponsiveErrorHandler.");
record_reporting_start_time();
STEP_IF("test safefetch in error handler", _verbose && TestSafeFetchInErrorHandler) // test whether it is safe to use SafeFetch32 in Crash Handler. Test twice // to test that resetting the signal handler works correctly.
st->print_cr("Will test SafeFetch..."); int* const invalid_pointer = (int*)segfault_address; constint x = 0x76543210; int i1 = SafeFetch32(invalid_pointer, x); int i2 = SafeFetch32(invalid_pointer, x); if (i1 == x && i2 == x) {
st->print_cr("SafeFetch OK."); // Correctly deflected and returned default pattern
} else {
st->print_cr("??");
} #endif// ASSERT
STEP("printing type of error") switch(static_cast<unsignedint>(_id)) { case OOM_MALLOC_ERROR: case OOM_MMAP_ERROR: case OOM_MPROTECT_ERROR: if (_size) {
st->print("# Native memory allocation ");
st->print((_id == (int)OOM_MALLOC_ERROR) ? "(malloc) failed to allocate " :
(_id == (int)OOM_MMAP_ERROR) ? "(mmap) failed to map " : "(mprotect) failed to protect ");
jio_snprintf(buf, sizeof(buf), SIZE_FORMAT, _size);
st->print("%s", buf);
st->print(" bytes"); if (strlen(_detail_msg) > 0) {
st->print(" for ");
st->print("%s", _detail_msg);
}
st->cr();
} else { if (strlen(_detail_msg) > 0) {
st->print("# ");
st->print_cr("%s", _detail_msg);
}
} // In error file give some solutions if (_verbose) {
print_oom_reasons(st);
} else { return; // that's enough for the screen
} break; case INTERNAL_ERROR: default: break;
}
STEP("printing exception/signal name")
st->print_cr("#");
st->print("# "); // Is it an OS exception/signal? if (os::exception_name(_id, buf, sizeof(buf))) {
st->print("%s", buf);
st->print(" (0x%x)", _id); // signal number
st->print(" at pc=" PTR_FORMAT, p2i(_pc)); if (_siginfo != NULL && os::signal_sent_by_kill(_siginfo)) {
st->print(" (sent by kill)");
}
} else { if (should_report_bug(_id)) {
st->print("Internal Error");
} else {
st->print("Out of Memory Error");
} if (_filename != NULL && _lineno > 0) { #ifdef PRODUCT // In product mode chop off pathname constchar *file = get_filename_only(); #else constchar *file = _filename; #endif
st->print(" (%s:%d)", file, _lineno);
} else {
st->print(" (0x%x)", _id);
}
}
STEP("printing current thread and pid") // process id, thread id
st->print(", pid=%d", os::current_process_id());
st->print(", tid=" UINTX_FORMAT, os::current_thread_id());
st->cr();
STEP_IF("printing target Java thread stack",
_verbose && _thread != nullptr && (_thread->is_Named_thread())) // printing Java thread stack trace if it is involved in GC crash
Thread* thread = ((NamedThread *)_thread)->processed_thread(); if (thread != NULL && thread->is_Java_thread()) {
JavaThread* jt = JavaThread::cast(thread);
st->print_cr("JavaThread " PTR_FORMAT " (nid = %d) was being processed", p2i(jt), jt->osthread()->thread_id());
print_stack_trace(st, jt, buf, sizeof(buf), true);
}
STEP_IF("printing siginfo", _verbose && _siginfo != nullptr) // signal no, signal code, address that caused the fault
st->cr();
os::print_siginfo(st, _siginfo);
st->cr();
STEP_IF("CDS archive access warning", _verbose && _siginfo != nullptr) // Print an explicit hint if we crashed on access to the CDS archive.
check_failing_cds_access(st, _siginfo);
st->cr();
STEP("printing top of stack, instructions near pc")
STEP_IF("printing top of stack, instructions near pc", _verbose && _context) // printing top of stack, instructions near pc
os::print_tos_pc(st, _context);
st->cr();
STEP_IF("inspecting top of stack",
_verbose && _context != nullptr && _thread != nullptr && Universe::is_fully_initialized()) // decode stack contents if possible
frame fr = os::fetch_frame_from_context(_context); constint slots = 8; const intptr_t *start = fr.sp(); const intptr_t *end = start + slots; if (is_aligned(start, sizeof(intptr_t)) && os::is_readable_range(start, end)) {
st->print_cr("Stack slot to memory mapping:"); for (int i = 0; i < slots; ++i) {
st->print("stack at sp + %d slots: ", i);
ResourceMark rm(_thread);
os::print_location(st, *(start + i));
}
}
st->cr();
STEP("printing code blobs if possible")
STEP_IF("printing code blobs if possible", _verbose) constint printed_capacity = max_error_log_print_code;
address printed[printed_capacity];
printed[0] = nullptr; int printed_len = 0; // Even though ErrorLogPrintCodeLimit is ranged checked // during argument parsing, there's no way to prevent it // subsequently (i.e., after parsing) being set to a // value outside the range. int limit = MIN2(ErrorLogPrintCodeLimit, printed_capacity); if (limit > 0) { // Scan the native stack if (!_print_native_stack_used) { // Only try to print code of the crashing frame since // the native stack cannot be walked with next_frame. if (print_code(st, _thread, _pc, true, printed, printed_capacity)) {
printed_len++;
}
} else {
frame fr = _context ? os::fetch_frame_from_context(_context)
: os::current_frame(); while (printed_len < limit && fr.pc() != nullptr) { if (print_code(st, _thread, fr.pc(), fr.pc() == _pc, printed, printed_capacity)) {
printed_len++;
}
fr = next_frame(fr, _thread);
}
}
// Scan the Java stack if (_thread != nullptr && _thread->is_Java_thread()) {
JavaThread* jt = JavaThread::cast(_thread); if (jt->has_last_Java_frame()) { for (StackFrameStream sfs(jt, true/* update */, true /* process_frames */); printed_len < limit && !sfs.is_done(); sfs.next()) {
address pc = sfs.current()->pc(); if (print_code(st, _thread, pc, pc == _pc, printed, printed_capacity)) {
printed_len++;
}
}
}
}
}
STEP_IF("printing VM operation", _verbose && _thread != nullptr && _thread->is_VM_thread())
VMThread* t = (VMThread*)_thread;
VM_Operation* op = t->vm_operation(); if (op) {
op->print_on_error(st);
st->cr();
st->cr();
}
STEP("printing process")
STEP_IF("printing process", _verbose)
st->cr();
st->print_cr("--------------- P R O C E S S ---------------");
st->cr();
STEP_IF("printing user info", ExtensiveErrorReports && _verbose)
os::print_user_info(st);
STEP_IF("printing all threads", _verbose && _thread) // all threads
Threads::print_on_error(st, _thread, buf, sizeof(buf));
st->cr();
STEP_IF("printing VM state", _verbose) // Safepoint state
st->print("VM state: ");
if (SafepointSynchronize::is_synchronizing()) st->print("synchronizing"); elseif (SafepointSynchronize::is_at_safepoint()) st->print("at safepoint"); else st->print("not at safepoint");
// Also see if error occurred during initialization or shutdown if (!Universe::is_fully_initialized()) {
st->print(" (not fully initialized)");
} elseif (VM_Exit::vm_exited()) {
st->print(" (shutting down)");
} else {
st->print(" (normal execution)");
}
st->cr();
st->cr();
STEP_IF("printing owned locks on error", _verbose) // mutexes/monitors that currently have an owner
print_owned_locks_on_error(st);
st->cr();
STEP_IF("printing number of OutOfMemoryError and StackOverflow exceptions",
_verbose && Exceptions::has_exception_counts())
st->print_cr("OutOfMemory and StackOverflow Exception counts:");
Exceptions::print_exception_counts_on_error(st);
st->cr();
STEP_IF("printing VM options", _verbose) // VM options
Arguments::print_on(st);
st->cr();
STEP_IF("printing flags", _verbose)
JVMFlag::printFlags(
st, true, // with comments false, // no ranges true); // skip defaults
st->cr();
STEP_IF("printing warning if internal testing API used", WhiteBox::used())
st->print_cr("Unsupported internal testing APIs have been used.");
st->cr();
STEP_IF("printing internal vm info", _verbose)
st->print_cr("vm_info: %s", VM_Version::internal_vm_info_string());
st->cr();
// print a defined marker to show that error handling finished correctly.
STEP_IF("printing end marker", _verbose)
st->print_cr("END.");
END
# undef BEGIN # undef STEP_IF # undef STEP # undef END
}
// Report for the vm_info_cmd. This prints out the information above omitting // crash and thread specific information. If output is added above, it should be added // here also, if it is safe to call during a running process. void VMError::print_vm_info(outputStream* st) {
// print a defined marker to show that error handling finished correctly. // STEP("printing end marker")
st->print_cr("END.");
}
/** Expand a pattern into a buffer starting at pos and open a file using constructed path */ staticint expand_and_open(constchar* pattern, bool overwrite_existing, char* buf, size_t buflen, size_t pos) { int fd = -1; int mode = O_RDWR | O_CREAT; if (overwrite_existing) {
mode |= O_TRUNC;
} else {
mode |= O_EXCL;
} if (Arguments::copy_expand_pid(pattern, strlen(pattern), &buf[pos], buflen - pos)) {
fd = open(buf, mode, 0666);
} return fd;
}
/** * Construct file name for a log file and return it's file descriptor. * Name and location depends on pattern, default_pattern params and access * permissions.
*/ int VMError::prepare_log_file(constchar* pattern, constchar* default_pattern, bool overwrite_existing, char* buf, size_t buflen) { int fd = -1;
// If possible, use specified pattern to construct log file name if (pattern != NULL) {
fd = expand_and_open(pattern, overwrite_existing, buf, buflen, 0);
}
// Either user didn't specify, or the user's location failed, // so use the default name in the current directory if (fd == -1) { constchar* cwd = os::get_current_directory(buf, buflen); if (cwd != NULL) {
size_t pos = strlen(cwd); int fsep_len = jio_snprintf(&buf[pos], buflen-pos, "%s", os::file_separator());
pos += fsep_len; if (fsep_len > 0) {
fd = expand_and_open(default_pattern, overwrite_existing, buf, buflen, pos);
}
}
}
// try temp directory if it exists. if (fd == -1) { constchar* tmpdir = os::get_temp_directory(); if (tmpdir != NULL && strlen(tmpdir) > 0) { int pos = jio_snprintf(buf, buflen, "%s%s", tmpdir, os::file_separator()); if (pos > 0) {
fd = expand_and_open(default_pattern, overwrite_existing, buf, buflen, pos);
}
}
}
void VMError::report_and_die(int id, constchar* message, constchar* detail_fmt, va_list detail_args,
Thread* thread, address pc, void* siginfo, void* context, constchar* filename, int lineno, size_t size)
{ // A single scratch buffer to be used from here on. // Do not rely on it being preserved across function calls. staticchar buffer[O_BUFLEN];
// File descriptor to tty to print an error summary to. // Hard wired to stdout; see JDK-8215004 (compatibility concerns). staticconstint fd_out = 1; // stdout
// File descriptor to the error log file. staticint fd_log = -1;
#ifdef CAN_SHOW_REGISTERS_ON_ASSERT // Disarm assertion poison page, since from this point on we do not need this mechanism anymore and it may // cause problems in error handling during native OOM, see JDK-8227275.
disarm_assert_poison(); #endif
// Use local fdStream objects only. Do not use global instances whose initialization // relies on dynamic initialization (see JDK-8214975). Do not rely on these instances // to carry over into recursions or invocations from other threads.
fdStream out(fd_out);
out.set_scratch_buffer(buffer, sizeof(buffer));
// Depending on the re-entrance depth at this point, fd_log may be -1 or point to an open hs-err file.
fdStream log(fd_log);
log.set_scratch_buffer(buffer, sizeof(buffer));
// How many errors occurred in error handler when reporting first_error. staticint recursive_error_count;
// We will first print a brief message to standard out (verbose = false), // then save detailed information in log file (verbose = true). staticbool out_done = false; // done printing to standard out staticbool log_done = false; // done saving error log
reporting_started(); if (!TestUnresponsiveErrorHandler) { // Record reporting_start_time unless we're running the // TestUnresponsiveErrorHandler test. For that test we record // reporting_start_time at the beginning of the test.
record_reporting_start_time();
} else {
out.print_raw_cr("Delaying recording reporting_start_time for TestUnresponsiveErrorHandler.");
}
if (ShowMessageBoxOnError || PauseAtExit) {
show_message_box(buffer, sizeof(buffer));
// User has asked JVM to abort. Reset ShowMessageBoxOnError so the // WatcherThread can kill JVM if the error handler hangs.
ShowMessageBoxOnError = false;
}
os::check_dump_limit(buffer, sizeof(buffer));
// reset signal handlers or exception filter; make sure recursive crashes // are handled properly.
install_secondary_signal_handler();
} else { #ifdefined(_WINDOWS) // If UseOSErrorReporting we call this for each level of the call stack // while searching for the exception handler. Only the first level needs // to be reported. if (UseOSErrorReporting && log_done) return; #endif
// This is not the first error, see if it happened in a different thread // or in the same thread during error reporting. if (_first_error_tid != mytid) { if (!SuppressFatalErrorMessage) { char msgbuf[64];
jio_snprintf(msgbuf, sizeof(msgbuf), "[thread " INTX_FORMAT " also had an error]",
mytid);
out.print_raw_cr(msgbuf);
}
// Error reporting is not MT-safe, nor can we let the current thread // proceed, so we block it.
os::infinite_sleep();
} else { if (recursive_error_count++ > 30) { if (!SuppressFatalErrorMessage) {
out.print_raw_cr("[Too many errors, abort]");
}
os::die();
}
if (SuppressFatalErrorMessage) { // If we already hit a secondary error during abort, then calling // it again is likely to hit another one. But eventually, if we // don't deadlock somewhere, we will call os::die() above.
os::abort(CreateCoredumpOnCrash);
}
outputStream* const st = log.is_open() ? &log : &out;
st->cr();
// Timeout handling. if (_step_did_timeout) { // The current step had a timeout. Lets continue reporting with the next step.
st->print_raw("[timeout occurred during error reporting in step \"");
st->print_raw(_current_step_info);
st->print_cr("\"] after " INT64_FORMAT " s.",
(int64_t)
((get_current_timestamp() - _step_start_time) / TIMESTAMP_TO_SECONDS_FACTOR));
} elseif (_reporting_did_timeout) { // We hit ErrorLogTimeout. Reporting will stop altogether. Let's wrap things // up, the process is about to be stopped by the WatcherThread.
st->print_cr("------ Timeout during error reporting after " INT64_FORMAT " s. ------",
(int64_t)
((get_current_timestamp() - _reporting_start_time) / TIMESTAMP_TO_SECONDS_FACTOR));
st->flush(); // Watcherthread is about to call os::die. Lets just wait.
os::infinite_sleep();
} else { // A secondary error happened. Print brief information, but take care, since crashing // here would just recurse endlessly. // Any information (signal, context, siginfo etc) printed here should use the function // arguments, not the information stored in *this, since those describe the primary crash. staticchar tmp[256]; // cannot use global scratch buffer // Note: this string does get parsed by a number of jtreg tests, // see hotspot/jtreg/runtime/ErrorHandling.
st->print("[error occurred during error reporting (%s), id 0x%x",
_current_step_info, id); if (os::exception_name(id, tmp, sizeof(tmp))) {
st->print(", %s (0x%x) at pc=" PTR_FORMAT, tmp, id, p2i(pc));
} else { if (should_report_bug(id)) {
st->print(", Internal Error (%s:%d)",
filename == NULL ? "??" : filename, lineno);
} else {
st->print(", Out of Memory Error (%s:%d)",
filename == NULL ? "??" : filename, lineno);
}
}
st->print_cr("]"); if (ErrorLogSecondaryErrorDetails) { staticbool recursed = false; if (!recursed) {
recursed = true; // Print even more information for secondary errors. This may generate a lot of output // and possibly disturb error reporting, therefore its optional and only available in debug builds. if (siginfo != nullptr) {
st->print("[");
os::print_siginfo(st, siginfo);
st->print_cr("]");
}
st->print("[stack: ");
frame fr = context ? os::fetch_frame_from_context(context) : os::current_frame(); // Subsequent secondary errors build up stack; to avoid flooding the hs-err file with irrelevant // call stacks, limit the stack we print here (we are only interested in what happened before the // last assert/fault). constint max_stack_size = 15;
print_native_stack(st, fr, _thread, true, max_stack_size, tmp, sizeof(tmp));
st->print_cr("]");
} // !recursed
recursed = false; // Note: reset outside !recursed
}
}
}
}
// Part 1: print an abbreviated version (the '#' section) to stdout. if (!out_done) { // Suppress this output if we plan to print Part 2 to stdout too. // No need to have the "#" section twice. if (!(ErrorFileToStdout && out.fd() == 1)) {
report(&out, false);
}
out_done = true;
_current_step = 0;
_current_step_info = "";
}
// Part 2: print a full error log file (optionally to stdout or stderr). // print to error log file if (!log_done) { // see if log file is already open if (!log.is_open()) { // open log file if (ErrorFileToStdout) {
fd_log = 1;
} elseif (ErrorFileToStderr) {
fd_log = 2;
} else {
fd_log = prepare_log_file(ErrorFile, "hs_err_pid%p.log", true,
buffer, sizeof(buffer)); if (fd_log != -1) {
out.print_raw("# An error report file with more information is saved as:\n# ");
out.print_raw_cr(buffer);
} else {
out.print_raw_cr("# Can not save log file, dump to screen..");
fd_log = 1;
}
}
log.set_fd(fd_log);
}
if (WINDOWS_ONLY(!UseOSErrorReporting) NOT_WINDOWS(true)) { // os::abort() will call abort hooks, try it first. staticbool skip_os_abort = false; if (!skip_os_abort) {
skip_os_abort = true; bool dump_core = should_report_bug(_id);
os::abort(dump_core && CreateCoredumpOnCrash, _siginfo, _context);
}
// if os::abort() doesn't abort, try os::die();
os::die();
}
}
/* * OnOutOfMemoryError scripts/commands executed while VM is a safepoint - this * ensures utilities such as jmap can observe the process is a consistent state.
*/ class VM_ReportJavaOutOfMemory : public VM_Operation { private: constchar* _message; public:
VM_ReportJavaOutOfMemory(constchar* message) { _message = message; }
VMOp_Type type() const { return VMOp_ReportJavaOutOfMemory; } void doit();
};
void VM_ReportJavaOutOfMemory::doit() { // Don't allocate large buffer on stack staticchar buffer[O_BUFLEN];
void VMError::show_message_box(char *buf, int buflen) { bool yes; do {
error_string(buf, buflen);
yes = os::start_debugging(buf,buflen);
} while (yes);
}
// Timeout handling: check if a timeout happened (either a single step did // timeout or the whole of error reporting hit ErrorLogTimeout). Interrupt // the reporting thread if that is the case. bool VMError::check_timeout() {
if (ErrorLogTimeout == 0) { returnfalse;
}
// Do not check for timeouts if we still have a message box to show to the // user or if there are OnError handlers to be run. if (ShowMessageBoxOnError
|| (OnError != NULL && OnError[0] != '\0')
|| Arguments::abort_hook() != NULL) { returnfalse;
}
const jlong reporting_start_time_l = get_reporting_start_time(); const jlong now = get_current_timestamp(); // Timestamp is stored in nanos. if (reporting_start_time_l > 0) { const jlong end = reporting_start_time_l + (jlong)ErrorLogTimeout * TIMESTAMP_TO_SECONDS_FACTOR; if (end <= now && !_reporting_did_timeout) { // We hit ErrorLogTimeout and we haven't interrupted the reporting // thread yet.
_reporting_did_timeout = true;
interrupt_reporting_thread(); returntrue; // global timeout
}
}
const jlong step_start_time_l = get_step_start_time(); if (step_start_time_l > 0) { // A step times out after a quarter of the total timeout. Steps are mostly fast unless they // hang for some reason, so this simple rule allows for three hanging step and still // hopefully leaves time enough for the rest of the steps to finish. const jlong end = step_start_time_l + (jlong)ErrorLogTimeout * TIMESTAMP_TO_SECONDS_FACTOR / 4; if (end <= now && !_step_did_timeout) { // The step timed out and we haven't interrupted the reporting // thread yet.
_step_did_timeout = true;
interrupt_reporting_thread(); returnfalse; // (Not a global timeout)
}
}
returnfalse;
}
#ifdef ASSERT typedefvoid (*voidfun_t)();
// Crash with an authentic sigfpe volatileint sigfpe_int = 0; staticvoid crash_with_sigfpe() {
// generate a native synchronous SIGFPE where possible;
sigfpe_int = sigfpe_int/sigfpe_int;
// if that did not cause a signal (e.g. on ppc), just // raise the signal. #ifndef _WIN32 // OSX implements raise(sig) incorrectly so we need to // explicitly target the current thread
pthread_kill(pthread_self(), SIGFPE); #endif
} // end: crash_with_sigfpe
// crash with sigsegv at non-null address. staticvoid crash_with_segfault() {
// Case 14 is tested by test/hotspot/jtreg/runtime/ErrorHandling/SafeFetchInErrorHandlingTest.java. // Case 15 is tested by test/hotspot/jtreg/runtime/ErrorHandling/SecondaryErrorTest.java. // Case 16 is tested by test/hotspot/jtreg/runtime/ErrorHandling/ThreadsListHandleInErrorHandlingTest.java. // Case 17 is tested by test/hotspot/jtreg/runtime/ErrorHandling/NestedThreadsListHandleInErrorHandlingTest.java.
// We try to grab Threads_lock to keep ThreadsSMRSupport::print_info_on() // from racing with Threads::add() or Threads::remove() as we // generate the hs_err_pid file. This makes our ErrorHandling tests // more stable. if (!Threads_lock->owned_by_self()) {
Threads_lock->try_lock(); // The VM is going to die so no need to unlock Thread_lock.
}
switch (how) { case 1: assert(how == 0, "test assert"); break; case 2: guarantee(how == 0, "test guarantee"); break;
// The other cases are unused. case 14: crash_with_segfault(); break; case 15: crash_with_sigfpe(); break; case 16: {
ThreadsListHandle tlh;
fatal("Force crash with an active ThreadsListHandle.");
} case 17: {
ThreadsListHandle tlh;
{
ThreadsListHandle tlh2;
fatal("Force crash with a nested ThreadsListHandle.");
}
} default: // If another number is given, give a generic crash.
fatal("Crashing with number %d", how);
}
tty->print_cr("controlled_crash: survived intentional crash. Did you suppress the assert?");
ShouldNotReachHere();
} #endif// !ASSERT
¤ Dauer der Verarbeitung: 0.39 Sekunden
(vorverarbeitet)
¤
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung ist noch experimentell.