返回 CodeWhale
fatal_signal_guard.rs
根目录 / crates / tui / src / tui / ui / fatal_signal_guard.rs
1 //! Async-signal-safe terminal restore for abort-class process deaths.
2 //!
3 //! #5424: a v0.9.7 user's TUI exited by itself mid-turn with none of the
4 //! ordinary cleanup running — no panic hook (so no crash dump), no
5 //! `TerminalCleanupGuard`, no tokio signal task — and the shell was left with
6 //! mouse capture still enabled, leaking SGR mouse-motion bytes into zsh.
7 //! Whatever the fatal cause (a stack overflow aborts after Rust prints its
8 //! message; an allocation failure aborts; `catch_unwind` cannot see either),
9 //! the *terminal poisoning* is fixable from a classic signal handler: one
10 //! fixed byte string written with `write(2)`.
11 //!
12 //! Scope is deliberately narrow:
13 //!
14 //! - **SIGABRT, SIGBUS, SIGILL, SIGFPE** are intercepted. **SIGSEGV is not**:
15 //! the Rust runtime's stack-overflow diagnostic runs on SIGSEGV, and this
16 //! handler must not bury it. Rust's overflow path itself funnels into
17 //! `abort()`, i.e. SIGABRT, so stack overflows still get the restore.
18 //! - After the restore bytes are written (best-effort, both stdout and the
19 //! crash marker file), the disposition is reset to `SIG_DFL` and the signal
20 //! is re-raised, so the process keeps dying with the same signal — wait
21 //! status, core-dump behavior, and `$?` are unchanged.
22 //! - Installed only when stdout is a TTY, so piped/embedded surfaces never
23 //! get escape bytes injected into their output.
24 //!
25 //! The marker file (`.codewhale/crashes/last-fatal-signal.log`, appended,
26 //! never truncated) records which signal fired. The kernel's mtime on the
27 //! file timestamps the crash without any time formatting in the handler. On
28 //! the next real-world #5424-class report, that one line distinguishes an
29 //! abort (stack overflow / alloc failure / double panic) from an OOM-kill
30 //! (SIGKILL — uninterceptable, no marker) before any logs arrive.
31
32 /// The restore byte string, written in a single `write(2)`.
33 ///
34 /// Mirrors `emergency_restore_terminal`'s mode teardown, minus every query
35 /// (a dead process cannot read replies). Raw mode is not in these bytes:
36 /// crossterm's termios state sits behind a lock the dying thread may hold, so
37 /// the handler restores the job-control guard's lock-free cooked snapshot with
38 /// `tcsetattr` instead (U03-02). When that guard is disabled or its snapshot
39 /// failed there is no snapshot, and raw mode is left for `stty sane`. Modes left
40 /// over that a shell does not self-heal are the ones that poison input:
41 /// mouse capture and the kitty keyboard stack get the full reset.
42 #[cfg(unix)]
43 pub(crate) const FATAL_RESTORE_BYTES: &[u8] = concat!(
44 "\x1b[?2026l", // close any open DEC 2026 synchronized-update batch
45 "\x1b[<1u", // pop one kitty keyboard-enhancement stack level
46 "\x1b[?1007l", // alternate scroll off
47 "\x1b[?1004l", // focus reporting off
48 "\x1b[?2004l", // bracketed paste off
49 "\x1b[?1006l", // SGR mouse encoding off
50 "\x1b[?1002l", // button-event mouse tracking off
51 "\x1b[?1003l", // any-motion mouse tracking off
52 "\x1b[?1000l", // normal mouse tracking off
53 "\x1b[?1049l", // leave the alternate screen
54 "\x1b[?25h", // show the cursor
55 )
56 .as_bytes();
57
58 /// Absolute path of the append-only fatal-signal marker, fixed at install
59 /// time (before any worker thread exists, after which it is never written
60 /// again — a plain load from the signal handler).
61 #[cfg(unix)]
62 static MARKER_PATH: std::sync::OnceLock<Box<[u8; 4096]>> = std::sync::OnceLock::new();
63 #[cfg(unix)]
64 static MARKER_LEN: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
65
66 /// Install the fatal-signal restore guard. POSIX only; no-op elsewhere.
67 ///
68 /// Call once, early, on the main thread before worker threads are spawned
69 /// (the install writes the `OnceLock`s; after that they are read-only).
70 pub(crate) fn install_fatal_signal_guard() {
71 #[cfg(unix)]
72 {
73 // Piped/embedded surfaces must never receive escape bytes.
74 // SAFETY: isatty(2) dereferences no pointers.
75 if unsafe { libc::isatty(libc::STDOUT_FILENO) } == 0 {
76 tracing::debug!("Fatal-signal terminal guard skipped: stdout is not a TTY");
77 return;
78 }
79 if let Ok(home) = codewhale_config::codewhale_home() {
80 let dir = home.join("crashes");
81 // Pre-create so the handler's open(2) cannot fail on ENOENT and
82 // so a first crash needs no directory creation mid-signal.
83 if std::fs::create_dir_all(&dir).is_ok() {
84 let path = dir.join("last-fatal-signal.log");
85 if let Ok(bytes) = std::ffi::CString::new(path.as_os_str().as_encoded_bytes()) {
86 let len = bytes.as_bytes().len();
87 if len < 4096 {
88 let mut buf = [0u8; 4096];
89 buf[..len].copy_from_slice(bytes.as_bytes());
90 let _ = MARKER_PATH.set(Box::new(buf));
91 MARKER_LEN.store(len, std::sync::atomic::Ordering::Release);
92 }
93 }
94 }
95 }
96 for signal in [libc::SIGABRT, libc::SIGBUS, libc::SIGILL, libc::SIGFPE] {
97 // SAFETY: ABRT/BUS/ILL/FPE all terminate by default.
98 unsafe { install_handler(signal) };
99 }
100 tracing::debug!("Fatal-signal terminal guard installed (ABRT/BUS/ILL/FPE)");
101 }
102 #[cfg(not(unix))]
103 {
104 // Windows console modes are restored by the panic hook and the
105 // cleanup guard; there is no signal-class death to intercept there.
106 }
107 }
108
109 /// Classic handler: write the fixed restore bytes, append the marker line,
110 /// then re-raise with the default disposition so the wait status is honest.
111 ///
112 /// # Safety
113 ///
114 /// Only async-signal-safe operations: `write(2)`, `tcsetattr(3)`, `open(2)`,
115 /// `close(2)`, `signal(2)`, `raise(2)`, and fixed-buffer arithmetic. No allocation, no
116 /// locks (the `OnceLock`/`AtomicUsize` reads complete before any thread
117 /// exists and are never written again).
118 #[cfg(unix)]
119 unsafe extern "C" fn fatal_signal_handler(signal: libc::c_int) {
120 // SAFETY: signal-safe syscalls only, per the contract above.
121 unsafe {
122 // 1. Restore the terminal: stdout first, stderr as fallback.
123 let mut written: usize = 0;
124 while written < FATAL_RESTORE_BYTES.len() {
125 let n = libc::write(
126 libc::STDOUT_FILENO,
127 FATAL_RESTORE_BYTES.as_ptr().add(written) as *const libc::c_void,
128 FATAL_RESTORE_BYTES.len() - written,
129 );
130 if n <= 0 {
131 break;
132 }
133 written += n as usize;
134 }
135 if written == 0 {
136 let _ = libc::write(
137 libc::STDERR_FILENO,
138 FATAL_RESTORE_BYTES.as_ptr() as *const libc::c_void,
139 FATAL_RESTORE_BYTES.len(),
140 );
141 }
142 // Leave raw mode from the cooked snapshot taken before it was enabled.
143 // `tcsetattr` is async-signal-safe; TCSANOW never waits on output.
144 if let Some(original) = super::job_control_guard::original_termios() {
145 let _ = libc::tcsetattr(libc::STDIN_FILENO, libc::TCSANOW, original);
146 }
147
148 // 2. Append the one-line marker (mtime timestamps it).
149 let len = MARKER_LEN.load(std::sync::atomic::Ordering::Acquire);
150 if len > 0
151 && let Some(path) = MARKER_PATH.get()
152 {
153 let fd = libc::open(
154 path.as_ptr() as *const libc::c_char,
155 libc::O_WRONLY | libc::O_APPEND | libc::O_CREAT,
156 0o600,
157 );
158 if fd >= 0 {
159 // "signal=NN\n" in a fixed buffer; no formatting machinery.
160 let mut line = [0u8; 16];
161 line[0] = b's';
162 line[1] = b'i';
163 line[2] = b'g';
164 line[3] = b'n';
165 line[4] = b'a';
166 line[5] = b'l';
167 line[6] = b'=';
168 let mut value = if signal < 0 { 0 } else { signal } as u32;
169 let mut digits = [0u8; 10];
170 let mut count = 0;
171 loop {
172 digits[count] = b'0' + (value % 10) as u8;
173 value /= 10;
174 count += 1;
175 if value == 0 || count == digits.len() {
176 break;
177 }
178 }
179 for index in 0..count {
180 line[7 + index] = digits[count - 1 - index];
181 }
182 let total = 7 + count;
183 line[total] = b'\n';
184 let _ = libc::write(fd, line.as_ptr() as *const libc::c_void, total + 1);
185 let _ = libc::close(fd);
186 }
187 }
188
189 // 3. Die with the honest wait status.
190 libc::signal(signal, libc::SIG_DFL);
191 libc::raise(signal);
192 }
193 }
194
195 /// Install [`fatal_signal_handler`] for one signal via `sigaction`.
196 ///
197 /// # Safety
198 ///
199 /// `signal` must be a fatal signal whose default action is to terminate.
200 #[cfg(unix)]
201 unsafe fn install_handler(signal: libc::c_int) {
202 // SAFETY: `action` is live and zeroed; oldact is null.
203 unsafe {
204 // Zero the whole struct then set our two fields: the remaining
205 // members (empty signal mask; any hidden per-OS plumbing like the
206 // Linux sa_restorer) are exactly what a zeroed default means, and
207 // the wrapper `sigaction` fills in what it owns.
208 let mut action: libc::sigaction = std::mem::zeroed();
209 action.sa_sigaction = fatal_signal_handler as *const () as libc::sighandler_t;
210 action.sa_flags = libc::SA_RESTART;
211 if libc::sigaction(signal, &action, std::ptr::null_mut()) != 0 {
212 tracing::warn!(signal, "fatal-signal guard install failed");
213 }
214 }
215 }
216
217 #[cfg(all(test, unix))]
218 mod tests {
219 use super::*;
220
221 #[test]
222 fn restore_bytes_cover_every_poisoning_mode() {
223 // Input-poisoning modes first: mouse capture (all four DEC modes)
224 // and the kitty keyboard stack.
225 let bytes = String::from_utf8_lossy(FATAL_RESTORE_BYTES).to_string();
226 for mode in [
227 "?1006l", "?1002l", "?1003l", "?1000l", "<1u", "?2004l", "?1004l", "?1007l", "?1049l",
228 "?2026l", "?25h",
229 ] {
230 assert!(
231 bytes.contains(mode),
232 "fatal restore must reset {mode}; got: {bytes:?}"
233 );
234 }
235 }
236
237 #[test]
238 fn job_control_guard_reuses_the_fatal_restore_bytes() {
239 // #6169: the SIGTSTP/SIGTTIN stop handler must not grow a second byte
240 // table. One teardown string is written on both the death and the
241 // suspend path, so a mode cannot be reverted on one and leaked by the
242 // other.
243 assert_eq!(
244 super::super::job_control_guard::SUSPEND_RESTORE_BYTES,
245 FATAL_RESTORE_BYTES
246 );
247 }
248
249 #[test]
250 fn restore_bytes_are_one_write_friendly() {
251 // No interior NULs, ASCII-only escape program, reasonable size.
252 assert!(!FATAL_RESTORE_BYTES.contains(&0));
253 assert!(FATAL_RESTORE_BYTES.len() < 128);
254 assert!(FATAL_RESTORE_BYTES.starts_with(b"\x1b[?2026l"));
255 }
256 }
257
257 lines RUST