#exception #hardware #handler #windows #seh

no-std microseh

Structured Exception Handling (SEH) for Rust

6 releases (stable)

1.0.3 Feb 22, 2024
1.0.2 Feb 12, 2024
1.0.0 Dec 13, 2023
0.2.0 Sep 21, 2023
0.1.1 Oct 26, 2022

#100 in Operating systems

Download history 1/week @ 2024-02-02 61/week @ 2024-02-09 1748/week @ 2024-02-16 3718/week @ 2024-02-23 3446/week @ 2024-03-01 2765/week @ 2024-03-08 2961/week @ 2024-03-15 1841/week @ 2024-03-22 2552/week @ 2024-03-29 1360/week @ 2024-04-05

9,117 downloads per month

MIT license

24KB
488 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.0"

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

fn guarded() -> Result<(), Box<dyn Error>> {
    
    
    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.

No runtime deps

~175KB