hooking 0.7.0

cross platform detour / hooking library in rust
Documentation
//! `HookKind` works the same for every kind of hook, through generics and
//! trait objects.

use std::hint::black_box;
use std::sync::atomic::{AtomicUsize, Ordering};

use hooking::{Hook, HookKind, MiniHook};

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

/// Defines a function long enough to hook, and a detour that calls the
/// original through `ORIGINAL` and adds 1. Each gets its own salt so the
/// optimizer can't merge them.
macro_rules! hookable {
    ($name:ident, $salt:literal) => {
        mod $name {
            use super::*;

            pub static ORIGINAL: AtomicUsize = AtomicUsize::new(0);
            static SALT: u64 = $salt;

            #[inline(never)]
            pub extern "C" fn function(a: u64, b: u64) -> u64 {
                let salt = *black_box(&SALT);
                let mut total = black_box(a);
                for i in 0..black_box(b) {
                    total = total.wrapping_mul(31).wrapping_add(i ^ salt);
                }
                total
            }

            pub extern "C" fn detour(a: u64, b: u64) -> u64 {
                let original: BinaryFn =
                    unsafe { std::mem::transmute(ORIGINAL.load(Ordering::Acquire)) };
                original(a, b) + 1
            }
        }
    };
}

hookable!(full, 1);
hookable!(mini, 2);

fn call(f: BinaryFn) -> u64 {
    black_box(f)(3, 10)
}

/// Create any kind of hook through the trait, and store its original
/// function where `detour` reads it.
fn create<H: HookKind>(function: BinaryFn, detour: BinaryFn, original: &AtomicUsize) -> H {
    let hook = unsafe { H::create(function as *mut u8, detour as *mut u8).unwrap() };
    original.store(
        hook.original_function().as_ptr() as usize,
        Ordering::Release,
    );
    hook
}

/// Apply then remove any kind of hook, checking `is_applied` along the way.
fn toggle(hook: &mut impl HookKind, function: BinaryFn, unhooked: u64) {
    unsafe { hook.apply_hook().unwrap() };
    assert!(hook.is_applied());
    assert_eq!(call(function), unhooked + 1);

    unsafe { hook.remove_hook().unwrap() };
    assert!(!hook.is_applied());
    assert_eq!(call(function), unhooked);
}

// One test, as both hook kinds patch the same functions.
#[test]
fn every_kind_of_hook_works_through_the_trait() {
    let unhooked = [call(full::function), call(mini::function)];

    let mut full_hook: Hook = create(full::function, full::detour, &full::ORIGINAL);
    let mut mini_hook: MiniHook = create(mini::function, mini::detour, &mini::ORIGINAL);

    // Static dispatch.
    toggle(&mut full_hook, full::function, unhooked[0]);
    toggle(&mut mini_hook, mini::function, unhooked[1]);

    // Dynamic dispatch, with both kinds in one collection.
    let functions: [BinaryFn; 2] = [full::function, mini::function];
    let mut hooks: Vec<Box<dyn HookKind>> = vec![Box::new(full_hook), Box::new(mini_hook)];
    for (hook, function) in hooks.iter().zip(functions) {
        assert_eq!(
            hook.target().as_ptr() as usize,
            function as *const () as usize
        );
        assert!(!hook.is_applied());
    }

    for hook in &mut hooks {
        unsafe { hook.apply_hook().unwrap() };
    }
    for (function, unhooked) in functions.iter().zip(unhooked) {
        assert_eq!(call(*function), unhooked + 1);
    }

    for hook in &mut hooks {
        unsafe { hook.remove_hook().unwrap() };
        assert!(!hook.is_applied());
    }
    for (function, unhooked) in functions.iter().zip(unhooked) {
        assert_eq!(call(*function), unhooked);
    }
}