use super::check;
use std::ffi::c_int;
use std::io;
use std::sync::atomic::{AtomicI32, AtomicU32, AtomicUsize, Ordering};
use std::time::{Duration, Instant};
pub(crate) mod signo {
use std::ffi::c_int;
pub(crate) const SIGINT: c_int = 2;
pub(crate) const SIGTERM: c_int = 15;
pub(crate) const SIGWINCH: c_int = 28;
#[cfg(target_os = "linux")]
pub(crate) const SIGTSTP: c_int = 20;
#[cfg(any(target_os = "macos", target_os = "freebsd"))]
pub(crate) const SIGTSTP: c_int = 18;
#[cfg(target_os = "linux")]
pub(crate) const SIGCONT: c_int = 18;
#[cfg(any(target_os = "macos", target_os = "freebsd"))]
pub(crate) const SIGCONT: c_int = 19;
}
const WATCHED: [c_int; 5] = [
signo::SIGINT,
signo::SIGTERM,
signo::SIGWINCH,
signo::SIGTSTP,
signo::SIGCONT,
];
const STOP_WAIT: Duration = Duration::from_millis(500);
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;
fn kill(pid: c_int, signum: c_int) -> c_int;
#[cfg(target_os = "linux")]
#[link_name = "__errno_location"]
fn errno_location() -> *mut c_int;
#[cfg(any(target_os = "macos", target_os = "freebsd"))]
#[link_name = "__error"]
fn errno_location() -> *mut c_int;
}
static SIGNAL_FD: AtomicI32 = AtomicI32::new(-1);
static CONTINUED: AtomicU32 = AtomicU32::new(0);
static PREVIOUS: [AtomicUsize; WATCHED.len()] =
[const { AtomicUsize::new(SIG_DFL) }; WATCHED.len()];
fn handler() -> usize {
let on: extern "C" fn(c_int) = on_signal;
on as usize
}
extern "C" fn on_signal(signum: c_int) {
let errno = unsafe { errno_location() };
let saved = unsafe { errno.read() };
let fd = SIGNAL_FD.load(Ordering::Relaxed);
if fd >= 0 {
let byte = u8::try_from(signum).unwrap_or(0);
let _ = unsafe { write(fd, (&raw const byte).cast(), 1) };
}
if signum == signo::SIGCONT {
let _ = CONTINUED.fetch_add(1, Ordering::SeqCst);
}
unsafe { errno.write(saved) };
}
pub(crate) fn watch_signals(fd: c_int) -> io::Result<()> {
SIGNAL_FD.store(fd, Ordering::Relaxed);
for (signum, previous) in WATCHED.iter().zip(&PREVIOUS) {
let before = unsafe { signal(*signum, handler()) };
if before == SIG_ERR {
return Err(io::Error::last_os_error());
}
previous.store(before, Ordering::SeqCst);
}
Ok(())
}
pub(crate) fn unwatch_signals() {
for (signum, previous) in WATCHED.iter().zip(&PREVIOUS) {
let before = previous.swap(SIG_DFL, Ordering::SeqCst);
let _ = unsafe { signal(*signum, before) };
}
SIGNAL_FD.store(-1, Ordering::Relaxed);
}
pub(crate) fn default_stop(default: bool) -> io::Result<()> {
let handling = if default { SIG_DFL } else { handler() };
let before = unsafe { signal(signo::SIGTSTP, handling) };
if before == SIG_ERR {
return Err(io::Error::last_os_error());
}
Ok(())
}
pub(crate) fn stop_process_group() -> io::Result<()> {
let before = CONTINUED.load(Ordering::SeqCst);
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::*;
const SIG_IGN: usize = 1;
unsafe extern "C" {
fn raise(signum: c_int) -> c_int;
}
#[test]
#[cfg_attr(miri, ignore)] fn a_signal_reaches_the_pipe_and_leaves_errno_and_the_old_handling() {
let original = unsafe { signal(signo::SIGWINCH, SIG_IGN) };
let pipe = crate::sys::Pipe::new().unwrap();
watch_signals(pipe.write).unwrap();
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);
while crate::sys::write_all_fd(pipe.write, &[0; 4096]).is_ok() {}
unsafe { errno_location().write(42) };
assert_eq!(unsafe { raise(signo::SIGWINCH) }, 0);
assert_eq!(unsafe { errno_location().read() }, 42, "errno kept");
unwatch_signals();
let after = unsafe { signal(signo::SIGWINCH, original) };
assert_eq!(after, SIG_IGN, "the handling before is given back");
}
}