blob: f4913d16ce2247d6cb9889a6a6f9c6441ddc8b77 [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.
use failure_details_rust_proto::{crash, FailureDetail};
use googletest::fixtures::Fixture;
use googletest::prelude::*;
use protobuf::Parse;
use runfiles::{rlocation, Runfiles};
use std::env;
use std::ffi::OsStr;
use std::fs;
use std::io::{self, ErrorKind};
use std::path::{Path, PathBuf};
use std::process::{self, Command, ExitStatus};
use std::sync::atomic::{AtomicUsize, Ordering};
static NEXT_TEST_DIR_ID: AtomicUsize = AtomicUsize::new(0);
const BANNER_PREFIX: &str = "FATAL: Server crashed due to an internal error (Rust panic): ";
struct TestDir {
path: PathBuf,
}
impl TestDir {
fn abrupt_exit_file(&self) -> PathBuf {
self.path.join("exit_code_to_use_on_abrupt_exit")
}
fn failure_detail_file(&self) -> PathBuf {
self.path.join("failure_detail.rawproto")
}
fn run_helper(&self, mode: &str) -> Result<CrashRun> {
self.run_helper_with_args(mode, &[])
}
fn run_helper_with_args(&self, mode: &str, extra_args: &[&OsStr]) -> Result<CrashRun> {
let mut command = Command::new(helper_binary_path()?);
command.arg(&self.path).arg(mode).args(extra_args);
let output = command.output().or_fail()?;
let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
let abrupt_exit =
read_optional_string(&self.abrupt_exit_file()).or_fail().with_failure_message(
|| format!("failed reading abrupt exit file; stderr:\n{stderr}"),
)?;
let failure_detail =
match read_optional_bytes(&self.failure_detail_file()).or_fail().with_failure_message(
|| format!("failed reading failure detail file; stderr:\n{stderr}"),
)? {
Some(bytes) => {
Some(FailureDetail::parse(&bytes).or_fail().with_failure_message(|| {
format!("invalid FailureDetail proto; stderr:\n{stderr}")
})?)
}
None => None,
};
Ok(CrashRun { status: output.status, stderr, abrupt_exit, failure_detail })
}
}
impl Fixture for TestDir {
fn set_up() -> Result<Self> {
let id = NEXT_TEST_DIR_ID.fetch_add(1, Ordering::Relaxed);
let base = env::var_os("TEST_TMPDIR").map(PathBuf::from).unwrap_or_else(env::temp_dir);
let path = base.join(format!("panic_handler_test_{}_{}", process::id(), id));
fs::create_dir_all(&path).or_fail()?;
Ok(Self { path })
}
fn tear_down(self) -> Result<()> {
fs::remove_dir_all(&self.path).or_fail()?;
Ok(())
}
}
struct CrashRun {
status: ExitStatus,
stderr: String,
abrupt_exit: Option<String>,
failure_detail: Option<FailureDetail>,
}
impl CrashRun {
fn exit_code(&self) -> Option<i32> {
self.status.code()
}
#[track_caller]
fn banner(&self) -> Result<&str> {
let banners: Vec<&str> =
self.stderr.lines().filter_map(|line| line.strip_prefix(BANNER_PREFIX)).collect();
verify_eq!(banners.len(), 1)
.with_failure_message(|| format!("stderr:\n{}", self.stderr))?;
Ok(banners[0])
}
#[track_caller]
fn expect_failure_detail<M>(&self, message_matcher: M) -> Result<()>
where
M: for<'a> Matcher<&'a str>,
{
let failure_detail = self.failure_detail.as_ref().or_fail().with_failure_message(|| {
format!("failure detail file not written; stderr:\n{}", self.stderr)
})?;
expect_true!(failure_detail.has_crash());
expect_eq!(failure_detail.crash().code(), crash::Code::CrashUnknown);
expect_true!(failure_detail.crash().causes().is_empty());
let message = failure_detail
.message()
.to_str()
.or_fail()
.with_failure_message(|| format!("non-UTF-8 message; stderr:\n{}", self.stderr))?;
let panic_message = message
.strip_prefix("Crashed: (Rust panic) ")
.or_fail()
.with_failure_message(|| format!("unexpected failure detail message: {message:?}"))?;
expect_that!(panic_message, message_matcher);
Ok(())
}
}
fn read_optional_bytes(path: &Path) -> io::Result<Option<Vec<u8>>> {
match fs::read(path) {
Ok(bytes) => Ok(Some(bytes)),
Err(err) if err.kind() == ErrorKind::NotFound => Ok(None),
Err(err) => Err(err),
}
}
fn read_optional_string(path: &Path) -> io::Result<Option<String>> {
match fs::read_to_string(path) {
Ok(contents) => Ok(Some(contents)),
Err(err) if err.kind() == ErrorKind::NotFound => Ok(None),
Err(err) => Err(err),
}
}
fn helper_binary_path() -> Result<PathBuf> {
let runfiles = Runfiles::create().or_fail()?;
let rlocation = env::var("PANIC_HANDLER_TEST_HELPER").or_fail()?;
rlocation!(runfiles, &rlocation).or_fail()
}
fn panic_message(payload: &str) -> impl for<'a> Matcher<&'a str> {
all!(
starts_with(format!("{payload} (at ")),
contains_regex(r"panic_handler_test_helper\.rs:[0-9]+:[0-9]+\)$"),
)
}
fn panic_message_regex(payload_regex: &str) -> impl for<'a> Matcher<&'a str> {
matches_regex(format!(r"{payload_regex} \(at .*panic_handler_test_helper\.rs:[0-9]+:[0-9]+\)"))
}
#[gtest]
fn panic_hook_writes_crash_files_and_exits(dir: &TestDir) -> Result<()> {
let run = dir.run_helper("panic")?;
expect_eq!(run.exit_code(), Some(37));
expect_that!(run.banner()?, panic_message("deliberate panic"));
expect_eq!(run.abrupt_exit.as_deref(), Some("37"));
run.expect_failure_detail(panic_message("deliberate panic"))?;
Ok(())
}
#[gtest]
fn long_panic_message_is_truncated_on_utf8_boundary(dir: &TestDir) -> Result<()> {
let mut banner_lengths = Vec::new();
// Each 'é' is 2 bytes, so 1500 of them is 3000 bytes (over the 2000-byte limit). Running with
// both a 0-byte and a 1-byte ASCII prefix on the same helper panic line ensures that one run
// lands on a character boundary (2000 bytes) and the other lands mid-character (1999 bytes)
// regardless of the location suffix length.
for prefix in ["", "x"] {
let _ = fs::remove_file(dir.failure_detail_file());
let run = dir.run_helper_with_args(
"long-message",
&[OsStr::new("é"), OsStr::new("1500"), OsStr::new(prefix)],
)?;
expect_eq!(run.exit_code(), Some(37));
let banner = run.banner()?;
expect_that!(banner, panic_message_regex(&format!(r"{prefix}é+\[truncated\]")));
run.expect_failure_detail(eq(banner))?;
banner_lengths.push(banner.len());
}
banner_lengths.sort();
expect_eq!(banner_lengths, vec![1999, 2000]);
Ok(())
}
#[gtest]
fn non_string_panic_payload_falls_back_to_unknown(dir: &TestDir) -> Result<()> {
let run = dir.run_helper("non-string")?;
expect_eq!(run.exit_code(), Some(37));
expect_that!(run.banner()?, panic_message("<unknown>"));
run.expect_failure_detail(panic_message("<unknown>"))?;
Ok(())
}
#[gtest]
fn installing_twice_crashes_the_process(dir: &TestDir) -> Result<()> {
let run = dir.run_helper("install-twice")?;
expect_eq!(run.exit_code(), Some(37));
expect_that!(run.stderr, contains_substring("PanicHandler::install called more than once"));
Ok(())
}
#[gtest]
fn panic_does_not_deadlock_when_another_thread_holds_stderr_lock(dir: &TestDir) -> Result<()> {
let run = dir.run_helper("stderr-locked")?;
expect_eq!(run.exit_code(), Some(37));
expect_that!(run.banner()?, panic_message("panic while stderr is locked"));
expect_eq!(run.abrupt_exit.as_deref(), Some("37"));
run.expect_failure_detail(panic_message("panic while stderr is locked"))?;
Ok(())
}
#[gtest]
fn concurrent_panics_report_only_one_panic(dir: &TestDir) -> Result<()> {
let run = dir.run_helper("concurrent-panics")?;
expect_eq!(run.exit_code(), Some(37));
let banner = run.banner()?;
expect_that!(banner, panic_message_regex(r"concurrent panic [0-9]+"));
expect_eq!(run.abrupt_exit.as_deref(), Some("37"));
run.expect_failure_detail(eq(banner))?;
Ok(())
}
#[gtest]
fn abrupt_exit_write_error_still_writes_failure_detail_and_exits(dir: &TestDir) -> Result<()> {
let run = dir.run_helper("missing-exit-dir")?;
expect_eq!(run.exit_code(), Some(37));
expect_that!(run.stderr, contains_substring("io error writing 37 to abrupt exit status file"));
expect_that!(run.banner()?, panic_message("panic with unwritable abrupt exit file"));
run.expect_failure_detail(panic_message("panic with unwritable abrupt exit file"))?;
Ok(())
}
#[gtest]
fn failure_detail_write_error_still_writes_abrupt_exit_and_exits(dir: &TestDir) -> Result<()> {
let run = dir.run_helper("missing-failure-detail-dir")?;
expect_eq!(run.exit_code(), Some(37));
expect_that!(run.stderr, contains_substring("io error writing failure detail to file"));
expect_that!(run.banner()?, panic_message("panic with unwritable failure detail file"));
expect_eq!(run.abrupt_exit.as_deref(), Some("37"));
Ok(())
}