interprocess_docfix/os/windows/
signal.rs

1//! C signal support on Windows.
2//!
3//! A big difference from POSIX platforms is the amount of signals that Windows supports. Signals on Windows are therefore much less useful than POSIX ones.
4//!
5//! # Signal safe C functions
6//! The C standard specifies that calling any functions *other than those ones* from a signal hook **results in undefined behavior**:
7//! - `abort`
8//! - `_Exit`
9//! - `quick_exit`
10//! - `signal`, but only if it is used for setting a handler for the same signal as the one being currently handled
11//! - atomic C functions, but only the ones which are lock-free (practically never used in Rust since it has its own atomics which use compiler intrinsics)
12//! - `atomic_is_lock_free`
13
14use super::imports::*;
15use std::{
16    convert::{TryFrom, TryInto},
17    error::Error,
18    fmt::{self, Formatter},
19    panic, process,
20};
21
22/// Installs the specified handler for the specified signal.
23///
24/// # Example
25/// ```no_run
26/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
27/// # #[cfg(all(windows, feature = "signals"))] {
28/// use interprocess::os::windows::signal::{self, SignalType, SignalHandler};
29///
30/// let handler = unsafe {
31///     // Since signal handlers are restricted to a specific set of C functions, creating a
32///     // handler from an arbitrary function is unsafe because it might call a function
33///     // outside the list, and there's no real way to know that at compile time with the
34///     // current version of Rust. Since we're only using the write() system call here, this
35///     // is safe.
36///     SignalHandler::from_fn(|| {
37///         println!("You pressed Ctrl-C!");
38///     })
39/// };
40///
41/// // Install our handler for the KeyboardInterrupt signal type.
42/// signal::set_handler(SignalType::KeyboardInterrupt, handler)?;
43/// # }
44/// # Ok(()) }
45/// ```
46pub fn set_handler(signal_type: SignalType, handler: SignalHandler) -> Result<(), SetHandlerError> {
47    if signal_type.is_unsafe() {
48        return Err(SetHandlerError::UnsafeSignal);
49    }
50
51    unsafe { set_unsafe_handler(signal_type, handler) }
52}
53/// Installs the specified handler for the specified unsafe signal.
54///
55/// # Safety
56/// The handler and all code that may or may not execute afterwards must be prepared for the aftermath of what might've caused the signal.
57///
58/// [`SegmentationFault`] or [`IllegalInstruction`] are most likely caused by undefined behavior invoked from Rust (the former is caused by dereferencing invalid memory, the latter is caused by dereferencing an incorrectly aligned pointer on ISAs like ARM which do not tolerate misaligned pointers), which means that the program is unsound and the only meaningful thing to do is to capture as much information as possible in a safe way – preferably using OS services to create a dump, rather than trying to read the program's global state, which might be irreversibly corrupted – and write the crash dump to some on-disk location.
59///
60/// # Example
61/// ```no_run
62/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
63/// # #[cfg(all(windows, feature = "signals"))] {
64/// use interprocess::os::windows::signal::{self, SignalType, SignalHandler};
65///
66/// let handler = unsafe {
67///     // Since signal handlers are restricted to a specific set of C functions, creating a
68///     // handler from an arbitrary function is unsafe because it might call a function
69///     // outside the list, and there's no real way to know that at compile time with the
70///     // current version of Rust. Since we're only using the write() system call here, this
71///     // is safe.
72///     SignalHandler::from_fn(|| {
73///         println!("Oh no, we're running on an i386!");
74///         std::process::abort();
75///     })
76/// };
77///
78/// unsafe {
79///     // Install our handler for the IllegalInstruction signal type.
80///     signal::set_unsafe_handler(SignalType::IllegalInstruction, handler)?;
81/// }
82/// # }
83/// # Ok(()) }
84/// ```
85///
86/// [`SegmentationFault`]: enum.SignalType.html#variant.SegmentationFault " "
87/// [`IllegalInstruction`]: enum.SignalType.html#variant.IllegalInstruction " "
88pub unsafe fn set_unsafe_handler(
89    signal_type: SignalType,
90    handler: SignalHandler,
91) -> Result<(), SetHandlerError> {
92    let signal_type = signal_type as u64;
93    let handlers = HANDLERS.read();
94    let new_signal = handlers.get(signal_type).is_none();
95    drop(handlers);
96    if new_signal {
97        let mut handlers = HANDLERS.write();
98        handlers.remove(signal_type);
99        handlers.insert(signal_type, handler);
100        drop(handlers);
101
102        let hook_val = match handler {
103            SignalHandler::Default => SIG_DFL,
104            _ => signal_receiver as usize,
105        };
106        unsafe {
107            // SAFETY: we're using a correct value for the hook
108            install_hook(signal_type as i32, hook_val)
109                .map_err(|_| SetHandlerError::UnexpectedLibcCallFailure)?
110        }
111    }
112    Ok(())
113}
114
115#[cfg(all(windows, feature = "signals"))]
116static HANDLERS: Lazy<RwLock<IntMap<SignalHandler>>> = Lazy::new(|| RwLock::new(IntMap::new()));
117
118unsafe fn install_hook(signum: i32, hook: usize) -> Result<(), ()> {
119    let success = unsafe {
120        // SAFETY: hook validity is required via safety contract
121        libc::signal(signum, hook)
122    } != libc::SIG_ERR as _;
123    if success {
124        Ok(())
125    } else {
126        Err(())
127    }
128}
129
130/// The actual hook which is passed to `sigaction` which dispatches signals according to the global handler map (the `HANDLERS` static).
131extern "C" fn signal_receiver(signum: i32) {
132    let catched = panic::catch_unwind(|| {
133        let handler = {
134            let handlers = HANDLERS.read();
135            let val = handlers
136                .get(signum as u64)
137                .expect("unregistered signal passed by the OS to the shared receiver");
138            *val
139        };
140        match handler {
141            SignalHandler::Ignore => {}
142            SignalHandler::Hook(hook) => hook.inner()(),
143            SignalHandler::NoReturnHook(hook) => hook.inner()(),
144            SignalHandler::Default => unreachable!(
145                "signal receiver was unregistered but has been called by the OS anyway"
146            ),
147        }
148    });
149    // The panic hook already ran, so we only have to abort the process
150    catched.unwrap_or_else(|_| process::abort());
151}
152
153/// The error produced when setting a signal handler fails.
154#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
155#[cfg_attr(all(windows, feature = "signals"), derive(Error))]
156pub enum SetHandlerError {
157    /// An unsafe signal was attempted to be handled using `set_handler` instead of `set_unsafe_handler`.
158    #[cfg_attr(
159        all(windows, feature = "signals"),
160        error(
161            "\
162an unsafe signal was attempted to be handled using `set_handler` instead of `set_unsafe_handler`"
163        )
164    )]
165    UnsafeSignal,
166    /// the C library call unexpectedly failed without error information.
167    #[cfg_attr(
168        all(windows, feature = "signals"),
169        error("the C library call unexpectedly failed without error information")
170    )]
171    UnexpectedLibcCallFailure,
172}
173
174/// A signal handling method.
175#[derive(Copy, Clone, Debug, PartialEq, Eq)]
176pub enum SignalHandler {
177    /// Use the default behavior specified by the C standard.
178    Default,
179    /// Ignore the signal whenever it is received.
180    Ignore,
181    /// Call a function whenever the signal is received. The function can return, execution will continue.
182    Hook(SignalHook),
183    /// Call a function whenever the signal is received. The function must not return.
184    NoReturnHook(NoReturnSignalHook),
185}
186impl SignalHandler {
187    /// Returns `true` for the [`Default`] variant, `false` otherwise.
188    ///
189    /// [`Default`]: #variant.Default.html " "
190    pub const fn is_default(self) -> bool {
191        matches!(self, Self::Default)
192    }
193    /// Returns `true` for the [`Ignore`] variant, `false` otherwise.
194    ///
195    /// [`Ignore`]: #variant.Ignore.html " "
196    pub const fn is_ignore(self) -> bool {
197        matches!(self, Self::Ignore)
198    }
199    /// Returns `true` for the [`Hook`] and [`NoReturnHook`] variants, `false` otherwise.
200    ///
201    /// [`Hook`]: #variant.Hook.html " "
202    /// [`NoReturnHook`]: #variant.NoReturnHook.html " "
203    pub const fn is_hook(self) -> bool {
204        matches!(self, Self::Hook(..))
205    }
206    /// Creates a handler which calls the specified function.
207    ///
208    /// # Safety
209    /// The function must not call any C functions which are not considered signal-safe. See the [module-level section on signal-safe C functions] for more.
210    ///
211    /// [module-level section on signal-safe C functions]: index.html#signal-safe-c-functions " "
212    pub unsafe fn from_fn(function: fn()) -> Self {
213        let hook = unsafe {
214            // SAFETY: hook validity required by safety contract
215            SignalHook::from_fn(function)
216        };
217        Self::Hook(hook)
218    }
219    /// Creates a handler which calls the specified function and is known to never return.
220    ///
221    /// # Safety
222    /// The function must not call any C functions which are not considered signal-safe. See the [module-level section on signal-safe C functions] for more.
223    ///
224    /// [module-level section on signal-safe C functions]: index.html#signal-safe-c-functions " "
225    pub unsafe fn from_fn_noreturn(function: fn() -> !) -> Self {
226        let hook = unsafe {
227            // SAFETY: hook validity required by safety contract
228            NoReturnSignalHook::from_fn(function)
229        };
230        Self::NoReturnHook(hook)
231    }
232}
233impl Default for SignalHandler {
234    /// Returns [`SignalHandler::Default`].
235    ///
236    /// [`SignalHandler::Default`]: #variant.Default " "
237    fn default() -> Self {
238        Self::Default
239    }
240}
241
242/// A function which can be used as a signal handler.
243#[repr(transparent)]
244#[derive(Copy, Clone, Debug, PartialEq, Eq)]
245pub struct SignalHook(fn());
246impl SignalHook {
247    /// Creates a hook which calls the specified function.
248    ///
249    /// # Safety
250    /// The function must not call any C functions which are not considered signal-safe. See the [module-level section on signal-safe functions] for more.
251    ///
252    /// [module-level section on signal-safe functions]: index.html#signal-safe-functions " "
253    pub unsafe fn from_fn(function: fn()) -> Self {
254        Self(function)
255    }
256    /// Returns the wrapped function.
257    pub fn inner(self) -> fn() {
258        self.0
259    }
260}
261impl From<SignalHook> for fn() {
262    fn from(op: SignalHook) -> Self {
263        op.0
264    }
265}
266
267/// A function which can be used as a signal handler, but one which also never returns.
268#[repr(transparent)]
269#[derive(Copy, Clone, Debug, PartialEq, Eq)]
270pub struct NoReturnSignalHook(fn() -> !);
271impl NoReturnSignalHook {
272    /// Creates a hook which calls the specified function.
273    ///
274    /// # Safety
275    /// Same as for the normal [`SignalHook`].
276    ///
277    /// [`SignalHook`]: struct.SignalHook.html " "
278    pub unsafe fn from_fn(function: fn() -> !) -> Self {
279        Self(function)
280    }
281    /// Returns the wrapped function.
282    pub fn inner(self) -> fn() -> ! {
283        self.0
284    }
285}
286impl From<NoReturnSignalHook> for fn() -> ! {
287    fn from(op: NoReturnSignalHook) -> Self {
288        op.0
289    }
290}
291
292/// All standard signal types as defined in the C standard.
293///
294/// The values can be safely and quickly converted to [`i32`]/[`u32`]. The reverse process involves safety checks, making sure that unknown signal values are never stored.
295///
296/// [`i32`]: https://doc.rust-lang.org/std/primitive.i32.html " "
297/// [`u32`]: https://doc.rust-lang.org/std/primitive.u32.html " "
298#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
299#[repr(i32)]
300#[non_exhaustive]
301pub enum SignalType {
302    /// `SIGINT` – keyboard interrupt, usually sent by pressing `Ctrl`+`C` by the terminal. This signal is typically set to be ignored if the program runs an interactive interface: GUI/TUI, interactive shell (the Python shell, for example) or any other kind of interface which runs in a loop, as opposed to a command-line invocation of the program which reads its standard input or command-line arguments, performs a task and exits. If the interactive interface is running a lengthy operation, a good idea is to temporarily re-enable the signal and abort the lengthy operation if the signal is received, then disable it again.
303    ///
304    /// *Default handler: process termination.*
305    KeyboardInterrupt = SIGINT,
306    /// `SIGILL` – illegal or malformed instruction exception, generated by the CPU whenever such an instruction is executed. This signal normally should not be overriden or masked out, since it likely means that the executable file or the memory of the process has been corrupted and further execution is a risk of invoking negative consequences.
307    ///
308    /// For reasons described above, **this signal is considered unsafe** – handling it requires using `set_unsafe_handler`. **Signal hooks for this signal are also required to never return** – those must be wrapped into a `NoReturnSignalHook`.
309    ///
310    /// *Default handler: process termination with a core dump.*
311    IllegalInstruction = SIGILL,
312    /// `SIGABRT` – abnormal termination requested. This signal is typically invoked by the program itself, using [`std::process::abort`] or the equivalent C function; still, like any other signal, it can be sent from outside the process.
313    ///
314    /// *Default handler: process termination with a core dump.*
315    ///
316    /// [`std::process::abort`]: https://doc.rust-lang.org/std/process/fn.abort.html " "
317    Abort = SIGABRT,
318    /// `SIGFPE` – mathematical exception. This signal is generated whenever an undefined mathematical operation is performed – mainly integer division by zero.
319    ///
320    /// **Signal hooks for this signal are required to never return** – those must be wrapped into a `NoReturnSignalHook`.
321    ///
322    /// *Default handler: process termination with a core dump.*
323    MathException = SIGFPE,
324    /// `SIGSEGV` – invaid memory access. This signal is issued by the OS whenever the program tries to access an invalid memory location, such as the `NULL` pointer or simply an address outside the user-mode address space as established by the OS. The only case when this signal can be received by a Rust program is if memory unsafety occurs due to misuse of unsafe code. As such, it should normally not be masked out or handled, as it likely indicates a critical bug (soundness hole), executable file corruption or process memory corruption.
325    ///
326    /// For reasons described above, **this signal is considered unsafe** – handling it requires using `set_unsafe_handler`. **Signal hooks for this signal are also required to never return** – those must be wrapped into a `NoReturnSignalHook`.
327    ///
328    /// *Default handler: process termination with a core dump.*
329    SegmentationFault = SIGSEGV,
330    /// `SIGTERM` – request for termination. This signal can only be sent using the usual signal sending procedures. Unlike [`KeyboardInterrupt`], this signal is not a request to break out of a lengthy operation, but rather to close the program as a whole. Signal handlers for this signal are expected to perform minimal cleanup and quick state save procedures and then exit.
331    ///
332    /// *Default handler: process termination.*
333    ///
334    /// [`KeyboardInterrupt`]: #variant.KeyboardInterrupt " "
335    Termination = SIGTERM,
336}
337impl SignalType {
338    /// Returns `true` if the value is a signal which requires its custom handler functions to never return, `false` otherwise.
339    pub const fn requires_diverging_hook(self) -> bool {
340        matches!(
341            self,
342            Self::SegmentationFault | Self::IllegalInstruction | Self::MathException
343        )
344    }
345    /// Returns `true` if the value is an unsafe signal which requires unsafe code when setting a handling method, `false` otherwise.
346    pub const fn is_unsafe(self) -> bool {
347        matches!(self, Self::SegmentationFault | Self::IllegalInstruction)
348    }
349}
350impl From<SignalType> for i32 {
351    fn from(op: SignalType) -> Self {
352        op as i32
353    }
354}
355impl From<SignalType> for u32 {
356    fn from(op: SignalType) -> Self {
357        op as u32
358    }
359}
360impl TryFrom<i32> for SignalType {
361    type Error = UnknownSignalError;
362    fn try_from(value: i32) -> Result<Self, Self::Error> {
363        match value {
364            SIGINT => Ok(Self::KeyboardInterrupt),
365            SIGILL => Ok(Self::IllegalInstruction),
366            SIGABRT => Ok(Self::Abort),
367            SIGFPE => Ok(Self::MathException),
368            SIGSEGV => Ok(Self::SegmentationFault),
369            SIGTERM => Ok(Self::Termination),
370            _ => Err(UnknownSignalError { value }),
371        }
372    }
373}
374impl TryFrom<u32> for SignalType {
375    type Error = UnknownSignalError;
376    fn try_from(value: u32) -> Result<Self, Self::Error> {
377        value.try_into()
378    }
379}
380/// Error type returned when a conversion from [`i32`]/[`u32`] to [`SignalType`] fails.
381///
382/// [`i32`]: https://doc.rust-lang.org/std/primitive.i32.html " "
383/// [`u32`]: https://doc.rust-lang.org/std/primitive.u32.html " "
384/// [`SignalType`]: enum.SignalType.html " "
385#[derive(Copy, Clone, Debug, PartialEq, Eq)]
386pub struct UnknownSignalError {
387    /// The unknown signal value which was encountered.
388    pub value: i32,
389}
390impl fmt::Display for UnknownSignalError {
391    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
392        write!(f, "unknown signal value {}", self.value)
393    }
394}
395impl fmt::Binary for UnknownSignalError {
396    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
397        write!(f, "unknown signal value {:b}", self.value)
398    }
399}
400impl fmt::LowerHex for UnknownSignalError {
401    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
402        write!(f, "unknown signal value {:x}", self.value)
403    }
404}
405impl fmt::UpperExp for UnknownSignalError {
406    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
407        write!(f, "unknown signal value {:X}", self.value)
408    }
409}
410impl fmt::Octal for UnknownSignalError {
411    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
412        write!(f, "unknown signal value {:o}", self.value)
413    }
414}
415impl Error for UnknownSignalError {}