hooking 0.8.0

cross platform detour / hooking library in rust
Documentation
//! Tests for the `create_save_registers` hook path, including functions
//! with JIT-style prologues (push rbp; sub rsp, imm32; lea rbp, ...).
#![cfg(target_arch = "x86_64")]

use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Mutex, MutexGuard};

use hooking::{DispatchResult, HookWriter};

/// Held by each test while it runs. The tests patch the same functions and
/// share `OVERRIDE_VALUE`, so they can't run in parallel.
static SERIAL: Mutex<()> = Mutex::new(());

fn serial() -> MutexGuard<'static, ()> {
    // A failed test poisons the lock; the next test can still run.
    SERIAL.lock().unwrap_or_else(|e| e.into_inner())
}

/// A dispatch function that either passes through or overrides based on
/// a global flag.
static OVERRIDE_VALUE: AtomicU64 = AtomicU64::new(u64::MAX);

extern "C" fn test_dispatch(
    _original: usize,
    _int_regs: *mut u64,
    _sse_regs: *mut [u8; 16],
) -> DispatchResult {
    let val = OVERRIDE_VALUE.load(Ordering::Relaxed);
    if val == u64::MAX {
        DispatchResult::passthrough()
    } else {
        DispatchResult::override_int(val)
    }
}

/// A function with a JIT-style prologue: push rbp; sub rsp, 0xa0;
/// lea rbp, [rsp+0xa0]; then does some work and returns.
/// Assembled by hand so the prologue matches real CoreCLR JIT output.
#[cfg(not(windows))]
#[unsafe(naked)]
extern "C" fn jit_style_function(a: u64, b: u64) -> u64 {
    core::arch::naked_asm!(
        "push rbp",
        "sub rsp, 0xa0",
        "lea rbp, [rsp+0xa0]",
        // Store args in the frame.
        "mov [rbp-8], rdi",
        "mov [rbp-16], rsi",
        // Compute a + b + 42.
        "mov rax, [rbp-8]",
        "add rax, [rbp-16]",
        "add rax, 42",
        // Epilogue.
        "add rsp, 0xa0",
        "pop rbp",
        "ret",
    );
}

/// Windows x64 version of the function above: arguments in rcx and rdx.
#[cfg(windows)]
#[unsafe(naked)]
extern "C" fn jit_style_function(a: u64, b: u64) -> u64 {
    core::arch::naked_asm!(
        "push rbp",
        "sub rsp, 0xa0",
        "lea rbp, [rsp+0xa0]",
        // Store args in the frame.
        "mov [rbp-8], rcx",
        "mov [rbp-16], rdx",
        // Compute a + b + 42.
        "mov rax, [rbp-8]",
        "add rax, [rbp-16]",
        "add rax, 42",
        // Epilogue.
        "add rsp, 0xa0",
        "pop rbp",
        "ret",
    );
}

/// Same pattern with sub rsp, 0x80 (matching DamageBlockInternal).
#[cfg(not(windows))]
#[unsafe(naked)]
extern "C" fn jit_style_function_80(a: u64, b: u64) -> u64 {
    core::arch::naked_asm!(
        "push rbp",
        "sub rsp, 0x80",
        "lea rbp, [rsp+0x80]",
        "mov [rbp-8], rdi",
        "mov [rbp-16], rsi",
        "mov rax, [rbp-8]",
        "add rax, [rbp-16]",
        "add rax, 100",
        "add rsp, 0x80",
        "pop rbp",
        "ret",
    );
}

/// Windows x64 version of the function above: arguments in rcx and rdx.
#[cfg(windows)]
#[unsafe(naked)]
extern "C" fn jit_style_function_80(a: u64, b: u64) -> u64 {
    core::arch::naked_asm!(
        "push rbp",
        "sub rsp, 0x80",
        "lea rbp, [rsp+0x80]",
        "mov [rbp-8], rcx",
        "mov [rbp-16], rdx",
        "mov rax, [rbp-8]",
        "add rax, [rbp-16]",
        "add rax, 100",
        "add rsp, 0x80",
        "pop rbp",
        "ret",
    );
}

#[test]
fn passthrough_preserves_arguments_and_return() {
    let _serial = serial();
    OVERRIDE_VALUE.store(u64::MAX, Ordering::Relaxed);

    let target = jit_style_function as *mut u8;
    let mut hook = unsafe { hooking::Hook::create_save_registers(target, test_dispatch).unwrap() };

    // Before hook: verify function works.
    assert_eq!(jit_style_function(10, 20), 72);

    unsafe { hook.apply_hook().unwrap() };

    // Passthrough: function should still work with all registers preserved.
    assert_eq!(jit_style_function(10, 20), 72);
    assert_eq!(jit_style_function(0, 0), 42);
    assert_eq!(jit_style_function(100, 200), 342);

    unsafe { hook.remove_hook().unwrap() };
    assert_eq!(jit_style_function(10, 20), 72);
}

#[test]
fn override_replaces_return_value() {
    let _serial = serial();
    OVERRIDE_VALUE.store(u64::MAX, Ordering::Relaxed);

    let target = jit_style_function as *mut u8;
    let mut hook = unsafe { hooking::Hook::create_save_registers(target, test_dispatch).unwrap() };
    unsafe { hook.apply_hook().unwrap() };

    // Passthrough first.
    assert_eq!(jit_style_function(10, 20), 72);

    // Override with a fixed value.
    OVERRIDE_VALUE.store(999, Ordering::Relaxed);
    assert_eq!(jit_style_function(10, 20), 999);
    assert_eq!(jit_style_function(0, 0), 999);

    // Back to passthrough.
    OVERRIDE_VALUE.store(u64::MAX, Ordering::Relaxed);
    assert_eq!(jit_style_function(10, 20), 72);

    unsafe { hook.remove_hook().unwrap() };
}

#[test]
fn smaller_frame_function_works() {
    let _serial = serial();
    OVERRIDE_VALUE.store(u64::MAX, Ordering::Relaxed);

    let target = jit_style_function_80 as *mut u8;
    let mut hook = unsafe { hooking::Hook::create_save_registers(target, test_dispatch).unwrap() };
    unsafe { hook.apply_hook().unwrap() };

    assert_eq!(jit_style_function_80(10, 20), 130);

    OVERRIDE_VALUE.store(0, Ordering::Relaxed);
    assert_eq!(jit_style_function_80(10, 20), 0);

    OVERRIDE_VALUE.store(u64::MAX, Ordering::Relaxed);
    assert_eq!(jit_style_function_80(10, 20), 130);

    unsafe { hook.remove_hook().unwrap() };
}

#[test]
fn works_with_hookwriter_and_protect_patcher() {
    let _serial = serial();
    OVERRIDE_VALUE.store(u64::MAX, Ordering::Relaxed);

    let patcher = hooking::patch::ProtectPatcher::new();
    let writer = HookWriter::from_static().with_patcher(&patcher);

    let target = jit_style_function as *mut u8;
    let mut hook = unsafe { writer.create_save_registers(target, test_dispatch).unwrap() };
    unsafe { hook.apply_hook().unwrap() };

    assert_eq!(jit_style_function(10, 20), 72);

    OVERRIDE_VALUE.store(7, Ordering::Relaxed);
    assert_eq!(jit_style_function(10, 20), 7);

    OVERRIDE_VALUE.store(u64::MAX, Ordering::Relaxed);
    unsafe { hook.remove_hook().unwrap() };
}

/// Like `jit_style_function`, but executes `ud2` if called with a stack that
/// isn't 16-byte aligned, as the System V ABI requires.
#[cfg(not(windows))]
#[unsafe(naked)]
extern "C" fn alignment_checking_function(a: u64, b: u64) -> u64 {
    core::arch::naked_asm!(
        "push rbp",
        "sub rsp, 0xa0",
        "lea rbp, [rsp+0xa0]",
        // After the call's return address and `push rbp`, an aligned caller
        // leaves rsp 16-byte aligned here.
        "test spl, 15",
        "jz 2f",
        "ud2",
        "2:",
        "mov rax, rdi",
        "add rax, rsi",
        "add rax, 42",
        "add rsp, 0xa0",
        "pop rbp",
        "ret",
    );
}

/// Windows x64 version of the function above: arguments in rcx and rdx.
#[cfg(windows)]
#[unsafe(naked)]
extern "C" fn alignment_checking_function(a: u64, b: u64) -> u64 {
    core::arch::naked_asm!(
        "push rbp",
        "sub rsp, 0xa0",
        "lea rbp, [rsp+0xa0]",
        // After the call's return address and `push rbp`, an aligned caller
        // leaves rsp 16-byte aligned here.
        "test spl, 15",
        "jz 2f",
        "ud2",
        "2:",
        "mov rax, rcx",
        "add rax, rdx",
        "add rax, 42",
        "add rsp, 0xa0",
        "pop rbp",
        "ret",
    );
}

/// Calls the original with `call_with_saved_regs` and returns its result
/// plus 1000.
extern "C" fn call_original_dispatch(
    original: usize,
    int_regs: *mut u64,
    sse_regs: *mut [u8; 16],
) -> DispatchResult {
    let returned = unsafe { hooking::call_with_saved_regs(original, int_regs, sse_regs) };
    DispatchResult::override_int(returned.int_val + 1000)
}

#[test]
fn call_with_saved_regs_calls_the_original() {
    let _serial = serial();

    let target = alignment_checking_function as *mut u8;
    assert_eq!(alignment_checking_function(10, 20), 72);

    let mut hook =
        unsafe { hooking::Hook::create_save_registers(target, call_original_dispatch).unwrap() };
    unsafe { hook.apply_hook().unwrap() };
    assert_eq!(alignment_checking_function(10, 20), 1072);
    unsafe { hook.remove_hook().unwrap() };
}

/// `mixed(a, b, c)`'s arguments, by the slot each is saved in. System V
/// numbers integer and SSE registers separately; Windows x64 gives the Nth
/// argument slot N of whichever set matches its type.
#[cfg(not(windows))]
mod mixed_slots {
    pub const A_INT: u8 = 0;
    pub const B_SSE: u8 = 0;
    pub const C_INT: u8 = 1;
}
#[cfg(windows)]
mod mixed_slots {
    pub const A_INT: u8 = 0;
    pub const B_SSE: u8 = 1;
    pub const C_INT: u8 = 2;
}

#[inline(never)]
extern "C" fn mixed(a: u64, b: f64, c: u64) -> f64 {
    std::hint::black_box(a) as f64 + std::hint::black_box(b) + std::hint::black_box(c) as f64
}

/// The arguments `mixed_dispatch` saw, as `[a, b's bits, c]`.
static SEEN: [AtomicU64; 3] = [AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0)];

/// Records `mixed`'s arguments, multiplies `c` by 10, then passes through.
extern "C" fn mixed_dispatch(
    _original: usize,
    int_regs: *mut u64,
    sse_regs: *mut [u8; 16],
) -> DispatchResult {
    let regs = hooking::SavedRegs { int_regs, sse_regs };
    let c = regs.read_int(mixed_slots::C_INT);
    SEEN[0].store(regs.read_int(mixed_slots::A_INT), Ordering::Relaxed);
    SEEN[1].store(
        regs.read_f64(mixed_slots::B_SSE).to_bits(),
        Ordering::Relaxed,
    );
    SEEN[2].store(c, Ordering::Relaxed);
    regs.write_int(mixed_slots::C_INT, c * 10);
    DispatchResult::passthrough()
}

#[test]
fn arguments_are_saved_in_the_platform_order() {
    let _serial = serial();
    let call = || {
        mixed(
            std::hint::black_box(1),
            std::hint::black_box(2.5),
            std::hint::black_box(3),
        )
    };
    assert_eq!(call(), 6.5);

    let mut hook =
        unsafe { hooking::Hook::create_save_registers(mixed as *mut u8, mixed_dispatch).unwrap() };
    unsafe { hook.apply_hook().unwrap() };
    let hooked = call();
    unsafe { hook.remove_hook().unwrap() };

    let seen: Vec<u64> = SEEN.iter().map(|s| s.load(Ordering::Relaxed)).collect();
    assert_eq!(seen, [1, 2.5f64.to_bits(), 3]);
    assert_eq!(
        hooked,
        1.0 + 2.5 + 30.0,
        "c was rewritten before the original ran"
    );
    assert_eq!(call(), 6.5);
}