hooking 0.8.0

cross platform detour / hooking library in rust
Documentation
//! Hook a function without writing a detour of its signature, using
//! `Hook::create_save_registers`.
//!
//! The trampoline saves every argument register and calls one dispatch
//! function with pointers to them. The dispatch function can read and
//! rewrite the arguments, then either pass through to the original, return
//! a value of its own, or call the original itself with
//! `call_with_saved_regs`.
//!
//! Registers are saved in the platform's argument order (see `SavedRegs`).
//! Only one dispatch function is in use at a time; the `original` argument
//! tells hooks apart.

use std::hint::black_box;

use hooking::{DispatchResult, Hook, SavedRegs, call_with_saved_regs};

/// `factor`'s SSE register. System V numbers integer and SSE arguments
/// separately, so it is xmm0. Windows gives the Nth argument slot N of
/// either set, so as the second argument it is xmm1.
const FACTOR_SSE: u8 = if cfg!(windows) { 1 } else { 0 };

/// `x` is the first argument, so integer register 0 on every platform. The
/// result is returned in xmm0.
#[inline(never)]
#[unsafe(no_mangle)]
pub extern "C" fn scale(x: u64, factor: f64) -> f64 {
    println!("    scale({x}, {factor})");
    x as f64 * factor
}

extern "C" fn dispatch(
    original: usize,
    int_regs: *mut u64,
    sse_regs: *mut [u8; 16],
) -> DispatchResult {
    let regs = SavedRegs { int_regs, sse_regs };
    let x = regs.read_int(0);
    let factor = regs.read_f64(FACTOR_SSE);
    println!("  dispatch: scale({x}, {factor})");

    match x {
        // Return a value of our own, without calling the original.
        0 => {
            println!("  returning -1 instead");
            DispatchResult::override_float(-1.0)
        }
        // Rewrite an argument, then let the original run.
        13 => {
            println!("  replacing 13 with 12, then passing through");
            regs.write_int(0, 12);
            DispatchResult::passthrough()
        }
        // Call the original ourselves and change what it returned.
        _ => {
            let returned = unsafe { call_with_saved_regs(original, int_regs, sse_regs) };
            println!("  the original returned {}, adding 0.5", returned.float_val);
            DispatchResult::override_float(returned.float_val + 0.5)
        }
    }
}

fn main() {
    let mut hook = unsafe { Hook::create_save_registers(scale as *mut u8, dispatch).unwrap() };

    let call = |x: u64| {
        let result = scale(black_box(x), black_box(2.0));
        println!("scale({x}, 2.0) = {result}\n");
    };

    unsafe { hook.apply_hook().unwrap() };
    call(0);
    call(13);
    call(5);

    unsafe { hook.remove_hook().unwrap() };
    println!("unhooked:");
    call(5);
}