use std::sync::{Arc, Mutex};
use std::thread::JoinHandle;
use std::time::Duration;
use snare_interpose::{SignalOutcome, SignalSource, Signals};
use crate::events::RecordedEvent;
use crate::scope::SimShared;
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Signal {
Interrupt,
Terminate,
Hangup,
Break,
Close,
Logoff,
Shutdown,
}
impl Signal {
pub fn raw(self) -> Option<i32> {
#[cfg(unix)]
{
match self {
Signal::Interrupt => Some(libc::SIGINT),
Signal::Terminate => Some(libc::SIGTERM),
Signal::Hangup => Some(libc::SIGHUP),
_ => None,
}
}
#[cfg(windows)]
{
use windows_sys::Win32::System::Console::{
CTRL_BREAK_EVENT, CTRL_C_EVENT, CTRL_CLOSE_EVENT, CTRL_LOGOFF_EVENT,
CTRL_SHUTDOWN_EVENT,
};
let event = match self {
Signal::Interrupt => CTRL_C_EVENT,
Signal::Break => CTRL_BREAK_EVENT,
Signal::Close => CTRL_CLOSE_EVENT,
Signal::Logoff => CTRL_LOGOFF_EVENT,
Signal::Shutdown => CTRL_SHUTDOWN_EVENT,
_ => return None,
};
Some(event as i32)
}
}
pub fn from_raw(raw: i32) -> Option<Signal> {
[
Signal::Interrupt,
Signal::Terminate,
Signal::Hangup,
Signal::Break,
Signal::Close,
Signal::Logoff,
Signal::Shutdown,
]
.into_iter()
.find(|signal| signal.raw() == Some(raw))
}
}
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SignalDelivery {
Handled,
HandledThenExit,
DefaultAction,
Ignored,
Unavailable,
}
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SignalOrigin {
Sim,
Process,
Real,
}
impl From<SignalOutcome> for SignalDelivery {
fn from(outcome: SignalOutcome) -> Self {
match outcome {
SignalOutcome::Handled => SignalDelivery::Handled,
SignalOutcome::HandledThenExit => SignalDelivery::HandledThenExit,
SignalOutcome::DefaultAction => SignalDelivery::DefaultAction,
SignalOutcome::Ignored => SignalDelivery::Ignored,
}
}
}
impl From<SignalSource> for SignalOrigin {
fn from(source: SignalSource) -> Self {
match source {
SignalSource::Sim => SignalOrigin::Sim,
SignalSource::Process => SignalOrigin::Process,
SignalSource::Real => SignalOrigin::Real,
}
}
}
#[derive(Clone)]
pub struct SignalHandle {
shared: Arc<SimShared>,
}
impl std::fmt::Debug for SignalHandle {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SignalHandle").finish_non_exhaustive()
}
}
impl SignalHandle {
pub(crate) fn new(shared: Arc<SimShared>) -> Self {
SignalHandle { shared }
}
pub fn raise(&self, signal: Signal) -> SignalDelivery {
let Some(raw) = signal.raw() else {
return SignalDelivery::Unavailable;
};
let Some(domain) = self.shared.domain.get().and_then(|d| d.upgrade()) else {
return SignalDelivery::Unavailable;
};
if domain.is_current() {
return deliver(&self.shared, raw, SignalSource::Sim);
}
let slot = Arc::new(Mutex::new(SignalDelivery::Unavailable));
let shared = self.shared.clone();
let out = slot.clone();
let thread = domain.spawn_injected("snare-signal", move || {
let delivery = deliver(&shared, raw, SignalSource::Sim);
snare_interpose::real(|| *out.lock().unwrap() = delivery);
});
match thread {
Ok(thread) => {
let _ = thread.join();
snare_interpose::real(|| *slot.lock().unwrap())
}
Err(_) => SignalDelivery::Unavailable,
}
}
pub fn raise_after(&self, signal: Signal, delay: Duration) -> PendingSignal {
let slot = Arc::new(Mutex::new(None));
let out = slot.clone();
let handle = self.clone();
let body = move || {
std::thread::sleep(delay);
let delivery = handle.raise(signal);
snare_interpose::real(|| *out.lock().unwrap() = Some(delivery));
};
let domain = self.shared.domain.get().and_then(|d| d.upgrade());
let thread = match domain {
Some(domain) if domain.is_current() => snare_interpose::simulated(|| {
std::thread::Builder::new()
.name("snare-signal-timer".into())
.spawn(body)
.ok()
}),
Some(domain) => domain.spawn_injected("snare-signal-timer", body).ok(),
None => None,
};
PendingSignal { thread, slot }
}
}
pub struct PendingSignal {
thread: Option<JoinHandle<()>>,
slot: Arc<Mutex<Option<SignalDelivery>>>,
}
impl std::fmt::Debug for PendingSignal {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("PendingSignal")
.field("started", &self.thread.is_some())
.finish_non_exhaustive()
}
}
impl PendingSignal {
pub fn wait(self) -> SignalDelivery {
if let Some(thread) = self.thread {
let _ = thread.join();
}
snare_interpose::real(|| {
self.slot
.lock()
.unwrap()
.unwrap_or(SignalDelivery::Unavailable)
})
}
}
#[cfg(unix)]
fn deliver(_shared: &Arc<SimShared>, raw: i32, source: SignalSource) -> SignalDelivery {
snare_interpose::deliver_here(raw, source).map_or(SignalDelivery::Unavailable, Into::into)
}
#[cfg(windows)]
fn deliver(shared: &Arc<SimShared>, raw: i32, source: SignalSource) -> SignalDelivery {
console::deliver_and_wait(shared, raw as u32, source)
}
pub(crate) struct SignalTable {
#[cfg(unix)]
actions: Mutex<Actions>,
#[cfg(unix)]
process_handlers: std::sync::atomic::AtomicBool,
#[cfg(windows)]
console: Mutex<console::Console>,
}
impl SignalTable {
pub(crate) fn new() -> Self {
SignalTable {
#[cfg(unix)]
actions: Mutex::new(Actions {
by_signal: [libc::SIGINT, libc::SIGTERM, libc::SIGHUP]
.into_iter()
.map(|sig| (sig, forward::inherited(sig)))
.collect(),
set: std::collections::HashSet::new(),
}),
#[cfg(unix)]
process_handlers: std::sync::atomic::AtomicBool::new(false),
#[cfg(windows)]
console: Mutex::default(),
}
}
}
#[cfg(unix)]
struct Actions {
by_signal: std::collections::HashMap<i32, libc::sigaction>,
set: std::collections::HashSet<i32>,
}
#[cfg(unix)]
type Handlers = std::collections::BTreeMap<i32, libc::sigaction>;
#[cfg(unix)]
static PROCESS_HANDLERS: Mutex<Handlers> = Mutex::new(std::collections::BTreeMap::new());
#[cfg(unix)]
fn process_handlers() -> std::sync::MutexGuard<'static, Handlers> {
PROCESS_HANDLERS.lock().unwrap_or_else(|e| e.into_inner())
}
#[cfg(unix)]
fn is_handler(action: &libc::sigaction) -> bool {
action.sa_sigaction != libc::SIG_DFL && action.sa_sigaction != libc::SIG_IGN
}
#[cfg(unix)]
impl SignalTable {
pub(crate) fn reach_process_handlers(&self, on: bool) {
self.process_handlers
.store(on, std::sync::atomic::Ordering::Relaxed);
}
}
pub(crate) struct SimSignals(pub(crate) Arc<SimShared>);
impl SimSignals {
fn table(&self) -> &SignalTable {
&self.0.signals
}
}
impl Signals for SimSignals {
#[cfg(unix)]
fn sigaction(&self, sig: i32, act: Option<&libc::sigaction>) -> libc::sigaction {
let mut actions = self.table().actions.lock().unwrap();
let previous = actions
.by_signal
.get(&sig)
.copied()
.unwrap_or_else(|| forward::inherited(sig));
if let Some(act) = act {
actions.by_signal.insert(sig, *act);
actions.set.insert(sig);
let mut process = process_handlers();
if is_handler(act) {
process.insert(sig, *act);
} else if process
.get(&sig)
.is_some_and(|installed| installed.sa_sigaction == previous.sa_sigaction)
{
process.remove(&sig);
}
}
previous
}
#[cfg(unix)]
fn take_disposition(&self, sig: i32) -> snare_interpose::Disposition {
use snare_interpose::Disposition;
let mut actions = self.table().actions.lock().unwrap();
if !actions.set.contains(&sig)
&& self
.table()
.process_handlers
.load(std::sync::atomic::Ordering::Relaxed)
&& let Some(installed) = process_handlers().get(&sig).copied()
{
actions.by_signal.insert(sig, installed);
actions.set.insert(sig);
}
let Some(action) = actions.by_signal.get_mut(&sig) else {
return Disposition::Default;
};
match action.sa_sigaction {
libc::SIG_DFL => return Disposition::Default,
libc::SIG_IGN => return Disposition::Ignore,
_ => {}
}
let address = action.sa_sigaction;
let resethand = action.sa_flags & libc::SA_RESETHAND != 0;
let disposition = Disposition::Handler {
address,
siginfo: action.sa_flags & libc::SA_SIGINFO != 0,
nodefer: action.sa_flags & libc::SA_NODEFER != 0
|| (resethand && cfg!(target_os = "linux")),
};
if resethand {
action.sa_sigaction = libc::SIG_DFL;
}
disposition
}
#[cfg(windows)]
fn set_console_ctrl_handler(&self, handler: usize, add: bool) -> Result<(), u32> {
self.table()
.console
.lock()
.unwrap()
.set_handler(handler, add)
}
#[cfg(windows)]
fn console_event(&self, event: u32) {
console::deliver_async(&self.0, event, SignalSource::Process);
}
#[cfg(windows)]
fn crt_signal(&self, sig: i32, handler: usize) -> usize {
self.table()
.console
.lock()
.unwrap()
.crt_signal(sig, handler)
}
#[cfg(windows)]
fn crt_raise(&self, sig: i32) -> i32 {
console::crt_raise(&self.0, sig);
0
}
fn record(&self, raw: i32, source: SignalSource, outcome: SignalOutcome) {
record(&self.0, raw, source, outcome.into());
}
}
fn record(shared: &SimShared, raw: i32, source: SignalSource, delivery: SignalDelivery) {
if let Some(signal) = Signal::from_raw(raw) {
shared.record(RecordedEvent::Signal {
signal,
origin: source.into(),
delivery,
});
}
}
#[cfg(unix)]
pub(crate) mod forward {
use std::collections::HashMap;
use std::sync::atomic::{AtomicI32, Ordering};
use std::sync::{Arc, Mutex};
use snare_interpose::{SignalOutcome, SignalSource};
use crate::scope::SimShared;
const SIGNALS: [libc::c_int; 3] = [libc::SIGINT, libc::SIGTERM, libc::SIGHUP];
#[derive(Default)]
struct Forwarder {
next_id: u64,
sims: Vec<(u64, Arc<SimShared>)>,
originals: HashMap<libc::c_int, libc::sigaction>,
}
static FORWARDER: Mutex<Option<Forwarder>> = Mutex::new(None);
static PIPE_WRITE: AtomicI32 = AtomicI32::new(-1);
static PIPE: std::sync::OnceLock<()> = std::sync::OnceLock::new();
pub(crate) struct Registration(u64);
impl Drop for Registration {
fn drop(&mut self) {
snare_interpose::real(|| {
let mut slot = FORWARDER.lock().unwrap();
let Some(forwarder) = slot.as_mut() else {
return;
};
forwarder.sims.retain(|(id, _)| *id != self.0);
if !forwarder.sims.is_empty() {
return;
}
let forwarder = slot.take().expect("forwarder");
for (sig, original) in &forwarder.originals {
unsafe { libc::sigaction(*sig, original, std::ptr::null_mut()) };
}
});
}
}
pub(crate) fn inherited(sig: libc::c_int) -> libc::sigaction {
snare_interpose::real(|| {
if let Some(original) = FORWARDER
.lock()
.unwrap()
.as_ref()
.and_then(|f| f.originals.get(&sig).copied())
{
return original;
}
unsafe {
let mut old: libc::sigaction = std::mem::zeroed();
libc::sigaction(sig, std::ptr::null(), &mut old);
old
}
})
}
extern "C" fn on_signal(sig: libc::c_int, _: *mut libc::siginfo_t, _: *mut libc::c_void) {
let byte = sig as u8;
unsafe {
let errno = errno_location();
let saved = *errno;
libc::write(
PIPE_WRITE.load(Ordering::SeqCst),
(&raw const byte).cast(),
1,
);
*errno = saved;
}
}
#[cfg(target_os = "linux")]
unsafe fn errno_location() -> *mut libc::c_int {
unsafe { libc::__errno_location() }
}
#[cfg(not(target_os = "linux"))]
unsafe fn errno_location() -> *mut libc::c_int {
unsafe { libc::__error() }
}
pub(crate) fn register(shared: Arc<SimShared>) -> Registration {
snare_interpose::real(|| {
let mut slot = FORWARDER.lock().unwrap();
let forwarder = slot.get_or_insert_with(install);
forwarder.next_id += 1;
let id = forwarder.next_id;
forwarder.sims.push((id, shared));
Registration(id)
})
}
fn install() -> Forwarder {
PIPE.get_or_init(|| {
let mut fds = [0; 2];
assert_eq!(
unsafe { libc::pipe(fds.as_mut_ptr()) },
0,
"pipe for signal forwarding"
);
PIPE_WRITE.store(fds[1], Ordering::SeqCst);
let read = fds[0];
let _ = std::thread::Builder::new()
.name("snare-signal-forwarder".into())
.spawn(move || {
let _service = snare_interpose::service_thread();
read_forwarded(read);
});
});
let mut originals = HashMap::new();
for sig in SIGNALS {
unsafe {
let mut act: libc::sigaction = std::mem::zeroed();
act.sa_sigaction = on_signal as *const () as libc::sighandler_t;
act.sa_flags = libc::SA_SIGINFO | libc::SA_RESTART;
libc::sigemptyset(&mut act.sa_mask);
let mut old: libc::sigaction = std::mem::zeroed();
libc::sigaction(sig, &act, &mut old);
originals.insert(sig, old);
}
}
Forwarder {
next_id: 0,
sims: Vec::new(),
originals,
}
}
fn read_forwarded(read: libc::c_int) {
loop {
let mut byte = 0u8;
let n = unsafe { libc::read(read, (&raw mut byte).cast(), 1) };
if n == 0 {
break;
}
if n < 0 {
if std::io::Error::last_os_error().kind() == std::io::ErrorKind::Interrupted {
continue;
}
break;
}
forward(libc::c_int::from(byte));
}
unsafe { libc::close(read) };
}
fn forward(sig: libc::c_int) {
let (sims, original) = {
let slot = FORWARDER.lock().unwrap();
let Some(forwarder) = slot.as_ref() else {
return;
};
let sims: Vec<Arc<SimShared>> = forwarder.sims.iter().map(|(_, s)| s.clone()).collect();
(sims, forwarder.originals.get(&sig).copied())
};
let mut taken = false;
for shared in sims {
let Some(domain) = shared.domain.get().and_then(|d| d.upgrade()) else {
continue;
};
let outcome = Arc::new(Mutex::new(None));
let out = outcome.clone();
let thread = domain.spawn_injected("snare-signal-forward", move || {
let r = snare_interpose::deliver_here(sig, SignalSource::Real);
snare_interpose::real(|| *out.lock().unwrap() = r);
});
if let Ok(thread) = thread {
let _ = thread.join();
}
taken |= matches!(
*outcome.lock().unwrap(),
Some(
SignalOutcome::Handled
| SignalOutcome::HandledThenExit
| SignalOutcome::Ignored
)
);
}
if taken {
return;
}
let Some(original) = original else {
return;
};
unsafe {
let mut ours: libc::sigaction = std::mem::zeroed();
libc::sigaction(sig, &original, &mut ours);
libc::raise(sig);
libc::sigaction(sig, &ours, std::ptr::null_mut());
}
}
}
#[cfg(windows)]
pub(crate) mod forward {
use std::sync::{Arc, Mutex};
use snare_interpose::SignalSource;
use crate::scope::SimShared;
#[derive(Default)]
struct Forwarder {
next_id: u64,
sims: Vec<(u64, Arc<SimShared>)>,
}
static FORWARDER: Mutex<Option<Forwarder>> = Mutex::new(None);
pub(crate) struct Registration(u64);
impl Drop for Registration {
fn drop(&mut self) {
snare_interpose::real(|| {
let mut slot = FORWARDER.lock().unwrap();
let Some(forwarder) = slot.as_mut() else {
return;
};
forwarder.sims.retain(|(id, _)| *id != self.0);
if forwarder.sims.is_empty() {
*slot = None;
unsafe {
windows_sys::Win32::System::Console::SetConsoleCtrlHandler(
Some(on_event),
0,
)
};
}
});
}
}
unsafe extern "system" fn on_event(event: u32) -> windows_sys::core::BOOL {
let sims: Vec<Arc<SimShared>> = snare_interpose::real(|| {
FORWARDER
.lock()
.unwrap()
.as_ref()
.map(|f| f.sims.iter().map(|(_, s)| s.clone()).collect())
.unwrap_or_default()
});
let mut taken = false;
for shared in sims {
let Some(domain) = shared.domain.get().and_then(|d| d.upgrade()) else {
continue;
};
let out = Arc::new(Mutex::new(None));
let slot = out.clone();
let thread = domain.spawn_injected("snare-signal-forward", move || {
let delivery = super::console::deliver_and_wait(&shared, event, SignalSource::Real);
snare_interpose::real(|| *slot.lock().unwrap() = Some(delivery));
});
if let Ok(thread) = thread {
let _ = thread.join();
}
taken |= matches!(
*out.lock().unwrap(),
Some(
super::SignalDelivery::Handled
| super::SignalDelivery::HandledThenExit
| super::SignalDelivery::Ignored
)
);
}
taken.into()
}
pub(crate) fn register(shared: Arc<SimShared>) -> Registration {
snare_interpose::real(|| {
let mut slot = FORWARDER.lock().unwrap();
let forwarder = slot.get_or_insert_with(|| {
unsafe {
windows_sys::Win32::System::Console::SetConsoleCtrlHandler(Some(on_event), 1)
};
Forwarder::default()
});
forwarder.next_id += 1;
let id = forwarder.next_id;
forwarder.sims.push((id, shared));
Registration(id)
})
}
}
#[cfg(windows)]
mod console {
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicU8, Ordering};
use std::time::Duration;
use snare_interpose::SignalSource;
use windows_sys::Win32::System::Console::{
CTRL_BREAK_EVENT, CTRL_C_EVENT, CTRL_CLOSE_EVENT, CTRL_LOGOFF_EVENT, CTRL_SHUTDOWN_EVENT,
};
use super::SignalDelivery;
use crate::readiness::{Deadline, readiness};
use crate::scope::SimShared;
const ERROR_INVALID_PARAMETER: u32 = 87;
const SIGINT: i32 = 2;
const SIGBREAK: i32 = 21;
const SIG_DFL: usize = 0;
const SIG_IGN: usize = 1;
const CRT_HANDLER: usize = usize::MAX;
#[derive(Default)]
pub(super) struct Console {
handlers: Vec<usize>,
ignore_ctrl_c: bool,
crt: HashMap<i32, usize>,
}
impl Console {
pub(super) fn set_handler(&mut self, handler: usize, add: bool) -> Result<(), u32> {
if handler == 0 {
self.ignore_ctrl_c = add;
return Ok(());
}
if add {
self.handlers.push(handler);
return Ok(());
}
match self.handlers.iter().rposition(|&h| h == handler) {
Some(i) => {
self.handlers.remove(i);
Ok(())
}
None => Err(ERROR_INVALID_PARAMETER),
}
}
pub(super) fn crt_signal(&mut self, sig: i32, handler: usize) -> usize {
if matches!(sig, SIGINT | SIGBREAK) && !self.handlers.contains(&CRT_HANDLER) {
self.handlers.push(CRT_HANDLER);
}
self.crt.insert(sig, handler).unwrap_or(SIG_DFL)
}
fn take_crt(&mut self, sig: i32) -> usize {
let handler = self.crt.get(&sig).copied().unwrap_or(SIG_DFL);
if handler != SIG_DFL && handler != SIG_IGN {
self.crt.insert(sig, SIG_DFL);
}
handler
}
}
fn table(shared: &SimShared) -> std::sync::MutexGuard<'_, Console> {
shared.signals.console.lock().unwrap()
}
fn event_of(sig: i32) -> Option<i32> {
match sig {
SIGINT => Some(CTRL_C_EVENT as i32),
SIGBREAK => Some(CTRL_BREAK_EVENT as i32),
_ => None,
}
}
fn call_crt(handler: usize, sig: i32) -> bool {
match handler {
SIG_DFL => false,
SIG_IGN => true,
f => {
let f: extern "C" fn(i32) = unsafe { std::mem::transmute(f) };
snare_interpose::simulated(|| f(sig));
true
}
}
}
pub(super) fn crt_raise(shared: &SimShared, sig: i32) {
let handler = snare_interpose::real(|| table(shared).take_crt(sig));
let delivery = match handler {
SIG_DFL => SignalDelivery::DefaultAction,
SIG_IGN => SignalDelivery::Ignored,
_ => SignalDelivery::Handled,
};
if let Some(event) = event_of(sig) {
snare_interpose::real(|| super::record(shared, event, SignalSource::Process, delivery));
}
call_crt(handler, sig);
}
fn user_session_ignored() -> bool {
use windows_sys::Win32::System::LibraryLoader::GetModuleHandleW;
let loaded = |name: &str| {
let wide: Vec<u16> = name.encode_utf16().chain(Some(0)).collect();
!unsafe { GetModuleHandleW(wide.as_ptr()) }.is_null()
};
loaded("user32.dll") || loaded("gdi32.dll")
}
const PENDING: u8 = 0;
fn encode(delivery: SignalDelivery) -> u8 {
match delivery {
SignalDelivery::Handled => 1,
SignalDelivery::HandledThenExit => 2,
SignalDelivery::DefaultAction => 3,
SignalDelivery::Ignored => 4,
_ => 5,
}
}
fn decode(code: u8) -> Option<SignalDelivery> {
Some(match code {
1 => SignalDelivery::Handled,
2 => SignalDelivery::HandledThenExit,
3 => SignalDelivery::DefaultAction,
4 => SignalDelivery::Ignored,
5 => SignalDelivery::Unavailable,
_ => return None,
})
}
fn run_handlers(shared: &SimShared, event: u32, source: SignalSource) -> SignalDelivery {
let closing = matches!(
event,
CTRL_CLOSE_EVENT | CTRL_LOGOFF_EVENT | CTRL_SHUTDOWN_EVENT
);
let (handlers, ignore) = snare_interpose::real(|| {
let console = table(shared);
(console.handlers.clone(), console.ignore_ctrl_c)
});
let early = if (event == CTRL_C_EVENT && ignore)
|| (matches!(event, CTRL_LOGOFF_EVENT | CTRL_SHUTDOWN_EVENT) && user_session_ignored())
{
Some(SignalDelivery::Ignored)
} else if closing {
Some(if handlers.is_empty() {
SignalDelivery::DefaultAction
} else {
SignalDelivery::HandledThenExit
})
} else {
None
};
if let Some(delivery) = early {
snare_interpose::real(|| super::record(shared, event as i32, source, delivery));
if delivery != SignalDelivery::HandledThenExit {
return delivery;
}
}
let mut handled = false;
for &handler in handlers.iter().rev() {
let taken = if handler == CRT_HANDLER {
let sig = match event {
CTRL_C_EVENT => SIGINT,
CTRL_BREAK_EVENT => SIGBREAK,
_ => continue,
};
let crt = snare_interpose::real(|| table(shared).take_crt(sig));
call_crt(crt, sig)
} else {
let f: unsafe extern "system" fn(u32) -> i32 =
unsafe { std::mem::transmute(handler) };
snare_interpose::simulated(|| unsafe { f(event) }) != 0
};
if taken {
handled = true;
break;
}
}
if let Some(delivery) = early {
return delivery;
}
let delivery = if handled {
SignalDelivery::Handled
} else {
SignalDelivery::DefaultAction
};
snare_interpose::real(|| super::record(shared, event as i32, source, delivery));
delivery
}
fn spawn_delivery(shared: &Arc<SimShared>, event: u32, source: SignalSource) -> Arc<AtomicU8> {
let slot = Arc::new(AtomicU8::new(PENDING));
let out = slot.clone();
let target = shared.clone();
let body = move || {
let delivery = run_handlers(&target, event, source);
out.store(encode(delivery), Ordering::SeqCst);
snare_interpose::real(|| target.bump());
};
let domain = shared.domain.get().and_then(|d| d.upgrade());
let spawned = match domain {
Some(domain) if domain.is_current() => snare_interpose::simulated(|| {
std::thread::Builder::new()
.name("snare-console-event".into())
.spawn(body)
.map(drop)
}),
Some(domain) => domain.spawn_injected("snare-console-event", body).map(drop),
None => Ok(()),
};
if spawned.is_err() {
slot.store(encode(SignalDelivery::Unavailable), Ordering::SeqCst);
}
slot
}
pub(super) fn deliver_async(shared: &Arc<SimShared>, event: u32, source: SignalSource) {
spawn_delivery(shared, event, source);
}
pub(super) fn deliver_and_wait(
shared: &Arc<SimShared>,
event: u32,
source: SignalSource,
) -> SignalDelivery {
let slot = spawn_delivery(shared, event, source);
let limit = match event {
CTRL_CLOSE_EVENT => Some(Duration::from_secs(5)),
CTRL_LOGOFF_EVENT | CTRL_SHUTDOWN_EVENT => Some(Duration::from_secs(20)),
_ => None,
};
let deadline = snare_interpose::real(|| limit.map(Deadline::timeout));
snare_interpose::real(|| {
readiness().wait_until("signal", deadline, || {
slot.load(Ordering::SeqCst) != PENDING
})
});
match decode(slot.load(Ordering::SeqCst)) {
Some(delivery) => delivery,
None if limit.is_some() => SignalDelivery::HandledThenExit,
None => SignalDelivery::Handled,
}
}
}