hooking 0.8.0

cross platform detour / hooking library in rust
Documentation
//! `HookKind`: work with every kind of hook the same way.
//!
//! The trait's constructors make the hooks generically, and as trait objects
//! a `Hook` and a `MiniHook` can be managed together.

use std::hint::black_box;
use std::sync::OnceLock;

use hooking::{Hook, HookKind, MiniHook};

type GreetFn = extern "C" fn(u32) -> u32;

static ORIGINAL_HELLO: OnceLock<GreetFn> = OnceLock::new();
static ORIGINAL_GOODBYE: OnceLock<GreetFn> = OnceLock::new();

#[inline(never)]
#[unsafe(no_mangle)]
pub extern "C" fn hello(times: u32) -> u32 {
    for _ in 0..times {
        println!("    hello");
    }
    times
}

#[inline(never)]
#[unsafe(no_mangle)]
pub extern "C" fn goodbye(times: u32) -> u32 {
    for _ in 0..times {
        println!("    goodbye");
    }
    times
}

extern "C" fn loud_hello(times: u32) -> u32 {
    println!("    (loud_hello, through a Hook)");
    ORIGINAL_HELLO.get().unwrap()(times * 2)
}

extern "C" fn loud_goodbye(times: u32) -> u32 {
    println!("    (loud_goodbye, through a MiniHook)");
    ORIGINAL_GOODBYE.get().unwrap()(times * 2)
}

/// Create any kind of hook, storing its original where the detour reads it.
fn create<H: HookKind>(target: GreetFn, detour: GreetFn, original: &OnceLock<GreetFn>) -> H {
    let hook = unsafe { H::create(target as *mut u8, detour as *mut u8).unwrap() };
    let original_fn: GreetFn = unsafe { std::mem::transmute(hook.original_function().as_ptr()) };
    original.set(original_fn).unwrap();
    hook
}

fn greet(when: &str, hooks: &[Box<dyn HookKind>]) {
    let applied: Vec<bool> = hooks.iter().map(|hook| hook.is_applied()).collect();
    println!("{when} (applied: {applied:?}):");
    hello(black_box(1));
    goodbye(black_box(1));
}

fn main() {
    let mut hooks: Vec<Box<dyn HookKind>> = vec![
        Box::new(create::<Hook>(hello, loud_hello, &ORIGINAL_HELLO)),
        Box::new(create::<MiniHook>(goodbye, loud_goodbye, &ORIGINAL_GOODBYE)),
    ];
    greet("before hooking", &hooks);

    for hook in &mut hooks {
        unsafe { hook.apply_hook().unwrap() };
    }
    greet("hooked", &hooks);

    for hook in &mut hooks {
        unsafe { hook.remove_hook().unwrap() };
    }
    greet("unhooked", &hooks);
}