hooking 0.8.0

cross platform detour / hooking library in rust
Documentation
//! The [`Hook`] handle and its placed-code metadata ([`HookData`]).
//!
//! ```no_run
//! use hooking::Hook;
//! # extern "C" fn target(a: u64) -> u64 { a }
//! # extern "C" fn detour(a: u64) -> u64 { a + 1 }
//! let mut hook = unsafe { Hook::create(target as *mut u8, detour as *mut u8) }.unwrap();
//! unsafe { hook.apply_hook().unwrap() };
//! ```

use core::ffi;
use core::ffi::CStr;
use core::ptr::NonNull;
use std::ffi::c_void;

use crate::error::Result;
use crate::patch::PatchWriter;

#[cfg(target_arch = "x86_64")]
use super::SavedRegsDispatch;
use super::builder::HookBuilder;
use super::patch_state::PatchState;

/// A function hook: patches a target so calls run a detour, with the original
/// still callable. Build one with [`Hook::create`] / [`Hook::by_name`] or
/// [`HookBuilder`], then [`apply_hook`](Self::apply_hook) it.
#[derive(Debug)]
pub struct Hook<'a> {
    /// The hook's placed code and patch (see [`HookData`]).
    pub data: HookData<'a>,
    state: PatchState<'a>,
}

impl Hook<'static> {
    /// Create a hook on `symbol` in `module`, or in any loaded module when
    /// `module` is `None`, using the default arena and patcher.
    ///
    /// # Safety
    /// `symbol` must name a function, and `destination` must be a function
    /// with the same signature and calling convention as it.
    pub unsafe fn by_name(
        module: Option<&CStr>,
        symbol: &CStr,
        destination: *mut u8,
    ) -> Result<Self> {
        let builder = match module {
            Some(module) => HookBuilder::in_module(module, symbol),
            None => HookBuilder::by_name(symbol),
        };
        unsafe { builder.detour(destination) }
    }

    /// Create a hook on `target` using the default arena and patcher.
    ///
    /// # Safety
    /// `target` must point to the start of a function that is at least as
    /// long as the patch, and `destination` must be a function with the same
    /// signature and calling convention as `target`.
    pub unsafe fn create(target: *mut u8, destination: *mut u8) -> Result<Self> {
        unsafe { HookBuilder::at(target).detour(destination) }
    }

    /// Like [`Hook::create`], but the trampoline saves all argument registers
    /// (integer and SSE) before calling `dispatch` with pointers to the saved
    /// state. The caller doesn't need to know the target's signature — the
    /// dispatch function reads and writes arguments through
    /// [`SavedRegs`](super::SavedRegs) and signals the outcome through
    /// [`DispatchResult`](super::DispatchResult).
    ///
    /// `dispatch` receives the original-function stub address as its first
    /// argument; each hook stores its own dispatch, so several targets can be
    /// hooked independently. For a higher-level detour that takes (and owns) a
    /// Rust closure instead of a raw function, see
    /// [`HookBuilder::save_registers_fn`](super::HookBuilder::save_registers_fn).
    ///
    /// ```no_run
    /// # use hooking::hooks::{Hook, SavedRegs, DispatchResult};
    /// extern "C" fn my_dispatch(
    ///     original: usize,
    ///     int_regs: *mut u64,
    ///     sse_regs: *mut [u8; 16],
    /// ) -> DispatchResult {
    ///     let regs = SavedRegs { int_regs, sse_regs };
    ///     // Inspect regs.read_int(0) for the first integer argument, etc.
    ///     // Return Passthrough to call the original:
    ///     DispatchResult::passthrough()
    /// }
    ///
    /// # let target: *mut u8 = std::ptr::null_mut();
    /// let mut hook = unsafe { Hook::create_save_registers(target, my_dispatch) }.unwrap();
    /// unsafe { hook.apply_hook() }.unwrap();
    /// ```
    ///
    /// # Safety
    /// `target` must point to the start of a function.
    #[cfg(target_arch = "x86_64")]
    pub unsafe fn create_save_registers(
        target: *mut u8,
        dispatch: SavedRegsDispatch,
    ) -> Result<Self> {
        Ok(unsafe { HookBuilder::at(target).save_registers(dispatch)? }.into())
    }
}

impl<'a> Hook<'a> {
    /// Build a hook from already-written table data and the patcher that will
    /// apply and remove it. The hook starts un-applied — call
    /// [`apply_hook`](Self::apply_hook) to patch the target.
    ///
    /// This is the seam most callers don't need:
    /// [`HookWriter`](super::writer::HookWriter) and [`HookBuilder`] call it for
    /// you. Reach for it directly only when you obtained [`HookData`] yourself
    /// — e.g. from
    /// [`HookWriter::write_hook_table`](super::writer::HookWriter::write_hook_table),
    /// which writes the hook into the arena without patching — and want a
    /// [`Hook`] to manage applying it.
    pub fn new(data: HookData<'a>, patcher: &'a dyn PatchWriter) -> Self {
        Self {
            data,
            state: PatchState::new(patcher),
        }
    }

    /// The hooked function's original code, relocated so it can still be
    /// called while the hook is applied.
    pub fn original_function(&self) -> NonNull<c_void> {
        NonNull::from(self.data.original_fn_call_stub_data).cast()
    }

    /// Whether the hook is currently applied.
    pub fn is_applied(&self) -> bool {
        self.state.is_applied()
    }

    /// Patch the target so calls to it run the hook. Does nothing if the
    /// hook is already applied.
    ///
    /// # Safety
    /// The target must still be the function the hook was created for, and
    /// nothing else may patch the same bytes while this hook is applied.
    pub unsafe fn apply_hook(&mut self) -> Result<()> {
        unsafe {
            self.state
                .apply(self.data.symbol_address, &self.data.patch_data)
        }
    }

    /// Restore the target's original instructions. Does nothing if the hook
    /// isn't applied.
    ///
    /// # Safety
    /// The target's patched bytes must not have been changed by anything
    /// else since the hook was applied.
    pub unsafe fn remove_hook(&mut self) -> Result<()> {
        unsafe {
            self.state
                .remove(self.data.symbol_address, &self.data.original_instructions)
        }
    }
}

/// The parts of a built hook: the code written into a
/// [`CodeArena`](crate::arena::CodeArena) (borrowed from it for `'a`) plus the
/// patch to apply. Returned by
/// [`HookWriter::write_hook_table`](super::writer::HookWriter::write_hook_table);
/// pair it with a patcher through [`Hook::new`] to get an applyable [`Hook`].
#[derive(Debug)]
pub struct HookData<'a> {
    /// Address of the hooked function — where [`patch_data`](Self::patch_data)
    /// is written to redirect calls, and restored from
    /// [`original_instructions`](Self::original_instructions) on removal.
    pub symbol_address: NonNull<ffi::c_void>,
    /// The hook's trampoline, placed in the arena: it records this hook's
    /// original-stub address and jumps to the detour.
    pub trampoline_data: &'a [u8],
    /// The target's overwritten instructions, relocated into the arena with a
    /// jump back to the rest of the target. Running this calls the original
    /// function while the hook is applied; [`Hook::original_function`] returns a
    /// pointer to it.
    pub original_fn_call_stub_data: &'a [u8],
    /// The bytes written over the start of the target to jump into the
    /// trampoline — what [`apply_hook`](Hook::apply_hook) installs.
    pub patch_data: Vec<u8>,
    /// The target's original bytes, saved so [`remove_hook`](Hook::remove_hook)
    /// can restore them.
    pub original_instructions: Vec<u8>,
}