hooking 0.8.0

cross platform detour / hooking library in rust
Documentation
//! The ergonomic hook API: [`HookBuilder`] for configuring a hook fluently, and
//! the high-level closure-based save-registers hooks ([`SavedRegisterHook`]),
//! layered over the raw [`SavedRegsDispatch`](super::SavedRegsDispatch) ABI.
//!
//! ```no_run
//! use hooking::HookBuilder;
//! # extern "C" fn target(a: u64) -> u64 { a }
//! # extern "C" fn detour(a: u64) -> u64 { a + 1 }
//! // Pick a target, then a detour kind:
//! let mut hook = unsafe { HookBuilder::at(target as *mut u8).detour(detour as *mut u8) }.unwrap();
//! unsafe { hook.apply_hook().unwrap() };
//! ```

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

use crate::error::{HookingError, Result};
use crate::sys;

use super::hook::Hook;
use super::writer::HookWriter;

#[cfg(target_arch = "x86_64")]
use super::save_registers::{
    DispatchResult, SaveRegsEntry, SavedRegs, SavedRegsDispatch, raw_entry,
};
#[cfg(target_arch = "x86_64")]
use crate::arena::CodeArena;
#[cfg(target_arch = "x86_64")]
use std::ops::{Deref, DerefMut};

/// What a [`HookBuilder`] places a hook on: a resolved address, or a symbol to
/// resolve (optionally within a named module).
enum Target<'t> {
    Address(*mut u8),
    Symbol {
        module: Option<&'t CStr>,
        symbol: &'t CStr,
    },
}

impl Target<'_> {
    /// Resolve to the function address to hook.
    unsafe fn resolve(&self) -> Result<std::ptr::NonNull<c_void>> {
        match self {
            Target::Address(addr) => std::ptr::NonNull::new(*addr as *mut c_void)
                .ok_or(HookingError::InvalidTarget(*addr as *const _)),
            Target::Symbol { module, symbol } => Ok(unsafe { sys::find_symbol(*module, symbol)? }),
        }
    }
}

/// Fluently configures and installs a hook.
///
/// Pick a target with [`at`](Self::at) / [`by_name`](Self::by_name), optionally
/// a custom [`writer`](Self::with_writer), then a terminal that chooses the
/// detour kind: [`detour`](Self::detour) (a raw destination), or — on x86-64 —
/// [`save_registers`](Self::save_registers) (a raw signature-agnostic dispatch)
/// or [`save_registers_fn`](Self::save_registers_fn) (a Rust closure).
///
/// ```no_run
/// # use core::ffi::CStr;
/// # use hooking::HookBuilder;
/// # #[cfg(target_arch = "x86_64")] {
/// let hook = unsafe {
///     HookBuilder::by_name(c"getenv")
///         .save_registers_fn(|d| {
///             println!("getenv called, first arg = {:#x}", d.regs.read_int(0));
///             hooking::DispatchResult::Passthrough
///         })
/// }
/// .unwrap();
/// # }
/// ```
pub struct HookBuilder<'t, 'w> {
    target: Target<'t>,
    writer: HookWriter<'w>,
}

impl<'t> HookBuilder<'t, 'static> {
    /// Hook the function at `target`, using the default arena and patcher.
    pub fn at(target: *mut u8) -> Self {
        Self {
            target: Target::Address(target),
            writer: HookWriter::from_static(),
        }
    }

    /// Hook the exported function `symbol`, resolved in any loaded module.
    pub fn by_name(symbol: &'t CStr) -> Self {
        Self {
            target: Target::Symbol {
                module: None,
                symbol,
            },
            writer: HookWriter::from_static(),
        }
    }

    /// Hook the exported function `symbol` resolved within `module`.
    pub fn in_module(module: &'t CStr, symbol: &'t CStr) -> Self {
        Self {
            target: Target::Symbol {
                module: Some(module),
                symbol,
            },
            writer: HookWriter::from_static(),
        }
    }
}

impl<'t, 'w> HookBuilder<'t, 'w> {
    /// Use a specific [`HookWriter`] (custom arena / patcher) for this hook.
    pub fn with_writer(self, writer: HookWriter<'w>) -> Self {
        Self { writer, ..self }
    }

    /// Install an ordinary detour: calls jump to `destination`, which must have
    /// the same signature and calling convention as the target.
    ///
    /// # Safety
    /// The target must be a function at least as long as the patch, and
    /// `destination` must match its signature and calling convention.
    pub unsafe fn detour(self, destination: *mut u8) -> Result<Hook<'w>> {
        let target = unsafe { self.target.resolve()? };
        let destination = std::ptr::NonNull::new(destination as *mut c_void)
            .ok_or(HookingError::InvalidDestination(destination as *const _))?;
        unsafe { self.writer.create_hook(target, destination) }
    }

    /// Install a [`MiniHook`](super::MiniHook): a trampoline-less detour that
    /// jumps straight to `destination`, leaving r10/r11 untouched.
    ///
    /// # Safety
    /// The target must be a function at least as long as the patch, and
    /// `destination` must match its signature and calling convention.
    pub unsafe fn mini(self, destination: *mut u8) -> Result<super::MiniHook<'w>> {
        let target = unsafe { self.target.resolve()? };
        let destination = std::ptr::NonNull::new(destination as *mut c_void)
            .ok_or(HookingError::InvalidDestination(destination as *const _))?;
        unsafe { self.writer.create_mini_hook(target, destination) }
    }

    /// Install a save-registers hook with a raw, signature-agnostic `dispatch`.
    /// No allocation: the returned [`SavedRegisterHook`] has no owned closure
    /// (its `detour` is `None`), and still lets the dispatch be swapped later
    /// with [`set_dispatch`](SavedRegisterHook::set_dispatch).
    ///
    /// # Safety
    /// The target must point to the start of a function.
    #[cfg(target_arch = "x86_64")]
    pub unsafe fn save_registers(
        self,
        dispatch: SavedRegsDispatch,
    ) -> Result<SavedRegisterHook<'w>> {
        let target = unsafe { self.target.resolve()? };
        let arena = self.writer.arena;
        let context = [raw_entry as SaveRegsEntry as usize, dispatch as usize];
        let hook = unsafe { self.writer.install_save_registers(target, context)? };
        Ok(SavedRegisterHook::new(hook, arena, None))
    }

    /// Install a save-registers hook whose detour is a Rust closure. The closure
    /// receives each call's saved registers as a [`Dispatch`] and returns a
    /// [`DispatchResult`]; the returned [`SavedRegisterHook`] owns the closure.
    ///
    /// # Safety
    /// The target must point to the start of a function.
    #[cfg(target_arch = "x86_64")]
    pub unsafe fn save_registers_fn<F>(self, detour: F) -> Result<SavedRegisterHook<'w>>
    where
        F: Fn(Dispatch) -> DispatchResult + Send + Sync + 'static,
    {
        let target = unsafe { self.target.resolve()? };
        let arena = self.writer.arena;
        let detour_ptr = box_detour(detour);
        let context = [closure_entry as SaveRegsEntry as usize, detour_ptr as usize];
        match unsafe { self.writer.install_save_registers(target, context) } {
            Ok(hook) => Ok(SavedRegisterHook::new(hook, arena, Some(detour_ptr))),
            Err(e) => {
                // Installation failed; reclaim the closure so it isn't leaked.
                drop(unsafe { Box::from_raw(detour_ptr) });
                Err(e)
            }
        }
    }
}

/// The saved argument registers of one hooked call, handed to a closure detour.
#[cfg(target_arch = "x86_64")]
pub struct Dispatch<'a> {
    /// The original-function stub address (stable per hook).
    pub original: usize,
    /// The saved integer and SSE argument registers, readable and writable.
    pub regs: &'a SavedRegs,
}

#[cfg(target_arch = "x86_64")]
type BoxedDetour = Box<dyn Fn(Dispatch) -> DispatchResult + Send + Sync + 'static>;

/// The [`SaveRegsEntry`] for a closure detour: `data` is a `*mut BoxedDetour`.
#[cfg(target_arch = "x86_64")]
extern "C" fn closure_entry(
    original: usize,
    int_regs: *mut u64,
    sse_regs: *mut [u8; 16],
    data: *mut c_void,
) -> DispatchResult {
    let detour = unsafe { &*(data as *const BoxedDetour) };
    let regs = SavedRegs { int_regs, sse_regs };
    detour(Dispatch {
        original,
        regs: &regs,
    })
}

/// Box a detour closure down to a thin pointer for the context data slot: that
/// slot holds one pointer, but `dyn Fn` is a fat pointer, so box the boxed
/// trait object and store the (thin) pointer to it.
#[cfg(target_arch = "x86_64")]
fn box_detour<F>(detour: F) -> *mut BoxedDetour
where
    F: Fn(Dispatch) -> DispatchResult + Send + Sync + 'static,
{
    let detour: BoxedDetour = Box::new(detour);
    Box::into_raw(Box::new(detour))
}

/// A save-registers hook, as returned by [`HookBuilder::save_registers`] (a raw
/// dispatch — no allocation, `detour` is `None`) and
/// [`HookBuilder::save_registers_fn`] (a closure it owns and frees on drop).
///
/// It derefs to the underlying [`Hook`], so `apply_hook` / `remove_hook` /
/// `original_function` work directly; converts to a bare [`Hook`] with
/// `.into()`; and its dispatch can be swapped while the hook is live with
/// [`set_dispatch`](Self::set_dispatch) / [`set_detour`](Self::set_detour).
///
/// ```no_run
/// use hooking::{Dispatch, DispatchResult, HookBuilder};
/// # extern "C" fn target(a: u64) -> u64 { a }
/// let mut hook = unsafe {
///     HookBuilder::at(target as *mut u8)
///         .save_registers_fn(|d: Dispatch| DispatchResult::OverrideInt(d.regs.read_int(0) + 1))
/// }
/// .unwrap();
/// unsafe { hook.apply_hook().unwrap() }; // via Deref to Hook
/// // Swap the detour without re-creating the hook:
/// unsafe { hook.set_detour(|_| DispatchResult::Passthrough).unwrap() };
/// ```
#[cfg(target_arch = "x86_64")]
pub struct SavedRegisterHook<'a> {
    hook: Hook<'a>,
    /// Address of this hook's context slot (`original - 16`).
    context_at: usize,
    /// The arena the hook's code lives in, used to rewrite the context slot.
    arena: &'a dyn CodeArena,
    /// The owned closure, if the detour is one; `None` for a raw `fn`.
    detour: Option<*mut BoxedDetour>,
}

// The detour is `Send + Sync`, so the hook that owns it is too.
#[cfg(target_arch = "x86_64")]
unsafe impl Send for SavedRegisterHook<'_> {}
#[cfg(target_arch = "x86_64")]
unsafe impl Sync for SavedRegisterHook<'_> {}

#[cfg(target_arch = "x86_64")]
impl<'a> SavedRegisterHook<'a> {
    fn new(hook: Hook<'a>, arena: &'a dyn CodeArena, detour: Option<*mut BoxedDetour>) -> Self {
        let context_at =
            hook.original_function().as_ptr() as usize - 2 * std::mem::size_of::<usize>();
        Self {
            hook,
            context_at,
            arena,
            detour,
        }
    }

    /// Overwrite this hook's `[entry_fn, data]` context slot through the arena
    /// (which writes via its writable view of the hook's code).
    unsafe fn write_context(&self, context: [usize; 2]) -> Result<()> {
        let mut bytes = [0u8; 16];
        bytes[..8].copy_from_slice(&context[0].to_ne_bytes());
        bytes[8..].copy_from_slice(&context[1].to_ne_bytes());
        unsafe { self.arena.write_at(self.context_at, &bytes) }
    }

    fn free_detour(&mut self) {
        if let Some(ptr) = self.detour.take() {
            drop(unsafe { Box::from_raw(ptr) });
        }
    }

    /// Replace the detour with a raw dispatch function, freeing any previously
    /// owned closure. Takes effect on the next call to the hooked function.
    ///
    /// # Safety
    /// `dispatch` must handle the target's calling convention (as for
    /// [`HookBuilder::save_registers`]), and the hooked function must not be
    /// called concurrently during the swap.
    pub unsafe fn set_dispatch(&mut self, dispatch: SavedRegsDispatch) -> Result<()> {
        unsafe { self.write_context([raw_entry as SaveRegsEntry as usize, dispatch as usize])? };
        self.free_detour();
        Ok(())
    }

    /// Replace the detour with a Rust closure, which this hook now owns, freeing
    /// any previously owned closure. Takes effect on the next call.
    ///
    /// # Safety
    /// The hooked function must not be called concurrently during the swap.
    pub unsafe fn set_detour<F>(&mut self, detour: F) -> Result<()>
    where
        F: Fn(Dispatch) -> DispatchResult + Send + Sync + 'static,
    {
        let detour_ptr = box_detour(detour);
        match unsafe {
            self.write_context([closure_entry as SaveRegsEntry as usize, detour_ptr as usize])
        } {
            Ok(()) => {
                self.free_detour();
                self.detour = Some(detour_ptr);
                Ok(())
            }
            Err(e) => {
                drop(unsafe { Box::from_raw(detour_ptr) });
                Err(e)
            }
        }
    }
}

#[cfg(target_arch = "x86_64")]
impl<'a> Deref for SavedRegisterHook<'a> {
    type Target = Hook<'a>;
    fn deref(&self) -> &Hook<'a> {
        &self.hook
    }
}

#[cfg(target_arch = "x86_64")]
impl<'a> DerefMut for SavedRegisterHook<'a> {
    fn deref_mut(&mut self) -> &mut Hook<'a> {
        &mut self.hook
    }
}

/// Converts into a bare [`Hook`], **leaking** any owned closure so the hook
/// keeps working without the wrapper (the dispatch can then no longer be
/// swapped). A raw-`fn` hook owns no closure, so nothing leaks.
#[cfg(target_arch = "x86_64")]
impl<'a> From<SavedRegisterHook<'a>> for Hook<'a> {
    fn from(hook: SavedRegisterHook<'a>) -> Hook<'a> {
        // The `Drop` frees the closure, so move the inner hook out without
        // running it; the closure (if any) is deliberately leaked.
        let hook = std::mem::ManuallyDrop::new(hook);
        unsafe { std::ptr::read(&hook.hook) }
    }
}

#[cfg(target_arch = "x86_64")]
impl Drop for SavedRegisterHook<'_> {
    fn drop(&mut self) {
        // Free the owned closure, if any. Keeping the hook applied past this
        // drop is the caller's responsibility (as with a raw `Hook`): `.into()`
        // a `Hook` or `std::mem::forget` the wrapper to persist it.
        self.free_detour();
    }
}