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. The set of
466/// functions allowed to be called from within is very limited (they are called async-signal-safe
467/// functions by POSIX). These specifically do *not* contain mutexes and memory
468/// allocation/deallocation. They *do* contain routines to terminate the program, to further
469/// manipulate signals (by the low-level functions, not by this library) and to read and write file
470/// descriptors. Calling program's own functions consisting only of these is OK, as is manipulating
471/// program's variables ‒ however, as the action can be called on any thread that does not have the
472/// given signal masked (by default no signal is masked on any thread), and mutexes are a no-go,
473/// this is harder than it looks like at first.
474///
475/// As panicking from within a signal handler would be a panic across FFI boundary (which is
476/// undefined behavior), the passed handler must not panic.
477///
478/// If you find these limitations hard to satisfy, choose from the helper functions in the
479/// [signal-hook](https://docs.rs/signal-hook) crate ‒ these provide safe interface to use some
480/// common signal handling patters.
481///
482/// # Race condition
483///
484/// Upon registering the first hook for a given signal into this library, there's a short race
485/// condition under the following circumstances:
486///
487/// * The program already has a signal handler installed for this particular signal (through some
488/// other library, possibly).
489/// * Concurrently, some other thread installs a different signal handler while it is being
490/// installed by this library.
491/// * At the same time, the signal is delivered.
492///
493/// Under such conditions signal-hook might wrongly "chain" to the older signal handler for a short
494/// while (until the registration is fully complete).
495///
496/// Note that the exact conditions of the race condition might change in future versions of the
497/// library. The recommended way to avoid it is to register signals before starting any additional
498/// threads, or at least not to register signals concurrently.
499///
500/// Alternatively, make sure all signals are handled through this library.
501///
502/// # Performance
503///
504/// Even when it is possible to repeatedly install and remove actions during the lifetime of a
505/// program, the installation and removal is considered a slow operation and should not be done
506/// very often. Also, there's limited (though huge) amount of distinct IDs (they are `u128`).
507///
508/// # Examples
509///
510/// ```rust
511/// extern crate signal_hook_registry;
512///
513/// use std::io::Error;
514/// use std::process;
515///
516/// fn main() -> Result<(), Error> {
517/// let signal = unsafe {
518/// signal_hook_registry::register(signal_hook::consts::SIGTERM, || process::abort())
519/// }?;
520/// // Stuff here...
521/// signal_hook_registry::unregister(signal); // Not really necessary.
522/// Ok(())
523/// }
524/// ```
525pub unsafe fn register<F>(signal: c_int, action: F) -> Result<SigId, Error>
526where
527 F: Fn() + Sync + Send + 'static,
528{
529 register_sigaction_impl(signal, move |_: &_| action())
530}
531
532/// Register a signal action.
533///
534/// This acts in the same way as [`register`], including the drawbacks, panics and performance
535/// characteristics. The only difference is the provided action accepts a [`siginfo_t`] argument,
536/// providing information about the received signal.
537///
538/// # Safety
539///
540/// See the details of [`register`].
541#[cfg(not(windows))]
542pub unsafe fn register_sigaction<F>(signal: c_int, action: F) -> Result<SigId, Error>
543where
544 F: Fn(&siginfo_t) + Sync + Send + 'static,
545{
546 register_sigaction_impl(signal, action)
547}
548
549unsafe fn register_sigaction_impl<F>(signal: c_int, action: F) -> Result<SigId, Error>
550where
551 F: Fn(&siginfo_t) + Sync + Send + 'static,
552{
553 assert!(
554 !FORBIDDEN.contains(&signal),
555 "Attempted to register forbidden signal {}",
556 signal,
557 );
558 register_unchecked_impl(signal, action)
559}
560
561/// Register a signal action without checking for forbidden signals.
562///
563/// This acts in the same way as [`register_unchecked`], including the drawbacks, panics and
564/// performance characteristics. The only difference is the provided action doesn't accept a
565/// [`siginfo_t`] argument.
566///
567/// # Safety
568///
569/// See the details of [`register`].
570pub unsafe fn register_signal_unchecked<F>(signal: c_int, action: F) -> Result<SigId, Error>
571where
572 F: Fn() + Sync + Send + 'static,
573{
574 register_unchecked_impl(signal, move |_: &_| action())
575}
576
577/// Register a signal action without checking for forbidden signals.
578///
579/// This acts the same way as [`register_sigaction`], but without checking for the [`FORBIDDEN`]
580/// signals. All the signals passed are registered and it is up to the caller to make some sense of
581/// them.
582///
583/// Note that you really need to know what you're doing if you change eg. the `SIGSEGV` signal
584/// handler. Generally, you don't want to do that. But unlike the other functions here, this
585/// function still allows you to do it.
586///
587/// # Safety
588///
589/// See the details of [`register`].
590#[cfg(not(windows))]
591pub unsafe fn register_unchecked<F>(signal: c_int, action: F) -> Result<SigId, Error>
592where
593 F: Fn(&siginfo_t) + Sync + Send + 'static,
594{
595 register_unchecked_impl(signal, action)
596}
597
598unsafe fn register_unchecked_impl<F>(signal: c_int, action: F) -> Result<SigId, Error>
599where
600 F: Fn(&siginfo_t) + Sync + Send + 'static,
601{
602 let globals = GlobalData::ensure();
603 let action = Arc::from(action);
604
605 let mut lock = globals.data.write();
606
607 let mut sigdata = SignalData::clone(&lock);
608 let id = ActionId(sigdata.next_id);
609 sigdata.next_id += 1;
610
611 match sigdata.signals.entry(signal) {
612 Entry::Occupied(mut occupied) => {
613 assert!(occupied.get_mut().actions.insert(id, action).is_none());
614 }
615 Entry::Vacant(place) => {
616 // While the sigaction/signal exchanges the old one atomically, we are not able to
617 // atomically store it somewhere a signal handler could read it. That poses a race
618 // condition where we could lose some signals delivered in between changing it and
619 // storing it.
620 //
621 // Therefore we first store the old one in the fallback storage. The fallback only
622 // covers the cases where the slot is not yet active and becomes "inert" after that,
623 // even if not removed (it may get overwritten by some other signal, but for that the
624 // mutex in globals.data must be unlocked here - and by that time we already stored the
625 // slot.
626 //
627 // And yes, this still leaves a short race condition when some other thread could
628 // replace the signal handler and we would be calling the outdated one for a short
629 // time, until we install the slot.
630 globals
631 .race_fallback
632 .write()
633 .store(Some(Prev::detect(signal)?));
634
635 let mut slot = Slot::new(signal)?;
636 slot.actions.insert(id, action);
637 place.insert(slot);
638 }
639 }
640
641 lock.store(sigdata);
642
643 Ok(SigId { signal, action: id })
644}
645
646/// Removes a previously installed action.
647///
648/// This function does nothing if the action was already removed. It returns true if it was removed
649/// and false if the action wasn't found.
650///
651/// It can unregister all the actions installed by [`register`] as well as the ones from downstream
652/// crates (like [`signal-hook`](https://docs.rs/signal-hook)).
653///
654/// # Warning
655///
656/// This does *not* currently return the default/previous signal handler if the last action for a
657/// signal was just unregistered. That means that if you replaced for example `SIGTERM` and then
658/// removed the action, the program will effectively ignore `SIGTERM` signals from now on, not
659/// terminate on them as is the default action. This is OK if you remove it as part of a shutdown,
660/// but it is not recommended to remove termination actions during the normal runtime of
661/// application (unless the desired effect is to create something that can be terminated only by
662/// SIGKILL).
663pub fn unregister(id: SigId) -> bool {
664 let globals = GlobalData::ensure();
665 let mut replace = false;
666 let mut lock = globals.data.write();
667 let mut sigdata = SignalData::clone(&lock);
668 if let Some(slot) = sigdata.signals.get_mut(&id.signal) {
669 replace = slot.actions.remove(&id.action).is_some();
670 }
671 if replace {
672 lock.store(sigdata);
673 }
674 replace
675}
676
677// We keep this one here for strict backwards compatibility, but the API is kind of bad. One can
678// delete actions that don't belong to them, which is kind of against the whole idea of not
679// breaking stuff for others.
680#[deprecated(
681 since = "1.3.0",
682 note = "Don't use. Can influence unrelated parts of program / unknown actions"
683)]
684#[doc(hidden)]
685pub fn unregister_signal(signal: c_int) -> bool {
686 let globals = GlobalData::ensure();
687 let mut replace = false;
688 let mut lock = globals.data.write();
689 let mut sigdata = SignalData::clone(&lock);
690 if let Some(slot) = sigdata.signals.get_mut(&signal) {
691 if !slot.actions.is_empty() {
692 slot.actions.clear();
693 replace = true;
694 }
695 }
696 if replace {
697 lock.store(sigdata);
698 }
699 replace
700}
701
702#[cfg(test)]
703mod tests {
704 use std::sync::atomic::{AtomicUsize, Ordering};
705 use std::sync::Arc;
706 use std::thread;
707 use std::time::Duration;
708
709 #[cfg(not(windows))]
710 use libc::{pid_t, SIGUSR1, SIGUSR2};
711
712 #[cfg(windows)]
713 use libc::SIGTERM as SIGUSR1;
714 #[cfg(windows)]
715 use libc::SIGTERM as SIGUSR2;
716
717 use super::*;
718
719 #[test]
720 #[should_panic]
721 fn panic_forbidden() {
722 let _ = unsafe { register(SIGILL, || ()) };
723 }
724
725 /// Registering the forbidden signals is allowed in the _unchecked version.
726 #[test]
727 #[allow(clippy::redundant_closure)] // Clippy, you're wrong. Because it changes the return value.
728 fn forbidden_raw() {
729 unsafe { register_signal_unchecked(SIGFPE, || std::process::abort()).unwrap() };
730 }
731
732 #[test]
733 fn signal_without_pid() {
734 let status = Arc::new(AtomicUsize::new(0));
735 let action = {
736 let status = Arc::clone(&status);
737 move || {
738 status.store(1, Ordering::Relaxed);
739 }
740 };
741 unsafe {
742 register(SIGUSR2, action).unwrap();
743 libc::raise(SIGUSR2);
744 }
745 for _ in 0..10 {
746 thread::sleep(Duration::from_millis(100));
747 let current = status.load(Ordering::Relaxed);
748 match current {
749 // Not yet
750 0 => continue,
751 // Good, we are done with the correct result
752 _ if current == 1 => return,
753 _ => panic!("Wrong result value {}", current),
754 }
755 }
756 panic!("Timed out waiting for the signal");
757 }
758
759 #[test]
760 #[cfg(not(windows))]
761 fn signal_with_pid() {
762 let status = Arc::new(AtomicUsize::new(0));
763 let action = {
764 let status = Arc::clone(&status);
765 move |siginfo: &siginfo_t| {
766 // Hack: currently, libc exposes only the first 3 fields of siginfo_t. The pid
767 // comes somewhat later on. Therefore, we do a Really Ugly Hack and define our
768 // own structure (and hope it is correct on all platforms). But hey, this is
769 // only the tests, so we are going to get away with this.
770 #[repr(C)]
771 struct SigInfo {
772 _fields: [c_int; 3],
773 #[cfg(all(target_pointer_width = "64", target_os = "linux"))]
774 _pad: c_int,
775 pid: pid_t,
776 }
777 let s: &SigInfo = unsafe {
778 (siginfo as *const _ as usize as *const SigInfo)
779 .as_ref()
780 .unwrap()
781 };
782 status.store(s.pid as usize, Ordering::Relaxed);
783 }
784 };
785 let pid;
786 unsafe {
787 pid = libc::getpid();
788 register_sigaction(SIGUSR2, action).unwrap();
789 libc::raise(SIGUSR2);
790 }
791 for _ in 0..10 {
792 thread::sleep(Duration::from_millis(100));
793 let current = status.load(Ordering::Relaxed);
794 match current {
795 // Not yet (PID == 0 doesn't happen)
796 0 => continue,
797 // Good, we are done with the correct result
798 _ if current == pid as usize => return,
799 _ => panic!("Wrong status value {}", current),
800 }
801 }
802 panic!("Timed out waiting for the signal");
803 }
804
805 /// Check that registration works as expected and that unregister tells if it did or not.
806 #[test]
807 fn register_unregister() {
808 let signal = unsafe { register(SIGUSR1, || ()).unwrap() };
809 // It was there now, so we can unregister
810 assert!(unregister(signal));
811 // The next time unregistering does nothing and tells us so.
812 assert!(!unregister(signal));
813 }
814}