blob: 1d4aac1cf953b353ff058f3af7ef99495b3a7980 [file] [edit]
// Copyright 2026 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! In-process Rust panic crash reporting and abrupt-exit handling for Bazel.
//!
//! Installing [`PanicHandler::install`] replaces Rust's default `SIGABRT` panic termination with a
//! structured crash pipeline that executes directly on the panicking thread without unwinding
//! across `extern "C"` or re-entering Java bytecode:
//!
//! 1. Captures the panic payload message and [`PanicHookInfo::location`].
//! 2. Writes Bazel's abrupt-exit status file (`37` = `BLAZE_INTERNAL_ERROR`) and serialized
//! `failure_details.FailureDetail` (`Crash`) protobuf file.
//! 3. Prints a diagnostic crash banner to `stderr` (`jvm.out` in server mode).
//! 4. Terminates the server process immediately (via `_exit(37)` on Unix or `TerminateProcess` on
//! Windows), avoiding `SIGABRT` core dumps and JVM shutdown-hook deadlocks.
use failure_details_rust_proto::{Crash, FailureDetail};
use protobuf::{Serialize, SerializeError};
use std::fmt::{self, Arguments};
use std::fs::{self, File};
use std::io::{self, Write};
use std::mem::ManuallyDrop;
use std::panic::{self, Location, PanicHookInfo};
use std::path::PathBuf;
use std::sync::Mutex;
/// Bazel exit code `37` (`ExitCode.BLAZE_INTERNAL_ERROR`).
const PANIC_EXIT_CODE: i32 = 37;
const MAX_MESSAGE_BYTES: usize = 2000;
const TRUNCATION_SUFFIX: &str = "[truncated]";
const _: () = assert!(MAX_MESSAGE_BYTES > TRUNCATION_SUFFIX.len());
/// Process-wide coordinator for fatal Rust panic reporting.
#[must_use = "a PanicHandler does nothing unless install() is called"]
pub struct PanicHandler {
/// Path to Bazel's abrupt-exit status file.
pub abrupt_exit_file: PathBuf,
/// Path to Bazel's `FailureDetail` protobuf file.
pub failure_detail_file: PathBuf,
}
impl PanicHandler {
/// Installs this handler as the process-wide fatal Rust panic hook.
///
/// # Panics
///
/// Panics if either crash file path is empty or if called more than once in the same process.
pub fn install(self) {
static INSTALLED: Mutex<bool> = Mutex::new(false);
assert!(
!self.abrupt_exit_file.as_os_str().is_empty(),
"PanicHandler::abrupt_exit_file must not be empty"
);
assert!(
!self.failure_detail_file.as_os_str().is_empty(),
"PanicHandler::failure_detail_file must not be empty"
);
let mut installed = INSTALLED.lock().expect("INSTALLED mutex should not be poisoned");
assert!(!*installed, "PanicHandler::install called more than once");
panic::set_hook(Box::new(move |info| self.panic_hook(info)));
*installed = true;
}
/// Process-wide panic hook installed by [`PanicHandler::install`]. Coordinates concurrent
/// panics, runs the crash-reporting pipeline, and terminates the process with
/// [`PANIC_EXIT_CODE`].
fn panic_hook(&self, info: &PanicHookInfo<'_>) {
static PANIC_LOCK: Mutex<()> = Mutex::new(());
// Only the first thread to enter the hook reports the panic and exits. Any other thread
// panicking concurrently blocks here until the process terminates.
//
// A same-thread panic inside this hook cannot re-enter here: `std` detects panics while a
// panic hook is running and aborts the process immediately.
let _guard = PANIC_LOCK.lock();
let raw_payload = info.payload_as_str().unwrap_or("<unknown>");
self.handle_panic(raw_payload, info.location());
exit_now();
}
/// Runs the panic-reporting pipeline before the process terminates.
fn handle_panic(&self, raw_payload: &str, location: Option<&Location<'_>>) {
let location_suffix = match location {
Some(location) => format!(" (at {location})"),
None => String::new(),
};
let exception_message = truncate_message(raw_payload, &location_suffix);
// Write Bazel abrupt-exit status and FailureDetail files first, before writing to stderr,
// so the client still receives them if stderr blocks.
let abrupt_exit_result = self.write_abrupt_exit_file();
let failure_detail_result = self.write_failure_detail_file(&exception_message);
let mut stderr = RawStderr::new();
if let Err(err) = abrupt_exit_result {
let _ = writeln!(
stderr,
"io error writing {} to abrupt exit status file {}: {}",
PANIC_EXIT_CODE,
self.abrupt_exit_file.display(),
err
);
}
if let Err(err) = failure_detail_result {
let _ = writeln!(
stderr,
"io error writing failure detail to file {}: {}",
self.failure_detail_file.display(),
err
);
}
// Emit human-readable crash diagnostics to stderr (`jvm.out`).
let _ = writeln!(
stderr,
"FATAL: Server crashed due to an internal error (Rust panic): {exception_message}"
);
}
/// Writes the abrupt-exit status file.
fn write_abrupt_exit_file(&self) -> io::Result<()> {
let exit_str = PANIC_EXIT_CODE.to_string();
fs::write(&self.abrupt_exit_file, exit_str.as_bytes())
}
/// Writes the `failure_details.FailureDetail` file.
fn write_failure_detail_file(&self, exception_message: &str) -> io::Result<()> {
let proto_bytes =
encode_crash_failure_detail(exception_message).map_err(io::Error::other)?;
fs::write(&self.failure_detail_file, &proto_bytes)
}
}
/// Lock-free writer to the process's raw `stderr` handle, inspired by `std`'s default panic hook.
///
/// Wraps the underlying OS descriptor/handle from [`io::stderr`] in a [`ManuallyDrop<File>`]
/// (without acquiring `std::io::stderr()`'s process-wide lock or allocating an extra descriptor) so
/// a panicking thread cannot deadlock if another thread holds `std::io::stderr().lock()` and still
/// works under file-descriptor exhaustion (`EMFILE`). Each `write_fmt` call is buffered into a
/// single `write_all` so formatted lines are not torn across concurrent stderr writers.
struct RawStderr(Option<ManuallyDrop<File>>);
impl RawStderr {
/// Creates a lock-free writer backed directly by the process's `stderr` descriptor/handle.
fn new() -> Self {
Self(raw_stderr_file())
}
}
impl Write for RawStderr {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
match &mut self.0 {
Some(file) => file.write(buf),
None => Ok(buf.len()),
}
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
fn write_fmt(&mut self, args: Arguments<'_>) -> io::Result<()> {
if let Some(s) = args.as_str() {
return self.write_all(s.as_bytes());
}
self.write_all(fmt::format(args).as_bytes())
}
}
/// Returns a [`ManuallyDrop<File>`] backed directly by the process's `stderr` descriptor/handle
/// without locking `std::io::stderr()`, or `None` if `stderr` is not attached to a valid handle.
fn raw_stderr_file() -> Option<ManuallyDrop<File>> {
raw_stderr_imp::raw_stderr_file()
}
#[cfg(unix)]
mod raw_stderr_imp {
use std::fs::File;
use std::io;
use std::mem::ManuallyDrop;
use std::os::fd::{AsRawFd, FromRawFd};
pub(super) fn raw_stderr_file() -> Option<ManuallyDrop<File>> {
let raw_fd = io::stderr().as_raw_fd();
(raw_fd >= 0).then(|| {
// SAFETY: `raw_fd` is the process's live stderr file descriptor (verified
// non-negative), obtained without locking `io::stderr()`. Wrapping the `File` in
// `ManuallyDrop` ensures the descriptor is never closed when the returned value is
// dropped.
ManuallyDrop::new(unsafe { File::from_raw_fd(raw_fd) })
})
}
}
#[cfg(windows)]
mod raw_stderr_imp {
use std::fs::File;
use std::io;
use std::mem::ManuallyDrop;
use std::os::windows::io::{AsRawHandle, FromRawHandle};
pub(super) fn raw_stderr_file() -> Option<ManuallyDrop<File>> {
let raw_handle = io::stderr().as_raw_handle();
(!raw_handle.is_null() && raw_handle as isize != -1).then(|| {
// SAFETY: `raw_handle` is a non-null, non-`INVALID_HANDLE_VALUE` handle to the
// process's live stderr, obtained without locking `io::stderr()`. Wrapping the `File`
// in `ManuallyDrop` ensures the handle is never closed when the returned value is
// dropped.
ManuallyDrop::new(unsafe { File::from_raw_handle(raw_handle) })
})
}
}
#[cfg(not(any(unix, windows)))]
mod raw_stderr_imp {
use std::fs::File;
use std::mem::ManuallyDrop;
pub(super) fn raw_stderr_file() -> Option<ManuallyDrop<File>> {
compile_error!("raw_stderr_file not implemented on this platform");
}
}
/// Immediately terminates the process with [`PANIC_EXIT_CODE`].
fn exit_now() -> ! {
exit_imp::exit_now()
}
#[cfg(unix)]
mod exit_imp {
use super::PANIC_EXIT_CODE;
use std::ffi::c_int;
unsafe extern "C" {
fn _exit(status: c_int) -> !;
}
pub(super) fn exit_now() -> ! {
// SAFETY: POSIX `_exit` is async-signal-safe and terminates the process immediately with
// exit code `37` (`BLAZE_INTERNAL_ERROR`) without running C++/JVM `atexit` handlers or
// raising `SIGABRT`.
unsafe { _exit(PANIC_EXIT_CODE) }
}
}
#[cfg(windows)]
mod exit_imp {
use super::PANIC_EXIT_CODE;
use std::ffi::c_void;
#[link(name = "kernel32")]
unsafe extern "system" {
fn GetCurrentProcess() -> *mut c_void;
fn TerminateProcess(process: *mut c_void, exit_code: u32) -> i32;
}
pub(super) fn exit_now() -> ! {
// SAFETY: `GetCurrentProcess` returns the pseudo-handle for the current process, and
// `TerminateProcess` terminates it immediately with `PANIC_EXIT_CODE` without running
// `atexit` handlers or DLL detach callbacks.
unsafe {
TerminateProcess(GetCurrentProcess(), PANIC_EXIT_CODE as u32);
}
std::process::abort()
}
}
#[cfg(not(any(unix, windows)))]
mod exit_imp {
pub(super) fn exit_now() -> ! {
compile_error!("exit_now not implemented on this platform");
}
}
/// Formats `payload` followed by `location_suffix`, truncating `payload` (and appending
/// [`TRUNCATION_SUFFIX`]) if needed so the result fits within [`MAX_MESSAGE_BYTES`] UTF-8 bytes
/// while preserving `location_suffix`.
fn truncate_message(payload: &str, location_suffix: &str) -> String {
if payload.len() + location_suffix.len() <= MAX_MESSAGE_BYTES {
return format!("{payload}{location_suffix}");
}
let suffix_len = location_suffix.len() + TRUNCATION_SUFFIX.len();
if suffix_len <= MAX_MESSAGE_BYTES {
let end = payload.floor_char_boundary(MAX_MESSAGE_BYTES - suffix_len);
return format!("{}{TRUNCATION_SUFFIX}{location_suffix}", &payload[..end]);
}
let combined = format!("{payload}{location_suffix}");
let end = combined.floor_char_boundary(MAX_MESSAGE_BYTES - TRUNCATION_SUFFIX.len());
format!("{}{TRUNCATION_SUFFIX}", &combined[..end])
}
/// Serializes a `failure_details.FailureDetail` message containing a `Crash` (with the default
/// code `CRASH_UNKNOWN`).
fn encode_crash_failure_detail(message: &str) -> Result<Vec<u8>, SerializeError> {
let mut failure_detail = FailureDetail::new();
// Matches the message format produced by `CrashFailureDetails.forThrowable` in Java.
failure_detail.set_message(format!("Crashed: (Rust panic) {message}"));
failure_detail.set_crash(Crash::new());
failure_detail.serialize()
}