#exception #hardware #handler #windows #seh

no-std microseh

Structured Exception Handling (SEH) for Rust

8 stable releases

1.1.2 Oct 7, 2024
1.1.1 Oct 3, 2024
1.0.3 Feb 22, 2024
1.0.0 Dec 13, 2023
0.1.1 Oct 26, 2022

#81 in Operating systems

Download history 4979/week @ 2024-08-19 4196/week @ 2024-08-26 3923/week @ 2024-09-02 4622/week @ 2024-09-09 4023/week @ 2024-09-16 2116/week @ 2024-09-23 4279/week @ 2024-09-30 2337/week @ 2024-10-07 2100/week @ 2024-10-14 3073/week @ 2024-10-21 3016/week @ 2024-10-28 5030/week @ 2024-11-04 4278/week @ 2024-11-11 2936/week @ 2024-11-18 3572/week @ 2024-11-25 4402/week @ 2024-12-02

15,202 downloads per month
Used in 2 crates (via winmmf)

MIT license

29KB
519 lines

MicroSEH 🔴


MicroSEH is a tiny library that implements Structured Exception Handling (SEH) in Rust and can catch and handle hardware exceptions.

Why?

Hardware exceptions are a very powerful tool for specific use cases. One such use case is to detect and handle illegal instructions at runtime.

Implementation

It turns out that implementing SEH in pure Rust has its own issues (as seen in this article from NAMAZSO)

This library uses a different, simpler approach, which is to use a C stub that calls back into Rust, wrapping the call in a __try __except block.

Usage

Add this to your Cargo.toml:

[dependencies]
microseh = "1.1"

Minimal Example: Dereference an invalid pointer without crashing the program, and return the handled exception.

fn guarded() -> Result<(), microseh::Exception> {
    microseh::try_seh(|| unsafe {
        // Read from an unallocated memory region. (we create an aligned not-null
        // pointer to skip the checks in read_volatile that would raise a panic)
        core::ptr::read_volatile(core::mem::align_of::<i32>() as *const i32);
    })
}

Accessing Exception Data: You can obtain the address and register dump of an exception.

if let Err(ex) = microseh::try_seh(|| unsafe {
    // *questionable life choices go here*
}) {
    println!("address: {:x}", ex.address());
    println!("rax: {:x}", ex.registers().rax());
}

For additional examples and practical use cases, please visit the examples directory!

Portability

SEH is an extension to the C language developed by Microsoft, and it is exclusively available on Windows when using Microsoft Visual C++ (MSVC).

MicroSEH is compatible with and has been tested on Windows platforms with the following architectures: x86, x86_64 and aarch64.

When building for other unsupported platforms, the library will disable exception handling and panic when try_seh is called.

Usage on Kernel Drivers

This library can compile to no_std and supports running in Windows Kernel Drivers using Microsoft's windows-drivers-rs project.

Cross-Compiling

Cross-compiling for Windows is possible with full support for SEH using the cargo-xwin project.

License

This work is released under the MIT license. A copy of the license is provided in the LICENSE file.

No runtime deps

~0–300KB