hooking 0.8.0

cross platform detour / hooking library in rust
Documentation
//! Save-registers hooks (x86-64): hook a function *without knowing its
//! signature*. The trampoline saves the argument registers and calls a dispatch
//! that reads/writes them through [`SavedRegs`] and returns a [`DispatchResult`]
//! (pass through, or override the return). Each hook carries its own dispatch.
//!
//! ```no_run
//! use hooking::{DispatchResult, Hook, SavedRegs};
//!
//! extern "C" fn dispatch(_: usize, int_regs: *mut u64, sse_regs: *mut [u8; 16]) -> DispatchResult {
//!     let regs = SavedRegs { int_regs, sse_regs };
//!     DispatchResult::OverrideInt(regs.read_int(0) + 1) // return arg0 + 1
//! }
//!
//! # extern "C" fn target(_: u64) -> u64 { 0 }
//! let mut hook = unsafe { Hook::create_save_registers(target as *mut u8, dispatch) }.unwrap();
//! unsafe { hook.apply_hook().unwrap() };
//! ```

use std::ffi::c_void;

#[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};

/// A per-hook save-registers entry. The fixed dispatch shim reads it, together
/// with a data pointer, from the hook's own context (placed just before the
/// original stub) and calls it — so each hook carries its own dispatch instead
/// of sharing one global function. `data` is the entry's to interpret.
pub(in crate::hooks) type SaveRegsEntry =
    extern "C" fn(usize, *mut u64, *mut [u8; 16], *mut c_void) -> DispatchResult;

/// Entry adapter for a raw [`SavedRegsDispatch`]: `data` is the dispatch pointer.
pub(in crate::hooks) extern "C" fn raw_entry(
    original: usize,
    int_regs: *mut u64,
    sse_regs: *mut [u8; 16],
    data: *mut c_void,
) -> DispatchResult {
    let dispatch: SavedRegsDispatch = unsafe { std::mem::transmute(data) };
    dispatch(original, int_regs, sse_regs)
}

/// 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
///
/// The function **returns** a [`DispatchResult`] telling the trampoline what to
/// do next (passthrough / override).
pub type SavedRegsDispatch =
    extern "C" fn(original: usize, int_regs: *mut u64, sse_regs: *mut [u8; 16]) -> 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 {
    /// Pointer to the saved integer argument registers, in the order listed on
    /// [`SavedRegs`].
    pub int_regs: *mut u64,
    /// Pointer to the saved SSE argument registers, 16 bytes each.
    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.
///
/// Returned **by value** from a [`SavedRegsDispatch`]. The layout is fixed
/// (`#[repr(C, u64)]`): a `u64` discriminant (0 = passthrough, 1 = override int,
/// 2 = override float) followed by the payload, so the System V trampoline reads
/// the discriminant from `rax` and the payload from `rdx`. On Win64 the 16-byte
/// value comes back through the hidden return pointer the trampoline provides.
///
/// Under the `reflect` feature it derives `facet::Facet` so a consumer (e.g. a
/// scripting runtime) can register it as a native enum and return it directly.
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
#[repr(C, u64)]
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum DispatchResult {
    /// 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),
}

impl DispatchResult {
    /// Restore registers and call the original.
    pub const fn passthrough() -> Self {
        Self::Passthrough
    }

    /// Return immediately with `val` in `rax`.
    pub const fn override_int(val: u64) -> Self {
        Self::OverrideInt(val)
    }

    /// Return immediately with `val` in `xmm0`.
    pub const fn override_float(val: f64) -> Self {
        Self::OverrideFloat(val)
    }
}

/// 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],
) -> DispatchResult {
    let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        // Each hook carries its own dispatch: the (entry-fn, data) context sits
        // immediately before its original stub, so read it at `original - 16`.
        // The context is baked right after the (variable-length) trampoline, so
        // it isn't necessarily 8-aligned — read it unaligned.
        let ctx = (original - 2 * std::mem::size_of::<usize>()) as *const [usize; 2];
        let [entry_fn, data] = unsafe { std::ptr::read_unaligned(ctx) };
        if entry_fn == 0 {
            return DispatchResult::passthrough();
        }
        let entry: SaveRegsEntry = unsafe { std::mem::transmute(entry_fn) };
        entry(original, int_regs, sse_regs, data as *mut c_void)
    }));
    outcome.unwrap_or(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.
///
/// Reflected with facet under the `reflect` feature (like [`DispatchResult`]),
/// so a scripting consumer can read it as a native struct after calling the
/// original from a hook.
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
#[repr(C)]
pub struct CallResult {
    /// The integer return value, from `rax`.
    pub int_val: u64,
    /// The floating-point return value, from `xmm0`.
    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
}