1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
#![deny(missing_docs)]
use std::cell::UnsafeCell;
use std::collections::hash_map::Entry;
use std::collections::HashMap;
use std::mem::ManuallyDrop;
use std::panic::{catch_unwind, AssertUnwindSafe};
use std::sync::{mpsc, Arc};
use parking_lot::lock_api::RawMutex;
use parking_lot::Mutex;
#[cfg(feature = "futures")]
use futures::channel::mpsc as async_mpsc;
#[cfg(feature = "futures")]
use futures::SinkExt;
static STATE: Mutex<Option<State>> = Mutex::const_new(RawMutex::INIT, None);
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ShutdownType {
Interrupt,
Terminate,
}
pub trait Handler: FnMut(ShutdownType) + Send + 'static {}
impl<T: FnMut(ShutdownType) + Send + 'static> Handler for T {}
struct Slot {
guard: ManuallyDrop<InternalGuard>,
handlers: Vec<Arc<UnsafeCell<dyn Handler>>>,
}
impl Slot {
fn new(type_: ShutdownType) -> Self {
let guard = unsafe { ManuallyDrop::new(enter(type_)) };
let handlers = Vec::new();
Self { guard, handlers }
}
}
impl Drop for Slot {
fn drop(&mut self) {
unsafe { leave(ManuallyDrop::take(&mut self.guard)) }
}
}
struct State {
slots: HashMap<ShutdownType, Slot>,
}
unsafe impl Send for State {}
impl State {
fn new() -> Self {
unsafe {
enter_outer();
}
Self {
slots: HashMap::new(),
}
}
}
impl Drop for State {
fn drop(&mut self) {
unsafe {
leave_outer();
}
}
}
fn handle(type_: ShutdownType) {
let guard = STATE.lock();
if let Some(state) = guard.as_ref() {
if let Some(slot) = state.slots.get(&type_) {
if let Some(handler) = slot.handlers.last() {
let _ = catch_unwind(AssertUnwindSafe(|| unsafe { (*handler.get())(type_) }));
return;
}
}
}
std::process::exit(3);
}
pub struct ShutdownGuard<'a> {
types: &'a [ShutdownType],
handler: Arc<UnsafeCell<dyn Handler>>,
}
impl<'a> ShutdownGuard<'a> {
pub fn new<H: Handler>(types: &'a [ShutdownType], handler: H) -> Self {
unsafe { Self::new_inner(types, Arc::new(UnsafeCell::new(handler))) }
}
pub fn new_channel(types: &'a [ShutdownType]) -> (Self, mpsc::Receiver<ShutdownType>) {
let (tx, rx) = mpsc::channel();
(
Self::new(types, move |t| {
let _ = tx.send(t);
}),
rx,
)
}
#[cfg(feature = "futures")]
pub fn new_stream(
types: &'a [ShutdownType],
) -> (Self, async_mpsc::UnboundedReceiver<ShutdownType>) {
let (mut tx, rx) = async_mpsc::unbounded();
(
Self::new(types, move |t| {
let _ = futures::executor::block_on(tx.send(t));
}),
rx,
)
}
unsafe fn new_inner(types: &'a [ShutdownType], handler: Arc<UnsafeCell<dyn Handler>>) -> Self {
if !types.is_empty() {
let mut guard = STATE.lock();
let state = guard.get_or_insert_with(State::new);
for &type_ in types {
state
.slots
.entry(type_)
.or_insert_with(|| Slot::new(type_))
.handlers
.push(handler.clone());
}
}
Self { types, handler }
}
pub fn forget(mut self) {
self.types = &[];
}
}
impl<'a> Drop for ShutdownGuard<'a> {
fn drop(&mut self) {
if !self.types.is_empty() {
let ptr = Arc::as_ptr(&self.handler) as *const ();
let mut guard = STATE.lock();
let state = guard.as_mut().expect("State should be initialized");
for &type_ in self.types {
if let Entry::Occupied(mut occ) = state.slots.entry(type_) {
let handlers = &mut occ.get_mut().handlers;
let (index, _) = handlers
.iter()
.enumerate()
.rev()
.find(|&(_, item)| Arc::as_ptr(item) as *const () == ptr)
.expect("State should contain handler");
handlers.remove(index);
if handlers.is_empty() {
occ.remove();
}
}
}
if state.slots.is_empty() {
guard.take();
}
}
}
}
#[cfg(windows)]
mod windows;
#[cfg(windows)]
use windows::*;
#[cfg(not(windows))]
mod unix;
#[cfg(not(windows))]
use unix::*;