hooking 0.7.0

cross platform detour / hooking library in rust
Documentation
//! `MiniHook`: a hook without a trampoline.
//!
//! The target jumps straight to the destination. r10 and r11 are left
//! untouched, so `original_function_ptr` isn't available in the destination;
//! `MiniHook::original_function` still gives the original, which this
//! example keeps in a `OnceLock`.

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

use hooking::MiniHook;

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

/// The original `roll_dice`, set once the hook has been created.
static ORIGINAL_ROLL: OnceLock<RollFn> = OnceLock::new();

#[inline(never)]
#[unsafe(no_mangle)]
pub extern "C" fn roll_dice(seed: u32) -> u32 {
    (seed.wrapping_mul(1_103_515_245).wrapping_add(12_345) >> 16) % 6 + 1
}

/// Rolls with the real dice, rerolling anything below 4.
extern "C" fn loaded_dice(seed: u32) -> u32 {
    let original = ORIGINAL_ROLL.get().expect("set before the hook is applied");
    let mut seed = seed;
    loop {
        let roll = original(seed);
        println!("  loaded_dice: the real dice rolled {roll}");
        if roll >= 4 {
            return roll;
        }
        seed = seed.wrapping_add(1);
    }
}

fn main() {
    let mut hook =
        unsafe { MiniHook::create(roll_dice as *mut u8, loaded_dice as *mut u8).unwrap() };
    let original: RollFn = unsafe { std::mem::transmute(hook.original_function().as_ptr()) };
    ORIGINAL_ROLL.set(original).unwrap();

    println!("before hooking: {}", roll_dice(black_box(13)));

    unsafe { hook.apply_hook().unwrap() };
    println!("hooked: {}", roll_dice(black_box(13)));

    unsafe { hook.remove_hook().unwrap() };
    println!("unhooked: {}", roll_dice(black_box(13)));
}