hooking 0.8.0

cross platform detour / hooking library in rust
Documentation
//! `MiniHook` jumps straight to its destination, with no trampoline, and can
//! still call the original.

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

use hooking::MiniHook;
use hooking::arena::{CodeArena, SealedArena};

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

/// `mov eax, 42; ret`: only one byte longer than a rel32 jump.
const RETURN_42: &[u8] = &[0xB8, 0x2A, 0x00, 0x00, 0x00, 0xC3];

/// `xor eax, eax; ret`, shorter than the patch, then `int3` padding as a
/// compiler would align the next function. The relocated original is a copy
/// of the whole function, as its `ret` comes before the jump back.
const RETURN_0_PADDED: &[u8] = &[
    0x31, 0xC0, // xor eax, eax
    0xC3, // ret
    0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC,
];

extern "C" fn returns_7() -> u32 {
    7
}

/// Place `code` in its own executable memory and return it as a function.
fn place(arena: &SealedArena, code: &[u8]) -> ReturnsU32 {
    let placed = arena.place(None, &mut |_| Ok(code.to_vec())).unwrap();
    unsafe { std::mem::transmute(placed.as_ptr()) }
}

fn bytes_of(function: ReturnsU32, len: usize) -> Vec<u8> {
    unsafe { std::slice::from_raw_parts(function as *const u8, len) }.to_vec()
}

/// Mini hook `function`, check calls reach `returns_7`, then check removing
/// it restores the original bytes and behaviour.
fn assert_replaces(function: ReturnsU32, len: usize, expected: u32) {
    let call = || black_box(function)();
    let original_bytes = bytes_of(function, len);
    assert_eq!(call(), expected);

    let mut hook = unsafe { MiniHook::create(function as *mut u8, returns_7 as *mut u8).unwrap() };
    assert_eq!(
        hook.data.original_instructions,
        original_bytes[..hook.data.patch_data.len()]
    );

    unsafe { hook.apply_hook().unwrap() };
    assert_eq!(call(), 7);

    unsafe { hook.remove_hook().unwrap() };
    assert_eq!(call(), expected);
    assert_eq!(bytes_of(function, len), original_bytes);
}

#[test]
fn replaces_a_tiny_function() {
    let arena = SealedArena::new();
    assert_replaces(place(&arena, RETURN_42), RETURN_42.len(), 42);
}

/// The original function `plus_one` calls, set by `calls_the_original`.
static ORIGINAL: AtomicUsize = AtomicUsize::new(0);

extern "C" fn plus_one() -> u32 {
    let original: ReturnsU32 = unsafe { std::mem::transmute(ORIGINAL.load(Ordering::Acquire)) };
    original() + 1
}

// One test for both targets, as they share `ORIGINAL`.
#[test]
fn calls_the_original() {
    let arena = SealedArena::new();
    for (code, expected) in [(RETURN_42, 42), (RETURN_0_PADDED, 0)] {
        let function = place(&arena, code);
        let call = || black_box(function)();

        let mut hook =
            unsafe { MiniHook::create(function as *mut u8, plus_one as *mut u8).unwrap() };
        ORIGINAL.store(
            hook.original_function().as_ptr() as usize,
            Ordering::Release,
        );

        unsafe { hook.apply_hook().unwrap() };
        assert_eq!(call(), expected + 1);
        unsafe { hook.remove_hook().unwrap() };
        assert_eq!(call(), expected);
    }
}

#[test]
fn jumps_straight_to_a_near_destination() {
    #[inline(never)]
    extern "C" fn near_target() -> u32 {
        black_box(42)
    }

    let hook = unsafe { MiniHook::create(near_target as *mut u8, returns_7 as *mut u8).unwrap() };
    assert!(hook.data.thunk_data.is_none(), "both are in this binary");
    // A rel32 jump, or a 2-byte rel8 jump when the two are very close.
    assert!(hook.data.patch_data.len() <= 5);
}

/// Code placed in fresh memory is usually more than 2GB from this binary on
/// x86_64, so reaching `returns_7` needs a thunk near the target.
#[test]
fn far_destinations_go_through_a_thunk() {
    let arena = SealedArena::new();
    let function = place(&arena, RETURN_42);
    let distance = (function as usize).abs_diff(returns_7 as *const () as usize);

    let hook = unsafe { MiniHook::create(function as *mut u8, returns_7 as *mut u8).unwrap() };
    if cfg!(target_pointer_width = "64") && distance >= 1 << 31 {
        assert!(hook.data.thunk_data.is_some());
    } else {
        assert!(hook.data.thunk_data.is_none());
    }
}

/// `#[mini_hook]` replaces libc's `getpid`, which `std::process::id` calls.
#[cfg(target_os = "linux")]
mod mini_hook_macro {
    use hooking::mini_hook;

    const FAKE_PID: u32 = 4242;

    #[mini_hook(method = "getpid")]
    extern "C" fn fake_getpid() -> std::ffi::c_int {
        FAKE_PID as std::ffi::c_int
    }

    #[test]
    fn replaces_getpid() {
        let real = std::process::id();
        assert_ne!(real, FAKE_PID);

        unsafe { fake_getpid::enable_hook().unwrap() };
        let hooked = std::process::id();
        let original = unsafe { fake_getpid::original_function().unwrap() };
        let from_original = original();
        unsafe { fake_getpid::disable_hook().unwrap() };

        assert_eq!(hooked, FAKE_PID);
        assert_eq!(from_original as u32, real);
        assert_eq!(std::process::id(), real);
    }
}