-
Notifications
You must be signed in to change notification settings - Fork 5.9k
Expand file tree
/
Copy pathlib.rs
More file actions
251 lines (211 loc) · 5.51 KB
/
lib.rs
File metadata and controls
251 lines (211 loc) · 5.51 KB
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
// Copyright 2018-2026 the Deno authors. MIT license.
use std::collections::HashMap;
use std::sync::Mutex;
use std::sync::OnceLock;
use std::sync::atomic::AtomicU32;
use std::sync::atomic::Ordering;
use signal_hook::consts::*;
use tokio::sync::watch;
mod dict;
pub use dict::*;
#[cfg(windows)]
static SIGHUP: i32 = 1;
static COUNTER: AtomicU32 = AtomicU32::new(0);
type Handler = Box<dyn Fn() + Send>;
type Handlers = HashMap<i32, Vec<(u32, bool, Handler)>>;
static HANDLERS: OnceLock<(Handle, Mutex<Handlers>)> = OnceLock::new();
#[cfg(unix)]
struct Handle(signal_hook::iterator::Handle);
#[cfg(windows)]
struct Handle;
fn handle_signal(signal: i32) -> bool {
let Some((_, handlers)) = HANDLERS.get() else {
return false;
};
let handlers = handlers.lock().unwrap();
let Some(handlers) = handlers.get(&signal) else {
return false;
};
let mut handled = false;
for (_, prevent_default, f) in handlers {
if *prevent_default {
handled = true;
}
f();
}
handled
}
#[cfg(unix)]
fn init() -> Handle {
use signal_hook::iterator::Signals;
let mut signals = Signals::new([SIGHUP, SIGTERM, SIGINT]).unwrap();
let handle = signals.handle();
std::thread::spawn(move || {
for signal in signals.forever() {
let handled = handle_signal(signal);
if !handled {
if signal == SIGHUP || signal == SIGTERM || signal == SIGINT {
run_exit();
}
signal_hook::low_level::emulate_default_handler(signal).unwrap();
}
}
});
Handle(handle)
}
#[cfg(windows)]
fn init() -> Handle {
unsafe extern "system" fn handle(ctrl_type: u32) -> i32 {
let signal = match ctrl_type {
0 => SIGINT,
1 => SIGBREAK,
2 => SIGHUP,
5 => SIGTERM,
6 => SIGTERM,
_ => return 0,
};
let handled = handle_signal(signal);
handled as _
}
// SAFETY: Registering handler
unsafe {
winapi::um::consoleapi::SetConsoleCtrlHandler(Some(handle), 1);
}
Handle
}
pub fn register(
signal: i32,
prevent_default: bool,
f: Box<dyn Fn() + Send>,
) -> Result<u32, std::io::Error> {
if is_forbidden(signal) {
return Err(std::io::Error::other(format!(
"Refusing to register signal {signal}"
)));
}
let (handle, handlers) = HANDLERS.get_or_init(|| {
let handle = init();
let handlers = Mutex::new(HashMap::new());
(handle, handlers)
});
let id = COUNTER.fetch_add(1, Ordering::Relaxed);
let mut handlers = handlers.lock().unwrap();
match handlers.entry(signal) {
std::collections::hash_map::Entry::Occupied(mut v) => {
v.get_mut().push((id, prevent_default, f))
}
std::collections::hash_map::Entry::Vacant(v) => {
v.insert(vec![(id, prevent_default, f)]);
#[cfg(unix)]
{
handle.0.add_signal(signal).unwrap();
}
#[cfg(windows)]
{
let _ = handle;
}
}
}
Ok(id)
}
pub fn unregister(signal: i32, id: u32) {
let Some((_, handlers)) = HANDLERS.get() else {
return;
};
let mut handlers = handlers.lock().unwrap();
let Some(handlers) = handlers.get_mut(&signal) else {
return;
};
let Some(index) = handlers.iter().position(|v| v.0 == id) else {
return;
};
let _ = handlers.swap_remove(index);
}
static BEFORE_EXIT: OnceLock<Mutex<Vec<Handler>>> = OnceLock::new();
pub fn before_exit(f: fn()) {
BEFORE_EXIT
.get_or_init(|| Mutex::new(vec![]))
.lock()
.unwrap()
.push(Box::new(f));
}
pub fn run_exit() {
if let Some(fns) = BEFORE_EXIT.get() {
let fns = fns.lock().unwrap();
for f in fns.iter() {
f();
}
}
}
pub fn is_forbidden(signo: i32) -> bool {
FORBIDDEN.contains(&signo)
}
pub struct SignalStream {
rx: watch::Receiver<()>,
}
impl SignalStream {
pub async fn recv(&mut self) -> Option<()> {
self.rx.changed().await.ok()
}
}
/// A stream that yields when any of several signals is received,
/// reporting which signal was caught.
pub struct SignalStreamWithKind {
rx: watch::Receiver<i32>,
}
impl SignalStreamWithKind {
pub async fn recv(&mut self) -> Option<i32> {
self.rx.changed().await.ok()?;
Some(*self.rx.borrow_and_update())
}
}
pub fn signal_stream(signo: i32) -> Result<SignalStream, std::io::Error> {
let (tx, rx) = watch::channel(());
let cb = Box::new(move || {
tx.send_replace(());
});
register(signo, true, cb)?;
Ok(SignalStream { rx })
}
pub async fn ctrl_c() -> std::io::Result<()> {
let mut stream = signal_stream(libc::SIGINT)?;
match stream.recv().await {
Some(_) => Ok(()),
None => Err(std::io::Error::other("failed to receive SIGINT signal")),
}
}
/// Creates an async stream that yields when a termination signal is
/// received (SIGTERM or SIGINT on unix, SIGINT on Windows). Returns
/// the signal number that was caught.
pub fn termination_signal_stream() -> std::io::Result<SignalStreamWithKind> {
let (tx, rx) = watch::channel(0i32);
let tx2 = tx.clone();
register(
SIGINT,
true,
Box::new(move || {
tx.send_replace(SIGINT);
}),
)?;
#[cfg(unix)]
register(
SIGTERM,
true,
Box::new(move || {
tx2.send_replace(SIGTERM);
}),
)?;
#[cfg(not(unix))]
drop(tx2);
Ok(SignalStreamWithKind { rx })
}
/// Re-raises the given signal with the default handler so the parent
/// process sees the correct signal exit status.
pub fn raise_default_signal(signo: i32) {
// SAFETY: Restoring the default signal handler and raising the signal
// are well-defined operations on both POSIX and Windows.
unsafe {
libc::signal(signo, libc::SIG_DFL);
libc::raise(signo);
}
}