set_unsafe_handler

Function set_unsafe_handler 

Source
pub unsafe fn set_unsafe_handler(
    signal_type: SignalType,
    handler: SignalHandler,
) -> Result<(), SetHandlerError>
Available on Windows and crate feature signals only.
Expand description

Installs the specified handler for the specified unsafe signal.

§Safety

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.

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.

§Example

use interprocess::os::windows::signal::{self, SignalType, SignalHandler};

let handler = unsafe {
    // Since signal handlers are restricted to a specific set of C functions, creating a
    // handler from an arbitrary function is unsafe because it might call a function
    // outside the list, and there's no real way to know that at compile time with the
    // current version of Rust. Since we're only using the write() system call here, this
    // is safe.
    SignalHandler::from_fn(|| {
        println!("Oh no, we're running on an i386!");
        std::process::abort();
    })
};

unsafe {
    // Install our handler for the IllegalInstruction signal type.
    signal::set_unsafe_handler(SignalType::IllegalInstruction, handler)?;
}