| 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 raw mode |
| 35 | /// (termios state lives behind a lock that may be held by the dying thread) |
| 36 | /// and minus every query (a dead process cannot read replies). Modes left |
| 37 | /// over that a shell does not self-heal are the ones that poison input: |
| 38 | /// mouse capture and the kitty keyboard stack get the full reset. |
| 39 | #[cfg(unix)] |
| 40 | pub(crate) const FATAL_RESTORE_BYTES: &[u8] = concat!( |
| 41 | "\x1b[?2026l", // close any open DEC 2026 synchronized-update batch |
| 42 | "\x1b[<1u", // pop one kitty keyboard-enhancement stack level |
| 43 | "\x1b[?1007l", // alternate scroll off |
| 44 | "\x1b[?1004l", // focus reporting off |
| 45 | "\x1b[?2004l", // bracketed paste off |
| 46 | "\x1b[?1006l", // SGR mouse encoding off |
| 47 | "\x1b[?1002l", // button-event mouse tracking off |
| 48 | "\x1b[?1003l", // any-motion mouse tracking off |
| 49 | "\x1b[?1000l", // normal mouse tracking off |
| 50 | "\x1b[?1049l", // leave the alternate screen |
| 51 | "\x1b[?25h", // show the cursor |
| 52 | ) |
| 53 | .as_bytes(); |
| 54 | |
| 55 | /// Absolute path of the append-only fatal-signal marker, fixed at install |
| 56 | /// time (before any worker thread exists, after which it is never written |
| 57 | /// again — a plain load from the signal handler). |
| 58 | #[cfg(unix)] |
| 59 | static MARKER_PATH: std::sync::OnceLock<Box<[u8; 4096]>> = std::sync::OnceLock::new(); |
| 60 | #[cfg(unix)] |
| 61 | static MARKER_LEN: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); |
| 62 | |
| 63 | /// Install the fatal-signal restore guard. POSIX only; no-op elsewhere. |
| 64 | /// |
| 65 | /// Call once, early, on the main thread before worker threads are spawned |
| 66 | /// (the install writes the `OnceLock`s; after that they are read-only). |
| 67 | pub(crate) fn install_fatal_signal_guard() { |
| 68 | #[cfg(unix)] |
| 69 | { |
| 70 | // Piped/embedded surfaces must never receive escape bytes. |
| 71 | // SAFETY: isatty(2) dereferences no pointers. |
| 72 | if unsafe { libc::isatty(libc::STDOUT_FILENO) } == 0 { |
| 73 | tracing::debug!("Fatal-signal terminal guard skipped: stdout is not a TTY"); |
| 74 | return; |
| 75 | } |
| 76 | if let Some(home) = crate::config::effective_home_dir() { |
| 77 | let dir = home.join(".codewhale").join("crashes"); |
| 78 | // Pre-create so the handler's open(2) cannot fail on ENOENT and |
| 79 | // so a first crash needs no directory creation mid-signal. |
| 80 | if std::fs::create_dir_all(&dir).is_ok() { |
| 81 | let path = dir.join("last-fatal-signal.log"); |
| 82 | if let Ok(bytes) = std::ffi::CString::new(path.as_os_str().as_encoded_bytes()) { |
| 83 | let len = bytes.as_bytes().len(); |
| 84 | if len < 4096 { |
| 85 | let mut buf = [0u8; 4096]; |
| 86 | buf[..len].copy_from_slice(bytes.as_bytes()); |
| 87 | let _ = MARKER_PATH.set(Box::new(buf)); |
| 88 | MARKER_LEN.store(len, std::sync::atomic::Ordering::Release); |
| 89 | } |
| 90 | } |
| 91 | } |
| 92 | } |
| 93 | for signal in [libc::SIGABRT, libc::SIGBUS, libc::SIGILL, libc::SIGFPE] { |
| 94 | // SAFETY: ABRT/BUS/ILL/FPE all terminate by default. |
| 95 | unsafe { install_handler(signal) }; |
| 96 | } |
| 97 | tracing::debug!("Fatal-signal terminal guard installed (ABRT/BUS/ILL/FPE)"); |
| 98 | } |
| 99 | #[cfg(not(unix))] |
| 100 | { |
| 101 | // Windows console modes are restored by the panic hook and the |
| 102 | // cleanup guard; there is no signal-class death to intercept there. |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | /// Classic handler: write the fixed restore bytes, append the marker line, |
| 107 | /// then re-raise with the default disposition so the wait status is honest. |
| 108 | /// |
| 109 | /// # Safety |
| 110 | /// |
| 111 | /// Only async-signal-safe operations: `write(2)`, `open(2)`, `close(2)`, |
| 112 | /// `signal(2)`, `raise(2)`, and fixed-buffer arithmetic. No allocation, no |
| 113 | /// locks (the `OnceLock`/`AtomicUsize` reads complete before any thread |
| 114 | /// exists and are never written again). |
| 115 | #[cfg(unix)] |
| 116 | unsafe extern "C" fn fatal_signal_handler(signal: libc::c_int) { |
| 117 | // SAFETY: signal-safe syscalls only, per the contract above. |
| 118 | unsafe { |
| 119 | // 1. Restore the terminal: stdout first, stderr as fallback. |
| 120 | let mut written: usize = 0; |
| 121 | while written < FATAL_RESTORE_BYTES.len() { |
| 122 | let n = libc::write( |
| 123 | libc::STDOUT_FILENO, |
| 124 | FATAL_RESTORE_BYTES.as_ptr().add(written) as *const libc::c_void, |
| 125 | FATAL_RESTORE_BYTES.len() - written, |
| 126 | ); |
| 127 | if n <= 0 { |
| 128 | break; |
| 129 | } |
| 130 | written += n as usize; |
| 131 | } |
| 132 | if written == 0 { |
| 133 | let _ = libc::write( |
| 134 | libc::STDERR_FILENO, |
| 135 | FATAL_RESTORE_BYTES.as_ptr() as *const libc::c_void, |
| 136 | FATAL_RESTORE_BYTES.len(), |
| 137 | ); |
| 138 | } |
| 139 | |
| 140 | // 2. Append the one-line marker (mtime timestamps it). |
| 141 | let len = MARKER_LEN.load(std::sync::atomic::Ordering::Acquire); |
| 142 | if len > 0 |
| 143 | && let Some(path) = MARKER_PATH.get() |
| 144 | { |
| 145 | let fd = libc::open( |
| 146 | path.as_ptr() as *const libc::c_char, |
| 147 | libc::O_WRONLY | libc::O_APPEND | libc::O_CREAT, |
| 148 | 0o600, |
| 149 | ); |
| 150 | if fd >= 0 { |
| 151 | // "signal=NN\n" in a fixed buffer; no formatting machinery. |
| 152 | let mut line = [0u8; 16]; |
| 153 | line[0] = b's'; |
| 154 | line[1] = b'i'; |
| 155 | line[2] = b'g'; |
| 156 | line[3] = b'n'; |
| 157 | line[4] = b'a'; |
| 158 | line[5] = b'l'; |
| 159 | line[6] = b'='; |
| 160 | let mut value = if signal < 0 { 0 } else { signal } as u32; |
| 161 | let mut digits = [0u8; 10]; |
| 162 | let mut count = 0; |
| 163 | loop { |
| 164 | digits[count] = b'0' + (value % 10) as u8; |
| 165 | value /= 10; |
| 166 | count += 1; |
| 167 | if value == 0 || count == digits.len() { |
| 168 | break; |
| 169 | } |
| 170 | } |
| 171 | for index in 0..count { |
| 172 | line[7 + index] = digits[count - 1 - index]; |
| 173 | } |
| 174 | let total = 7 + count; |
| 175 | line[total] = b'\n'; |
| 176 | let _ = libc::write(fd, line.as_ptr() as *const libc::c_void, total + 1); |
| 177 | let _ = libc::close(fd); |
| 178 | } |
| 179 | } |
| 180 | |
| 181 | // 3. Die with the honest wait status. |
| 182 | libc::signal(signal, libc::SIG_DFL); |
| 183 | libc::raise(signal); |
| 184 | } |
| 185 | } |
| 186 | |
| 187 | /// Install [`fatal_signal_handler`] for one signal via `sigaction`. |
| 188 | /// |
| 189 | /// # Safety |
| 190 | /// |
| 191 | /// `signal` must be a fatal signal whose default action is to terminate. |
| 192 | #[cfg(unix)] |
| 193 | unsafe fn install_handler(signal: libc::c_int) { |
| 194 | // SAFETY: `action` is live and zeroed; oldact is null. |
| 195 | unsafe { |
| 196 | // Zero the whole struct then set our two fields: the remaining |
| 197 | // members (empty signal mask; any hidden per-OS plumbing like the |
| 198 | // Linux sa_restorer) are exactly what a zeroed default means, and |
| 199 | // the wrapper `sigaction` fills in what it owns. |
| 200 | let mut action: libc::sigaction = std::mem::zeroed(); |
| 201 | action.sa_sigaction = fatal_signal_handler as *const () as libc::sighandler_t; |
| 202 | action.sa_flags = libc::SA_RESTART; |
| 203 | if libc::sigaction(signal, &action, std::ptr::null_mut()) != 0 { |
| 204 | tracing::warn!(signal, "fatal-signal guard install failed"); |
| 205 | } |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | #[cfg(all(test, unix))] |
| 210 | mod tests { |
| 211 | use super::*; |
| 212 | |
| 213 | #[test] |
| 214 | fn restore_bytes_cover_every_poisoning_mode() { |
| 215 | // Input-poisoning modes first: mouse capture (all four DEC modes) |
| 216 | // and the kitty keyboard stack. |
| 217 | let bytes = String::from_utf8_lossy(FATAL_RESTORE_BYTES).to_string(); |
| 218 | for mode in [ |
| 219 | "?1006l", "?1002l", "?1003l", "?1000l", "<1u", "?2004l", "?1004l", "?1007l", "?1049l", |
| 220 | "?2026l", "?25h", |
| 221 | ] { |
| 222 | assert!( |
| 223 | bytes.contains(mode), |
| 224 | "fatal restore must reset {mode}; got: {bytes:?}" |
| 225 | ); |
| 226 | } |
| 227 | } |
| 228 | |
| 229 | #[test] |
| 230 | fn job_control_guard_reuses_the_fatal_restore_bytes() { |
| 231 | // #6169: the SIGTSTP/SIGTTIN stop handler must not grow a second byte |
| 232 | // table. One teardown string is written on both the death and the |
| 233 | // suspend path, so a mode cannot be reverted on one and leaked by the |
| 234 | // other. |
| 235 | assert_eq!( |
| 236 | super::super::job_control_guard::SUSPEND_RESTORE_BYTES, |
| 237 | FATAL_RESTORE_BYTES |
| 238 | ); |
| 239 | } |
| 240 | |
| 241 | #[test] |
| 242 | fn restore_bytes_are_one_write_friendly() { |
| 243 | // No interior NULs, ASCII-only escape program, reasonable size. |
| 244 | assert!(!FATAL_RESTORE_BYTES.contains(&0)); |
| 245 | assert!(FATAL_RESTORE_BYTES.len() < 128); |
| 246 | assert!(FATAL_RESTORE_BYTES.starts_with(b"\x1b[?2026l")); |
| 247 | } |
| 248 | } |
| 249 |