.cargo/
crates/
brain/
diff/
files/
highlight/
repo/
signals/
src/
lib.rs
9.2 KiB
Cargo.toml
344 B
tui/
tui-core/
tui-termion/
tui-widgets/
scripts/
src/
.gitignore
30 B
.gitsigners
198 B
AGENTS.md
1.9 KiB
CONTRIBUTING
1.7 KiB
Cargo.lock
5.4 KiB
Cargo.toml
1.9 KiB
LICENSE
1.1 KiB
README.md
245 B
STYLE
3.7 KiB
clippy.toml
213 B
crates/signals/src/lib.rs
raw
| 1 | //! POSIX signal notifications. |
| 2 | //! |
| 3 | //! This crate keeps unsafe signal-handler wiring behind a small channel-based |
| 4 | //! API. The installed handler only writes the signal number into a nonblocking |
| 5 | //! pipe, and a normal Rust thread turns those bytes into typed notifications. |
| 6 | |
| 7 | use std::fs::File; |
| 8 | use std::io::{self, Read}; |
| 9 | use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd}; |
| 10 | use std::sync::Mutex; |
| 11 | use std::sync::atomic::{AtomicI32, Ordering}; |
| 12 | use std::sync::mpsc; |
| 13 | use std::thread; |
| 14 | |
| 15 | /// File descriptor not currently connected to signal delivery. |
| 16 | const NO_FD: RawFd = -1; |
| 17 | /// Whether this process already has a rustik signal registration. |
| 18 | static INSTALLED: Mutex<bool> = Mutex::new(false); |
| 19 | /// Nonblocking pipe write end used by the signal handler. |
| 20 | static WRITE_FD: AtomicI32 = AtomicI32::new(NO_FD); |
| 21 | |
| 22 | /// Operating system signal. |
| 23 | #[derive(Debug, Copy, Clone, PartialEq, Eq)] |
| 24 | pub enum Signal { |
| 25 | /// `SIGINT`. |
| 26 | Interrupt, |
| 27 | /// `SIGTERM`. |
| 28 | Terminate, |
| 29 | /// `SIGHUP`. |
| 30 | Hangup, |
| 31 | /// `SIGWINCH`. |
| 32 | WindowChanged, |
| 33 | } |
| 34 | |
| 35 | impl Signal { |
| 36 | /// Returns this signal's platform number. |
| 37 | fn number(self) -> libc::c_int { |
| 38 | match self { |
| 39 | Self::Interrupt => libc::SIGINT, |
| 40 | Self::Terminate => libc::SIGTERM, |
| 41 | Self::Hangup => libc::SIGHUP, |
| 42 | Self::WindowChanged => libc::SIGWINCH, |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | /// Returns the signal represented by a platform number. |
| 47 | fn from_number(number: libc::c_int) -> Option<Self> { |
| 48 | match number { |
| 49 | libc::SIGINT => Some(Self::Interrupt), |
| 50 | libc::SIGTERM => Some(Self::Terminate), |
| 51 | libc::SIGHUP => Some(Self::Hangup), |
| 52 | libc::SIGWINCH => Some(Self::WindowChanged), |
| 53 | _ => None, |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | /// Installs the crate's signal handler and returns a guard that restores |
| 58 | /// the default disposition on drop. |
| 59 | fn install_handler(self) -> io::Result<InstalledHandler> { |
| 60 | let handler = handle_signal as *const () as libc::sighandler_t; |
| 61 | // SAFETY: `handler` is the crate's signal handler for `self.number()`. |
| 62 | if unsafe { libc::signal(self.number(), handler) } == libc::SIG_ERR { |
| 63 | return Err(io::Error::last_os_error()); |
| 64 | } |
| 65 | Ok(InstalledHandler(self)) |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | /// Guard that restores the default disposition for its signal on drop. |
| 70 | struct InstalledHandler(Signal); |
| 71 | |
| 72 | impl Drop for InstalledHandler { |
| 73 | fn drop(&mut self) { |
| 74 | // SAFETY: restores the default disposition for a known signal. |
| 75 | unsafe { libc::signal(self.0.number(), libc::SIG_DFL) }; |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | /// Installed signal notification stream. |
| 80 | pub struct Signals { |
| 81 | /// Handlers that uninstall themselves on drop. |
| 82 | installed: Vec<InstalledHandler>, |
| 83 | /// Signal receiver. |
| 84 | receiver: mpsc::Receiver<Signal>, |
| 85 | /// Pipe write end kept alive until signal handlers are uninstalled. |
| 86 | _write_fd: OwnedFd, |
| 87 | } |
| 88 | |
| 89 | impl Signals { |
| 90 | /// Installs signal handlers and returns a typed notification stream. |
| 91 | pub fn install(signals: &[Signal]) -> io::Result<Self> { |
| 92 | // Mutex poison only happens if a previous `install` panicked mid-setup |
| 93 | // (e.g. OOM in `thread::spawn`); fall through to the same exclusivity |
| 94 | // check rather than surfacing a separate error. |
| 95 | let mut guard = INSTALLED.lock().unwrap_or_else(|e| e.into_inner()); |
| 96 | if *guard { |
| 97 | return Err(io::Error::new( |
| 98 | io::ErrorKind::AlreadyExists, |
| 99 | "signal handling is already installed", |
| 100 | )); |
| 101 | } |
| 102 | let (read_fd, write_fd) = pipe()?; |
| 103 | set_close_on_exec(read_fd.as_raw_fd())?; |
| 104 | set_close_on_exec(write_fd.as_raw_fd())?; |
| 105 | set_nonblocking(write_fd.as_raw_fd())?; |
| 106 | |
| 107 | WRITE_FD.store(write_fd.as_raw_fd(), Ordering::SeqCst); |
| 108 | let installed = signals |
| 109 | .iter() |
| 110 | .copied() |
| 111 | .map(Signal::install_handler) |
| 112 | .collect::<io::Result<Vec<_>>>() |
| 113 | .inspect_err(|_| WRITE_FD.store(NO_FD, Ordering::SeqCst))?; |
| 114 | |
| 115 | let (tx, receiver) = mpsc::channel(); |
| 116 | thread::spawn(move || read_signals(read_fd, tx)); |
| 117 | *guard = true; |
| 118 | |
| 119 | Ok(Self { |
| 120 | installed, |
| 121 | _write_fd: write_fd, |
| 122 | receiver, |
| 123 | }) |
| 124 | } |
| 125 | |
| 126 | /// Receives the next signal notification. |
| 127 | pub fn recv(&self) -> Result<Signal, mpsc::RecvError> { |
| 128 | self.receiver.recv() |
| 129 | } |
| 130 | |
| 131 | /// Receives the next signal notification before the timeout expires. |
| 132 | pub fn recv_timeout( |
| 133 | &self, |
| 134 | timeout: std::time::Duration, |
| 135 | ) -> Result<Signal, mpsc::RecvTimeoutError> { |
| 136 | self.receiver.recv_timeout(timeout) |
| 137 | } |
| 138 | } |
| 139 | |
| 140 | impl Drop for Signals { |
| 141 | fn drop(&mut self) { |
| 142 | WRITE_FD.store(NO_FD, Ordering::SeqCst); |
| 143 | // Each `InstalledHandler` restores the default disposition on drop. |
| 144 | self.installed.clear(); |
| 145 | if let Ok(mut installed) = INSTALLED.lock() { |
| 146 | *installed = false; |
| 147 | } |
| 148 | } |
| 149 | } |
| 150 | |
| 151 | /// Handles an OS signal. |
| 152 | extern "C" fn handle_signal(signal: libc::c_int) { |
| 153 | // SAFETY: `errno_location` returns the thread-local errno pointer for this |
| 154 | // platform. |
| 155 | let location = unsafe { errno_location() }; |
| 156 | // SAFETY: the pointer is valid for reading and writing the current thread's errno. |
| 157 | let errno = unsafe { *location }; |
| 158 | |
| 159 | let fd = WRITE_FD.load(Ordering::Relaxed); |
| 160 | if fd != NO_FD { |
| 161 | let byte = [signal as u8]; |
| 162 | // SAFETY: `write` is async-signal-safe, and the byte buffer is valid for |
| 163 | // the duration of the call. |
| 164 | unsafe { |
| 165 | let _ = libc::write(fd, byte.as_ptr().cast(), byte.len()); |
| 166 | } |
| 167 | } |
| 168 | // SAFETY: the pointer is valid for reading and writing the current thread's errno. |
| 169 | unsafe { |
| 170 | *location = errno; |
| 171 | } |
| 172 | } |
| 173 | |
| 174 | /// Platform accessor for this thread's `errno` storage. |
| 175 | #[cfg(any(target_os = "linux", target_os = "android"))] |
| 176 | use libc::__errno_location as errno_location; |
| 177 | |
| 178 | /// Platform accessor for this thread's `errno` storage. |
| 179 | #[cfg(any( |
| 180 | target_os = "macos", |
| 181 | target_os = "ios", |
| 182 | target_os = "freebsd", |
| 183 | target_os = "netbsd", |
| 184 | target_os = "openbsd", |
| 185 | target_os = "dragonfly" |
| 186 | ))] |
| 187 | use libc::__error as errno_location; |
| 188 | |
| 189 | /// Reads signal bytes and forwards typed notifications. |
| 190 | fn read_signals(read_fd: OwnedFd, tx: mpsc::Sender<Signal>) { |
| 191 | let mut file = File::from(read_fd); |
| 192 | let mut bytes = [0_u8; 128]; |
| 193 | |
| 194 | loop { |
| 195 | let len = match file.read(&mut bytes) { |
| 196 | Ok(0) => break, |
| 197 | Ok(n) => n, |
| 198 | Err(error) if error.kind() == io::ErrorKind::Interrupted => continue, |
| 199 | Err(_) => break, |
| 200 | }; |
| 201 | for &byte in &bytes[..len] { |
| 202 | let Some(signal) = Signal::from_number(i32::from(byte)) else { |
| 203 | continue; |
| 204 | }; |
| 205 | if tx.send(signal).is_err() { |
| 206 | return; |
| 207 | } |
| 208 | } |
| 209 | } |
| 210 | } |
| 211 | |
| 212 | /// Creates a pipe. |
| 213 | fn pipe() -> io::Result<(OwnedFd, OwnedFd)> { |
| 214 | let mut fds = [NO_FD; 2]; |
| 215 | // SAFETY: `fds` points to two file descriptor slots for libc to initialize. |
| 216 | if unsafe { libc::pipe(fds.as_mut_ptr()) } == -1 { |
| 217 | Err(io::Error::last_os_error()) |
| 218 | } else { |
| 219 | // SAFETY: successful `pipe` initializes both file descriptors, and |
| 220 | // `OwnedFd` takes responsibility for closing them. |
| 221 | unsafe { Ok((OwnedFd::from_raw_fd(fds[0]), OwnedFd::from_raw_fd(fds[1]))) } |
| 222 | } |
| 223 | } |
| 224 | |
| 225 | /// Sets `FD_CLOEXEC` on a file descriptor. |
| 226 | /// |
| 227 | /// `FD_CLOEXEC` is the only fd-level flag POSIX defines, so a plain `F_SETFD` |
| 228 | /// is enough — no read-modify-write needed. |
| 229 | fn set_close_on_exec(fd: RawFd) -> io::Result<()> { |
| 230 | // SAFETY: `F_SETFD` with a known integer flag value. |
| 231 | if unsafe { libc::fcntl(fd, libc::F_SETFD, libc::FD_CLOEXEC) } == -1 { |
| 232 | return Err(io::Error::last_os_error()); |
| 233 | } |
| 234 | Ok(()) |
| 235 | } |
| 236 | |
| 237 | /// Adds `O_NONBLOCK` to a file descriptor's status flags. |
| 238 | fn set_nonblocking(fd: RawFd) -> io::Result<()> { |
| 239 | // SAFETY: `F_GETFL` takes no third argument; `F_SETFL` takes the flag bitmask. |
| 240 | let flags = unsafe { libc::fcntl(fd, libc::F_GETFL) }; |
| 241 | if flags == -1 || unsafe { libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK) } == -1 { |
| 242 | return Err(io::Error::last_os_error()); |
| 243 | } |
| 244 | Ok(()) |
| 245 | } |
| 246 | |
| 247 | #[cfg(test)] |
| 248 | mod tests { |
| 249 | use std::sync::Mutex; |
| 250 | use std::time::Duration; |
| 251 | |
| 252 | use super::*; |
| 253 | |
| 254 | static TEST_LOCK: Mutex<()> = Mutex::new(()); |
| 255 | |
| 256 | #[test] |
| 257 | fn signal_channel_receives_window_change() { |
| 258 | let _guard = TEST_LOCK.lock().unwrap(); |
| 259 | let signals = Signals::install(&[Signal::WindowChanged]).unwrap(); |
| 260 | |
| 261 | // SAFETY: raising SIGWINCH for the current process exercises the handler |
| 262 | // installed by this test. |
| 263 | assert_eq!(unsafe { libc::raise(libc::SIGWINCH) }, 0); |
| 264 | assert_eq!( |
| 265 | signals.recv_timeout(Duration::from_secs(1)).unwrap(), |
| 266 | Signal::WindowChanged |
| 267 | ); |
| 268 | } |
| 269 | |
| 270 | #[test] |
| 271 | fn signal_registration_is_exclusive_until_dropped() { |
| 272 | let _guard = TEST_LOCK.lock().unwrap(); |
| 273 | let signals = Signals::install(&[Signal::WindowChanged]).unwrap(); |
| 274 | |
| 275 | let Err(error) = Signals::install(&[Signal::WindowChanged]) else { |
| 276 | panic!("second signal install should fail"); |
| 277 | }; |
| 278 | assert_eq!(error.kind(), io::ErrorKind::AlreadyExists); |
| 279 | drop(signals); |
| 280 | |
| 281 | let _signals = Signals::install(&[Signal::WindowChanged]).unwrap(); |
| 282 | } |
| 283 | } |