oscall 0.0.1

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
Documentation
//! Receiving console control events on Windows: `SetConsoleCtrlHandler`.
//!
//! The system runs the handler on a thread it creates for the purpose, so
//! nothing is interrupted and the handler could do anything; it does as
//! little as a Unix signal handler all the same, and wakes the waiters.

use core::sync::atomic::Ordering::SeqCst;
use core::sync::atomic::{AtomicBool, AtomicU32};
use core::time::Duration;

use crate::process::Wake;
use crate::sys::{cvt, dll, sync};
use crate::{ErrorKind, Result};

// The `CTRL_*_EVENT` values.
pub(crate) const INTERRUPT: i32 = 0;
pub(crate) const BREAK: i32 = 1;
pub(crate) const HANGUP: i32 = 2;
pub(crate) const LOGOFF: i32 = 5;
pub(crate) const TERMINATE: i32 = 6;
const EVENTS: usize = 7;

const INFINITE: u32 = u32::MAX;

type Handler = unsafe extern "system" fn(u32) -> i32;

dll!("kernel32.dll" {
    fn SetConsoleCtrlHandler(handler: Option<Handler>, add: i32) -> i32;
    fn GenerateConsoleCtrlEvent(event: u32, group: u32) -> i32;
    fn Sleep(milliseconds: u32);
});

/// What the process knows about one event.
struct Slot {
    /// Whether a `Signals` listens to it.
    owned: AtomicBool,
    /// Whether it happened since it was last asked about.
    pending: AtomicBool,
}

static SLOTS: [Slot; EVENTS] = [const {
    Slot {
        owned: AtomicBool::new(false),
        pending: AtomicBool::new(false),
    }
}; EVENTS];

/// Changes with every event recorded: what the waiters sleep on.
static GENERATION: AtomicU32 = AtomicU32::new(0);

/// Held while slots are taken or released and the handler added or
/// removed: 0 when free.
static LOCK: AtomicU32 = AtomicU32::new(0);
/// The number of `Signals` that exist, under `LOCK`. The handler is in the
/// process's list while it is not zero.
static SUBSCRIPTIONS: AtomicU32 = AtomicU32::new(0);

struct Guard;

fn lock() -> Guard {
    while LOCK.swap(1, SeqCst) != 0 {
        let _ = sync::wait(&LOCK, 1, None);
    }
    Guard
}

impl Drop for Guard {
    fn drop(&mut self) {
        LOCK.store(0, SeqCst);
        sync::wake(&LOCK, true);
    }
}

/// The handler: on its own thread, one event at a time.
unsafe extern "system" fn handler(event: u32) -> i32 {
    let Some(slot) = SLOTS.get(event as usize) else {
        return 0;
    };
    if !slot.owned.load(SeqCst) {
        // Not ours to answer: the next handler of the list, and in the
        // end the system's, which terminates the process.
        return 0;
    }
    slot.pending.store(true, SeqCst);
    GENERATION.fetch_add(1, SeqCst);
    sync::wake(&GENERATION, true);
    // The pollers the subscription is registered with.
    #[cfg(feature = "alloc")]
    crate::sys::event::signal_delivered(event);
    match event as i32 {
        // The process goes on.
        INTERRUPT | BREAK => 1,
        // The system terminates the process when this function returns,
        // whatever it returns, and after a delay of its own if it does
        // not: the program has that long to do what it must and exit.
        _ => loop {
            // SAFETY: no memory is involved.
            unsafe { Sleep(INFINITE) };
        },
    }
}

pub(crate) fn send_ctrl_event(event: i32, group: u32) -> Result<()> {
    if !matches!(event, INTERRUPT | BREAK) {
        return Err(ErrorKind::InvalidInput.into());
    }
    // SAFETY: no memory is involved.
    cvt(unsafe { GenerateConsoleCtrlEvent(event as u32, group) })
}

pub(crate) fn set_ctrl_c_ignored(ignored: bool) -> Result<()> {
    // SAFETY: with no handler, the call sets or clears the attribute of
    // the process that makes it ignore Ctrl-C.
    cvt(unsafe { SetConsoleCtrlHandler(None, ignored as i32) })
}

#[derive(Debug)]
pub(crate) struct Signals {
    /// Bit `n` for event `n`.
    set: u8,
}

impl Signals {
    pub(crate) fn new(events: &[i32]) -> Result<Self> {
        let _guard = lock();
        let mut set = 0u8;
        let release = |set: u8| {
            for (event, slot) in SLOTS.iter().enumerate() {
                if set & 1 << event != 0 {
                    slot.pending.store(false, SeqCst);
                    slot.owned.store(false, SeqCst);
                }
            }
        };
        for &event in events {
            if !matches!(event, INTERRUPT | BREAK | HANGUP | LOGOFF | TERMINATE) {
                release(set);
                return Err(ErrorKind::InvalidInput.into());
            }
            if set & 1 << event != 0 {
                continue;
            }
            let slot = &SLOTS[event as usize];
            if slot.owned.swap(true, SeqCst) {
                release(set);
                return Err(ErrorKind::ResourceBusy.into());
            }
            slot.pending.store(false, SeqCst);
            set |= 1 << event;
        }
        if SUBSCRIPTIONS.load(SeqCst) == 0 {
            // SAFETY: the handler is a function of this program, which
            // stays valid for as long as it is in the list.
            if let Err(error) = cvt(unsafe { SetConsoleCtrlHandler(Some(handler), 1) }) {
                release(set);
                return Err(error);
            }
        }
        SUBSCRIPTIONS.fetch_add(1, SeqCst);
        Ok(Self { set })
    }

    /// The slots of the events of the set.
    fn slots(&self) -> impl Iterator<Item = (i32, &'static Slot)> {
        let set = self.set;
        SLOTS
            .iter()
            .enumerate()
            .filter(move |(event, _)| set & 1 << event != 0)
            .map(|(event, slot)| (event as i32, slot))
    }

    /// The events of the set, bit `n` for event `n`: what tells this
    /// subscription from the others that exist.
    #[cfg(feature = "alloc")]
    pub(crate) fn set(&self) -> u8 {
        self.set
    }

    /// Whether an event of the set is waiting to be taken.
    #[cfg(feature = "alloc")]
    pub(crate) fn is_pending(&self) -> bool {
        self.slots().any(|(_, slot)| slot.pending.load(SeqCst))
    }

    pub(crate) fn try_next(&self) -> Option<i32> {
        self.slots()
            .find(|(_, slot)| slot.pending.swap(false, SeqCst))
            .map(|(event, _)| event)
    }

    pub(crate) fn wait_once(&self, timeout: Option<Duration>) -> Result<Wake> {
        // Read before the flags are: an event recorded after this changes
        // the value, and the wait does not sleep.
        let generation = GENERATION.load(SeqCst);
        if self.slots().any(|(_, slot)| slot.pending.load(SeqCst)) {
            return Ok(Wake::Ready);
        }
        Ok(if sync::wait(&GENERATION, generation, timeout)? {
            Wake::Ready
        } else {
            Wake::TimedOut
        })
    }
}

impl Drop for Signals {
    fn drop(&mut self) {
        let _guard = lock();
        // No poller is told of this subscription's events any more, nor
        // of those of the next one to have them.
        #[cfg(feature = "alloc")]
        crate::sys::event::signals_dropped(self.set);
        for (_, slot) in self.slots() {
            slot.owned.store(false, SeqCst);
            slot.pending.store(false, SeqCst);
        }
        if SUBSCRIPTIONS.fetch_sub(1, SeqCst) == 1 {
            // SAFETY: removes the handler added by the first subscription.
            unsafe { SetConsoleCtrlHandler(Some(handler), 0) };
        }
    }
}