use std::hint::black_box;
use std::sync::atomic::{AtomicUsize, Ordering};
use hooking::{Hook, HookKind, MiniHook};
type BinaryFn = extern "C" fn(u64, u64) -> u64;
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)
}
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
}
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);
}
#[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);
toggle(&mut full_hook, full::function, unhooked[0]);
toggle(&mut mini_hook, mini::function, unhooked[1]);
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);
}
}