use parking_lot::Mutex;
use std::{
io::Write,
panic::{AssertUnwindSafe, catch_unwind},
sync::Once,
};
pub struct ExitSlot<T>(Mutex<Option<T>>);
static DROPS: Mutex<Vec<Box<dyn FnOnce() + Send>>> = Mutex::new(Vec::new());
static REGISTER: Once = Once::new();
unsafe extern "C" {
fn atexit(callback: extern "C" fn()) -> i32;
}
type Drops = Mutex<Vec<Box<dyn FnOnce() + Send>>>;
extern "C" fn drop_every_slot() {
drain(&DROPS);
}
fn drain(registry: &Drops) {
loop {
let batch = std::mem::take(&mut *registry.lock());
if batch.is_empty() {
return;
}
run_drops(batch);
}
}
fn run_drops(drops: Vec<Box<dyn FnOnce() + Send>>) {
for drop_slot in drops {
if catch_unwind(AssertUnwindSafe(drop_slot)).is_err() {
let _ = writeln!(
std::io::stderr().lock(),
"exit slot: a value's destructor panicked; continuing with the rest"
);
}
}
}
impl<T: Send + 'static> ExitSlot<T> {
pub const fn new() -> Self {
Self(Mutex::new(None))
}
pub fn with<R>(&'static self, init: impl FnOnce() -> T, read: impl FnOnce(&T) -> R) -> R {
let mut slot = self.0.lock();
if slot.is_none() {
let value = init();
REGISTER.call_once(|| {
let registered = unsafe { atexit(drop_every_slot) };
assert_eq!(
registered, 0,
"register the exit callback that drops the slot"
);
});
DROPS.lock().push(Box::new(move || self.clear()));
*slot = Some(value);
}
read(slot.as_ref().expect("filled just above"))
}
fn clear(&self) {
let value = self.0.lock().take();
drop(value);
}
}
#[cfg(test)]
mod tests {
use std::sync::atomic::{AtomicBool, Ordering};
use super::*;
#[test]
fn a_panicking_drop_closure_neither_escapes_nor_skips_later_ones() {
static LATER_RAN: AtomicBool = AtomicBool::new(false);
let drops: Vec<Box<dyn FnOnce() + Send>> = vec![
Box::new(|| panic!("a drop that misbehaves")),
Box::new(|| {
LATER_RAN.store(true, Ordering::Relaxed);
}),
];
run_drops(drops);
assert!(
LATER_RAN.load(Ordering::Relaxed),
"the closure after the panicking one did not run"
);
}
#[test]
fn a_drop_registered_during_the_drain_runs_and_does_not_deadlock() {
static REGISTRY: Drops = Mutex::new(Vec::new());
static SECOND_RAN: AtomicBool = AtomicBool::new(false);
REGISTRY.lock().push(Box::new(|| {
REGISTRY
.lock()
.push(Box::new(|| SECOND_RAN.store(true, Ordering::Relaxed)));
}));
let (done, finished) = std::sync::mpsc::channel();
std::thread::spawn(move || {
drain(®ISTRY);
let _ = done.send(());
});
assert!(
finished
.recv_timeout(std::time::Duration::from_secs(10))
.is_ok(),
"the drain held its registry lock while running a drop: deadlock"
);
assert!(
SECOND_RAN.load(Ordering::Relaxed),
"a drop registered during the drain never ran"
);
}
}