hooking 0.8.0

cross platform detour / hooking library in rust
Documentation
//! A `#[hook]` that reaches the original function with
//! `hooking::original_function_ptr` instead of the macro's
//! `original_function()`.
//!
//! - `hooked_atoi::original_function()` reads the original from the hook's
//!   static, and works on every architecture.
//! - `hooking::original_function_ptr()` reads it from registers the
//!   trampoline sets, on x86_64 only. It needs no static, but must be called
//!   first thing in the hook.

#[cfg(target_os = "linux")]
mod example {
    use std::ffi::CStr;

    use hooking::hook;

    /// Parses numbers as usual, but doubles them.
    ///
    /// `#[hook]` copies these types into a generated module, so they are
    /// written as full paths.
    #[hook(method = "atoi")]
    unsafe extern "C" fn hooked_atoi(s: *const std::ffi::c_char) -> std::ffi::c_int {
        // Read the original function before doing anything else.
        let original = hooking::original_function_ptr().expect("called from the hook");
        let original: hooked_atoi::FunctionSignature =
            unsafe { std::mem::transmute(original.as_ptr()) };

        let parsed = original(s);
        println!(
            "  atoi({:?}) parsed {parsed}, returning {}",
            unsafe { CStr::from_ptr(s) },
            parsed * 2
        );
        parsed * 2
    }

    pub fn main() {
        // black_box stops the compiler from evaluating `atoi` on a constant
        // string at compile time, which would skip the hook.
        let parse = |s: &CStr| unsafe { libc::atoi(std::hint::black_box(s.as_ptr())) };

        println!("before hooking: {}", parse(c"21"));

        unsafe { hooked_atoi::enable_hook().unwrap() };
        println!("hooked: {}", parse(c"21"));

        unsafe { hooked_atoi::disable_hook().unwrap() };
        println!("unhooked: {}", parse(c"21"));
    }
}

#[cfg(target_os = "linux")]
fn main() {
    example::main();
}

#[cfg(not(target_os = "linux"))]
fn main() {
    println!("this example needs linux");
}