signal_hook_registry/
lib.rs

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