Skip to main content

targeted_mutation/
interrupt.rs

1//! Cooperative SIGINT/SIGTERM handling so active test workers are stopped and reaped
2//! before `cargo tmt` exits.
3
4use std::fmt;
5use std::sync::atomic::{AtomicU8, AtomicUsize, Ordering};
6use std::time::Duration;
7
8/// Bounded grace period given to owned child process groups after SIGTERM on
9/// the first interrupt signal before escalating to SIGKILL.
10pub const INTERRUPT_GRACE: Duration = Duration::from_secs(2);
11
12const SIG_NONE: u8 = 0;
13const SIG_INT: u8 = 2;
14const SIG_TERM: u8 = 15;
15
16/// Error returned when execution stops due to SIGINT or SIGTERM.
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub struct Interrupted;
19
20impl fmt::Display for Interrupted {
21    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
22        write!(f, "interrupted by {}", signal_name())
23    }
24}
25
26impl std::error::Error for Interrupted {}
27
28static INTERRUPT_COUNT: AtomicUsize = AtomicUsize::new(0);
29static FIRST_SIGNAL: AtomicU8 = AtomicU8::new(SIG_NONE);
30
31/// Returns true if `err` (or any cause in its chain) is [`Interrupted`].
32pub fn is_interrupted_err(err: &anyhow::Error) -> bool {
33    err.chain().any(|cause| cause.is::<Interrupted>())
34}
35
36/// Returns true once at least one SIGINT or SIGTERM has been received.
37pub fn is_interrupted() -> bool {
38    INTERRUPT_COUNT.load(Ordering::Acquire) > 0
39}
40
41/// Returns true if a second (or subsequent) SIGINT/SIGTERM requested immediate SIGKILL
42/// escalation without waiting out the grace period.
43pub fn force_kill_requested() -> bool {
44    INTERRUPT_COUNT.load(Ordering::Acquire) >= 2
45}
46
47/// Name of the first interrupting signal received (`"SIGTERM"` or `"SIGINT"`).
48pub fn signal_name() -> &'static str {
49    match FIRST_SIGNAL.load(Ordering::Acquire) {
50        SIG_TERM => "SIGTERM",
51        _ => "SIGINT",
52    }
53}
54
55/// Process exit code corresponding to the first interrupting signal (`143` for
56/// SIGTERM, `130` for SIGINT).
57pub fn exit_code() -> u8 {
58    match FIRST_SIGNAL.load(Ordering::Acquire) {
59        SIG_TERM => 143,
60        _ => 130,
61    }
62}
63
64/// Returns `Err(Interrupted)` if a SIGINT or SIGTERM has been received.
65pub fn check() -> anyhow::Result<()> {
66    if is_interrupted() {
67        Err(Interrupted.into())
68    } else {
69        Ok(())
70    }
71}
72
73#[cfg(unix)]
74mod unix {
75    use std::ffi::c_int;
76    use std::os::fd::RawFd;
77    use std::sync::Once;
78    use std::sync::atomic::{AtomicI32, Ordering};
79
80    use super::{FIRST_SIGNAL, INTERRUPT_COUNT, SIG_INT, SIG_TERM};
81
82    const SIGINT: c_int = 2;
83    const SIGTERM: c_int = 15;
84    const F_SETFD: c_int = 2;
85    const FD_CLOEXEC: c_int = 1;
86    const F_GETFL: c_int = 3;
87    const F_SETFL: c_int = 4;
88
89    #[cfg(any(
90        target_os = "macos",
91        target_os = "ios",
92        target_os = "freebsd",
93        target_os = "netbsd",
94        target_os = "openbsd",
95        target_os = "dragonfly"
96    ))]
97    const O_NONBLOCK: c_int = 0x0004;
98
99    #[cfg(all(
100        target_os = "linux",
101        any(
102            target_arch = "x86_64",
103            target_arch = "x86",
104            target_arch = "aarch64",
105            target_arch = "riscv64"
106        )
107    ))]
108    const O_NONBLOCK: c_int = 0o4000;
109
110    #[cfg(not(any(
111        target_os = "macos",
112        target_os = "ios",
113        target_os = "freebsd",
114        target_os = "netbsd",
115        target_os = "openbsd",
116        target_os = "dragonfly",
117        all(
118            target_os = "linux",
119            any(
120                target_arch = "x86_64",
121                target_arch = "x86",
122                target_arch = "aarch64",
123                target_arch = "riscv64"
124            )
125        )
126    )))]
127    const O_NONBLOCK: c_int = 0;
128
129    static INSTALL: Once = Once::new();
130    static WAKE_READ_FD: AtomicI32 = AtomicI32::new(-1);
131    static WAKE_WRITE_FD: AtomicI32 = AtomicI32::new(-1);
132
133    unsafe extern "C" {
134        fn pipe(fds: *mut c_int) -> c_int;
135        fn close(fd: c_int) -> c_int;
136        fn fcntl(fd: c_int, cmd: c_int, ...) -> c_int;
137        fn write(fd: c_int, buf: *const std::ffi::c_void, count: usize) -> isize;
138        fn signal(sig: c_int, handler: extern "C" fn(c_int)) -> usize;
139        fn siginterrupt(sig: c_int, flag: c_int) -> c_int;
140    }
141
142    extern "C" fn handle_signal(sig: c_int) {
143        let code = if sig == SIGTERM { SIG_TERM } else { SIG_INT };
144        let _ = FIRST_SIGNAL.compare_exchange(0, code, Ordering::SeqCst, Ordering::Acquire);
145        INTERRUPT_COUNT.fetch_add(1, Ordering::SeqCst);
146        let fd = WAKE_WRITE_FD.load(Ordering::Acquire);
147        if fd >= 0 {
148            let byte: u8 = 1;
149            // SAFETY: `write(2)` on a non-blocking pipe fd with a 1-byte stack
150            // buffer is async-signal-safe per POSIX.
151            let _ = unsafe { write(fd, (&byte as *const u8).cast(), 1) };
152        }
153    }
154
155    pub(super) fn install() {
156        INSTALL.call_once(|| {
157            if O_NONBLOCK != 0 {
158                let mut fds = [-1 as c_int; 2];
159                // SAFETY: `fds` is a valid 2-element array for `pipe(2)`.
160                if unsafe { pipe(fds.as_mut_ptr()) } == 0 {
161                    let mut ok = true;
162                    for &fd in &fds {
163                        // SAFETY: `fd` is a valid open pipe descriptor.
164                        if unsafe { fcntl(fd, F_SETFD, FD_CLOEXEC) } < 0 {
165                            ok = false;
166                        }
167                        let flags = unsafe { fcntl(fd, F_GETFL) };
168                        if flags < 0 || unsafe { fcntl(fd, F_SETFL, flags | O_NONBLOCK) } < 0 {
169                            ok = false;
170                        }
171                    }
172                    if ok {
173                        WAKE_READ_FD.store(fds[0], Ordering::Release);
174                        WAKE_WRITE_FD.store(fds[1], Ordering::Release);
175                    } else {
176                        unsafe {
177                            let _ = close(fds[0]);
178                            let _ = close(fds[1]);
179                        }
180                    }
181                }
182            }
183            // SAFETY: `handle_signal` only performs async-signal-safe operations
184            // (atomic RMW and non-blocking 1-byte `write(2)`).
185            unsafe {
186                let _ = signal(SIGINT, handle_signal);
187                let _ = siginterrupt(SIGINT, 1);
188                let _ = signal(SIGTERM, handle_signal);
189                let _ = siginterrupt(SIGTERM, 1);
190            }
191        });
192    }
193
194    pub(super) fn wake_read_fd() -> Option<RawFd> {
195        let fd = WAKE_READ_FD.load(Ordering::Acquire);
196        (fd >= 0).then_some(fd)
197    }
198}
199
200/// Installs the process-wide SIGINT handler. Safe to call multiple times.
201pub fn install() {
202    #[cfg(unix)]
203    unix::install();
204}
205
206/// Returns the non-blocking self-pipe read descriptor woken on SIGINT, if installed.
207#[cfg(unix)]
208pub(crate) fn wake_read_fd() -> Option<std::os::fd::RawFd> {
209    unix::wake_read_fd()
210}
211
212#[cfg(test)]
213pub(crate) mod test_support {
214    use std::sync::{Mutex, MutexGuard};
215
216    use super::*;
217
218    static LOCK: Mutex<()> = Mutex::new(());
219
220    pub(crate) struct Guard {
221        _guard: MutexGuard<'static, ()>,
222    }
223
224    impl Guard {
225        pub(crate) fn set(count: usize) -> Self {
226            let guard = LOCK.lock().unwrap_or_else(|e| e.into_inner());
227            FIRST_SIGNAL.store(SIG_NONE, Ordering::SeqCst);
228            INTERRUPT_COUNT.store(count, Ordering::SeqCst);
229            Self { _guard: guard }
230        }
231    }
232
233    impl Drop for Guard {
234        fn drop(&mut self) {
235            INTERRUPT_COUNT.store(0, Ordering::SeqCst);
236            FIRST_SIGNAL.store(SIG_NONE, Ordering::SeqCst);
237        }
238    }
239}
240
241#[cfg(test)]
242mod tests {
243    use super::*;
244
245    #[test]
246    fn interrupt_flags_and_error_detection_follow_signal_count() {
247        let _guard = test_support::Guard::set(0);
248        assert!(!is_interrupted());
249        assert!(!force_kill_requested());
250        assert_eq!(signal_name(), "SIGINT");
251        assert_eq!(exit_code(), 130);
252        assert!(check().is_ok());
253
254        INTERRUPT_COUNT.store(1, Ordering::SeqCst);
255        assert!(is_interrupted());
256        assert!(!force_kill_requested());
257        let err = check().unwrap_err();
258        assert!(is_interrupted_err(&err));
259        assert_eq!(err.to_string(), "interrupted by SIGINT");
260        let wrapped = err.context("running baseline");
261        assert!(is_interrupted_err(&wrapped));
262        assert!(!is_interrupted_err(&anyhow::anyhow!("other error")));
263
264        INTERRUPT_COUNT.store(2, Ordering::SeqCst);
265        assert!(is_interrupted());
266        assert!(force_kill_requested());
267    }
268
269    #[test]
270    fn sigterm_records_exit_code_143_and_preserves_first_signal() {
271        let _guard = test_support::Guard::set(0);
272        let _ = FIRST_SIGNAL.compare_exchange(0, SIG_TERM, Ordering::SeqCst, Ordering::Acquire);
273        INTERRUPT_COUNT.fetch_add(1, Ordering::SeqCst);
274        assert!(is_interrupted());
275        assert!(!force_kill_requested());
276        assert_eq!(signal_name(), "SIGTERM");
277        assert_eq!(exit_code(), 143);
278        assert_eq!(check().unwrap_err().to_string(), "interrupted by SIGTERM");
279
280        // A subsequent SIGINT escalates to force-kill without overwriting the first signal.
281        let _ = FIRST_SIGNAL.compare_exchange(0, SIG_INT, Ordering::SeqCst, Ordering::Acquire);
282        INTERRUPT_COUNT.fetch_add(1, Ordering::SeqCst);
283        assert!(force_kill_requested());
284        assert_eq!(signal_name(), "SIGTERM");
285        assert_eq!(exit_code(), 143);
286    }
287}