Coverage Report

Created: 2025-08-29 06:13

/rust/registry/src/index.crates.io-6f17d22bba15001f/signal-hook-registry-1.4.6/src/lib.rs
Line
Count
Source (jump to first uncovered line)
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
65
extern crate libc;
66
67
mod half_lock;
68
69
use std::collections::hash_map::Entry;
70
use std::collections::{BTreeMap, HashMap};
71
use std::io::Error;
72
use std::mem;
73
use std::ptr;
74
use 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)]
78
use std::sync::ONCE_INIT;
79
use std::sync::{Arc, Once};
80
81
#[cfg(not(windows))]
82
use libc::{c_int, c_void, sigaction, siginfo_t};
83
#[cfg(windows)]
84
use libc::{c_int, sighandler_t};
85
86
#[cfg(not(windows))]
87
use libc::{SIGFPE, SIGILL, SIGKILL, SIGSEGV, SIGSTOP};
88
#[cfg(windows)]
89
use libc::{SIGFPE, SIGILL, SIGSEGV};
90
91
use 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)]
96
const SIG_DFL: sighandler_t = 0;
97
#[cfg(windows)]
98
const SIG_IGN: sighandler_t = 1;
99
#[cfg(windows)]
100
const SIG_GET: sighandler_t = 2;
101
#[cfg(windows)]
102
const SIG_ERR: sighandler_t = !0;
103
104
// To simplify implementation. Not to be exposed.
105
#[cfg(windows)]
106
#[allow(non_camel_case_types)]
107
struct 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)]
123
struct 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)]
130
pub 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)]
138
type Action = Fn(&siginfo_t) + Send + Sync;
139
140
#[derive(Clone)]
141
struct 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
148
impl 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
0
    fn new(signal: libc::c_int) -> Result<Self, Error> {
163
0
        // C data structure, expected to be zeroed out.
164
0
        let mut new: libc::sigaction = unsafe { mem::zeroed() };
165
0
166
0
        // Note: AIX fixed their naming in libc 0.2.171.
167
0
        //
168
0
        // However, if we mandate that _for everyone_, other systems fail to compile on old Rust
169
0
        // versions (eg. 1.26.0), because they are no longer able to compile this new libc.
170
0
        //
171
0
        // There doesn't seem to be a way to make Cargo force the dependency for only one target
172
0
        // (it doesn't compile the ones it doesn't need, but it stills considers the other targets
173
0
        // for version resolution).
174
0
        //
175
0
        // Therefore, we let the user have freedom - if they want AIX, they can upgrade to new
176
0
        // enough libc. If they want ancient rustc, they can force older versions of libc.
177
0
        //
178
0
        // See #169.
179
0
180
0
        new.sa_sigaction = handler as usize; // If it doesn't compile on AIX, upgrade the libc dependency
181
0
182
0
        // Android is broken and uses different int types than the rest (and different depending on
183
0
        // the pointer width). This converts the flags to the proper type no matter what it is on
184
0
        // the given platform.
185
0
        #[cfg(target_os = "nto")]
186
0
        let flags = 0;
187
0
        // SA_RESTART is supported by qnx https://www.qnx.com/support/knowledgebase.html?id=50130000000SmiD
188
0
        #[cfg(not(target_os = "nto"))]
189
0
        let flags = libc::SA_RESTART;
190
0
        #[allow(unused_assignments)]
191
0
        let mut siginfo = flags;
192
0
        siginfo = libc::SA_SIGINFO as _;
193
0
        let flags = flags | siginfo;
194
0
        new.sa_flags = flags as _;
195
0
        // C data structure, expected to be zeroed out.
196
0
        let mut old: libc::sigaction = unsafe { mem::zeroed() };
197
0
        // FFI ‒ pointers are valid, it doesn't take ownership.
198
0
        if unsafe { libc::sigaction(signal, &new, &mut old) } != 0 {
199
0
            return Err(Error::last_os_error());
200
0
        }
201
0
        Ok(Slot {
202
0
            prev: Prev { signal, info: old },
203
0
            actions: BTreeMap::new(),
204
0
        })
205
0
    }
206
}
207
208
#[derive(Clone)]
209
struct SignalData {
210
    signals: HashMap<c_int, Slot>,
211
    next_id: u128,
212
}
213
214
#[derive(Clone)]
215
struct Prev {
216
    signal: c_int,
217
    #[cfg(windows)]
218
    info: sighandler_t,
219
    #[cfg(not(windows))]
220
    info: sigaction,
221
}
222
223
impl 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
0
    fn detect(signal: c_int) -> Result<Self, Error> {
235
0
        // C data structure, expected to be zeroed out.
236
0
        let mut old: libc::sigaction = unsafe { mem::zeroed() };
237
0
        // FFI ‒ pointers are valid, it doesn't take ownership.
238
0
        if unsafe { libc::sigaction(signal, ptr::null(), &mut old) } != 0 {
239
0
            return Err(Error::last_os_error());
240
0
        }
241
0
242
0
        Ok(Prev { signal, info: old })
243
0
    }
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
0
    unsafe fn execute(&self, sig: c_int, info: *mut siginfo_t, data: *mut c_void) {
259
0
        let fptr = self.info.sa_sigaction;
260
0
        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
0
            let mut siginfo = self.info.sa_flags;
270
0
            siginfo = libc::SA_SIGINFO as _;
271
0
            if self.info.sa_flags & siginfo == 0 {
272
0
                let action = mem::transmute::<usize, extern "C" fn(c_int)>(fptr);
273
0
                action(sig);
274
0
            } else {
275
0
                type SigAction = extern "C" fn(c_int, *mut siginfo_t, *mut c_void);
276
0
                let action = mem::transmute::<usize, SigAction>(fptr);
277
0
                action(sig, info, data);
278
0
            }
279
0
        }
280
0
    }
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.
289
struct 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
299
static GLOBAL_DATA: AtomicPtr<GlobalData> = AtomicPtr::new(ptr::null_mut());
300
#[allow(deprecated)]
301
static GLOBAL_INIT: Once = ONCE_INIT;
302
303
impl GlobalData {
304
0
    fn get() -> &'static Self {
305
0
        let data = GLOBAL_DATA.load(Ordering::Acquire);
306
0
        // # Safety
307
0
        //
308
0
        // * The data actually does live forever - created by Box::into_raw.
309
0
        // * It is _never_ modified (apart for interior mutability, but that one is fine).
310
0
        unsafe { data.as_ref().expect("We shall be set up already") }
311
0
    }
312
0
    fn ensure() -> &'static Self {
313
0
        GLOBAL_INIT.call_once(|| {
314
0
            let data = Box::into_raw(Box::new(GlobalData {
315
0
                data: HalfLock::new(SignalData {
316
0
                    signals: HashMap::new(),
317
0
                    next_id: 1,
318
0
                }),
319
0
                race_fallback: HalfLock::new(None),
320
0
            }));
321
0
            let old = GLOBAL_DATA.swap(data, Ordering::Release);
322
0
            assert!(old.is_null());
323
0
        });
324
0
        Self::get()
325
0
    }
326
}
327
328
#[cfg(windows)]
329
extern "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))]
373
0
extern "C" fn handler(sig: c_int, info: *mut siginfo_t, data: *mut c_void) {
374
0
    let globals = GlobalData::get();
375
0
    let fallback = globals.race_fallback.read();
376
0
    let sigdata = globals.data.read();
377
378
0
    if let Some(slot) = sigdata.signals.get(&sig) {
379
0
        unsafe { slot.prev.execute(sig, info, data) };
380
0
381
0
        let info = unsafe { info.as_ref() };
382
0
        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
0
                libc::write(2, MSG.as_ptr() as *const _, MSG.len());
392
0
                libc::abort();
393
            }
394
0
        });
395
396
0
        for action in slot.actions.values() {
397
0
            action(info);
398
0
        }
399
0
    } 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
0
        if prev.signal == sig {
404
0
            unsafe { prev.execute(sig, info, data) };
405
0
        }
406
        // else -> probably should not happen, but races with other threads are possible so
407
        // better safe
408
0
    }
409
0
}
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`].
418
pub const FORBIDDEN: &[c_int] = FORBIDDEN_IMPL;
419
420
#[cfg(windows)]
421
const FORBIDDEN_IMPL: &[c_int] = &[SIGILL, SIGFPE, SIGSEGV];
422
#[cfg(not(windows))]
423
const 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
/// ```
541
0
pub unsafe fn register<F>(signal: c_int, action: F) -> Result<SigId, Error>
542
0
where
543
0
    F: Fn() + Sync + Send + 'static,
544
0
{
545
0
    register_sigaction_impl(signal, move |_: &_| action())
Unexecuted instantiation: signal_hook_registry::register::<tokio::signal::unix::signal_enable::{closure#0}::{closure#0}>::{closure#0}
Unexecuted instantiation: signal_hook_registry::register::<_>::{closure#0}
546
0
}
Unexecuted instantiation: signal_hook_registry::register::<tokio::signal::unix::signal_enable::{closure#0}::{closure#0}>
Unexecuted instantiation: signal_hook_registry::register::<_>
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))]
558
0
pub unsafe fn register_sigaction<F>(signal: c_int, action: F) -> Result<SigId, Error>
559
0
where
560
0
    F: Fn(&siginfo_t) + Sync + Send + 'static,
561
0
{
562
0
    register_sigaction_impl(signal, action)
563
0
}
564
565
0
unsafe fn register_sigaction_impl<F>(signal: c_int, action: F) -> Result<SigId, Error>
566
0
where
567
0
    F: Fn(&siginfo_t) + Sync + Send + 'static,
568
0
{
569
0
    assert!(
570
0
        !FORBIDDEN.contains(&signal),
571
0
        "Attempted to register forbidden signal {}",
572
        signal,
573
    );
574
0
    register_unchecked_impl(signal, action)
575
0
}
Unexecuted instantiation: signal_hook_registry::register_sigaction_impl::<signal_hook_registry::register<tokio::signal::unix::signal_enable::{closure#0}::{closure#0}>::{closure#0}>
Unexecuted instantiation: signal_hook_registry::register_sigaction_impl::<_>
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`].
586
0
pub unsafe fn register_signal_unchecked<F>(signal: c_int, action: F) -> Result<SigId, Error>
587
0
where
588
0
    F: Fn() + Sync + Send + 'static,
589
0
{
590
0
    register_unchecked_impl(signal, move |_: &_| action())
591
0
}
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))]
607
0
pub unsafe fn register_unchecked<F>(signal: c_int, action: F) -> Result<SigId, Error>
608
0
where
609
0
    F: Fn(&siginfo_t) + Sync + Send + 'static,
610
0
{
611
0
    register_unchecked_impl(signal, action)
612
0
}
613
614
0
unsafe fn register_unchecked_impl<F>(signal: c_int, action: F) -> Result<SigId, Error>
615
0
where
616
0
    F: Fn(&siginfo_t) + Sync + Send + 'static,
617
0
{
618
0
    let globals = GlobalData::ensure();
619
0
    let action = Arc::from(action);
620
0
621
0
    let mut lock = globals.data.write();
622
0
623
0
    let mut sigdata = SignalData::clone(&lock);
624
0
    let id = ActionId(sigdata.next_id);
625
0
    sigdata.next_id += 1;
626
0
627
0
    match sigdata.signals.entry(signal) {
628
0
        Entry::Occupied(mut occupied) => {
629
0
            assert!(occupied.get_mut().actions.insert(id, action).is_none());
630
        }
631
0
        Entry::Vacant(place) => {
632
0
            // While the sigaction/signal exchanges the old one atomically, we are not able to
633
0
            // atomically store it somewhere a signal handler could read it. That poses a race
634
0
            // condition where we could lose some signals delivered in between changing it and
635
0
            // storing it.
636
0
            //
637
0
            // Therefore we first store the old one in the fallback storage. The fallback only
638
0
            // covers the cases where the slot is not yet active and becomes "inert" after that,
639
0
            // even if not removed (it may get overwritten by some other signal, but for that the
640
0
            // mutex in globals.data must be unlocked here - and by that time we already stored the
641
0
            // slot.
642
0
            //
643
0
            // And yes, this still leaves a short race condition when some other thread could
644
0
            // replace the signal handler and we would be calling the outdated one for a short
645
0
            // time, until we install the slot.
646
0
            globals
647
0
                .race_fallback
648
0
                .write()
649
0
                .store(Some(Prev::detect(signal)?));
650
651
0
            let mut slot = Slot::new(signal)?;
652
0
            slot.actions.insert(id, action);
653
0
            place.insert(slot);
654
        }
655
    }
656
657
0
    lock.store(sigdata);
658
0
659
0
    Ok(SigId { signal, action: id })
660
0
}
Unexecuted instantiation: signal_hook_registry::register_unchecked_impl::<signal_hook_registry::register<tokio::signal::unix::signal_enable::{closure#0}::{closure#0}>::{closure#0}>
Unexecuted instantiation: signal_hook_registry::register_unchecked_impl::<_>
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).
679
0
pub fn unregister(id: SigId) -> bool {
680
0
    let globals = GlobalData::ensure();
681
0
    let mut replace = false;
682
0
    let mut lock = globals.data.write();
683
0
    let mut sigdata = SignalData::clone(&lock);
684
0
    if let Some(slot) = sigdata.signals.get_mut(&id.signal) {
685
0
        replace = slot.actions.remove(&id.action).is_some();
686
0
    }
687
0
    if replace {
688
0
        lock.store(sigdata);
689
0
    }
690
0
    replace
691
0
}
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)]
701
0
pub fn unregister_signal(signal: c_int) -> bool {
702
0
    let globals = GlobalData::ensure();
703
0
    let mut replace = false;
704
0
    let mut lock = globals.data.write();
705
0
    let mut sigdata = SignalData::clone(&lock);
706
0
    if let Some(slot) = sigdata.signals.get_mut(&signal) {
707
0
        if !slot.actions.is_empty() {
708
0
            slot.actions.clear();
709
0
            replace = true;
710
0
        }
711
0
    }
712
0
    if replace {
713
0
        lock.store(sigdata);
714
0
    }
715
0
    replace
716
0
}
717
718
#[cfg(test)]
719
mod 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
}