]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys_common/at_exit_imp.rs
Rollup merge of #68093 - GuillaumeGomez:fix-deref-impl-typedef, r=oli-obk
[rust.git] / src / libstd / sys_common / at_exit_imp.rs
1 //! Implementation of running at_exit routines
2 //!
3 //! Documentation can be found on the `rt::at_exit` function.
4
5 use crate::mem;
6 use crate::ptr;
7 use crate::sys_common::mutex::Mutex;
8
9 type Queue = Vec<Box<dyn FnOnce()>>;
10
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();
19
20 const DONE: *mut Queue = 1_usize as *mut _;
21
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;
27
28 unsafe fn init() -> bool {
29     if QUEUE.is_null() {
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
34         return false;
35     }
36
37     true
38 }
39
40 pub fn cleanup() {
41     for i in 1..=ITERS {
42         unsafe {
43             let queue = {
44                 let _guard = LOCK.lock();
45                 mem::replace(&mut QUEUE, if i == ITERS { DONE } else { ptr::null_mut() })
46             };
47
48             // make sure we're not recursively cleaning up
49             assert!(queue != DONE);
50
51             // If we never called init, not need to cleanup!
52             if !queue.is_null() {
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.
56                     to_run();
57                 }
58             }
59         }
60     }
61 }
62
63 pub fn push(f: Box<dyn FnOnce()>) -> bool {
64     unsafe {
65         let _guard = LOCK.lock();
66         if init() {
67             // We are just moving `f` around, not calling it.
68             // There is no possibility of reentrancy here.
69             (*QUEUE).push(f);
70             true
71         } else {
72             false
73         }
74     }
75 }