hooking 0.8.0

cross platform detour / hooking library in rust
Documentation
//! Writing hook tables into the arena: [`HookWriter`], the [`HookLayout`] of a
//! placed hook, and the low-level `create_hook` / `write_hook_table` machinery.

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

use crate::arena::{CodeArena, DefaultArena};
use crate::asm;
use crate::error::{HookingError, Result};
use crate::patch::{DefaultPatcher, PatchWriter};
use crate::sys;

use super::hook::{Hook, HookData};
#[cfg(target_arch = "x86_64")]
use super::save_registers::{
    SaveRegsEntry, SavedRegsDispatch, raw_entry, save_registers_trampoline,
};

static DEFAULT_ARENA: DefaultArena = DefaultArena::new();
static DEFAULT_PATCHER: DefaultPatcher = DefaultPatcher::new();

/// The longest x86 instruction.
const MAX_INSTRUCTION_LEN: usize = 15;

/// Where each part of a hook's code is, as offsets into the code placed in
/// the arena:
///
/// | Bytes | Contents |
/// | --- | --- |
/// | pointer size | Address of `original_fn`, read by the trampoline on x86_64 |
/// | `trampoline` | Passes that address to the hook, then jumps to the hook |
/// | `original_fn` | The instructions overwritten by the patch, then a jump back |
struct HookLayout {
    trampoline: Range<usize>,
    original_fn: Range<usize>,
    /// The jump to the trampoline, written over the target.
    patch: Vec<u8>,
}

impl HookLayout {
    /// Assemble a hook's code to run at `at`. `target_code` is the start of
    /// the target function, which runs at `target`.
    fn assemble(
        at: usize,
        target: usize,
        target_code: &[u8],
        destination: usize,
        context: Option<[usize; 2]>,
    ) -> Result<(Vec<u8>, Self)> {
        let slot_len = std::mem::size_of::<usize>();

        let trampoline_at = at + slot_len;
        let trampoline = asm::trampoline(trampoline_at, destination, at)?;

        // An optional per-hook context (entry-fn pointer + data pointer) placed
        // immediately before `original_fn`, so a dispatch handed `original_fn`'s
        // address can read it at `original - 16`. Only save-registers hooks use
        // it; ordinary hooks pass `None` and reserve nothing.
        let context_len = if context.is_some() { 2 * slot_len } else { 0 };

        let original_fn_at = trampoline_at + trampoline.len() + context_len;
        let patch = asm::patch(target, trampoline_at)?;
        // The target is live code, so the calls it makes are readable.
        let original_fn =
            unsafe { asm::relocate(target_code, target, original_fn_at, patch.len())? };

        let mut bytes = original_fn_at.to_ne_bytes().to_vec();
        bytes.extend_from_slice(&trampoline);
        if let Some([entry_fn, data]) = context {
            bytes.extend_from_slice(&entry_fn.to_ne_bytes());
            bytes.extend_from_slice(&data.to_ne_bytes());
        }
        bytes.extend_from_slice(&original_fn);

        let trampoline = slot_len..slot_len + trampoline.len();
        let original_fn = trampoline.end + context_len..bytes.len();
        let layout = Self {
            trampoline,
            original_fn,
            patch,
        };
        Ok((bytes, layout))
    }
}

/// Builds hooks into a [`CodeArena`], patching their targets with a
/// [`PatchWriter`]. [`from_static`](Self::from_static) uses the crate's shared
/// default arena and patcher; [`new`](Self::new) / [`with_patcher`](Self::with_patcher)
/// pick your own.
///
/// ```no_run
/// use core::ptr::NonNull;
/// use hooking::{HookWriter, arena::SealedArena};
///
/// # extern "C" fn target(a: u64) -> u64 { a }
/// # extern "C" fn detour(a: u64) -> u64 { a + 1 }
/// // Build hooks into a chosen arena instead of the shared default one.
/// let arena = SealedArena::new();
/// let writer = HookWriter::new(&arena);
/// let mut hook = unsafe {
///     writer.create_hook(
///         NonNull::new(target as *mut _).unwrap(),
///         NonNull::new(detour as *mut _).unwrap(),
///     )
/// }
/// .unwrap();
/// unsafe { hook.apply_hook().unwrap() };
/// ```
pub struct HookWriter<'a> {
    pub(in crate::hooks) arena: &'a dyn CodeArena,
    pub(in crate::hooks) patcher: &'a dyn PatchWriter,
}

impl HookWriter<'static> {
    /// A writer over the crate's shared default arena and patcher.
    pub const fn from_static() -> Self {
        Self::new(&DEFAULT_ARENA)
    }
}

impl<'a> HookWriter<'a> {
    /// A writer over `arena`, using the default patcher.
    pub const fn new(arena: &'a dyn CodeArena) -> Self {
        Self {
            arena,
            patcher: &DEFAULT_PATCHER,
        }
    }

    /// Use `patcher` to write hooks into their target functions.
    pub const fn with_patcher(self, patcher: &'a dyn PatchWriter) -> Self {
        Self {
            arena: self.arena,
            patcher,
        }
    }

    /// Like [`Hook::create_save_registers`], but uses this writer's arena
    /// and patcher.
    ///
    /// # Safety
    /// `target` must point to the start of a function.
    #[cfg(target_arch = "x86_64")]
    pub unsafe fn create_save_registers(
        &self,
        target: *mut u8,
        dispatch: SavedRegsDispatch,
    ) -> Result<Hook<'a>> {
        let target = NonNull::new(target as *mut c_void)
            .ok_or(HookingError::InvalidTarget(target as *const _))?;
        unsafe {
            self.install_save_registers(
                target,
                [raw_entry as SaveRegsEntry as usize, dispatch as usize],
            )
        }
    }

    /// Installs a save-registers hook on an already-resolved `target`, baking in
    /// the per-hook `[entry_fn, data]` context the dispatch shim reads at
    /// `original - 16`. Shared by the raw and closure-based constructors.
    #[cfg(target_arch = "x86_64")]
    pub(in crate::hooks) unsafe fn install_save_registers(
        &self,
        target: NonNull<c_void>,
        context: [usize; 2],
    ) -> Result<Hook<'a>> {
        let destination = NonNull::new(save_registers_trampoline as *mut c_void)
            .expect("function pointer is not null");
        unsafe { self.create_hook_ctx(target, destination, Some(context)) }
    }

    /// Like [`HookWriter::create_save_registers`], but resolves the target by
    /// symbol name (optionally within `module`) the way
    /// [`create_hook_by_name`](Self::create_hook_by_name) does, instead of
    /// taking its address. Lets a signature-agnostic hook be placed on an
    /// exported function without the caller first resolving the symbol.
    ///
    /// # Safety
    /// `symbol` must name a function, and `dispatch` must be prepared to
    /// handle that function's calling convention.
    #[cfg(target_arch = "x86_64")]
    pub unsafe fn create_save_registers_by_name(
        &self,
        module: Option<&CStr>,
        symbol: &CStr,
        dispatch: SavedRegsDispatch,
    ) -> Result<Hook<'a>> {
        unsafe {
            let target = sys::find_symbol(module, symbol)?;
            self.install_save_registers(
                target,
                [raw_entry as SaveRegsEntry as usize, dispatch as usize],
            )
        }
    }

    /// Like [`Hook::by_name`], but uses this writer's 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 create_hook_by_name(
        &self,
        module: Option<&CStr>,
        symbol: &CStr,
        destination: *mut u8,
    ) -> Result<Hook<'a>> {
        let destination = NonNull::new(destination as *mut c_void).ok_or_else(|| {
            HookingError::NoDestination(symbol.to_str().unwrap_or("<invalid-symbol-name>").into())
        })?;

        unsafe {
            let symbol_address = sys::find_symbol(module, symbol)?;
            self.create_hook(symbol_address, destination)
        }
    }

    /// Like [`Hook::create`], but uses this writer's 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_hook(
        &self,
        target: NonNull<c_void>,
        destination: NonNull<c_void>,
    ) -> Result<Hook<'a>> {
        unsafe { self.create_hook_ctx(target, destination, None) }
    }

    /// Like [`create_hook`](Self::create_hook), with an optional per-hook
    /// save-registers context (entry-fn + data pointers) baked into the table.
    unsafe fn create_hook_ctx(
        &self,
        target: NonNull<c_void>,
        destination: NonNull<c_void>,
        context: Option<[usize; 2]>,
    ) -> Result<Hook<'a>> {
        let hook_data = unsafe { self.write_hook_table_ctx(target, destination, context)? };
        Ok(Hook::new(hook_data, self.patcher))
    }

    /// Write a hook's trampoline and relocated original instructions into
    /// the arena, without patching the target.
    ///
    /// # Safety
    /// `target` must point to the start of a function that is at least as
    /// long as the patch, and `destination_fn` must be a function with the same
    /// signature and calling convention as `target`.
    pub unsafe fn write_hook_table(
        &self,
        target: NonNull<ffi::c_void>,
        destination_fn: NonNull<ffi::c_void>,
    ) -> Result<HookData<'a>> {
        unsafe { self.write_hook_table_ctx(target, destination_fn, None) }
    }

    /// Like [`write_hook_table`](Self::write_hook_table), but bakes an optional
    /// per-hook context (entry-fn + data pointers) in just before the relocated
    /// original, reachable from a save-registers dispatch at `original - 16`.
    unsafe fn write_hook_table_ctx(
        &self,
        target: NonNull<ffi::c_void>,
        destination_fn: NonNull<ffi::c_void>,
        context: Option<[usize; 2]>,
    ) -> Result<HookData<'a>> {
        let target_address = target.as_ptr() as usize;
        let target_code = unsafe { decodable_code(target) };
        let destination = destination_fn.as_ptr() as usize;

        // `place` may assemble more than once; the last layout is the one placed.
        let mut layout = None;
        let placed_at = self.arena.place(Some(target_address), &mut |at| {
            let (bytes, assembled) =
                HookLayout::assemble(at, target_address, target_code, destination, context)?;
            layout = Some(assembled);
            Ok(bytes)
        })?;
        let layout = layout.expect("place assembles the code it places");

        let placed = |range: Range<usize>| unsafe {
            std::slice::from_raw_parts(placed_at.as_ptr().add(range.start), range.len())
        };

        Ok(HookData {
            symbol_address: target,
            trampoline_data: placed(layout.trampoline),
            original_fn_call_stub_data: placed(layout.original_fn),
            original_instructions: target_code[..layout.patch.len()].to_vec(),
            patch_data: layout.patch,
        })
    }
}

/// The code at the start of `target` that relocation may decode: the
/// longest patch, plus one more instruction that may start inside it.
///
/// Reading stops at the end of the page holding the last byte the longest
/// patch could overwrite, so it never touches a page the patch wouldn't.
pub(in crate::hooks) unsafe fn decodable_code<'a>(target: NonNull<c_void>) -> &'a [u8] {
    let start = target.as_ptr() as usize;
    let page_end = sys::align_up(start + asm::MAX_PATCH_LEN, sys::page_size());
    let len = (asm::MAX_PATCH_LEN + MAX_INSTRUCTION_LEN).min(page_end - start);
    unsafe { std::slice::from_raw_parts(target.as_ptr().cast(), len) }
}