/rust/registry/src/index.crates.io-1949cf8c6b5b557f/signal-hook-registry-1.4.8/src/lib.rs
Line | Count | Source |
1 | | #![doc(test(attr(deny(warnings))))] |
2 | | #![warn(missing_docs)] |
3 | | #![allow(unknown_lints, renamed_and_remove_lints, bare_trait_objects)] |
4 | | |
5 | | //! Backend of the [signal-hook] crate. |
6 | | //! |
7 | | //! The [signal-hook] crate tries to provide an API to the unix signals, which are a global |
8 | | //! resource. Therefore, it is desirable an application contains just one version of the crate |
9 | | //! which manages this global resource. But that makes it impossible to make breaking changes in |
10 | | //! the API. |
11 | | //! |
12 | | //! Therefore, this crate provides very minimal and low level API to the signals that is unlikely |
13 | | //! to have to change, while there may be multiple versions of the [signal-hook] that all use this |
14 | | //! low-level API to provide different versions of the high level APIs. |
15 | | //! |
16 | | //! It is also possible some other crates might want to build a completely different API. This |
17 | | //! split allows these crates to still reuse the same low-level routines in this crate instead of |
18 | | //! going to the (much more dangerous) unix calls. |
19 | | //! |
20 | | //! # What this crate provides |
21 | | //! |
22 | | //! The only thing this crate does is multiplexing the signals. An application or library can add |
23 | | //! or remove callbacks and have multiple callbacks for the same signal. |
24 | | //! |
25 | | //! It handles dispatching the callbacks and managing them in a way that uses only the |
26 | | //! [async-signal-safe] functions inside the signal handler. Note that the callbacks are still run |
27 | | //! inside the signal handler, so it is up to the caller to ensure they are also |
28 | | //! [async-signal-safe]. |
29 | | //! |
30 | | //! # What this is for |
31 | | //! |
32 | | //! This is a building block for other libraries creating reasonable abstractions on top of |
33 | | //! signals. The [signal-hook] is the generally preferred way if you need to handle signals in your |
34 | | //! application and provides several safe patterns of doing so. |
35 | | //! |
36 | | //! # Rust version compatibility |
37 | | //! |
38 | | //! Currently builds on 1.26.0 an newer and this is very unlikely to change. However, tests |
39 | | //! require dependencies that don't build there, so tests need newer Rust version (they are run on |
40 | | //! stable). |
41 | | //! |
42 | | //! Note that this ancient version of rustc no longer compiles current versions of `libc`. If you |
43 | | //! want to use rustc this old, you need to force your dependency resolution to pick old enough |
44 | | //! version of `libc` (`0.2.156` was found to work, but newer ones may too). |
45 | | //! |
46 | | //! # Portability |
47 | | //! |
48 | | //! This crate includes a limited support for Windows, based on `signal`/`raise` in the CRT. |
49 | | //! There are differences in both API and behavior: |
50 | | //! |
51 | | //! - Due to lack of `siginfo_t`, we don't provide `register_sigaction` or `register_unchecked`. |
52 | | //! - Due to lack of signal blocking, there's a race condition. |
53 | | //! After the call to `signal`, there's a moment where we miss a signal. |
54 | | //! That means when you register a handler, there may be a signal which invokes |
55 | | //! neither the default handler or the handler you register. |
56 | | //! - Handlers registered by `signal` in Windows are cleared on first signal. |
57 | | //! To match behavior in other platforms, we re-register the handler each time the handler is |
58 | | //! called, but there's a moment where we miss a handler. |
59 | | //! That means when you receive two signals in a row, there may be a signal which invokes |
60 | | //! the default handler, nevertheless you certainly have registered the handler. |
61 | | //! |
62 | | //! [signal-hook]: https://docs.rs/signal-hook |
63 | | //! [async-signal-safe]: http://www.man7.org/linux/man-pages/man7/signal-safety.7.html |
64 | | |
65 | | extern crate errno; |
66 | | extern crate libc; |
67 | | |
68 | | mod half_lock; |
69 | | mod vec_map; |
70 | | |
71 | | use std::io::Error; |
72 | | use std::mem; |
73 | | use std::ptr; |
74 | | use std::sync::atomic::{AtomicPtr, Ordering}; |
75 | | // Once::new is now a const-fn. But it is not stable in all the rustc versions we want to support |
76 | | // yet. |
77 | | #[allow(deprecated)] |
78 | | use std::sync::ONCE_INIT; |
79 | | use std::sync::{Arc, Once}; |
80 | | |
81 | | use errno::Errno; |
82 | | #[cfg(not(windows))] |
83 | | use libc::{c_int, c_void, sigaction, siginfo_t}; |
84 | | #[cfg(windows)] |
85 | | use libc::{c_int, sighandler_t}; |
86 | | |
87 | | #[cfg(not(windows))] |
88 | | use libc::{SIGFPE, SIGILL, SIGKILL, SIGSEGV, SIGSTOP}; |
89 | | #[cfg(windows)] |
90 | | use libc::{SIGFPE, SIGILL, SIGSEGV}; |
91 | | |
92 | | use half_lock::HalfLock; |
93 | | use vec_map::VecMap; |
94 | | |
95 | | // These constants are not defined in the current version of libc, but it actually |
96 | | // exists in Windows CRT. |
97 | | #[cfg(windows)] |
98 | | const SIG_DFL: sighandler_t = 0; |
99 | | #[cfg(windows)] |
100 | | const SIG_IGN: sighandler_t = 1; |
101 | | #[cfg(windows)] |
102 | | const SIG_GET: sighandler_t = 2; |
103 | | #[cfg(windows)] |
104 | | const SIG_ERR: sighandler_t = !0; |
105 | | |
106 | | // To simplify implementation. Not to be exposed. |
107 | | #[cfg(windows)] |
108 | | #[allow(non_camel_case_types)] |
109 | | struct siginfo_t; |
110 | | |
111 | | // # Internal workings |
112 | | // |
113 | | // This uses a form of RCU. There's an atomic pointer to the current action descriptors (in the |
114 | | // form of IndependentArcSwap, to be able to track what, if any, signal handlers still use the |
115 | | // version). A signal handler takes a copy of the pointer and calls all the relevant actions. |
116 | | // |
117 | | // Modifications to that are protected by a mutex, to avoid juggling multiple signal handlers at |
118 | | // once (eg. not calling sigaction concurrently). This should not be a problem, because modifying |
119 | | // the signal actions should be initialization only anyway. To avoid all allocations and also |
120 | | // deallocations inside the signal handler, after replacing the pointer, the modification routine |
121 | | // needs to busy-wait for the reference count on the old pointer to drop to 1 and take ownership ‒ |
122 | | // that way the one deallocating is the modification routine, outside of the signal handler. |
123 | | |
124 | | #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)] |
125 | | struct ActionId(u128); |
126 | | |
127 | | /// An ID of registered action. |
128 | | /// |
129 | | /// This is returned by all the registration routines and can be used to remove the action later on |
130 | | /// with a call to [`unregister`]. |
131 | | #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)] |
132 | | pub struct SigId { |
133 | | signal: c_int, |
134 | | action: ActionId, |
135 | | } |
136 | | |
137 | | // This should be dyn Fn(...), but we want to support Rust 1.26.0 and that one doesn't allow dyn |
138 | | // yet. |
139 | | #[allow(unknown_lints, bare_trait_objects)] |
140 | | type Action = Fn(&siginfo_t) + Send + Sync; |
141 | | |
142 | | #[derive(Clone)] |
143 | | struct Slot { |
144 | | prev: Prev, |
145 | | // Actions are stored and executed in the order they were registered. |
146 | | actions: VecMap<ActionId, Arc<Action>>, |
147 | | } |
148 | | |
149 | | impl Slot { |
150 | | #[cfg(windows)] |
151 | | fn new(signal: libc::c_int) -> Result<Self, Error> { |
152 | | let old = unsafe { libc::signal(signal, handler as *const () as sighandler_t) }; |
153 | | if old == SIG_ERR { |
154 | | return Err(Error::last_os_error()); |
155 | | } |
156 | | Ok(Slot { |
157 | | prev: Prev { signal, info: old }, |
158 | | actions: VecMap::new(), |
159 | | }) |
160 | | } |
161 | | |
162 | | #[cfg(not(windows))] |
163 | 0 | fn new(signal: libc::c_int) -> Result<Self, Error> { |
164 | | // C data structure, expected to be zeroed out. |
165 | 0 | let mut new: libc::sigaction = unsafe { mem::zeroed() }; |
166 | | |
167 | | // Note: AIX fixed their naming in libc 0.2.171. |
168 | | // |
169 | | // However, if we mandate that _for everyone_, other systems fail to compile on old Rust |
170 | | // versions (eg. 1.26.0), because they are no longer able to compile this new libc. |
171 | | // |
172 | | // There doesn't seem to be a way to make Cargo force the dependency for only one target |
173 | | // (it doesn't compile the ones it doesn't need, but it stills considers the other targets |
174 | | // for version resolution). |
175 | | // |
176 | | // Therefore, we let the user have freedom - if they want AIX, they can upgrade to new |
177 | | // enough libc. If they want ancient rustc, they can force older versions of libc. |
178 | | // |
179 | | // See #169. |
180 | | |
181 | 0 | new.sa_sigaction = handler as *const () as usize; // If it doesn't compile on AIX, upgrade the libc dependency |
182 | | |
183 | | #[cfg(target_os = "nto")] |
184 | | let flags = 0; |
185 | | // SA_RESTART is not supported by qnx https://www.qnx.com/support/knowledgebase.html?id=50130000000SmiD |
186 | | #[cfg(not(target_os = "nto"))] |
187 | 0 | let flags = libc::SA_RESTART; |
188 | | // Android is broken and uses different int types than the rest (and different depending on |
189 | | // the pointer width). This converts the flags to the proper type no matter what it is on |
190 | | // the given platform. |
191 | | #[allow(unused_assignments)] |
192 | 0 | let mut siginfo = flags; |
193 | 0 | siginfo = libc::SA_SIGINFO as _; |
194 | 0 | let flags = flags | siginfo; |
195 | 0 | new.sa_flags = flags as _; |
196 | | // C data structure, expected to be zeroed out. |
197 | 0 | let mut old: libc::sigaction = unsafe { mem::zeroed() }; |
198 | | // FFI ‒ pointers are valid, it doesn't take ownership. |
199 | 0 | if unsafe { libc::sigaction(signal, &new, &mut old) } != 0 { |
200 | 0 | return Err(Error::last_os_error()); |
201 | 0 | } |
202 | 0 | Ok(Slot { |
203 | 0 | prev: Prev { signal, info: old }, |
204 | 0 | actions: VecMap::new(), |
205 | 0 | }) |
206 | 0 | } |
207 | | } |
208 | | |
209 | | #[derive(Clone)] |
210 | | struct SignalData { |
211 | | signals: VecMap<c_int, Slot>, |
212 | | next_id: u128, |
213 | | } |
214 | | |
215 | | #[derive(Clone)] |
216 | | struct Prev { |
217 | | signal: c_int, |
218 | | #[cfg(windows)] |
219 | | info: sighandler_t, |
220 | | #[cfg(not(windows))] |
221 | | info: sigaction, |
222 | | } |
223 | | |
224 | | impl Prev { |
225 | | #[cfg(windows)] |
226 | | fn detect(signal: c_int) -> Result<Self, Error> { |
227 | | let old = unsafe { libc::signal(signal, SIG_GET) }; |
228 | | if old == SIG_ERR { |
229 | | return Err(Error::last_os_error()); |
230 | | } |
231 | | Ok(Prev { signal, info: old }) |
232 | | } |
233 | | |
234 | | #[cfg(not(windows))] |
235 | 0 | fn detect(signal: c_int) -> Result<Self, Error> { |
236 | | // C data structure, expected to be zeroed out. |
237 | 0 | let mut old: libc::sigaction = unsafe { mem::zeroed() }; |
238 | | // FFI ‒ pointers are valid, it doesn't take ownership. |
239 | 0 | if unsafe { libc::sigaction(signal, ptr::null(), &mut old) } != 0 { |
240 | 0 | return Err(Error::last_os_error()); |
241 | 0 | } |
242 | | |
243 | 0 | Ok(Prev { signal, info: old }) |
244 | 0 | } |
245 | | |
246 | | #[cfg(windows)] |
247 | | fn execute(&self, sig: c_int) { |
248 | | let fptr = self.info; |
249 | | if fptr != 0 && fptr != SIG_DFL && fptr != SIG_IGN { |
250 | | // `sighandler_t` is an integer type. Transmuting it directly from an integer to a |
251 | | // function pointer seems dubious w.r.t. pointer provenance -- at least Miri complains |
252 | | // about it. Casting to a raw pointer first side-steps the issue. |
253 | | let fptr = fptr as *mut (); |
254 | | // FFI ‒ calling the original signal handler. |
255 | | unsafe { |
256 | | let action = mem::transmute::<*mut (), extern "C" fn(c_int)>(fptr); |
257 | | action(sig); |
258 | | } |
259 | | } |
260 | | } |
261 | | |
262 | | #[cfg(not(windows))] |
263 | | // libc re-exports the core::ffi::c_void on rustc >= 1.30, else defines its own type |
264 | | // cfg_attr is needed because the `allow(clippy::lint)` syntax was added in Rust 1.31 |
265 | | #[cfg_attr(clippy, allow(clippy::incompatible_msrv))] |
266 | 0 | unsafe fn execute(&self, sig: c_int, info: *mut siginfo_t, data: *mut c_void) { |
267 | 0 | let fptr = self.info.sa_sigaction; |
268 | 0 | if fptr != 0 && fptr != libc::SIG_DFL && fptr != libc::SIG_IGN { |
269 | | // `sa_sigaction` is usually stored as integer type. Transmuting it directly from an |
270 | | // integer to a function pointer seems dubious w.r.t. pointer provenance -- at least |
271 | | // Miri complains about it. Casting to a raw pointer first side-steps the issue. |
272 | 0 | let fptr = fptr as *mut (); |
273 | | // Android is broken and uses different int types than the rest (and different |
274 | | // depending on the pointer width). This converts the flags to the proper type no |
275 | | // matter what it is on the given platform. |
276 | | // |
277 | | // The trick is to create the same-typed variable as the sa_flags first and then |
278 | | // set it to the proper value (does Rust have a way to copy a type in a different |
279 | | // way?) |
280 | | #[allow(unused_assignments)] |
281 | 0 | let mut siginfo = self.info.sa_flags; |
282 | 0 | siginfo = libc::SA_SIGINFO as _; |
283 | 0 | if self.info.sa_flags & siginfo == 0 { |
284 | 0 | let action = mem::transmute::<*mut (), extern "C" fn(c_int)>(fptr); |
285 | 0 | action(sig); |
286 | 0 | } else { |
287 | | type SigAction = extern "C" fn(c_int, *mut siginfo_t, *mut c_void); |
288 | 0 | let action = mem::transmute::<*mut (), SigAction>(fptr); |
289 | 0 | action(sig, info, data); |
290 | | } |
291 | 0 | } |
292 | 0 | } |
293 | | } |
294 | | |
295 | | /// Lazy-initiated data structure with our global variables. |
296 | | /// |
297 | | /// Used inside a structure to cut down on boilerplate code to lazy-initialize stuff. We don't dare |
298 | | /// use anything fancy like lazy-static or once-cell, since we are not sure they are |
299 | | /// async-signal-safe in their access. Our code uses the [Once], but only on the write end outside |
300 | | /// of signal handler. The handler assumes it has already been initialized. |
301 | | struct GlobalData { |
302 | | /// The data structure describing what needs to be run for each signal. |
303 | | data: HalfLock<SignalData>, |
304 | | |
305 | | /// A fallback to fight/minimize a race condition during signal initialization. |
306 | | /// |
307 | | /// See the comment inside [`register_unchecked_impl`]. |
308 | | race_fallback: HalfLock<Option<Prev>>, |
309 | | } |
310 | | |
311 | | static GLOBAL_DATA: AtomicPtr<GlobalData> = AtomicPtr::new(ptr::null_mut()); |
312 | | #[allow(deprecated)] |
313 | | static GLOBAL_INIT: Once = ONCE_INIT; |
314 | | |
315 | | impl GlobalData { |
316 | 0 | fn get() -> &'static Self { |
317 | 0 | let data = GLOBAL_DATA.load(Ordering::Acquire); |
318 | | // # Safety |
319 | | // |
320 | | // * The data actually does live forever - created by Box::into_raw. |
321 | | // * It is _never_ modified (apart for interior mutability, but that one is fine). |
322 | 0 | unsafe { data.as_ref().expect("We shall be set up already") } |
323 | 0 | } |
324 | 0 | fn ensure() -> &'static Self { |
325 | 0 | GLOBAL_INIT.call_once(|| { |
326 | 0 | let data = Box::into_raw(Box::new(GlobalData { |
327 | 0 | data: HalfLock::new(SignalData { |
328 | 0 | signals: VecMap::new(), |
329 | 0 | next_id: 1, |
330 | 0 | }), |
331 | 0 | race_fallback: HalfLock::new(None), |
332 | 0 | })); |
333 | 0 | let old = GLOBAL_DATA.swap(data, Ordering::Release); |
334 | 0 | assert!(old.is_null()); |
335 | 0 | }); |
336 | 0 | Self::get() |
337 | 0 | } |
338 | | } |
339 | | |
340 | | #[cfg(windows)] |
341 | | extern "C" fn handler(sig: c_int) { |
342 | | let _errno = ErrnoGuard::new(); |
343 | | |
344 | | if sig != SIGFPE { |
345 | | // Windows CRT `signal` resets handler every time, unless for SIGFPE. |
346 | | // Reregister the handler to retain maximal compatibility. |
347 | | // Problems: |
348 | | // - It's racy. But this is inevitably racy in Windows. |
349 | | // - Interacts poorly with handlers outside signal-hook-registry. |
350 | | let old = unsafe { libc::signal(sig, handler as *const () as sighandler_t) }; |
351 | | if old == SIG_ERR { |
352 | | // MSDN doesn't describe which errors might occur, |
353 | | // but we can tell from the Linux manpage that |
354 | | // EINVAL (invalid signal number) is mostly the only case. |
355 | | // Therefore, this branch must not occur. |
356 | | // In any case we can do nothing useful in the signal handler, |
357 | | // so we're going to abort silently. |
358 | | unsafe { |
359 | | libc::abort(); |
360 | | } |
361 | | } |
362 | | } |
363 | | |
364 | | let globals = GlobalData::get(); |
365 | | let fallback = globals.race_fallback.read(); |
366 | | let sigdata = globals.data.read(); |
367 | | |
368 | | if let Some(ref slot) = sigdata.signals.get(&sig) { |
369 | | slot.prev.execute(sig); |
370 | | |
371 | | for action in slot.actions.values() { |
372 | | action(&siginfo_t); |
373 | | } |
374 | | } else if let Some(prev) = fallback.as_ref() { |
375 | | // In case we get called but don't have the slot for this signal set up yet, we are under |
376 | | // the race condition. We may have the old signal handler stored in the fallback |
377 | | // temporarily. |
378 | | if sig == prev.signal { |
379 | | prev.execute(sig); |
380 | | } |
381 | | // else -> probably should not happen, but races with other threads are possible so |
382 | | // better safe |
383 | | } |
384 | | } |
385 | | |
386 | | #[cfg(not(windows))] |
387 | | // libc re-exports the core::ffi::c_void on rustc >= 1.30, else defines its own type |
388 | | // cfg_attr is needed because the `allow(clippy::lint)` syntax was added in Rust 1.31 |
389 | | #[cfg_attr(clippy, allow(clippy::incompatible_msrv))] |
390 | 0 | extern "C" fn handler(sig: c_int, info: *mut siginfo_t, data: *mut c_void) { |
391 | 0 | let _errno = ErrnoGuard::new(); |
392 | | |
393 | 0 | let globals = GlobalData::get(); |
394 | 0 | let fallback = globals.race_fallback.read(); |
395 | 0 | let sigdata = globals.data.read(); |
396 | | |
397 | 0 | if let Some(slot) = sigdata.signals.get(&sig) { |
398 | 0 | unsafe { slot.prev.execute(sig, info, data) }; |
399 | | |
400 | 0 | let info = unsafe { info.as_ref() }; |
401 | 0 | let info = info.unwrap_or_else(|| { |
402 | | // The info being null seems to be illegal according to POSIX, but has been observed on |
403 | | // some probably broken platform. We can't do anything about that, that is just broken, |
404 | | // but we are not allowed to panic in a signal handler, so we are left only with simply |
405 | | // aborting. We try to write a message what happens, but using the libc stuff |
406 | | // (`eprintln` is not guaranteed to be async-signal-safe). |
407 | | unsafe { |
408 | | const MSG: &[u8] = |
409 | | b"Platform broken, got NULL as siginfo to signal handler. Aborting"; |
410 | 0 | libc::write(2, MSG.as_ptr() as *const _, MSG.len()); |
411 | 0 | libc::abort(); |
412 | | } |
413 | | }); |
414 | | |
415 | 0 | for action in slot.actions.values() { |
416 | 0 | action(info); |
417 | 0 | } |
418 | 0 | } else if let Some(prev) = fallback.as_ref() { |
419 | | // In case we get called but don't have the slot for this signal set up yet, we are under |
420 | | // the race condition. We may have the old signal handler stored in the fallback |
421 | | // temporarily. |
422 | 0 | if prev.signal == sig { |
423 | 0 | unsafe { prev.execute(sig, info, data) }; |
424 | 0 | } |
425 | | // else -> probably should not happen, but races with other threads are possible so |
426 | | // better safe |
427 | 0 | } |
428 | 0 | } |
429 | | |
430 | | struct ErrnoGuard(Errno); |
431 | | |
432 | | impl ErrnoGuard { |
433 | 0 | fn new() -> Self { |
434 | 0 | ErrnoGuard(errno::errno()) |
435 | 0 | } |
436 | | } |
437 | | |
438 | | impl Drop for ErrnoGuard { |
439 | 0 | fn drop(&mut self) { |
440 | 0 | errno::set_errno(self.0); |
441 | 0 | } |
442 | | } |
443 | | |
444 | | /// List of forbidden signals. |
445 | | /// |
446 | | /// Some signals are impossible to replace according to POSIX and some are so special that this |
447 | | /// library refuses to handle them (eg. SIGSEGV). The routines panic in case registering one of |
448 | | /// these signals is attempted. |
449 | | /// |
450 | | /// See [`register`]. |
451 | | pub const FORBIDDEN: &[c_int] = FORBIDDEN_IMPL; |
452 | | |
453 | | #[cfg(windows)] |
454 | | const FORBIDDEN_IMPL: &[c_int] = &[SIGILL, SIGFPE, SIGSEGV]; |
455 | | #[cfg(not(windows))] |
456 | | const FORBIDDEN_IMPL: &[c_int] = &[SIGKILL, SIGSTOP, SIGILL, SIGFPE, SIGSEGV]; |
457 | | |
458 | | /// Registers an arbitrary action for the given signal. |
459 | | /// |
460 | | /// This makes sure there's a signal handler for the given signal. It then adds the action to the |
461 | | /// ones called each time the signal is delivered. If multiple actions are set for the same signal, |
462 | | /// all are called, in the order of registration. |
463 | | /// |
464 | | /// If there was a previous signal handler for the given signal, it is chained ‒ it will be called |
465 | | /// as part of this library's signal handler, before any actions set through this function. |
466 | | /// |
467 | | /// On success, the function returns an ID that can be used to remove the action again with |
468 | | /// [`unregister`]. |
469 | | /// |
470 | | /// # Panics |
471 | | /// |
472 | | /// If the signal is one of (see [`FORBIDDEN`]): |
473 | | /// |
474 | | /// * `SIGKILL` |
475 | | /// * `SIGSTOP` |
476 | | /// * `SIGILL` |
477 | | /// * `SIGFPE` |
478 | | /// * `SIGSEGV` |
479 | | /// |
480 | | /// The first two are not possible to override (and the underlying C functions simply ignore all |
481 | | /// requests to do so, which smells of possible bugs, or return errors). The rest can be set, but |
482 | | /// generally needs very special handling to do so correctly (direct manipulation of the |
483 | | /// application's address space, `longjmp` and similar). Unless you know very well what you're |
484 | | /// doing, you'll shoot yourself into the foot and this library won't help you with that. |
485 | | /// |
486 | | /// # Errors |
487 | | /// |
488 | | /// Since the library manipulates signals using the low-level C functions, all these can return |
489 | | /// errors. Generally, the errors mean something like the specified signal does not exist on the |
490 | | /// given platform ‒ after a program is debugged and tested on a given OS, it should never return |
491 | | /// an error. |
492 | | /// |
493 | | /// However, if an error *is* returned, there are no guarantees if the given action was registered |
494 | | /// or not. |
495 | | /// |
496 | | /// # Safety |
497 | | /// |
498 | | /// This function is unsafe, because the `action` is run inside a signal handler. While Rust is |
499 | | /// somewhat vague about the consequences of such, it is reasonably to assume that similar |
500 | | /// restrictions as specified in C or C++ apply. |
501 | | /// |
502 | | /// In particular: |
503 | | /// |
504 | | /// * Calling any OS functions that are not async-signal-safe as specified as POSIX is not allowed. |
505 | | /// * Accessing globals or thread-locals without synchronization is not allowed (however, mutexes |
506 | | /// are not within the async-signal-safe functions, therefore the synchronization is limited to |
507 | | /// using atomics). |
508 | | /// |
509 | | /// The underlying reason is, signals are asynchronous (they can happen at arbitrary time) and are |
510 | | /// run in context of arbitrary thread (with some limited control of at which thread they can run). |
511 | | /// As a consequence, things like mutexes are prone to deadlocks, memory allocators can likely |
512 | | /// contain mutexes and the compiler doesn't expect the interruption during optimizations. |
513 | | /// |
514 | | /// Things that generally are part of the async-signal-safe set (though check specifically) are |
515 | | /// routines to terminate the program, to further manipulate signals (by the low-level functions, |
516 | | /// not by this library) and to read and write file descriptors. The async-signal-safety is |
517 | | /// transitive - that is, a function composed only from computations (with local variables or with |
518 | | /// variables accessed with proper synchronizations) and other async-signal-safe functions is also |
519 | | /// safe. |
520 | | /// |
521 | | /// As panicking from within a signal handler would be a panic across FFI boundary (which is |
522 | | /// undefined behavior), the passed handler must not panic. |
523 | | /// |
524 | | /// Note that many innocently-looking functions do contain some of the forbidden routines (a lot of |
525 | | /// things lock or allocate). |
526 | | /// |
527 | | /// If you find these limitations hard to satisfy, choose from the helper functions in the |
528 | | /// [signal-hook](https://docs.rs/signal-hook) crate ‒ these provide safe interface to use some |
529 | | /// common signal handling patters. |
530 | | /// |
531 | | /// # Race condition |
532 | | /// |
533 | | /// Upon registering the first hook for a given signal into this library, there's a short race |
534 | | /// condition under the following circumstances: |
535 | | /// |
536 | | /// * The program already has a signal handler installed for this particular signal (through some |
537 | | /// other library, possibly). |
538 | | /// * Concurrently, some other thread installs a different signal handler while it is being |
539 | | /// installed by this library. |
540 | | /// * At the same time, the signal is delivered. |
541 | | /// |
542 | | /// Under such conditions signal-hook might wrongly "chain" to the older signal handler for a short |
543 | | /// while (until the registration is fully complete). |
544 | | /// |
545 | | /// Note that the exact conditions of the race condition might change in future versions of the |
546 | | /// library. The recommended way to avoid it is to register signals before starting any additional |
547 | | /// threads, or at least not to register signals concurrently. |
548 | | /// |
549 | | /// Alternatively, make sure all signals are handled through this library. |
550 | | /// |
551 | | /// # Performance |
552 | | /// |
553 | | /// Even when it is possible to repeatedly install and remove actions during the lifetime of a |
554 | | /// program, the installation and removal is considered a slow operation and should not be done |
555 | | /// very often. Also, there's limited (though huge) amount of distinct IDs (they are `u128`). |
556 | | /// |
557 | | /// # Examples |
558 | | /// |
559 | | /// ```rust |
560 | | /// extern crate signal_hook_registry; |
561 | | /// |
562 | | /// use std::io::Error; |
563 | | /// use std::process; |
564 | | /// |
565 | | /// fn main() -> Result<(), Error> { |
566 | | /// let signal = unsafe { |
567 | | /// signal_hook_registry::register(signal_hook::consts::SIGTERM, || process::abort()) |
568 | | /// }?; |
569 | | /// // Stuff here... |
570 | | /// signal_hook_registry::unregister(signal); // Not really necessary. |
571 | | /// Ok(()) |
572 | | /// } |
573 | | /// ``` |
574 | 0 | pub unsafe fn register<F>(signal: c_int, action: F) -> Result<SigId, Error> |
575 | 0 | where |
576 | 0 | F: Fn() + Sync + Send + 'static, |
577 | | { |
578 | 0 | register_sigaction_impl(signal, Arc::new(move |_: &_| action())) Unexecuted instantiation: signal_hook_registry::register::<signal_hook::flag::register_usize::{closure#0}>::{closure#0}Unexecuted instantiation: signal_hook_registry::register::<signal_hook::flag::register_conditional_default::{closure#1}>::{closure#0}Unexecuted instantiation: signal_hook_registry::register::<signal_hook::flag::register_conditional_shutdown::{closure#0}>::{closure#0}Unexecuted instantiation: signal_hook_registry::register::<signal_hook::flag::register::{closure#0}>::{closure#0}Unexecuted instantiation: signal_hook_registry::register::<signal_hook::low_level::pipe::register_raw::{closure#0}>::{closure#0}Unexecuted instantiation: signal_hook_registry::register::<_>::{closure#0} |
579 | 0 | } Unexecuted instantiation: signal_hook_registry::register::<signal_hook::flag::register_usize::{closure#0}>Unexecuted instantiation: signal_hook_registry::register::<signal_hook::flag::register_conditional_default::{closure#1}>Unexecuted instantiation: signal_hook_registry::register::<signal_hook::flag::register_conditional_shutdown::{closure#0}>Unexecuted instantiation: signal_hook_registry::register::<signal_hook::flag::register::{closure#0}>Unexecuted instantiation: signal_hook_registry::register::<signal_hook::low_level::pipe::register_raw::{closure#0}>Unexecuted instantiation: signal_hook_registry::register::<_> |
580 | | |
581 | | /// Register a signal action. |
582 | | /// |
583 | | /// This acts in the same way as [`register`], including the drawbacks, panics and performance |
584 | | /// characteristics. The only difference is the provided action accepts a [`siginfo_t`] argument, |
585 | | /// providing information about the received signal. |
586 | | /// |
587 | | /// # Safety |
588 | | /// |
589 | | /// See the details of [`register`]. |
590 | | #[cfg(not(windows))] |
591 | 0 | pub unsafe fn register_sigaction<F>(signal: c_int, action: F) -> Result<SigId, Error> |
592 | 0 | where |
593 | 0 | F: Fn(&siginfo_t) + Sync + Send + 'static, |
594 | | { |
595 | 0 | register_sigaction_impl(signal, Arc::new(action)) |
596 | 0 | } Unexecuted instantiation: signal_hook_registry::register_sigaction::<<signal_hook::iterator::backend::PendingSignals<signal_hook::iterator::exfiltrator::SignalOnly> as signal_hook::iterator::backend::AddSignal>::add_signal::{closure#0}>Unexecuted instantiation: signal_hook_registry::register_sigaction::<_> |
597 | | |
598 | 0 | unsafe fn register_sigaction_impl(signal: c_int, action: Arc<Action>) -> Result<SigId, Error> { |
599 | 0 | assert!( |
600 | 0 | !FORBIDDEN.contains(&signal), |
601 | | "Attempted to register forbidden signal {}", |
602 | | signal, |
603 | | ); |
604 | 0 | register_unchecked_impl(signal, action) |
605 | 0 | } |
606 | | |
607 | | /// Register a signal action without checking for forbidden signals. |
608 | | /// |
609 | | /// This acts in the same way as [`register_unchecked`], including the drawbacks, panics and |
610 | | /// performance characteristics. The only difference is the provided action doesn't accept a |
611 | | /// [`siginfo_t`] argument. |
612 | | /// |
613 | | /// # Safety |
614 | | /// |
615 | | /// See the details of [`register`]. |
616 | 0 | pub unsafe fn register_signal_unchecked<F>(signal: c_int, action: F) -> Result<SigId, Error> |
617 | 0 | where |
618 | 0 | F: Fn() + Sync + Send + 'static, |
619 | | { |
620 | 0 | register_unchecked_impl(signal, Arc::new(move |_: &_| action())) |
621 | 0 | } |
622 | | |
623 | | /// Register a signal action without checking for forbidden signals. |
624 | | /// |
625 | | /// This acts the same way as [`register_sigaction`], but without checking for the [`FORBIDDEN`] |
626 | | /// signals. All the signals passed are registered and it is up to the caller to make some sense of |
627 | | /// them. |
628 | | /// |
629 | | /// Note that you really need to know what you're doing if you change eg. the `SIGSEGV` signal |
630 | | /// handler. Generally, you don't want to do that. But unlike the other functions here, this |
631 | | /// function still allows you to do it. |
632 | | /// |
633 | | /// # Safety |
634 | | /// |
635 | | /// See the details of [`register`]. |
636 | | #[cfg(not(windows))] |
637 | 0 | pub unsafe fn register_unchecked<F>(signal: c_int, action: F) -> Result<SigId, Error> |
638 | 0 | where |
639 | 0 | F: Fn(&siginfo_t) + Sync + Send + 'static, |
640 | | { |
641 | 0 | register_unchecked_impl(signal, Arc::new(action)) |
642 | 0 | } |
643 | | |
644 | 0 | unsafe fn register_unchecked_impl(signal: c_int, action: Arc<Action>) -> Result<SigId, Error> { |
645 | 0 | let globals = GlobalData::ensure(); |
646 | | |
647 | 0 | let mut lock = globals.data.write(); |
648 | | |
649 | 0 | let mut sigdata = SignalData::clone(&lock); |
650 | 0 | let id = ActionId(sigdata.next_id); |
651 | 0 | sigdata.next_id += 1; |
652 | | |
653 | 0 | if sigdata.signals.contains(&signal) { |
654 | 0 | let slot = sigdata.signals.get_mut(&signal).unwrap(); |
655 | 0 | assert!(slot.actions.insert(id, action).is_none()); |
656 | | } else { |
657 | | // While the sigaction/signal exchanges the old one atomically, we are not able to |
658 | | // atomically store it somewhere a signal handler could read it. That poses a race |
659 | | // condition where we could lose some signals delivered in between changing it and |
660 | | // storing it. |
661 | | // |
662 | | // Therefore we first store the old one in the fallback storage. The fallback only |
663 | | // covers the cases where the slot is not yet active and becomes "inert" after that, |
664 | | // even if not removed (it may get overwritten by some other signal, but for that the |
665 | | // mutex in globals.data must be unlocked here - and by that time we already stored the |
666 | | // slot. |
667 | | // |
668 | | // And yes, this still leaves a short race condition when some other thread could |
669 | | // replace the signal handler and we would be calling the outdated one for a short |
670 | | // time, until we install the slot. |
671 | 0 | globals |
672 | 0 | .race_fallback |
673 | 0 | .write() |
674 | 0 | .store(Some(Prev::detect(signal)?)); |
675 | | |
676 | 0 | let mut slot = Slot::new(signal)?; |
677 | 0 | slot.actions.insert(id, action); |
678 | 0 | sigdata.signals.insert(signal, slot); |
679 | | } |
680 | | |
681 | 0 | lock.store(sigdata); |
682 | | |
683 | 0 | Ok(SigId { signal, action: id }) |
684 | 0 | } |
685 | | |
686 | | /// Removes a previously installed action. |
687 | | /// |
688 | | /// This function does nothing if the action was already removed. It returns true if it was removed |
689 | | /// and false if the action wasn't found. |
690 | | /// |
691 | | /// It can unregister all the actions installed by [`register`] as well as the ones from downstream |
692 | | /// crates (like [`signal-hook`](https://docs.rs/signal-hook)). |
693 | | /// |
694 | | /// # Warning |
695 | | /// |
696 | | /// This does *not* currently return the default/previous signal handler if the last action for a |
697 | | /// signal was just unregistered. That means that if you replaced for example `SIGTERM` and then |
698 | | /// removed the action, the program will effectively ignore `SIGTERM` signals from now on, not |
699 | | /// terminate on them as is the default action. This is OK if you remove it as part of a shutdown, |
700 | | /// but it is not recommended to remove termination actions during the normal runtime of |
701 | | /// application (unless the desired effect is to create something that can be terminated only by |
702 | | /// SIGKILL). |
703 | 0 | pub fn unregister(id: SigId) -> bool { |
704 | 0 | let globals = GlobalData::ensure(); |
705 | 0 | let mut replace = false; |
706 | 0 | let mut lock = globals.data.write(); |
707 | 0 | let mut sigdata = SignalData::clone(&lock); |
708 | 0 | if let Some(slot) = sigdata.signals.get_mut(&id.signal) { |
709 | 0 | replace = slot.actions.remove(&id.action).is_some(); |
710 | 0 | } |
711 | 0 | if replace { |
712 | 0 | lock.store(sigdata); |
713 | 0 | } |
714 | 0 | replace |
715 | 0 | } |
716 | | |
717 | | // We keep this one here for strict backwards compatibility, but the API is kind of bad. One can |
718 | | // delete actions that don't belong to them, which is kind of against the whole idea of not |
719 | | // breaking stuff for others. |
720 | | #[deprecated( |
721 | | since = "1.3.0", |
722 | | note = "Don't use. Can influence unrelated parts of program / unknown actions" |
723 | | )] |
724 | | #[doc(hidden)] |
725 | 0 | pub fn unregister_signal(signal: c_int) -> bool { |
726 | 0 | let globals = GlobalData::ensure(); |
727 | 0 | let mut replace = false; |
728 | 0 | let mut lock = globals.data.write(); |
729 | 0 | let mut sigdata = SignalData::clone(&lock); |
730 | 0 | if let Some(slot) = sigdata.signals.get_mut(&signal) { |
731 | 0 | if !slot.actions.is_empty() { |
732 | 0 | slot.actions.clear(); |
733 | 0 | replace = true; |
734 | 0 | } |
735 | 0 | } |
736 | 0 | if replace { |
737 | 0 | lock.store(sigdata); |
738 | 0 | } |
739 | 0 | replace |
740 | 0 | } |
741 | | |
742 | | #[cfg(test)] |
743 | | mod tests { |
744 | | use std::sync::atomic::{AtomicUsize, Ordering}; |
745 | | use std::sync::Arc; |
746 | | use std::thread; |
747 | | use std::time::Duration; |
748 | | |
749 | | #[cfg(not(windows))] |
750 | | use libc::{pid_t, SIGUSR1, SIGUSR2}; |
751 | | |
752 | | #[cfg(windows)] |
753 | | use libc::SIGTERM as SIGUSR1; |
754 | | #[cfg(windows)] |
755 | | use libc::SIGTERM as SIGUSR2; |
756 | | |
757 | | use super::*; |
758 | | |
759 | | #[test] |
760 | | #[should_panic] |
761 | | fn panic_forbidden() { |
762 | | let _ = unsafe { register(SIGILL, || ()) }; |
763 | | } |
764 | | |
765 | | /// Registering the forbidden signals is allowed in the _unchecked version. |
766 | | #[test] |
767 | | #[allow(clippy::redundant_closure)] // Clippy, you're wrong. Because it changes the return value. |
768 | | fn forbidden_raw() { |
769 | | unsafe { register_signal_unchecked(SIGFPE, || std::process::abort()).unwrap() }; |
770 | | } |
771 | | |
772 | | #[test] |
773 | | fn signal_without_pid() { |
774 | | let status = Arc::new(AtomicUsize::new(0)); |
775 | | let action = { |
776 | | let status = Arc::clone(&status); |
777 | | move || { |
778 | | status.store(1, Ordering::Relaxed); |
779 | | } |
780 | | }; |
781 | | unsafe { |
782 | | register(SIGUSR2, action).unwrap(); |
783 | | libc::raise(SIGUSR2); |
784 | | } |
785 | | for _ in 0..10 { |
786 | | thread::sleep(Duration::from_millis(100)); |
787 | | let current = status.load(Ordering::Relaxed); |
788 | | match current { |
789 | | // Not yet |
790 | | 0 => continue, |
791 | | // Good, we are done with the correct result |
792 | | _ if current == 1 => return, |
793 | | _ => panic!("Wrong result value {}", current), |
794 | | } |
795 | | } |
796 | | panic!("Timed out waiting for the signal"); |
797 | | } |
798 | | |
799 | | #[test] |
800 | | #[cfg(not(windows))] |
801 | | fn signal_with_pid() { |
802 | | let status = Arc::new(AtomicUsize::new(0)); |
803 | | let action = { |
804 | | let status = Arc::clone(&status); |
805 | | move |siginfo: &siginfo_t| { |
806 | | // Hack: currently, libc exposes only the first 3 fields of siginfo_t. The pid |
807 | | // comes somewhat later on. Therefore, we do a Really Ugly Hack and define our |
808 | | // own structure (and hope it is correct on all platforms). But hey, this is |
809 | | // only the tests, so we are going to get away with this. |
810 | | #[repr(C)] |
811 | | struct SigInfo { |
812 | | _fields: [c_int; 3], |
813 | | #[cfg(all(target_pointer_width = "64", target_os = "linux"))] |
814 | | _pad: c_int, |
815 | | pid: pid_t, |
816 | | } |
817 | | let s: &SigInfo = unsafe { |
818 | | (siginfo as *const _ as usize as *const SigInfo) |
819 | | .as_ref() |
820 | | .unwrap() |
821 | | }; |
822 | | status.store(s.pid as usize, Ordering::Relaxed); |
823 | | } |
824 | | }; |
825 | | let pid; |
826 | | unsafe { |
827 | | pid = libc::getpid(); |
828 | | register_sigaction(SIGUSR2, action).unwrap(); |
829 | | libc::raise(SIGUSR2); |
830 | | } |
831 | | for _ in 0..10 { |
832 | | thread::sleep(Duration::from_millis(100)); |
833 | | let current = status.load(Ordering::Relaxed); |
834 | | match current { |
835 | | // Not yet (PID == 0 doesn't happen) |
836 | | 0 => continue, |
837 | | // Good, we are done with the correct result |
838 | | _ if current == pid as usize => return, |
839 | | _ => panic!("Wrong status value {}", current), |
840 | | } |
841 | | } |
842 | | panic!("Timed out waiting for the signal"); |
843 | | } |
844 | | |
845 | | /// Check that registration works as expected and that unregister tells if it did or not. |
846 | | #[test] |
847 | | fn register_unregister() { |
848 | | let signal = unsafe { register(SIGUSR1, || ()).unwrap() }; |
849 | | // It was there now, so we can unregister |
850 | | assert!(unregister(signal)); |
851 | | // The next time unregistering does nothing and tells us so. |
852 | | assert!(!unregister(signal)); |
853 | | } |
854 | | |
855 | | /// Check that errno is not clobbered by the signal handler. |
856 | | #[test] |
857 | | fn save_restore_errno() { |
858 | | const MAGIC_ERRNO: i32 = 123456; |
859 | | let action = move || { |
860 | | errno::set_errno(Errno(MAGIC_ERRNO)); |
861 | | }; |
862 | | unsafe { |
863 | | register(SIGUSR1, action).unwrap(); |
864 | | libc::raise(SIGUSR1); |
865 | | } |
866 | | // NB: raise() might clobber errno on some platforms, so this test isn't waterproof. But it |
867 | | // fails at least sometimes on some platforms if the errno save/restore is removed. |
868 | | assert!(errno::errno().0 != MAGIC_ERRNO); |
869 | | } |
870 | | } |