targeted_mutation/
interrupt.rs1use std::fmt;
5use std::sync::atomic::{AtomicU8, AtomicUsize, Ordering};
6use std::time::Duration;
7
8pub 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#[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
31pub fn is_interrupted_err(err: &anyhow::Error) -> bool {
33 err.chain().any(|cause| cause.is::<Interrupted>())
34}
35
36pub fn is_interrupted() -> bool {
38 INTERRUPT_COUNT.load(Ordering::Acquire) > 0
39}
40
41pub fn force_kill_requested() -> bool {
44 INTERRUPT_COUNT.load(Ordering::Acquire) >= 2
45}
46
47pub fn signal_name() -> &'static str {
49 match FIRST_SIGNAL.load(Ordering::Acquire) {
50 SIG_TERM => "SIGTERM",
51 _ => "SIGINT",
52 }
53}
54
55pub fn exit_code() -> u8 {
58 match FIRST_SIGNAL.load(Ordering::Acquire) {
59 SIG_TERM => 143,
60 _ => 130,
61 }
62}
63
64pub 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 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 if unsafe { pipe(fds.as_mut_ptr()) } == 0 {
161 let mut ok = true;
162 for &fd in &fds {
163 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 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
200pub fn install() {
202 #[cfg(unix)]
203 unix::install();
204}
205
206#[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 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}