1 //! Implementation of running at_exit routines
3 //! Documentation can be found on the `rt::at_exit` function.
7 use crate::sys_common::mutex::Mutex;
9 type Queue = Vec<Box<dyn FnOnce()>>;
11 // NB these are specifically not types from `std::sync` as they currently rely
12 // on poisoning and this module needs to operate at a lower level than requiring
13 // the thread infrastructure to be in place (useful on the borders of
14 // initialization/destruction).
15 // We never call `LOCK.init()`, so it is UB to attempt to
16 // acquire this mutex reentrantly!
17 static LOCK: Mutex = Mutex::new();
18 static mut QUEUE: *mut Queue = ptr::null_mut();
20 const DONE: *mut Queue = 1_usize as *mut _;
22 // The maximum number of times the cleanup routines will be run. While running
23 // the at_exit closures new ones may be registered, and this count is the number
24 // of times the new closures will be allowed to register successfully. After
25 // this number of iterations all new registrations will return `false`.
26 const ITERS: usize = 10;
28 unsafe fn init() -> bool {
30 let state: Box<Queue> = box Vec::new();
31 QUEUE = Box::into_raw(state);
32 } else if QUEUE == DONE {
33 // can't re-init after a cleanup
44 let _guard = LOCK.lock();
45 mem::replace(&mut QUEUE, if i == ITERS { DONE } else { ptr::null_mut() })
48 // make sure we're not recursively cleaning up
49 assert!(queue != DONE);
51 // If we never called init, not need to cleanup!
53 let queue: Box<Queue> = Box::from_raw(queue);
54 for to_run in *queue {
55 // We are not holding any lock, so reentrancy is fine.
63 pub fn push(f: Box<dyn FnOnce()>) -> bool {
65 let _guard = LOCK.lock();
67 // We are just moving `f` around, not calling it.
68 // There is no possibility of reentrancy here.