Skip to main content

vtcode_commons/
process_exit.rs

1//! Emergency process termination that skips libc `exit` cleanup on Unix.
2//!
3//! [`std::process::exit`] delegates to libc's `exit`, which runs `atexit`
4//! handlers and thread-local destructors and tears down process-wide state Rust
5//! shares with libc and the kernel — notably the main thread's alternate signal
6//! stack. Calling it from a child thread races the still-running main thread:
7//! a destructor can be dropped twice, or the alt stack the main thread still
8//! relies on can be unmapped. VT Code's emergency exits run on a Tokio task
9//! (double Ctrl+C) and on the `signal_hook` thread (SIGTERM), so both are
10//! exposed to that class of bug.
11//!
12//! These paths have already restored the terminal and flushed their own output
13//! before exiting, so they do not need libc's cleanup. On Unix we use the raw
14//! `_exit` syscall to skip it entirely; other platforms keep
15//! [`std::process::exit`].
16
17/// Terminate the process immediately with `code`.
18///
19/// On Unix this is a raw `_exit` syscall: no Rust destructors, `atexit`
20/// handlers, or thread-local destructors run after it. Other platforms fall
21/// back to [`std::process::exit`] and follow its cleanup semantics. Callers
22/// must flush any buffered output they care about *before* calling it.
23#[cfg_attr(
24    unix,
25    expect(unsafe_code, reason = "raw _exit syscall skips all exit handlers by design")
26)]
27pub fn emergency_exit(code: i32) -> ! {
28    #[cfg(unix)]
29    {
30        // SAFETY: `_exit` consumes only a process status, cannot return, and
31        // touches no Rust-owned memory, so no invariant can be observed after
32        // this point. Skipping libc cleanup is the intended behavior.
33        unsafe { libc::_exit(code) }
34    }
35    #[cfg(not(unix))]
36    {
37        std::process::exit(code)
38    }
39}
40
41#[cfg(all(test, unix))]
42mod tests {
43    use super::*;
44    use std::path::PathBuf;
45    use std::process::Command;
46    use std::sync::OnceLock;
47
48    const CHILD_ENV: &str = "VTCODE_EMERGENCY_EXIT_TEST_CHILD";
49    const MARKER_ENV: &str = "VTCODE_EMERGENCY_EXIT_MARKER_PATH";
50    const TEST_NAME: &str = "process_exit::tests::emergency_exit_skips_atexit_handlers";
51
52    static MARKER_PATH: OnceLock<PathBuf> = OnceLock::new();
53
54    /// Runs only if libc `exit` invokes `atexit` handlers. Its absence proves
55    /// `emergency_exit` used `_exit`.
56    extern "C" fn write_marker_on_exit() {
57        let Some(path) = MARKER_PATH.get() else {
58            return;
59        };
60        // `fs::write` reports I/O failures as `Err` rather than unwinding, so
61        // this `extern "C"` callback stays non-unwinding during teardown.
62        std::fs::write(path, b"x").unwrap_or_default();
63    }
64
65    #[test]
66    #[expect(unsafe_code, reason = "test-only atexit registration to verify _exit semantics")]
67    fn emergency_exit_skips_atexit_handlers() {
68        let marker = std::env::temp_dir().join(format!("vtcode-emergency-exit-{}", std::process::id()));
69        std::fs::remove_file(&marker).unwrap_or_default();
70
71        if std::env::var_os(CHILD_ENV).is_some() {
72            let path = std::env::var_os(MARKER_ENV).expect("marker path in child");
73            MARKER_PATH.set(PathBuf::from(path)).unwrap_or_default();
74            // SAFETY: the handler is an `extern "C" fn` that cannot unwind, and
75            // `atexit` only registers it in this short-lived child process.
76            assert_eq!(unsafe { libc::atexit(write_marker_on_exit) }, 0);
77            emergency_exit(42);
78        }
79
80        let exe = std::env::current_exe().expect("test binary path");
81        let output = Command::new(exe)
82            .env(CHILD_ENV, "1")
83            .env(MARKER_ENV, &marker)
84            .arg("--exact")
85            .arg(TEST_NAME)
86            .output()
87            .expect("spawn child test process");
88
89        assert_eq!(output.status.code(), Some(42), "child stdout: {}", String::from_utf8_lossy(&output.stdout));
90        assert!(!marker.exists(), "atexit handler ran; emergency_exit must use _exit on Unix");
91        std::fs::remove_file(&marker).unwrap_or_default();
92    }
93}