hooking 0.8.0

cross platform detour / hooking library in rust
Documentation
//! Hook a function with a **closure** detour, then **swap the detour** while the
//! hook is live — using `HookBuilder::save_registers_fn` and the returned
//! `SavedRegisterHook`'s `set_detour` / `set_dispatch`.

use std::hint::black_box;

use hooking::{Dispatch, DispatchResult, HookBuilder};

#[inline(never)]
#[unsafe(no_mangle)]
pub extern "C" fn add(a: u64, b: u64) -> u64 {
    a + b
}

/// A raw dispatch that lets the original run unchanged.
extern "C" fn passthrough(_: usize, _: *mut u64, _: *mut [u8; 16]) -> DispatchResult {
    DispatchResult::Passthrough
}

fn call() -> u64 {
    add(black_box(2), black_box(3))
}

fn main() {
    let bias = 100u64; // captured by the first detour

    // A closure detour. The returned `SavedRegisterHook` owns the closure and
    // derefs to `Hook`, so `apply_hook` works directly.
    let mut hook = unsafe {
        HookBuilder::at(add as *mut u8).save_registers_fn(move |d: Dispatch| {
            DispatchResult::OverrideInt(d.regs.read_int(0) + d.regs.read_int(1) + bias)
        })
    }
    .expect("install closure hook");
    unsafe { hook.apply_hook().unwrap() };
    println!("closure #1 (a + b + 100): add(2, 3) = {}", call());
    assert_eq!(call(), 105);

    // Swap to a different closure — no re-create, same hook.
    unsafe {
        hook.set_detour(|d: Dispatch| {
            DispatchResult::OverrideInt(d.regs.read_int(0) * d.regs.read_int(1))
        })
        .unwrap()
    };
    println!("closure #2 (a * b):       add(2, 3) = {}", call());
    assert_eq!(call(), 6);

    // Swap to a raw passthrough dispatch (frees the closure, no allocation now).
    unsafe { hook.set_dispatch(passthrough).unwrap() };
    println!("raw passthrough:          add(2, 3) = {}", call());
    assert_eq!(call(), 5);

    unsafe { hook.remove_hook().unwrap() };
    println!("unhooked:                 add(2, 3) = {}", call());
    assert_eq!(call(), 5);

    println!("ok");
}