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