use core::cell::UnsafeCell;
use core::ffi::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::time::Timespec;
use crate::sys::{errno, syscall};
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 SIGBUS: i32 = 7;
const SIGFPE: i32 = 8;
const SIGKILL: i32 = 9;
const SIGSEGV: i32 = 11;
const SIGSTOP: i32 = 19;
const SIGSYS: i32 = 31;
const SIGNALS: usize = 64;
const LIBC_FIRST: i32 = 32;
const LIBC_LAST: i32 = 34;
const SIG_DFL: usize = 0;
const SIG_IGN: usize = 1;
const SA_SIGINFO: usize = 0x0000_0004;
#[cfg(any(target_arch = "x86", target_arch = "x86_64", target_arch = "arm"))]
const SA_RESTORER: usize = 0x0400_0000;
const SA_ONSTACK: usize = 0x0800_0000;
const SA_RESTART: usize = 0x1000_0000;
const SIGSET_SIZE: usize = 8;
#[repr(C)]
#[derive(Clone, Copy)]
struct Action {
handler: usize,
flags: usize,
#[cfg(not(any(target_arch = "riscv32", target_arch = "riscv64")))]
restorer: usize,
mask: [usize; SIGSET_SIZE / size_of::<usize>()],
}
impl Action {
const fn new(handler: usize, flags: usize) -> Self {
Self {
handler,
flags,
#[cfg(not(any(target_arch = "riscv32", target_arch = "riscv64")))]
restorer: 0,
mask: [0; SIGSET_SIZE / size_of::<usize>()],
}
}
}
#[cfg(target_arch = "x86_64")]
#[unsafe(naked)]
unsafe extern "C" fn restorer() -> ! {
core::arch::naked_asm!(
"mov eax, {rt_sigreturn}",
"syscall",
"ud2",
rt_sigreturn = const crate::sys::nr::RT_SIGRETURN,
)
}
#[cfg(target_arch = "x86")]
#[unsafe(naked)]
unsafe extern "C" fn restorer() -> ! {
core::arch::naked_asm!(
"mov eax, {rt_sigreturn}",
"int 0x80",
"ud2",
rt_sigreturn = const crate::sys::nr::RT_SIGRETURN,
)
}
#[cfg(target_arch = "arm")]
#[unsafe(naked)]
unsafe extern "C" fn restorer() -> ! {
core::arch::naked_asm!(
"mov r7, #{rt_sigreturn}",
"svc 0",
"udf #0",
rt_sigreturn = const crate::sys::nr::RT_SIGRETURN,
)
}
fn handler_action() -> Action {
#[allow(unused_mut)]
let mut action = Action::new(
handler as *const () as usize,
SA_SIGINFO | SA_RESTART | SA_ONSTACK,
);
action.mask = [usize::MAX; SIGSET_SIZE / size_of::<usize>()];
#[cfg(any(target_arch = "x86", target_arch = "x86_64", target_arch = "arm"))]
{
action.flags |= SA_RESTORER;
action.restorer = restorer as *const () as usize;
}
action
}
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);
unsafe { syscall!(RT_SIGACTION, signal, new, old, SIGSET_SIZE) }.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 {}
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: i32, _info: *mut c_void, _context: *mut c_void) {
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 one: u64 = 1;
let _ = unsafe { syscall!(WRITE, fd, &raw const one, size_of::<u64>()) };
slot.waking.fetch_sub(1, SeqCst);
} else if slot
.state
.compare_exchange(FREE, HANDLER, SeqCst, SeqCst)
.is_ok()
{
let mut current = Action::new(SIG_DFL, 0);
if sigaction(signal, None, Some(&mut current)).is_ok()
&& current.handler == handler as *const () as usize
{
unsafe {
if sigaction(signal, Some(&*slot.previous.get()), None).is_ok()
&& let (Ok(pid), Ok(tid)) = (syscall!(GETPID), syscall!(GETTID))
{
let _ = syscall!(TGKILL, pid, tid, signal);
}
}
}
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 {
let _ = unsafe { syscall!(SCHED_YIELD) };
} else {
let _ = crate::sys::time::sleep(Duration::from_micros(100));
}
}
false
}
fn claim(signal: i32) -> Result<&'static Slot> {
if signal < 1 || (LIBC_FIRST..=LIBC_LAST).contains(&signal) {
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()),
}
}
}
pub(crate) fn set_disposition(signal: i32, ignore: bool) -> Result<()> {
let slot = claim(signal)?;
let action = Action::new(if ignore { SIG_IGN } else { SIG_DFL }, 0);
let result = sigaction(signal, Some(&action), None);
if result.is_ok() {
unsafe { *slot.previous.get() = action };
}
slot.state.store(FREE, SeqCst);
result
}
#[repr(C)]
struct PollFd {
fd: i32,
events: i16,
revents: i16,
}
const POLLIN: i16 = 1;
const EFD_CLOEXEC: usize = 0o2000000;
const EFD_NONBLOCK: usize = 0o4000;
pub(crate) struct Signals {
wake: ManuallyDrop<OwnedHandle>,
set: u64,
}
impl Signals {
pub(crate) fn new(signals: &[i32]) -> Result<Self> {
let fd = unsafe { syscall!(EVENTFD2, 0, EFD_CLOEXEC | EFD_NONBLOCK) }? as i32;
let wake = ManuallyDrop::new(unsafe { OwnedHandle::from_raw(fd) });
let mut this = Self { wake, 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;
}
let _ = unsafe { syscall!(SCHED_YIELD) };
}
}
pub(crate) fn try_next(&self) -> Option<i32> {
if let Some(signal) = self.take() {
return Some(signal);
}
self.settle();
let mut count: u64 = 0;
let _ = unsafe { syscall!(READ, self.wake.as_raw(), &raw mut count, size_of::<u64>()) };
self.take()
}
pub(crate) fn wait_once(&self, timeout: Option<Duration>) -> Result<Wake> {
let mut fd = PollFd {
fd: self.wake.as_raw(),
events: POLLIN,
revents: 0,
};
let timeout = timeout.map(Timespec::from_duration);
let timeout = timeout
.as_ref()
.map_or(core::ptr::null(), core::ptr::from_ref);
#[cfg(target_pointer_width = "32")]
let result = unsafe { syscall!(PPOLL_TIME64, &raw mut fd, 1, timeout, 0, SIGSET_SIZE) };
#[cfg(target_pointer_width = "64")]
let result = unsafe { syscall!(PPOLL, &raw mut fd, 1, timeout, 0, SIGSET_SIZE) };
match result {
Ok(0) => Ok(Wake::TimedOut),
Ok(_) => Ok(Wake::Ready),
Err(error) if error.raw_os_error() == errno::EINTR => Ok(Wake::Interrupted),
Err(error) => Err(error),
}
}
pub(crate) fn handle(&self) -> BorrowedHandle<'_> {
self.wake.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);
if sigaction(signal, None, Some(&mut current)).is_ok() && current.handler == ours {
let _ = sigaction(signal, Some(unsafe { &*slot.previous.get() }), None);
}
slot.wake.store(-1, SeqCst);
}
if handlers_done() {
unsafe { ManuallyDrop::drop(&mut self.wake) };
}
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("wake", &*self.wake)
.field("set", &format_args!("{:#x}", self.set))
.finish()
}
}