petitcarnets 0.0.11

Terminal user interfaces in the Elm architecture (model, update, view), with no dependencies.
Documentation
//! Signals, installed with `signal(2)` (see the module above for why not
//! `sigaction`), and stopping the process group.

use super::check;
use std::ffi::c_int;
use std::io;
use std::sync::atomic::{AtomicI32, AtomicU32, AtomicUsize, Ordering};
use std::time::{Duration, Instant};

/// Signal numbers. `SIGINT`, `SIGTERM` and `SIGWINCH` are the same on
/// Linux, macOS and FreeBSD; `SIGTSTP` and `SIGCONT` are not.
pub(crate) mod signo {
    use std::ffi::c_int;
    /// Interrupt (Ctrl-C outside raw mode, or `kill -INT`).
    pub(crate) const SIGINT: c_int = 2;
    /// Termination request.
    pub(crate) const SIGTERM: c_int = 15;
    /// The window changed size.
    pub(crate) const SIGWINCH: c_int = 28;
    /// Stop from the terminal (Ctrl-Z outside raw mode, or `kill -TSTP`).
    #[cfg(target_os = "linux")]
    pub(crate) const SIGTSTP: c_int = 20;
    /// Stop from the terminal (Ctrl-Z outside raw mode, or `kill -TSTP`).
    #[cfg(any(target_os = "macos", target_os = "freebsd"))]
    pub(crate) const SIGTSTP: c_int = 18;
    /// Continue after a stop (`fg`, or `kill -CONT`).
    #[cfg(target_os = "linux")]
    pub(crate) const SIGCONT: c_int = 18;
    /// Continue after a stop (`fg`, or `kill -CONT`).
    #[cfg(any(target_os = "macos", target_os = "freebsd"))]
    pub(crate) const SIGCONT: c_int = 19;
}

/// The signals a running program listens for. Like Bubble Tea, not
/// `SIGQUIT` or `SIGHUP`: a quit is meant to dump core as it is, and
/// after a hang-up there is no terminal left to restore.
const WATCHED: [c_int; 5] = [
    signo::SIGINT,
    signo::SIGTERM,
    signo::SIGWINCH,
    signo::SIGTSTP,
    signo::SIGCONT,
];

/// How long [`stop_process_group`] waits for the stop to take hold: a
/// process group the system will not stop (an orphaned one) carries on
/// after this.
const STOP_WAIT: Duration = Duration::from_millis(500);

/// `SIG_DFL` and `SIG_ERR`, as the handler values `signal` takes and
/// returns (a handler is a function's address, or one of these).
const SIG_DFL: usize = 0;
const SIG_ERR: usize = usize::MAX;

unsafe extern "C" {
    fn signal(signum: c_int, handler: usize) -> usize;
    fn write(fd: c_int, buf: *const std::ffi::c_void, count: usize) -> isize;
    // `pid_t` is a 32-bit `int` on Linux, macOS and FreeBSD.
    fn kill(pid: c_int, signum: c_int) -> c_int;
    /// The calling thread's `errno`.
    #[cfg(target_os = "linux")]
    #[link_name = "__errno_location"]
    fn errno_location() -> *mut c_int;
    /// The calling thread's `errno`.
    #[cfg(any(target_os = "macos", target_os = "freebsd"))]
    #[link_name = "__error"]
    fn errno_location() -> *mut c_int;
}

/// Where the signal handler writes: the wake pipe's write end, or -1.
/// The pipe is never closed (see `super::wake_pipe`), so a handler that
/// read the descriptor just before it was cleared still writes to it.
static SIGNAL_FD: AtomicI32 = AtomicI32::new(-1);

/// How many times the process has been continued (`SIGCONT`).
static CONTINUED: AtomicU32 = AtomicU32::new(0);

/// Each watched signal's handling before [`watch_signals`], given back
/// by [`unwatch_signals`].
static PREVIOUS: [AtomicUsize; WATCHED.len()] =
    [const { AtomicUsize::new(SIG_DFL) }; WATCHED.len()];

/// [`on_signal`] as the handler value `signal` takes.
fn handler() -> usize {
    let on: extern "C" fn(c_int) = on_signal;
    on as usize
}

/// The signal handler: writes the signal's number, as one byte, to
/// [`SIGNAL_FD`], and counts `SIGCONT`. `write`, `errno` and lock-free
/// atomics are async-signal-safe, the pipe never blocks, and `errno` is
/// put back, so the interrupted code sees its own. If the pipe is full
/// (64 KiB of bytes the reader has not read), the byte is dropped.
///
/// The byte goes first: once [`stop_process_group`] sees the count
/// change, the `SIGCONT` byte is already in the pipe, ahead of anything
/// written after, so a paused reader drops it rather than taking it for
/// a stop from outside.
extern "C" fn on_signal(signum: c_int) {
    // SAFETY: `errno_location` returns this thread's `errno`, which is
    // valid for the thread's life; it is read now and written back last.
    let errno = unsafe { errno_location() };
    // SAFETY: as above.
    let saved = unsafe { errno.read() };
    let fd = SIGNAL_FD.load(Ordering::Relaxed);
    if fd >= 0 {
        let byte = u8::try_from(signum).unwrap_or(0);
        // SAFETY: `byte` is a live local; `fd` is the wake pipe's write
        // end, which is never closed.
        let _ = unsafe { write(fd, (&raw const byte).cast(), 1) };
    }
    if signum == signo::SIGCONT {
        let _ = CONTINUED.fetch_add(1, Ordering::SeqCst);
    }
    // SAFETY: as above.
    unsafe { errno.write(saved) };
}

/// Sends `SIGINT`, `SIGTERM`, `SIGWINCH`, `SIGTSTP` and `SIGCONT` to
/// `fd`, one byte each, saving their handling before.
pub(crate) fn watch_signals(fd: c_int) -> io::Result<()> {
    SIGNAL_FD.store(fd, Ordering::Relaxed);
    for (signum, previous) in WATCHED.iter().zip(&PREVIOUS) {
        // SAFETY: `on_signal` is an `extern "C" fn(c_int)` that only does
        // async-signal-safe work.
        let before = unsafe { signal(*signum, handler()) };
        if before == SIG_ERR {
            return Err(io::Error::last_os_error());
        }
        previous.store(before, Ordering::SeqCst);
    }
    Ok(())
}

/// Gives the watched signals the handling they had before
/// [`watch_signals`]: the default, the application's own handler, or
/// ignored (as a shell leaves `SIGINT` for a background job).
pub(crate) fn unwatch_signals() {
    for (signum, previous) in WATCHED.iter().zip(&PREVIOUS) {
        let before = previous.swap(SIG_DFL, Ordering::SeqCst);
        // SAFETY: `before` is what `signal` returned for this signal, so
        // a valid disposition: a handler, `SIG_DFL` or `SIG_IGN`.
        let _ = unsafe { signal(*signum, before) };
    }
    SIGNAL_FD.store(-1, Ordering::Relaxed);
}

/// Gives `SIGTSTP` its default handling (`default`), so a stop from the
/// keyboard stops the process with whatever runs in the terminal, or
/// sends it to the pipe again.
pub(crate) fn default_stop(default: bool) -> io::Result<()> {
    let handling = if default { SIG_DFL } else { handler() };
    // SAFETY: `on_signal` only does async-signal-safe work, and the
    // default disposition is always valid.
    let before = unsafe { signal(signo::SIGTSTP, handling) };
    if before == SIG_ERR {
        return Err(io::Error::last_os_error());
    }
    Ok(())
}

/// Stops the process and the rest of its process group, as a shell's
/// Ctrl-Z does and as Bubble Tea does (`kill(0, SIGTSTP)`), and returns
/// once it has been continued. `SIGTSTP` must have its default handling
/// ([`default_stop`]), and `SIGCONT` must be watched.
pub(crate) fn stop_process_group() -> io::Result<()> {
    let before = CONTINUED.load(Ordering::SeqCst);
    // SAFETY: `kill` takes a process group (0, the caller's) and a valid
    // signal number; it touches no memory of ours.
    check(unsafe { kill(0, signo::SIGTSTP) }).map(drop)?;
    let deadline = Instant::now() + STOP_WAIT;
    while CONTINUED.load(Ordering::SeqCst) == before && Instant::now() < deadline {
        std::thread::sleep(Duration::from_millis(2));
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    /// `SIG_IGN`: 1 on every supported system.
    const SIG_IGN: usize = 1;

    unsafe extern "C" {
        fn raise(signum: c_int) -> c_int;
    }

    /// One test, as handlers are the process's: a signal reaches the
    /// pipe, the handler keeps the interrupted code's `errno` even when
    /// its write fails, and unwatching gives back the handling before.
    #[test]
    #[cfg_attr(miri, ignore)] // calls libc
    fn a_signal_reaches_the_pipe_and_leaves_errno_and_the_old_handling() {
        // SAFETY: ignoring `SIGWINCH` is always valid.
        let original = unsafe { signal(signo::SIGWINCH, SIG_IGN) };
        let pipe = crate::sys::Pipe::new().unwrap();
        watch_signals(pipe.write).unwrap();
        // SAFETY: `on_signal` handles `SIGWINCH`; it runs on this thread.
        assert_eq!(unsafe { raise(signo::SIGWINCH) }, 0);
        let mut buf = [0u8; 4];
        assert_eq!(crate::sys::read_fd(pipe.read, &mut buf).unwrap(), 1);
        assert_eq!(c_int::from(buf[0]), signo::SIGWINCH);
        // Fill the pipe, so the handler's write fails with EAGAIN.
        while crate::sys::write_all_fd(pipe.write, &[0; 4096]).is_ok() {}
        // SAFETY: this thread's `errno`, valid while it runs.
        unsafe { errno_location().write(42) };
        // SAFETY: as above.
        assert_eq!(unsafe { raise(signo::SIGWINCH) }, 0);
        // SAFETY: as above.
        assert_eq!(unsafe { errno_location().read() }, 42, "errno kept");
        unwatch_signals();
        // SAFETY: restoring the original disposition is always valid.
        let after = unsafe { signal(signo::SIGWINCH, original) };
        assert_eq!(after, SIG_IGN, "the handling before is given back");
    }
}