hooking 0.7.0

cross platform detour / hooking library in rust
Documentation
//! Reach the original function from inside a hook with
//! `hooking::original_function_ptr`, without storing it anywhere.
//!
//! On x86_64 the hook's trampoline passes the original function in r10 (with
//! a checksum in r11), so the hook can read it back. It must be read first
//! thing in the hook, before anything else can overwrite those registers.

use std::hint::black_box;

use hooking::Hook;

type MultiplyFn = extern "C" fn(u64, u64) -> u64;

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

extern "C" fn hooked_multiply(a: u64, b: u64) -> u64 {
    // Read the original function before doing anything else.
    let original = hooking::original_function_ptr().expect("called from the hook");
    let original: MultiplyFn = unsafe { std::mem::transmute(original.as_ptr()) };

    println!("  hooked_multiply({a}, {b}), calling the original");
    let result = original(a, b);
    println!("  the original returned {result}, returning {}", result + 1);
    result + 1
}

fn main() {
    // Outside a hook, r10 and r11 don't hold a matching checksum.
    assert!(hooking::original_function_ptr().is_none());

    let mut hook =
        unsafe { Hook::create(multiply as *mut u8, hooked_multiply as *mut u8).unwrap() };

    println!("before hooking: {}", multiply(black_box(6), black_box(7)));

    unsafe { hook.apply_hook().unwrap() };
    println!("hooked: {}", multiply(black_box(6), black_box(7)));

    unsafe { hook.remove_hook().unwrap() };
    println!("unhooked: {}", multiply(black_box(6), black_box(7)));
}