hooking 0.7.0

cross platform detour / hooking library in rust
Documentation
use std::sync::atomic::AtomicUsize;

#[cfg(not(windows))]
mod sysv;
#[cfg(not(windows))]
use self::sysv as abi;
#[cfg(windows)]
mod win64;
#[cfg(windows)]
use self::win64 as abi;

use self::abi::call_original_trampoline;
pub(in crate::hooks) use self::abi::save_registers_trampoline;
pub use self::abi::{INT_ARG_REGS, SSE_ARG_REGS};

/// The dispatch function currently in use. Set by `create_save_registers`
/// before the hook is applied, read by the trampoline's dispatch shim.
pub(super) static SAVE_REGISTERS_DISPATCH: AtomicUsize = AtomicUsize::new(0);

/// The function signature the naked trampoline calls. The consumer
/// provides this — hooking-rs only provides the trampoline that saves
/// registers and calls it.
///
/// - `original`: the original-function stub address (use it as a key to
///   look up per-hook callback data)
/// - `int_regs`: pointer to [`INT_ARG_REGS`] saved integer argument
///   registers, readable and writable (see [`SavedRegs`] for the order)
/// - `sse_regs`: pointer to [`SSE_ARG_REGS`] saved SSE argument registers,
///   each 16 bytes, readable and writable
/// - `result`: pointer to a [`DispatchResult`] the function must write
///   before returning
pub type SavedRegsDispatch = extern "C" fn(
    original: usize,
    int_regs: *mut u64,
    sse_regs: *mut [u8; 16],
    result: *mut DispatchResult,
);

/// Pointers to the integer and SSE argument registers saved on the
/// trampoline's stack. Valid only during a dispatch call.
///
/// The registers are stored in the platform's argument order:
///
/// | ABI | Integer registers | SSE registers |
/// | --- | --- | --- |
/// | System V (linux) | `[rdi, rsi, rdx, rcx, r8, r9]` | `[xmm0, ..., xmm7]` |
/// | Windows x64 | `[rcx, rdx, r8, r9]` | `[xmm0, ..., xmm3]` |
///
/// System V numbers integer and SSE arguments separately: in
/// `f(a: u64, b: f64, c: u64)`, `c` is integer register 1 and `b` is SSE
/// register 0. Windows gives the Nth argument slot N of whichever set
/// matches its type, so `c` is integer register 2 and `b` is SSE register 1.
/// Arguments passed on the stack aren't saved.
///
/// ```
/// # use hooking::hooks::SavedRegs;
/// # let mut ints = [0u64; 6];
/// # let mut sses = [[0u8; 16]; 8];
/// let regs = SavedRegs { int_regs: ints.as_mut_ptr(), sse_regs: sses.as_mut_ptr() };
/// // Read the first integer argument:
/// let first_arg = regs.read_int(0);
/// // Write a modified value back:
/// regs.write_int(0, 42);
/// // Read a float from xmm0:
/// let f = regs.read_f64(0);
/// ```
pub struct SavedRegs {
    pub int_regs: *mut u64,
    pub sse_regs: *mut [u8; 16],
}

impl SavedRegs {
    /// Read integer argument register `index`, in the order listed on
    /// [`SavedRegs`].
    pub fn read_int(&self, index: u8) -> u64 {
        assert!(
            (index as usize) < INT_ARG_REGS,
            "integer register index out of range"
        );
        unsafe { *self.int_regs.add(index as usize) }
    }

    /// Write integer register at `index`.
    pub fn write_int(&self, index: u8, val: u64) {
        assert!(
            (index as usize) < INT_ARG_REGS,
            "integer register index out of range"
        );
        unsafe { *self.int_regs.add(index as usize) = val }
    }

    /// Read a 32-bit float from SSE argument register `index` (`xmm<index>`).
    pub fn read_f32(&self, index: u8) -> f32 {
        assert!(
            (index as usize) < SSE_ARG_REGS,
            "SSE register index out of range"
        );
        let bytes = unsafe { &*self.sse_regs.add(index as usize) };
        f32::from_le_bytes(bytes[..4].try_into().unwrap())
    }

    /// Read a 64-bit float from SSE register at `index`.
    pub fn read_f64(&self, index: u8) -> f64 {
        assert!(
            (index as usize) < SSE_ARG_REGS,
            "SSE register index out of range"
        );
        let bytes = unsafe { &*self.sse_regs.add(index as usize) };
        f64::from_le_bytes(bytes[..8].try_into().unwrap())
    }

    /// Write a 32-bit float to SSE register at `index`.
    pub fn write_f32(&self, index: u8, val: f32) {
        assert!(
            (index as usize) < SSE_ARG_REGS,
            "SSE register index out of range"
        );
        let bytes = unsafe { &mut *self.sse_regs.add(index as usize) };
        bytes[..4].copy_from_slice(&val.to_le_bytes());
    }

    /// Write a 64-bit float to SSE register at `index`.
    pub fn write_f64(&self, index: u8, val: f64) {
        assert!(
            (index as usize) < SSE_ARG_REGS,
            "SSE register index out of range"
        );
        let bytes = unsafe { &mut *self.sse_regs.add(index as usize) };
        bytes[..8].copy_from_slice(&val.to_le_bytes());
    }
}

/// What the dispatch function tells the trampoline to do after it
/// returns.
#[derive(Debug, Clone, Copy)]
pub enum HookAction {
    /// Restore all saved registers and tail-call the original function.
    Passthrough,
    /// Return immediately with this value in `rax`.
    OverrideInt(u64),
    /// Return immediately with this value in `xmm0`.
    OverrideFloat(f64),
}

/// The result the dispatch function writes to the trampoline's stack.
/// The trampoline reads `action` to decide what to do next.
///
/// Use [`DispatchResult::passthrough`], [`DispatchResult::override_int`],
/// or [`DispatchResult::override_float`] to construct.
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct DispatchResult {
    /// 0 = passthrough, 1 = override int (rax), 2 = override float (xmm0).
    action: u64,
    int_val: u64,
    float_val: f64,
}

impl DispatchResult {
    /// Restore registers and call the original.
    pub fn passthrough() -> Self {
        Self {
            action: 0,
            int_val: 0,
            float_val: 0.0,
        }
    }

    /// Return immediately with `val` in `rax`.
    pub fn override_int(val: u64) -> Self {
        Self {
            action: 1,
            int_val: val,
            float_val: 0.0,
        }
    }

    /// Return immediately with `val` in `xmm0`.
    pub fn override_float(val: f64) -> Self {
        Self {
            action: 2,
            int_val: 0,
            float_val: val,
        }
    }
}

impl From<HookAction> for DispatchResult {
    fn from(action: HookAction) -> Self {
        match action {
            HookAction::Passthrough => Self::passthrough(),
            HookAction::OverrideInt(v) => Self::override_int(v),
            HookAction::OverrideFloat(v) => Self::override_float(v),
        }
    }
}

/// Shim called from the naked trampoline. Reads the real dispatch fn
/// from the atomic and forwards the call. Any panic is caught so it
/// cannot unwind through the naked trampoline (which has no unwind
/// info and would abort the process).
extern "C" fn save_registers_dispatch_shim(
    original: usize,
    int_regs: *mut u64,
    sse_regs: *mut [u8; 16],
    result: *mut DispatchResult,
) {
    let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        let dispatch_addr = SAVE_REGISTERS_DISPATCH.load(std::sync::atomic::Ordering::Acquire);
        if dispatch_addr == 0 {
            unsafe { *result = DispatchResult::passthrough() };
            return;
        }
        let dispatch: SavedRegsDispatch = unsafe { std::mem::transmute(dispatch_addr) };
        dispatch(original, int_regs, sse_regs, result);
    }));
    if outcome.is_err() {
        unsafe { *result = DispatchResult::passthrough() };
    }
}

/// The return value of [`call_with_saved_regs`]: both possible return
/// slots so the caller can pick the right one based on the method's
/// return type.
#[repr(C)]
pub struct CallResult {
    pub int_val: u64,
    pub float_val: f64,
}

/// Calls `original` with the integer and SSE registers from the
/// saved-register arrays, as if the original function had been called
/// directly. Returns both `rax` and `xmm0` so the caller can pick
/// the right one based on the return type.
///
/// # Safety
///
/// `original` must be a valid function pointer (the stub returned by
/// hooking). `int_regs` must point to at least [`INT_ARG_REGS`] `u64`s and
/// `sse_regs` to at least [`SSE_ARG_REGS`] 16-byte slots, as the
/// [`SavedRegsDispatch`] callback receives them. Arguments the original
/// takes on the stack aren't passed.
pub unsafe fn call_with_saved_regs(
    original: usize,
    int_regs: *const u64,
    sse_regs: *const [u8; 16],
) -> CallResult {
    let mut result = CallResult {
        int_val: 0,
        float_val: 0.0,
    };
    unsafe {
        call_original_trampoline(original, int_regs, sse_regs, &mut result as *mut CallResult);
    }
    result
}