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