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