Skip to main content

targeted_mutation/
interrupt.rs

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