hooking 0.8.0

cross platform detour / hooking library in rust
Documentation
//! `HookBuilder`'s fluent terminals, on local functions:
//!
//! - [`detour`](hooking::HookBuilder::detour): a plain, same-signature detour
//!   that calls the original.
//! - [`save_registers`](hooking::HookBuilder::save_registers): a raw,
//!   signature-agnostic dispatch.
//! - [`save_registers_fn`](hooking::HookBuilder::save_registers_fn): a closure.
//!
//! Pick the target with `at` (an address) or `by_name` / `in_module` (an
//! exported symbol); `mini` installs a trampoline-less hook instead.

use std::hint::black_box;

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

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

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

#[inline(never)]
#[unsafe(no_mangle)]
pub extern "C" fn neg(x: i64) -> i64 {
    -x
}

/// A plain detour for `mul`: call the original (via `original_function_ptr`)
/// and double its result.
extern "C" fn mul_detour(a: u64, b: u64) -> u64 {
    let original = hooking::original_function_ptr().expect("called from the hook");
    let original: extern "C" fn(u64, u64) -> u64 =
        unsafe { std::mem::transmute(original.as_ptr()) };
    original(a, b) * 2
}

/// A raw save-registers dispatch for `add`: override with `arg0 - arg1`.
extern "C" fn add_dispatch(
    _: usize,
    int_regs: *mut u64,
    sse_regs: *mut [u8; 16],
) -> DispatchResult {
    let regs = SavedRegs { int_regs, sse_regs };
    DispatchResult::OverrideInt(regs.read_int(0).wrapping_sub(regs.read_int(1)))
}

fn main() {
    // 1. A plain detour with the target's signature, calling the original.
    let mut mul_hook =
        unsafe { HookBuilder::at(mul as *mut u8).detour(mul_detour as *mut u8) }.unwrap();
    unsafe { mul_hook.apply_hook().unwrap() };
    println!(
        "detour:            mul(3, 4) = {}",
        mul(black_box(3), black_box(4))
    );
    assert_eq!(mul(black_box(3), black_box(4)), 24); // (3 * 4) * 2

    // 2. A raw save-registers dispatch — no knowledge of the signature.
    let mut add_hook =
        unsafe { HookBuilder::at(add as *mut u8).save_registers(add_dispatch) }.unwrap();
    unsafe { add_hook.apply_hook().unwrap() };
    println!(
        "save_registers:    add(10, 4) = {}",
        add(black_box(10), black_box(4))
    );
    assert_eq!(add(black_box(10), black_box(4)), 6); // 10 - 4

    // 3. A closure detour.
    let mut neg_hook = unsafe {
        HookBuilder::at(neg as *mut u8)
            .save_registers_fn(|d: Dispatch| DispatchResult::OverrideInt(d.regs.read_int(0) + 1))
    }
    .unwrap();
    unsafe { neg_hook.apply_hook().unwrap() };
    println!("save_registers_fn: neg(5) = {}", neg(black_box(5)));
    assert_eq!(neg(black_box(5)), 6); // 5 + 1 (override ignores the negation)

    println!("ok");
}