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