use core::cell::UnsafeCell;
use core::ffi::{c_int, c_void};
use core::mem::ManuallyDrop;
use core::sync::atomic::Ordering::SeqCst;
use core::sync::atomic::{AtomicBool, AtomicI32, AtomicU8, AtomicU32};
use core::time::Duration;
use crate::process::Wake;
use crate::sys::{cvt, errno, last_error};
use crate::{AsHandle, BorrowedHandle, ErrorKind, OwnedHandle, Result};
pub(crate) const HANGUP: i32 = 1;
pub(crate) const INTERRUPT: i32 = 2;
pub(crate) const TERMINATE: i32 = 15;
const SIGILL: i32 = 4;
const SIGTRAP: i32 = 5;
const SIGFPE: i32 = 8;
const SIGKILL: i32 = 9;
const SIGBUS: i32 = 10;
const SIGSEGV: i32 = 11;
const SIGSYS: i32 = 12;
const SIGURG: i32 = 16;
const SIGSTOP: i32 = 17;
const SIGCONT: i32 = 19;
const SIGCHLD: i32 = 20;
const SIGIO: i32 = 23;
const SIGWINCH: i32 = 28;
const SIGINFO: i32 = 29;
const SIGNALS: usize = 31;
const SIG_DFL: usize = 0;
const SIG_IGN: usize = 1;
const SA_ONSTACK: c_int = 0x0001;
const SA_RESTART: c_int = 0x0002;
#[repr(C)]
#[derive(Clone, Copy)]
struct Action {
handler: usize,
mask: u32,
flags: c_int,
}
impl Action {
const fn new(handler: usize, flags: c_int) -> Self {
Self {
handler,
mask: 0,
flags,
}
}
}
#[repr(C)]
struct PollFd {
fd: c_int,
events: i16,
revents: i16,
}
const POLLIN: i16 = 1;
unsafe extern "C" {
#[link_name = "sigaction"]
fn c_sigaction(signal: c_int, new: *const Action, old: *mut Action) -> c_int;
fn __error() -> *mut c_int;
fn write(fd: c_int, buf: *const c_void, len: usize) -> isize;
fn read(fd: c_int, buf: *mut c_void, len: usize) -> isize;
fn poll(fds: *mut PollFd, count: u32, timeout: c_int) -> c_int;
fn sched_yield() -> c_int;
fn raise(signal: c_int) -> c_int;
}
fn sigaction(signal: i32, new: Option<&Action>, old: Option<&mut Action>) -> Result<()> {
let new = new.map_or(core::ptr::null(), core::ptr::from_ref);
let old = old.map_or(core::ptr::null_mut(), core::ptr::from_mut);
cvt(unsafe { c_sigaction(signal, new, old) }).map(drop)
}
struct Slot {
state: AtomicU8,
wake: AtomicI32,
pending: AtomicBool,
waking: AtomicU32,
previous: UnsafeCell<Action>,
}
const FREE: u8 = 0;
const OWNED: u8 = 1;
const HANDLER: u8 = 2;
unsafe impl Sync for Slot {}
fn discards(signal: i32, action: &Action) -> bool {
action.handler == SIG_IGN
|| (action.handler == SIG_DFL
&& matches!(
signal,
SIGURG | SIGCONT | SIGCHLD | SIGIO | SIGWINCH | SIGINFO
))
}
static SLOTS: [Slot; SIGNALS + 1] = [const {
Slot {
state: AtomicU8::new(FREE),
wake: AtomicI32::new(-1),
pending: AtomicBool::new(false),
waking: AtomicU32::new(0),
previous: UnsafeCell::new(Action::new(SIG_DFL, 0)),
}
}; SIGNALS + 1];
static ACTIVE: AtomicU32 = AtomicU32::new(0);
unsafe extern "C" fn handler(signal: c_int) {
ACTIVE.fetch_add(1, SeqCst);
if let Some(slot) = SLOTS.get(signal as usize) {
let fd = slot.wake.load(SeqCst);
if fd >= 0 {
slot.waking.fetch_add(1, SeqCst);
slot.pending.store(true, SeqCst);
let byte = 0u8;
unsafe {
let errno = __error();
let saved = *errno;
let _ = write(fd, (&raw const byte).cast(), 1);
*errno = saved;
}
slot.waking.fetch_sub(1, SeqCst);
} else if slot
.state
.compare_exchange(FREE, HANDLER, SeqCst, SeqCst)
.is_ok()
{
unsafe {
let previous = &*slot.previous.get();
if !discards(signal, previous) {
let errno = __error();
let saved = *errno;
let mut current = Action::new(SIG_DFL, 0);
if c_sigaction(signal, core::ptr::null(), &raw mut current) == 0
&& current.handler == handler as *const () as usize
&& c_sigaction(signal, previous, core::ptr::null_mut()) == 0
{
let _ = raise(signal);
}
*errno = saved;
}
}
slot.state.store(FREE, SeqCst);
}
}
ACTIVE.fetch_sub(1, SeqCst);
}
fn handlers_done() -> bool {
for round in 0..2000 {
if ACTIVE.load(SeqCst) == 0 {
return true;
}
if round < 1000 {
unsafe { sched_yield() };
} else {
let _ = crate::sys::time::sleep(Duration::from_micros(100));
}
}
false
}
fn claim(signal: i32) -> Result<&'static Slot> {
if signal < 1 {
return Err(ErrorKind::InvalidInput.into());
}
let slot = SLOTS.get(signal as usize).ok_or(ErrorKind::InvalidInput)?;
loop {
match slot.state.compare_exchange(FREE, OWNED, SeqCst, SeqCst) {
Ok(_) => return Ok(slot),
Err(HANDLER) => core::hint::spin_loop(),
Err(_) => return Err(ErrorKind::ResourceBusy.into()),
}
}
}
fn handler_action() -> Action {
let mut action = Action::new(handler as *const () as usize, SA_RESTART | SA_ONSTACK);
action.mask = u32::MAX;
action
}
pub(crate) fn set_disposition(signal: i32, ignore: bool) -> Result<()> {
if matches!(signal, SIGKILL | SIGSTOP) {
return Err(ErrorKind::InvalidInput.into());
}
let slot = claim(signal)?;
let action = Action::new(if ignore { SIG_IGN } else { SIG_DFL }, 0);
let result = (|| {
let mut current = Action::new(SIG_DFL, 0);
sigaction(signal, None, Some(&mut current))?;
let caught = current.handler != SIG_DFL && current.handler != SIG_IGN;
if caught && discards(signal, &action) {
sigaction(signal, Some(&handler_action()), None)
} else {
sigaction(signal, Some(&action), None)
}
})();
if result.is_ok() {
unsafe { *slot.previous.get() = action };
}
slot.state.store(FREE, SeqCst);
result
}
pub(crate) struct Signals {
read: ManuallyDrop<OwnedHandle>,
write: ManuallyDrop<OwnedHandle>,
set: u32,
}
impl Signals {
pub(crate) fn new(signals: &[i32]) -> Result<Self> {
let (read, write) = crate::sys::io::pipe()?;
crate::sys::io::set_nonblocking(read.as_handle(), true)?;
crate::sys::io::set_nonblocking(write.as_handle(), true)?;
let fd = write.as_raw();
let mut this = Self {
read: ManuallyDrop::new(read),
write: ManuallyDrop::new(write),
set: 0,
};
let action = handler_action();
for &signal in signals {
if matches!(
signal,
SIGKILL | SIGSTOP | SIGILL | SIGTRAP | SIGBUS | SIGFPE | SIGSEGV | SIGSYS
) {
return Err(ErrorKind::InvalidInput.into());
}
if this.contains(signal) {
continue;
}
let slot = claim(signal)?;
slot.pending.store(false, SeqCst);
slot.wake.store(fd, SeqCst);
this.set |= 1 << (signal - 1);
let mut old = Action::new(SIG_DFL, 0);
sigaction(signal, Some(&action), Some(&mut old))?;
if old.handler != action.handler {
unsafe { *slot.previous.get() = old };
}
}
Ok(this)
}
fn contains(&self, signal: i32) -> bool {
(1..=SIGNALS as i32).contains(&signal) && self.set & 1 << (signal - 1) != 0
}
fn slots(&self) -> impl Iterator<Item = (i32, &'static Slot)> {
let set = self.set;
(1..=SIGNALS as i32)
.filter(move |signal| set & 1 << (signal - 1) != 0)
.map(|signal| (signal, &SLOTS[signal as usize]))
}
fn take(&self) -> Option<i32> {
self.slots()
.find(|(_, slot)| slot.pending.swap(false, SeqCst))
.map(|(signal, _)| signal)
}
fn settle(&self) {
for _ in 0..1000 {
if self.slots().all(|(_, slot)| slot.waking.load(SeqCst) == 0) {
return;
}
unsafe { sched_yield() };
}
}
pub(crate) fn try_next(&self) -> Option<i32> {
if let Some(signal) = self.take() {
return Some(signal);
}
self.settle();
let mut buf = [0u8; 64];
loop {
let n = unsafe { read(self.read.as_raw(), buf.as_mut_ptr().cast(), buf.len()) };
if n < buf.len() as isize {
break;
}
}
self.take()
}
pub(crate) fn wait_once(&self, timeout: Option<Duration>) -> Result<Wake> {
let mut fd = PollFd {
fd: self.read.as_raw(),
events: POLLIN,
revents: 0,
};
let timeout = match timeout {
None => -1,
Some(timeout) => {
let millis = timeout.as_nanos().div_ceil(1_000_000);
c_int::try_from(millis).unwrap_or(c_int::MAX)
}
};
match unsafe { poll(&raw mut fd, 1, timeout) } {
0 => Ok(Wake::TimedOut),
-1 => {
let error = last_error();
if error.raw_os_error() == errno::EINTR {
Ok(Wake::Interrupted)
} else {
Err(error)
}
}
_ => Ok(Wake::Ready),
}
}
pub(crate) fn handle(&self) -> BorrowedHandle<'_> {
self.read.as_handle()
}
}
impl Drop for Signals {
fn drop(&mut self) {
let ours = handler as *const () as usize;
for (signal, slot) in self.slots() {
let mut current = Action::new(SIG_DFL, 0);
let previous = unsafe { &*slot.previous.get() };
if !discards(signal, previous)
&& sigaction(signal, None, Some(&mut current)).is_ok()
&& current.handler == ours
{
let _ = sigaction(signal, Some(previous), None);
}
slot.wake.store(-1, SeqCst);
}
if handlers_done() {
unsafe {
ManuallyDrop::drop(&mut self.read);
ManuallyDrop::drop(&mut self.write);
}
}
for (_, slot) in self.slots() {
slot.pending.store(false, SeqCst);
slot.state.store(FREE, SeqCst);
}
}
}
impl core::fmt::Debug for Signals {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("Signals")
.field("read", &*self.read)
.field("write", &*self.write)
.field("set", &format_args!("{:#x}", self.set))
.finish()
}
}