hooking 0.7.0

cross platform detour / hooking library in rust
Documentation
//! Choose where hook code is placed and how the target is patched, with a
//! `HookWriter` built from a `CodeArena` and a `PatchWriter`.
//!
//! - `SealedArena` gives each hook its own memory, made executable once and
//!   never written again.
//! - `ProtectPatcher` makes the target's pages writable while patching, then
//!   restores their protection.
//!
//! The original function is kept in a `OnceLock`, which works on every
//! architecture.

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

use hooking::HookWriter;
use hooking::arena::SealedArena;
use hooking::patch::ProtectPatcher;

static ARENA: SealedArena = SealedArena::new();
static PATCHER: ProtectPatcher = ProtectPatcher::new();

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

/// The original `greet`, set once the hook has been created.
static ORIGINAL_GREET: OnceLock<GreetFn> = OnceLock::new();

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

extern "C" fn hooked_greet(times: u32) -> u32 {
    let original = ORIGINAL_GREET
        .get()
        .expect("set before the hook is applied");
    println!("  hooked_greet({times}), greeting twice as often");
    original(times * 2)
}

fn main() {
    let writer = HookWriter::new(&ARENA).with_patcher(&PATCHER);
    let mut hook = unsafe {
        writer
            .create_hook(
                NonNull::new(greet as *mut _).unwrap(),
                NonNull::new(hooked_greet as *mut _).unwrap(),
            )
            .unwrap()
    };
    let original: GreetFn = unsafe { std::mem::transmute(hook.original_function().as_ptr()) };
    ORIGINAL_GREET.set(original).unwrap();

    println!("before hooking:");
    greet(black_box(1));

    unsafe { hook.apply_hook().unwrap() };
    println!("hooked:");
    greet(black_box(1));

    unsafe { hook.remove_hook().unwrap() };
    println!("unhooked:");
    greet(black_box(1));
}