Skip to main content

uucore/mods/
panic.rs

1// This file is part of the uutils coreutils package.
2//
3// For the full copyright and license information, please view the LICENSE
4// file that was distributed with this source code.
5//! Custom panic hooks that allow silencing certain types of errors.
6//!
7//! Use the [`mute_sigpipe_panic`] function to silence panics caused by
8//! broken pipe errors. This can happen when a process is still
9//! producing data when the consuming process terminates and closes the
10//! pipe. For example,
11//!
12//! ```sh
13//! $ seq inf | head -n 1
14//! ```
15//!
16use std::panic::{self, PanicHookInfo};
17
18/// Decide whether a panic was caused by a broken pipe (SIGPIPE) error.
19fn is_broken_pipe(info: &PanicHookInfo) -> bool {
20    if let Some(res) = info.payload().downcast_ref::<String>() {
21        if res.contains("BrokenPipe") || res.contains("Broken pipe") {
22            return true;
23        }
24    }
25    false
26}
27
28/// Terminate without error on panics that occur due to broken pipe errors.
29///
30/// For background discussions on `SIGPIPE` handling, see
31///
32/// * `<https://github.com/uutils/coreutils/issues/374>`
33/// * `<https://github.com/uutils/coreutils/pull/1106>`
34/// * `<https://github.com/rust-lang/rust/issues/62569>`
35/// * `<https://github.com/BurntSushi/ripgrep/issues/200>`
36/// * `<https://github.com/crev-dev/cargo-crev/issues/287>`
37///
38pub fn mute_sigpipe_panic() {
39    let hook = panic::take_hook();
40    panic::set_hook(Box::new(move |info| {
41        if !is_broken_pipe(info) {
42            hook(info);
43        }
44    }));
45}
46
47/// Preserve inherited SIGPIPE settings from parent process.
48///
49/// Rust unconditionally sets SIGPIPE to SIG_IGN on startup. This function
50/// checks if the parent process (e.g., `env --default-signal=PIPE`) intended
51/// for SIGPIPE to be set to default by checking the RUST_SIGPIPE environment
52/// variable. If set to "default", it restores SIGPIPE to SIG_DFL.
53#[cfg(unix)]
54pub fn preserve_inherited_sigpipe() {
55    use nix::libc;
56
57    // Check if parent specified that SIGPIPE should be default
58    if let Ok(val) = std::env::var("RUST_SIGPIPE") {
59        if val == "default" {
60            unsafe {
61                libc::signal(libc::SIGPIPE, libc::SIG_DFL);
62                // Remove the environment variable so child processes don't inherit it incorrectly
63                std::env::remove_var("RUST_SIGPIPE");
64            }
65        }
66    }
67}
68
69#[cfg(not(unix))]
70pub fn preserve_inherited_sigpipe() {
71    // No-op on non-Unix platforms
72}