oscall 0.0.2

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
Documentation
//! Requests to stop, and other asynchronous notifications: Unix signals
//! and Windows console control events, received without running any of the
//! caller's code in a signal handler.

use core::fmt;
use core::time::Duration;

use crate::time::Clock;
use crate::{ErrorKind, Result, sys};

/// An asynchronous notification from the system to the process: a signal
/// on Linux and macOS, a console control event on Windows.
///
/// Three exist everywhere:
///
/// | | Linux, macOS | Windows |
/// |---|---|---|
/// | [`INTERRUPT`](Self::INTERRUPT) | `SIGINT` | `CTRL_C_EVENT` |
/// | [`TERMINATE`](Self::TERMINATE) | `SIGTERM` | `CTRL_SHUTDOWN_EVENT` |
/// | [`HANGUP`](Self::HANGUP) | `SIGHUP` | `CTRL_CLOSE_EVENT` |
///
/// The others are the system's own: any signal number through
/// `unix::SignalExt`, and `windows::CTRL_BREAK` and `windows::CTRL_LOGOFF`.
///
/// What a process may still do once it has been notified differs. A signal
/// is only a message: the process goes on for as long as it likes. So does
/// it after Ctrl-C or Ctrl-Break on Windows. But when Windows closes the
/// console, logs the user off or shuts down, the notification is a notice
/// period: the process is terminated a few seconds later whatever it does
/// (about 5 seconds; the delay is the system's to choose), and at once
/// if it lets the system know it is done, which is what returning from
/// `main` or calling [`exit`](super::exit) does. To give the program all
/// of that time, oscall's handler does not return for these three events.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct Signal(pub(crate) i32);

impl Signal {
    /// The user asks the program to stop what it is doing: Ctrl-C in a
    /// terminal or a console. A process that does not listen is terminated
    /// by it.
    ///
    /// On Windows a process can be made deaf to it, by its creator
    /// (`CREATE_NEW_PROCESS_GROUP`) or by itself: nothing is delivered
    /// then, and listening changes nothing to that. See
    /// `windows::set_ctrl_c_ignored`.
    pub const INTERRUPT: Self = Self(sys::process::signal::INTERRUPT);

    /// The system, or another program, asks this one to end: what `kill`
    /// sends by default and what a Unix system sends to every process when
    /// it shuts down; on Windows, the notice that the system is shutting
    /// down, which a service or a console program without a window
    /// receives. (Windows has no message to ask one process to end:
    /// `TerminateProcess` gives no notice.)
    pub const TERMINATE: Self = Self(sys::process::signal::TERMINATE);

    /// The terminal or the console of the process is gone: its window was
    /// closed, the connection was lost. On Linux and macOS it is also what
    /// daemons are conventionally sent to make them read their
    /// configuration again.
    pub const HANGUP: Self = Self(sys::process::signal::HANGUP);
}

impl fmt::Debug for Signal {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            Self::INTERRUPT => f.write_str("Signal::INTERRUPT"),
            Self::TERMINATE => f.write_str("Signal::TERMINATE"),
            Self::HANGUP => f.write_str("Signal::HANGUP"),
            Self(raw) => write!(f, "Signal({raw})"),
        }
    }
}

/// How a backend's wait for a notification ended.
#[allow(dead_code)]
pub(crate) enum Wake {
    /// Something may be pending.
    Ready,
    /// The timeout passed, or as much of it as the system counts at once.
    TimedOut,
    /// A signal handler ran in the thread.
    Interrupted,
}

/// A subscription to a set of [`Signal`]s: while it exists they are
/// recorded instead of doing what they do by default (most terminate the
/// process), and the program asks for them when it suits it.
///
/// No code of the caller ever runs in a signal handler. oscall installs
/// its own, which does the only things that are safe there (it sets a flag
/// and wakes a descriptor), and the program learns of the signal from an
/// ordinary thread, with [`try_next`](Self::try_next) or
/// [`wait`](Self::wait).
///
/// ```no_run
/// use oscall::process::{Signal, Signals};
///
/// let signals = Signals::new(&[Signal::INTERRUPT, Signal::TERMINATE])?;
/// // Work, until asked to stop.
/// while signals.try_next().is_none() {
///     // ...
/// }
/// // Or, in a thread of its own: sleep until then.
/// let signal = signals.wait(None)?;
/// # Ok::<(), oscall::Error>(())
/// ```
///
/// # What is reported
///
/// That a signal was delivered since the last time it was reported, not
/// how many times: deliveries that the program has not yet been told of
/// merge into one, as they do in the system itself. Each signal of the set
/// has its own flag, so different signals never hide one another. A signal
/// that came before the subscription is not kept for it; one that the
/// system was still delivering at that very moment may be reported.
///
/// # One subscription per signal
///
/// Dispositions belong to the whole process. Two `Signals` cannot have a
/// signal in common: the second [`new`](Self::new) fails with
/// [`ErrorKind::ResourceBusy`]. Several with different signals are fine,
/// and one can be shared between threads.
///
/// Dropping a `Signals` puts back what it replaced, and what happened in
/// between and was not asked for is forgotten. From then on a signal of
/// the set does what it did before, which for most is to terminate the
/// process: that includes one that was sent while the subscription
/// existed and is delivered a moment after its end. A program that drops
/// its `Signals` while the signal can still come is terminated by it
/// exactly as if it had never listened; keep the subscription for as long
/// as that is not wanted.
///
/// - **Linux, macOS**: the previous action of each signal is restored
///   (`sigaction`). A handler that was there before does not run while
///   the subscription exists: oscall does not chain. A signal that was
///   ignored (as `nohup` does for `SIGHUP`) is listened to all the same.
///   Signals are not blocked: a system call that one of them interrupts
///   in another thread is restarted where the system can do it
///   (`SA_RESTART`), and fails with [`ErrorKind::Interrupted`] where it
///   cannot.
///
///   If other code has installed an action of its own in the meantime,
///   that one is left alone. Should that code later put back what it had
///   found, which is oscall's handler (C's `system` does this around the
///   command it runs), the handler finds that nobody listens when the
///   signal next comes: it then restores the previous action itself and
///   sends the signal again, to the same thread, for that action to take
///   it. A new `Signals` never takes oscall's own handler for the action
///   to go back to.
///
///   **macOS** cannot safely turn a signal that has a handler into one
///   that is ignored. Its kernel decides to deliver a signal, then reads
///   the action again: if "ignore" has replaced the handler in between,
///   the process jumps to address 1 and dies; if "default" has, the
///   process is terminated, even by a signal whose default is to do
///   nothing (`SIGCHLD`, `SIGWINCH`, `SIGURG`, `SIGIO`, `SIGINFO`,
///   `SIGCONT`). So where the action to go back to amounts to ignoring
///   the signal, oscall's handler stays in place on macOS and discards
///   the signal. To the process that is the same, with two differences:
///   a program it starts otherwise than with `Command` finds the default
///   action instead of "ignore", and `SIGCHLD` discarded by a handler does
///   not make the system collect the children, as ignoring it does.
/// - **Windows**: the handler is added to the process's list
///   (`SetConsoleCtrlHandler`) with the first subscription and removed
///   with the last. It answers for the events subscribed to, and passes
///   the others on to the handlers installed before it.
///
/// # Waiting with other things
///
/// On every system that has signals, a
/// [`Poller`](crate::event::Poller) waits for a `Signals` along with
/// sockets and timers:
/// [`Poller::register_signals`](crate::event::Poller::register_signals).
/// Call `try_next` until it returns `None` each time the poller reports
/// it.
///
/// On Linux and macOS a `Signals` also implements
/// [`AsHandle`](crate::AsHandle): the handle (an `eventfd`, the read end
/// of a pipe) is readable when [`try_next`](Self::try_next) may have
/// something to return, and stops being so once it has returned `None`.
/// It is there to be waited for by [`event::poll`](crate::event::poll)
/// (`event::unix::poll_entry`) or by a poller in another mode
/// (`event::unix::register`, level- or edge-triggered), and must not be
/// read from. Call `try_next` until it returns `None` each time the
/// handle is reported: that call leaves the handle not readable, until
/// the next signal of the set is delivered, so that a level-triggered
/// poller does not report it again for nothing. (To that end `try_next`
/// waits for a handler that has recorded a signal and not yet woken the
/// handle, the matter of an instant. It does not wait for ever: if the
/// thread such a handler runs in is kept from running for long, the
/// handle is reported once more with nothing to take.)
///
/// # WebAssembly
///
/// There are no signals: [`new`](Self::new) fails with
/// [`ErrorKind::Unsupported`].
#[derive(Debug)]
pub struct Signals(sys::process::signal::Signals);

impl Signals {
    /// Starts listening to `signals`. Naming one twice is the same as
    /// naming it once.
    ///
    /// # Errors
    ///
    /// - [`ErrorKind::ResourceBusy`] if another `Signals` has one of them.
    /// - [`ErrorKind::InvalidInput`] if the list is empty, or names what
    ///   the system does not have or does not let a process receive this
    ///   way. On Linux and macOS: `SIGKILL` and `SIGSTOP`, which cannot be
    ///   caught; the signals a thread gets for its own faults (`SIGSEGV`,
    ///   `SIGBUS`, `SIGFPE`, `SIGILL`, `SIGTRAP`, `SIGSYS`), which cannot
    ///   be handled later; and on Linux signals 32 to 34, which C
    ///   libraries keep for themselves.
    /// - [`ErrorKind::Unsupported`] on WebAssembly.
    ///
    /// When it fails, nothing is listened to.
    pub fn new(signals: &[Signal]) -> Result<Self> {
        if signals.is_empty() && sys::process::HAS_PROCESSES {
            return Err(ErrorKind::InvalidInput.into());
        }
        // `Signal` is a transparent enough `i32`, but not declared so:
        // hand the numbers over one at a time.
        let mut raw = [0; 64];
        let mut count = 0;
        for signal in signals {
            if raw[..count].contains(&signal.0) {
                continue;
            }
            *raw.get_mut(count).ok_or(ErrorKind::InvalidInput)? = signal.0;
            count += 1;
        }
        sys::process::signal::Signals::new(&raw[..count]).map(Self)
    }

    /// A signal of the set that was delivered and not yet reported, if
    /// there is one; it is then no longer pending. Never blocks.
    ///
    /// When several are pending, which one comes first is not specified.
    pub fn try_next(&self) -> Option<Signal> {
        self.0.try_next().map(Signal)
    }

    /// The system's side of the subscription, for the
    /// [`Poller`](crate::event::Poller) that registers it.
    #[cfg(feature = "alloc")]
    #[inline]
    pub(crate) fn sys(&self) -> &sys::process::signal::Signals {
        &self.0
    }

    /// Waits until a signal of the set is delivered, and returns it as
    /// [`try_next`](Self::try_next) does; `None` if `timeout` passes
    /// first. Without a timeout, waits for as long as it takes.
    ///
    /// The timeout is measured on the clock
    /// [`Clock::Monotonic`] reads. A signal that is already pending is
    /// returned at once, a zero timeout never sleeps.
    ///
    /// Any number of threads may wait on the same `Signals`; each signal
    /// is reported to one of them.
    ///
    /// # Errors
    ///
    /// On Linux and macOS, [`ErrorKind::Interrupted`] when the handler of
    /// a signal that is not of this set ran in the calling thread during
    /// the wait, be it a signal of another `Signals`; it can be called
    /// again, and nothing of this set was lost.
    ///
    /// `ppoll` on Linux, `poll` on macOS, `WaitOnAddress` on Windows.
    pub fn wait(&self, timeout: Option<Duration>) -> Result<Option<Signal>> {
        // A deadline too far to be counted is none at all.
        let deadline = match timeout {
            Some(timeout) => Clock::Monotonic.now()?.checked_add(timeout),
            None => None,
        };
        loop {
            if let Some(signal) = self.try_next() {
                return Ok(Some(signal));
            }
            let remaining = match deadline {
                Some(deadline) => match deadline.checked_sub(Clock::Monotonic.now()?) {
                    Some(remaining) if !remaining.is_zero() => Some(remaining),
                    _ => return Ok(None),
                },
                None => None,
            };
            match self.0.wait_once(remaining)? {
                // Look again: the deadline decides when there is nothing.
                Wake::Ready | Wake::TimedOut => {}
                Wake::Interrupted => {
                    // Perhaps by one of ours, delivered to this thread.
                    return match self.try_next() {
                        Some(signal) => Ok(Some(signal)),
                        None => Err(ErrorKind::Interrupted.into()),
                    };
                }
            }
        }
    }
}

/// On Linux and macOS, the handle that is readable when a signal may be
/// pending: see [`Signals`].
#[cfg(any(target_os = "linux", target_os = "fullrust", target_os = "macos"))]
impl crate::AsHandle for Signals {
    #[inline]
    fn as_handle(&self) -> crate::BorrowedHandle<'_> {
        self.0.handle()
    }
}