# HG changeset patch # User stuefe # Date 1477490657 -7200 # Node ID 32c75d094995db79f7816969b2eaf0181351765c # Parent a26b9492461b8cee870da58946cced75032b325b 8166944: Hanging Error Reporting steps may lead to torn error logs. Reviewed-by: cjplummer, dholmes Summary: Interupt error reporting if reporting steps hang to enable subsequent reporting steps to run. diff --git a/src/os/posix/vm/vmError_posix.cpp b/src/os/posix/vm/vmError_posix.cpp --- a/src/os/posix/vm/vmError_posix.cpp +++ b/src/os/posix/vm/vmError_posix.cpp @@ -59,6 +59,21 @@ static int resettedSigflags[NUM_SIGNALS]; static address resettedSighandler[NUM_SIGNALS]; +// Needed for cancelable steps. +static volatile pthread_t reporter_thread_id; + +void VMError::reporting_started() { + // record pthread id of reporter thread. + reporter_thread_id = ::pthread_self(); +} + +void VMError::interrupt_reporting_thread() { + // We misuse SIGILL here, but it does not really matter. We need + // a signal which is handled by crash_handler and not likely to + // occurr during error reporting itself. + ::pthread_kill(reporter_thread_id, SIGILL); +} + static void save_signal(int idx, int sig) { struct sigaction sa; diff --git a/src/os/windows/vm/vmError_windows.cpp b/src/os/windows/vm/vmError_windows.cpp --- a/src/os/windows/vm/vmError_windows.cpp +++ b/src/os/windows/vm/vmError_windows.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2016, Oracle and/or its affiliates. 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 @@ -66,3 +66,10 @@ } } } + +// Error reporting canceleation: there is no easy way to implement this on Windows, because we do +// not have an easy way to send signals to threads (aka to cause a win32 Exception in another +// thread). We would need something like "RaiseException(HANDLE thread)"... +void VMError::reporting_started() {} +void VMError::interrupt_reporting_thread() {} + diff --git a/src/share/vm/runtime/globals.hpp b/src/share/vm/runtime/globals.hpp --- a/src/share/vm/runtime/globals.hpp +++ b/src/share/vm/runtime/globals.hpp @@ -935,6 +935,9 @@ notproduct(bool, TestSafeFetchInErrorHandler, false, \ "If true, tests SafeFetch inside error handler.") \ \ + notproduct(bool, TestUnresponsiveErrorHandler, false, \ + "If true, simulates an unresponsive error handler.") \ + \ develop(bool, Verbose, false, \ "Print additional debugging information from other modes") \ \ diff --git a/src/share/vm/runtime/thread.cpp b/src/share/vm/runtime/thread.cpp --- a/src/share/vm/runtime/thread.cpp +++ b/src/share/vm/runtime/thread.cpp @@ -1289,28 +1289,32 @@ if (is_error_reported()) { // A fatal error has happened, the error handler(VMError::report_and_die) // should abort JVM after creating an error log file. However in some - // rare cases, the error handler itself might deadlock. Here we try to - // kill JVM if the fatal error handler fails to abort in 2 minutes. - // + // rare cases, the error handler itself might deadlock. Here periodically + // check for error reporting timeouts, and if it happens, just proceed to + // abort the VM. + // This code is in WatcherThread because WatcherThread wakes up // periodically so the fatal error handler doesn't need to do anything; // also because the WatcherThread is less likely to crash than other // threads. for (;;) { - if (!ShowMessageBoxOnError - && (OnError == NULL || OnError[0] == '\0') - && Arguments::abort_hook() == NULL) { - os::sleep(this, (jlong)ErrorLogTimeout * 1000, false); // in seconds + // Note: we use naked sleep in this loop because we want to avoid using + // any kind of VM infrastructure which may be broken at this point. + if (VMError::check_timeout()) { + // We hit error reporting timeout. Error reporting was interrupted and + // will be wrapping things up now (closing files etc). Give it some more + // time, then quit the VM. + os::naked_short_sleep(200); + // Print a message to stderr. fdStream err(defaultStream::output_fd()); err.print_raw_cr("# [ timer expired, abort... ]"); // skip atexit/vm_exit/vm_abort hooks os::die(); } - // Wake up 5 seconds later, the fatal handler may reset OnError or - // ShowMessageBoxOnError when it is ready to abort. - os::sleep(this, 5 * 1000, false); + // Wait a second, then recheck for timeout. + os::naked_short_sleep(999); } } diff --git a/src/share/vm/utilities/vmError.cpp b/src/share/vm/utilities/vmError.cpp --- a/src/share/vm/utilities/vmError.cpp +++ b/src/share/vm/utilities/vmError.cpp @@ -38,6 +38,7 @@ #include "runtime/thread.inline.hpp" #include "runtime/vmThread.hpp" #include "runtime/vm_operations.hpp" +#include "runtime/vm_version.hpp" #include "services/memTracker.hpp" #include "trace/traceMacros.hpp" #include "utilities/debug.hpp" @@ -312,10 +313,36 @@ int VMError::_current_step; const char* VMError::_current_step_info; +// Timeout handling. +static volatile jlong reporting_start_time = -1; +static volatile bool reporting_timeout = false; +static volatile jlong step_start_time = -1; +static volatile bool step_timeout = false; + +// Helper function, sets a timestamp to the current time. +static void set_to_now(volatile jlong* p) { + const jlong now = os::javaTimeMillis(); + if (VM_Version::supports_cx8()) { + Atomic::store(now, p); + } else { + *p = now; + } +} + +// helper function, returns value of time stamp. +static jlong get_timestamp(volatile jlong* p) { + if (VM_Version::supports_cx8()) { + return Atomic::load(p); + } else { + return *p; + } +} + void VMError::report(outputStream* st, bool _verbose) { # define BEGIN if (_current_step == 0) { _current_step = __LINE__; -# define STEP(s) } if (_current_step < __LINE__) { _current_step = __LINE__; _current_step_info = s; +# define STEP(s) } if (_current_step < __LINE__) { _current_step = __LINE__; _current_step_info = s; \ + set_to_now(&step_start_time); step_timeout = false; # define END } // don't allocate large buffer on stack @@ -352,6 +379,17 @@ controlled_crash(TestCrashInErrorHandler); } + // TestUnresponsiveErrorHandler: three times to trigger first a step timeout, then + // the global error reporting timeout. + STEP("test unresponsive error reporting step 1") + if (_verbose && TestUnresponsiveErrorHandler) { os::infinite_sleep(); } + + STEP("test unresponsive error reporting step 2") + if (_verbose && TestUnresponsiveErrorHandler) { os::infinite_sleep(); } + + STEP("test unresponsive error reporting step 3") + if (_verbose && TestUnresponsiveErrorHandler) { os::infinite_sleep(); } + STEP("test safefetch in error handler") // test whether it is safe to use SafeFetch32 in Crash Handler. Test twice // to test that resetting the signal handler works correctly. @@ -1176,6 +1214,9 @@ // first time set_error_reported(); + reporting_started(); + set_to_now(&reporting_start_time); + if (ShowMessageBoxOnError || PauseAtExit) { show_message_box(buffer, sizeof(buffer)); @@ -1216,17 +1257,30 @@ os::die(); } - jio_snprintf(buffer, sizeof(buffer), - "[error occurred during error reporting (%s), id 0x%x]", + outputStream* const st = log.is_open() ? &log : &out; + st->cr(); + + // Timeout handling. + if (step_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 " ms.", os::javaTimeMillis() - step_start_time); + } else if (reporting_timeout) { + // We hit ErrorLogTimeout. Reporting will stop altogether. Lets wrap things + // up, the process is about to be stopped by the WatcherThread. + st->print_cr("------ Timout during error reporting after " INT64_FORMAT "ms. ------", + os::javaTimeMillis() - reporting_start_time); + st->flush(); + // Watcherthread is about to call os::die. Lets just wait. + os::infinite_sleep(); + } else { + // Crash or assert during error reporting. Lets continue reporting with the next step. + jio_snprintf(buffer, sizeof(buffer), + "[error occurred during error reporting (%s), id 0x%x]", _current_step_info, _id); - if (log.is_open()) { - log.cr(); - log.print_raw_cr(buffer); - log.cr(); - } else { - out.cr(); - out.print_raw_cr(buffer); - out.cr(); + st->print_raw_cr(buffer); + st->cr(); } } } @@ -1421,3 +1475,49 @@ 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) { + return false; + } + + // 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) { + return false; + } + + const jlong reporting_start_time_l = get_timestamp(&reporting_start_time); + const jlong now = os::javaTimeMillis(); + if (reporting_start_time_l > 0) { + const jlong end = reporting_start_time_l + ErrorLogTimeout * 1000; + if (end <= now) { + reporting_timeout = true; + VMError::interrupt_reporting_thread(); + return true; // global timeout + } + } + + const jlong step_start_time_l = get_timestamp(&step_start_time); + if (step_start_time_l > 0) { + // A step times out after half of the total timeout. Steps are mostly fast unless they + // hang for some reason, so this simple rule allows for one hanging step and still + // leaves time enough for the rest of the steps to finish. + const jlong end = step_start_time_l + ErrorLogTimeout * 1000 / 2; + if (end <= now) { + step_timeout = true; + VMError::interrupt_reporting_thread(); + return false; // (Not a global timeout) + } + } + + return false; + +} + diff --git a/src/share/vm/utilities/vmError.hpp b/src/share/vm/utilities/vmError.hpp --- a/src/share/vm/utilities/vmError.hpp +++ b/src/share/vm/utilities/vmError.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2016, Oracle and/or its affiliates. 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 @@ -104,6 +104,10 @@ static fdStream out; static fdStream log; // error log used by VMError::report_and_die() + // Platform dependend helper functions used for timeout handling. + static void reporting_started(); + static void interrupt_reporting_thread(); + public: // return a string to describe the error @@ -147,6 +151,11 @@ static bool fatal_error_in_progress() { return first_error_tid != -1; } static intptr_t get_first_error_tid() { return first_error_tid; } + + // Called by WatcherThread to check if the currently running error reporting did timeout. + // Returns true if reporting did hit the global ErrorLogTimeout. + static bool check_timeout(); + }; #endif // SHARE_VM_UTILITIES_VMERROR_HPP diff --git a/test/runtime/ErrorHandling/TimeoutInErrorHandlingTest.java b/test/runtime/ErrorHandling/TimeoutInErrorHandlingTest.java new file mode 100644 --- /dev/null +++ b/test/runtime/ErrorHandling/TimeoutInErrorHandlingTest.java @@ -0,0 +1,131 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. 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. + */ + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStreamReader; +import java.util.regex.Pattern; + +import jdk.test.lib.process.OutputAnalyzer; +import jdk.test.lib.Platform; +import jdk.test.lib.process.ProcessTools; + +/* + * @test + * @bug 8166944 + * @summary Hanging Error Reporting steps may lead to torn error logs + * @modules java.base/jdk.internal.misc + * @library /test/lib + * @requires vm.debug == true + * @author Thomas Stuefe (SAP) + */ + +public class TimeoutInErrorHandlingTest { + + + public static void main(String[] args) throws Exception { + + /* Start the VM and let it crash. Specify TestUnresponsiveErrorHandler which will + * let three subsequent error reporting steps hang. The Timeout handling triggered + * by the WatcherThread should kick in and interrupt those steps. + * + * Timeout in Error Reporting is controlled by ErrorLogTimeout, which defines after + * how many seconds error reporting is stopped altogether and the VM is aborted. + * Each error reporting step is granted up to half of this time before it is canceled + * and the next step is started (the logic being, typically error steps are + * instantaneous, if they hang, its typically an error which only should affect one + * or two steps). + * So, by causing three subsequent steps to hang, we expect the error log to contain + * at least one, possibly two step-timeout messages, and then the global ErrorLogTimeout + * should have been reached and the VM should have been aborted by the WatcherThread, + * which should write "timer expired, abort..." to stderr. */ + + // Not debug, not windows (yet) + if (!Platform.isDebugBuild() || Platform.isWindows()) { + return; + } + + ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + "-XX:+UnlockDiagnosticVMOptions", + "-Xmx100M", + "-XX:ErrorHandlerTest=14", + "-XX:+TestUnresponsiveErrorHandler", + "-XX:ErrorLogTimeout=10", // 10 seconds + "-XX:-CreateCoredumpOnCrash", + "-version"); + + OutputAnalyzer output_detail = new OutputAnalyzer(pb.start()); + + // we should have crashed with a SIGSEGV + output_detail.shouldMatch("# A fatal error has been detected by the Java Runtime Environment:.*"); + output_detail.shouldMatch("# +(?:SIGSEGV|EXCEPTION_ACCESS_VIOLATION).*"); + + // VM should have been aborted by WatcherThread + output_detail.shouldMatch(".*timer expired, abort.*"); + + // extract hs-err file + String hs_err_file = output_detail.firstMatch("# *(\\S*hs_err_pid\\d+\\.log)", 1); + if (hs_err_file == null) { + throw new RuntimeException("Did not find hs-err file in output.\n"); + } + + File f = new File(hs_err_file); + if (!f.exists()) { + throw new RuntimeException("hs-err file missing at " + + f.getAbsolutePath() + ".\n"); + } + + System.out.println("Found hs_err file. Scanning..."); + + FileInputStream fis = new FileInputStream(f); + BufferedReader br = new BufferedReader(new InputStreamReader(fis)); + String line = null; + + Pattern [] pattern = new Pattern[] { + Pattern.compile(".*timeout occurred during error reporting in step.*") + }; + int currentPattern = 0; + + String lastLine = null; + while ((line = br.readLine()) != null) { + if (currentPattern < pattern.length) { + if (pattern[currentPattern].matcher(line).matches()) { + System.out.println("Found: " + line + "."); + currentPattern ++; + } + } + lastLine = line; + } + br.close(); + + if (currentPattern < pattern.length) { + throw new RuntimeException("hs-err file incomplete (first missing pattern: " + currentPattern + ")"); + } + + System.out.println("OK."); + + } + +} +