subc-os 0.1.61

Operating-system primitives for the subc daemon that need unsafe code, behind a safe API: per-process identity, signalling, memory and CPU usage, and the launch-nonce descriptor handoff.
Documentation
use std::{
    ffi::c_void,
    io,
    ptr::{null_mut, NonNull},
    sync::Mutex,
    task::{Context, Poll, Waker},
};

use windows_sys::Win32::{
    Foundation::{HANDLE, INVALID_HANDLE_VALUE},
    System::Threading::{
        RegisterWaitForSingleObject, UnregisterWaitEx, INFINITE, WT_EXECUTEONLYONCE,
    },
};

#[derive(Default, Debug)]
struct State {
    fired: bool,
    waker: Option<Waker>,
}

#[derive(Debug)]
pub(super) struct ProcessWait {
    registration: HANDLE,
    state: NonNull<Mutex<State>>,
}

// SAFETY: A registration can be unregistered from any thread and its
// callback accesses only the shared mutex-protected state.
unsafe impl Send for ProcessWait {}
// SAFETY: The handle is used only by the owner on teardown; state is a mutex.
unsafe impl Sync for ProcessWait {}

impl ProcessWait {
    pub(super) fn new(process: HANDLE) -> io::Result<Self> {
        let state = NonNull::from(Box::leak(Box::<Mutex<State>>::default()));
        let mut registration = null_mut();
        // SAFETY: The child retains the process handle until this registration
        // is dropped. Box keeps the callback address stable even if it runs
        // before RegisterWaitForSingleObject returns.
        if unsafe {
            RegisterWaitForSingleObject(
                &mut registration,
                process,
                Some(notify),
                state.as_ptr().cast(),
                INFINITE,
                WT_EXECUTEONLYONCE,
            )
        } == 0
        {
            let error = io::Error::last_os_error();
            // SAFETY: Registration failed so it does not borrow the allocation.
            drop(unsafe { Box::from_raw(state.as_ptr()) });
            return Err(error);
        }
        Ok(Self {
            registration,
            state,
        })
    }

    pub(super) fn poll(&self, cx: &Context<'_>) -> Poll<()> {
        // SAFETY: self owns the allocation; the callback only borrows it.
        let mut state = unsafe { self.state.as_ref() }
            .lock()
            .unwrap_or_else(|p| p.into_inner());
        if state.fired {
            Poll::Ready(())
        } else {
            match &mut state.waker {
                Some(waker) => waker.clone_from(cx.waker()),
                slot => *slot = Some(cx.waker().clone()),
            }
            Poll::Pending
        }
    }
}

impl Drop for ProcessWait {
    fn drop(&mut self) {
        // SAFETY: INVALID_HANDLE_VALUE joins any outstanding callback before
        // returning. If teardown fails, keep the callback's storage alive.
        if unsafe { UnregisterWaitEx(self.registration, INVALID_HANDLE_VALUE) } != 0 {
            // SAFETY: No callback can still be using the original allocation.
            drop(unsafe { Box::from_raw(self.state.as_ptr()) });
        }
    }
}

unsafe extern "system" fn notify(state: *mut c_void, _: bool) {
    // SAFETY: The registration borrows this allocation until unregistered.
    let state = unsafe { &*state.cast::<Mutex<State>>() };
    let waker = {
        let mut state = state.lock().unwrap_or_else(|p| p.into_inner());
        state.fired = true;
        state.waker.take()
    };
    if let Some(waker) = waker {
        waker.wake();
    }
}