Skip to main content

reverie_process/
exit_status.rs

1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 * All rights reserved.
4 *
5 * This source code is licensed under the BSD-style license found in the
6 * LICENSE file in the root directory of this source tree.
7 */
8
9use std::os::unix::process::ExitStatusExt;
10
11use nix::sys::signal;
12use nix::sys::signal::SigHandler;
13use nix::sys::signal::SigSet;
14use nix::sys::signal::SigmaskHow;
15use nix::sys::signal::Signal;
16
17/// Describes the result of a process after it has exited.
18///
19/// This is similar to `std::process::ExitStatus`, but is easier to match
20/// against and provides additional functionality like `raise_or_exit` that
21/// helps with propagating an exit status.
22#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
23pub enum ExitStatus {
24    /// Program exited with an exit code.
25    Exited(i32),
26    /// Program killed by signal, with or without a coredump.
27    Signaled(Signal, bool),
28    /// Program killed by a signal that nix's [`Signal`] cannot name, a
29    /// realtime signal (32 to 64), with or without a coredump. The number is
30    /// the raw signal number (<https://github.com/rrnewton/reverie/issues/997>).
31    /// It is only for numbers nix cannot name: build a status from a raw
32    /// number with [`ExitStatus::signaled`], which picks this or
33    /// [`ExitStatus::Signaled`].
34    SignaledRaw(i32, bool),
35}
36
37impl ExitStatus {
38    /// A successful exit status.
39    pub const SUCCESS: Self = ExitStatus::Exited(0);
40
41    /// Construct an `ExitStatus` from a raw exit code.
42    pub fn from_raw(code: i32) -> Self {
43        if libc::WIFEXITED(code) {
44            ExitStatus::Exited(libc::WEXITSTATUS(code))
45        } else {
46            Self::signaled(libc::WTERMSIG(code), libc::WCOREDUMP(code))
47        }
48    }
49
50    /// The status of a process killed by the raw signal `signal`:
51    /// [`ExitStatus::Signaled`] when nix names it, else
52    /// [`ExitStatus::SignaledRaw`].
53    pub fn signaled(signal: i32, coredump: bool) -> Self {
54        match Signal::try_from(signal) {
55            Ok(signal) => ExitStatus::Signaled(signal, coredump),
56            Err(_) => ExitStatus::SignaledRaw(signal, coredump),
57        }
58    }
59
60    /// Converts the exit status into a raw number.
61    pub fn into_raw(self) -> i32 {
62        match self {
63            ExitStatus::Exited(code) => code << 8,
64            ExitStatus::Signaled(sig, coredump) => {
65                if coredump {
66                    (sig as i32 | 0x80) & 0xff
67                } else {
68                    sig as i32 & 0x7f
69                }
70            }
71            ExitStatus::SignaledRaw(sig, coredump) => {
72                if coredump {
73                    (sig | 0x80) & 0xff
74                } else {
75                    sig & 0x7f
76                }
77            }
78        }
79    }
80
81    /// If the process was terminated by a signal, returns that signal.
82    pub fn signal(&self) -> Option<i32> {
83        match self {
84            ExitStatus::Exited(_) => None,
85            ExitStatus::Signaled(sig, _) => Some(*sig as i32 & 0x7f),
86            ExitStatus::SignaledRaw(sig, _) => Some(*sig & 0x7f),
87        }
88    }
89
90    /// Was termination successful? Signal termination is not considered a
91    /// success, and success is defined as a zero exit status.
92    pub fn success(&self) -> bool {
93        self == &ExitStatus::Exited(0)
94    }
95
96    /// Returns the exit code of the process, if any. If the process was
97    /// terminated by a signal, this will return `None`.
98    pub fn code(&self) -> Option<i32> {
99        if let ExitStatus::Exited(code) = *self {
100            Some(code)
101        } else {
102            None
103        }
104    }
105
106    /// Propagate the exit status such that the current process exits in the same
107    /// way that the child process exited.
108    pub fn raise_or_exit(self) -> ! {
109        match self {
110            ExitStatus::Signaled(signal, core_dump) => {
111                if core_dump {
112                    // Prevent the current process from producing a core dump as
113                    // well when the signal is propagated.
114                    let limit = libc::rlimit {
115                        rlim_cur: 0,
116                        rlim_max: 0,
117                    };
118                    unsafe { libc::setrlimit(libc::RLIMIT_CORE, &limit) };
119                }
120
121                // Raise the same signal, which may or may not be fatal.
122                let _ = unsafe { signal::signal(signal, SigHandler::SigDfl) };
123                let _ = signal::raise(signal);
124
125                // Unblock the signal.
126                let mut mask = SigSet::empty();
127                mask.add(signal);
128                let _ = signal::sigprocmask(SigmaskHow::SIG_UNBLOCK, Some(&mask), None);
129
130                // Incase the signal is not fatal:
131                std::process::exit(signal as i32 + 128);
132            }
133            ExitStatus::SignaledRaw(signal, core_dump) => {
134                if core_dump {
135                    let limit = libc::rlimit {
136                        rlim_cur: 0,
137                        rlim_max: 0,
138                    };
139                    unsafe { libc::setrlimit(libc::RLIMIT_CORE, &limit) };
140                }
141                // As above, with the raw number nix cannot name, through raw
142                // syscalls: glibc's signal(), raise() and sigprocmask() refuse
143                // 32 and 33, which it reserves for itself. The kernel's
144                // sigaction is handler, flags, restorer and a 64-bit mask.
145                let default: [u64; 4] = [libc::SIG_DFL as u64, 0, 0, 0];
146                // A number outside 1 to 64 names no signal: none is raised,
147                // and the process exits below.
148                let unblock: u64 = u32::try_from(signal - 1)
149                    .ok()
150                    .and_then(|bit| 1u64.checked_shl(bit))
151                    .unwrap_or(0);
152                unsafe {
153                    libc::syscall(
154                        libc::SYS_rt_sigaction,
155                        signal,
156                        default.as_ptr(),
157                        std::ptr::null_mut::<u64>(),
158                        8,
159                    );
160                    libc::syscall(
161                        libc::SYS_tgkill,
162                        libc::getpid(),
163                        libc::syscall(libc::SYS_gettid),
164                        signal,
165                    );
166                    libc::syscall(
167                        libc::SYS_rt_sigprocmask,
168                        libc::SIG_UNBLOCK,
169                        &unblock as *const u64,
170                        std::ptr::null_mut::<u64>(),
171                        8,
172                    );
173                }
174                std::process::exit(signal + 128);
175            }
176            ExitStatus::Exited(code) => std::process::exit(code),
177        }
178    }
179}
180
181impl From<ExitStatus> for std::process::ExitStatus {
182    fn from(status: ExitStatus) -> Self {
183        Self::from_raw(status.into_raw())
184    }
185}
186
187impl From<std::process::ExitStatus> for ExitStatus {
188    fn from(status: std::process::ExitStatus) -> Self {
189        if let Some(sig) = status.signal() {
190            ExitStatus::signaled(sig, status.core_dumped())
191        } else {
192            ExitStatus::Exited(status.code().unwrap_or(255))
193        }
194    }
195}
196
197impl serde::Serialize for ExitStatus {
198    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
199    where
200        S: serde::ser::Serializer,
201    {
202        serializer.serialize_i32(self.into_raw())
203    }
204}
205
206impl<'de> serde::Deserialize<'de> for ExitStatus {
207    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
208    where
209        D: serde::de::Deserializer<'de>,
210    {
211        let value = i32::deserialize(deserializer)?;
212        Ok(ExitStatus::from_raw(value))
213    }
214}
215
216// `sanitized` is a Meta-internal cfg (set for sanitizer builds to skip these
217// fork-based tests); it is never set in the open-source build. It is declared
218// via `check-cfg` in this crate's Cargo.toml so it is a known cfg name.
219#[cfg(all(test, not(sanitized)))]
220mod tests_non_sanitized {
221    use nix::sys::signal;
222    use nix::sys::signal::Signal;
223    use nix::sys::wait::WaitStatus;
224    use nix::sys::wait::waitpid;
225    use nix::unistd::ForkResult;
226    use nix::unistd::fork;
227
228    use super::*;
229
230    // Runs a closure in a forked process and reports the exit status.
231    fn run_forked<F>(f: F) -> nix::Result<ExitStatus>
232    where
233        F: FnOnce() -> nix::Result<()>,
234    {
235        match unsafe { fork() }? {
236            ForkResult::Parent { child, .. } => {
237                // Simply wait for the child to exit.
238                match waitpid(child, None)? {
239                    WaitStatus::Exited(_, code) => Ok(ExitStatus::Exited(code)),
240                    WaitStatus::Signaled(_, sig, coredump) => {
241                        Ok(ExitStatus::Signaled(sig, coredump))
242                    }
243                    wait_status => unreachable!("Got unexpected wait status: {:?}", wait_status),
244                }
245            }
246            ForkResult::Child => {
247                // Suppress core dumps for testing purposes.
248                let limit = libc::rlimit {
249                    rlim_cur: 0,
250                    rlim_max: 0,
251                };
252                unsafe {
253                    // restore some sighandlers to default
254                    for &sig in &[libc::SIGALRM, libc::SIGINT, libc::SIGVTALRM] {
255                        libc::signal(sig, libc::SIG_DFL);
256                    }
257                    // disable coredump
258                    libc::setrlimit(libc::RLIMIT_CORE, &limit)
259                };
260
261                // Run the child.
262                let code = match f() {
263                    Ok(()) => 0,
264                    Err(err) => {
265                        eprintln!("{}", err);
266                        1
267                    }
268                };
269
270                // The closure should have called `exit` by this point, but just
271                // in case it didn't, call it ourselves.
272                //
273                // Note: We also can't use the normal exit function here because we
274                // don't want to call atexit handlers since `execve` was never
275                // called.
276                unsafe { ::libc::_exit(code) };
277            }
278        }
279    }
280
281    #[test]
282    fn normal_exit() {
283        if crate::test_runs_in_own_process() {
284            return;
285        }
286        assert_eq!(
287            run_forked(|| { unsafe { libc::_exit(0) } }),
288            Ok(ExitStatus::Exited(0))
289        );
290
291        assert_eq!(
292            run_forked(|| { unsafe { libc::_exit(42) } }),
293            Ok(ExitStatus::Exited(42))
294        );
295
296        // Thread exit
297        assert_eq!(
298            run_forked(|| {
299                unsafe { libc::syscall(libc::SYS_exit, 42) };
300                unreachable!();
301            }),
302            Ok(ExitStatus::Exited(42))
303        );
304
305        // exit_group. Should be identical to `libc::_exit`.
306        assert_eq!(
307            run_forked(|| {
308                unsafe { libc::syscall(libc::SYS_exit_group, 42) };
309                unreachable!();
310            }),
311            Ok(ExitStatus::Exited(42))
312        );
313    }
314
315    #[test]
316    fn exit_by_signal() {
317        if crate::test_runs_in_own_process() {
318            return;
319        }
320        assert_eq!(
321            run_forked(|| {
322                signal::raise(Signal::SIGALRM)?;
323                unreachable!();
324            }),
325            Ok(ExitStatus::Signaled(Signal::SIGALRM, false))
326        );
327
328        assert_eq!(
329            run_forked(|| {
330                signal::raise(Signal::SIGILL)?;
331                unreachable!();
332            }),
333            Ok(ExitStatus::Signaled(Signal::SIGILL, true))
334        );
335    }
336
337    // Like `run_forked`, decoding the raw wait status with
338    // `ExitStatus::from_raw`, which keeps a realtime signal nix's
339    // `WaitStatus` cannot hold.
340    fn run_forked_raw<F>(f: F) -> ExitStatus
341    where
342        F: FnOnce(),
343    {
344        match unsafe { fork() }.unwrap() {
345            ForkResult::Parent { child, .. } => {
346                let mut status = 0;
347                assert_eq!(
348                    unsafe { libc::waitpid(child.as_raw(), &mut status, 0) },
349                    child.as_raw()
350                );
351                ExitStatus::from_raw(status)
352            }
353            ForkResult::Child => {
354                let limit = libc::rlimit {
355                    rlim_cur: 0,
356                    rlim_max: 0,
357                };
358                unsafe { libc::setrlimit(libc::RLIMIT_CORE, &limit) };
359                f();
360                unsafe { ::libc::_exit(0) };
361            }
362        }
363    }
364
365    /// A raw signal status round-trips through `into_raw` and `from_raw`,
366    /// and `signaled` picks `SignaledRaw` only for a number nix cannot name.
367    /// Converting to std's `ExitStatus` and back keeps every status,
368    /// including whether a core was dumped, for named signals and for
369    /// realtime ones, 32 and 33 among them.
370    #[test]
371    fn statuses_round_trip_through_std() {
372        let statuses = [
373            ExitStatus::Exited(0),
374            ExitStatus::Exited(42),
375            ExitStatus::Signaled(Signal::SIGKILL, false),
376            ExitStatus::Signaled(Signal::SIGILL, true),
377            ExitStatus::SignaledRaw(32, false),
378            ExitStatus::SignaledRaw(33, false),
379            ExitStatus::SignaledRaw(33, true),
380            ExitStatus::SignaledRaw(64, false),
381            ExitStatus::SignaledRaw(64, true),
382        ];
383        for status in statuses {
384            let std_status = std::process::ExitStatus::from(status);
385            assert_eq!(ExitStatus::from(std_status), status, "{status:?}");
386            assert_eq!(
387                std_status.core_dumped(),
388                status.into_raw() & 0x80 != 0 && status.code().is_none()
389            );
390        }
391    }
392
393    #[test]
394    fn raw_signal_statuses_round_trip() {
395        for (signal, coredump) in [(34, false), (64, false), (40, true)] {
396            let status = ExitStatus::SignaledRaw(signal, coredump);
397            assert_eq!(ExitStatus::from_raw(status.into_raw()), status);
398            assert_eq!(ExitStatus::signaled(signal, coredump), status);
399        }
400        assert_eq!(
401            ExitStatus::signaled(libc::SIGKILL, false),
402            ExitStatus::Signaled(Signal::SIGKILL, false)
403        );
404    }
405
406    /// A process killed by a realtime signal, which nix's `Signal` cannot
407    /// name, is `SignaledRaw` with its number, and `raise_or_exit`
408    /// propagates it (<https://github.com/rrnewton/reverie/issues/997>),
409    /// including 32 and 33, which glibc reserves and its `raise()` refuses.
410    #[test]
411    fn exit_by_a_realtime_signal() {
412        if crate::test_runs_in_own_process() {
413            return;
414        }
415        for signal in [32, 33, libc::SIGRTMIN() + 1] {
416            // glibc handles 32 and 33 itself; the child sets the default
417            // action and unblocks the signal with raw syscalls first.
418            let killed = run_forked_raw(|| unsafe {
419                let default: [u64; 4] = [libc::SIG_DFL as u64, 0, 0, 0];
420                let unblock: u64 = 1 << (signal - 1);
421                libc::syscall(
422                    libc::SYS_rt_sigaction,
423                    signal,
424                    default.as_ptr(),
425                    std::ptr::null_mut::<u64>(),
426                    8,
427                );
428                libc::syscall(
429                    libc::SYS_rt_sigprocmask,
430                    libc::SIG_UNBLOCK,
431                    &unblock as *const u64,
432                    std::ptr::null_mut::<u64>(),
433                    8,
434                );
435                libc::syscall(
436                    libc::SYS_tgkill,
437                    libc::getpid(),
438                    libc::syscall(libc::SYS_gettid),
439                    signal,
440                );
441            });
442            assert_eq!(killed, ExitStatus::SignaledRaw(signal, false));
443            assert_eq!(killed.signal(), Some(signal));
444            assert_eq!(killed.code(), None);
445            assert_eq!(
446                run_forked_raw(|| ExitStatus::SignaledRaw(signal, false).raise_or_exit()),
447                ExitStatus::SignaledRaw(signal, false),
448                "raise_or_exit of signal {signal}"
449            );
450            // With the signal blocked first, raise_or_exit must unblock it.
451            assert_eq!(
452                run_forked_raw(|| {
453                    let block: u64 = 1 << (signal - 1);
454                    unsafe {
455                        libc::syscall(
456                            libc::SYS_rt_sigprocmask,
457                            libc::SIG_BLOCK,
458                            &block as *const u64,
459                            std::ptr::null_mut::<u64>(),
460                            8,
461                        )
462                    };
463                    ExitStatus::SignaledRaw(signal, false).raise_or_exit()
464                }),
465                ExitStatus::SignaledRaw(signal, false),
466                "raise_or_exit of blocked signal {signal}"
467            );
468        }
469    }
470
471    #[test]
472    fn propagate_exit() {
473        if crate::test_runs_in_own_process() {
474            return;
475        }
476        // NOTE: These tests fail under a sanitized build. ASAN leak detection
477        // must be disabled for this to run correctly. To disable ASAN leak
478        // detection, set the `ASAN_OPTIONS=detect_leaks=0` environment variable
479        // *before* the test starts up. (This is currently done in the TARGETS
480        // file.) Alternatively, we *could* bypass the atexit handler that ASAN
481        // sets up by calling `libc::_exit`, but that may have unintended
482        // consequences for real code.
483        assert_eq!(
484            run_forked(|| { ExitStatus::Exited(0).raise_or_exit() }),
485            Ok(ExitStatus::Exited(0))
486        );
487        assert_eq!(
488            run_forked(|| { ExitStatus::Exited(42).raise_or_exit() }),
489            Ok(ExitStatus::Exited(42))
490        );
491    }
492
493    #[test]
494    fn propagate_signal() {
495        if crate::test_runs_in_own_process() {
496            return;
497        }
498        assert_eq!(
499            run_forked(|| { ExitStatus::Signaled(Signal::SIGILL, true).raise_or_exit() }),
500            Ok(ExitStatus::Signaled(Signal::SIGILL, true))
501        );
502        assert_eq!(
503            run_forked(|| { ExitStatus::Signaled(Signal::SIGALRM, false).raise_or_exit() }),
504            Ok(ExitStatus::Signaled(Signal::SIGALRM, false))
505        );
506    }
507}
508
509#[cfg(test)]
510mod tests {
511    use super::*;
512
513    #[test]
514    fn exit_code_into_raw() {
515        assert_eq!(ExitStatus::Exited(1).into_raw(), 0x1 << 8);
516        assert_eq!(
517            ExitStatus::Signaled(Signal::SIGINT, false).into_raw(),
518            Signal::SIGINT as i32
519        );
520        assert_eq!(
521            ExitStatus::Signaled(Signal::SIGILL, true).into_raw(),
522            0x80 | Signal::SIGILL as i32
523        );
524        assert_ne!(
525            ExitStatus::Exited(2).into_raw(),
526            ExitStatus::Signaled(Signal::SIGINT, false).into_raw()
527        );
528    }
529
530    #[test]
531    fn exit_status_from_raw() {
532        assert_eq!(ExitStatus::from_raw(0x100).code(), Some(1));
533        assert_eq!(ExitStatus::from_raw(0x100).signal(), None);
534        assert_eq!(ExitStatus::from_raw(0x84).code(), None);
535        assert_eq!(ExitStatus::from_raw(0x84).signal(), Some(4));
536    }
537}