hooking 0.8.0

cross platform detour / hooking library in rust
Documentation
#![cfg_attr(docsrs, feature(doc_cfg))]
#![warn(missing_docs)]
//! Function hooking (detours) for Linux and Windows on x86-64 and x86.
//!
//! Patch the start of a function so calls run your code instead — the original
//! stays callable, because its overwritten instructions are relocated.
//!
//! # Ways to hook
//!
//! - **Attribute macros** — [`#[hook]`](macro@hook) / [`#[mini_hook]`](macro@mini_hook)
//!   create a hook at startup and generate `enable_hook` / `disable_hook`.
//! - **[`Hook`]** — [`Hook::create`] (by address) or [`Hook::by_name`] (by
//!   symbol) build a detour whose signature matches the target.
//! - **[`HookBuilder`]** — a fluent front-end: pick a target
//!   ([`at`](HookBuilder::at) / [`by_name`](HookBuilder::by_name)), then a
//!   detour.
//! - **Save-registers hooks** (x86-64) — hook a function *without knowing its
//!   signature*: the trampoline saves the argument registers and calls a
//!   dispatch that returns a [`DispatchResult`] (pass through, or override the
//!   return). The detour can be a raw function ([`HookBuilder::save_registers`])
//!   or a Rust closure ([`HookBuilder::save_registers_fn`]). Each hook carries
//!   its own dispatch — no global state.
//!
//! # Example — a detour with [`Hook`]
//!
//! [`Hook::create`] redirects a function to a same-signature detour; the
//! original stays reachable through [`Hook::original_function`].
//!
//! ```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() }; // calls to `target` now run `detour`
//! unsafe { hook.remove_hook().unwrap() };
//! ```
//!
//! # Example — a closure detour, no signature needed
//!
//! [`HookBuilder`] is the fluent way to reach every hook kind; here a closure
//! detour that doesn't need the target's signature.
//!
//! ```no_run
//! # #[cfg(target_arch = "x86_64")] {
//! use hooking::{Dispatch, DispatchResult, HookBuilder};
//!
//! # extern "C" fn target(_: u64) -> u64 { 0 }
//! let mut hook = unsafe {
//!     HookBuilder::at(target as *mut u8).save_registers_fn(|d: Dispatch| {
//!         let first = d.regs.read_int(0); // read argument register 0
//!         DispatchResult::OverrideInt(first + 1) // return first + 1 instead
//!     })
//! }
//! .unwrap();
//! unsafe { hook.apply_hook().unwrap() };
//! # }
//! ```
//!
//! The `examples/` directory covers the rest: the attribute macros, calling the
//! original, argument rewriting, mini hooks, and custom arenas.
//!
//! # Features
//!
//! - `macros` (default) — the `#[hook]` / `#[mini_hook]` attribute macros.
//! - `reflect` — derive `facet::Facet` on [`DispatchResult`] / [`CallResult`]
//!   so a reflection-based consumer (e.g. a scripting runtime) can register and
//!   return them.

pub mod arena;
pub mod asm;
pub mod error;
pub mod hooks;
pub mod mem;
pub mod patch;
mod sys;

cfg_select! {
    feature = "macros" => {
        mod macros;

        pub use hooking_macros::{hook, mini_hook};
        /// Implementation details the `#[hook]` / `#[mini_hook]` macros expand
        /// to. Not a stable API — do not use directly.
        pub mod __macro_support {
            pub use super::macros::*;
            /// Re-exported so crates using the macros don't need `ctor` themselves.
            pub use ::ctor;
        }
    }
    _ => {}
}

pub use hooks::{Hook, HookBuilder, HookData, HookKind, HookWriter, MiniHook, MiniHookData};

#[cfg(target_arch = "x86_64")]
pub use hooks::{
    CallResult, Dispatch, DispatchResult, SavedRegisterHook, SavedRegs, SavedRegsDispatch,
    call_with_saved_regs,
};

#[cfg(target_arch = "x86_64")]
pub(crate) const ORIGINAL_FN_CHECKSUM_MAGIC: usize = 0xDEADBEEFCAFEBABE;

/// The original function of the hook currently running, which its trampoline
/// passes in r10, with a checksum of it in r11. Returns `None` when not
/// called from a hook.
///
/// It must be called at the very start of the hook, before anything else
/// uses those registers. Only x86_64 has registers to spare for this; on any
/// architecture, [`Hook::original_function`] gives a hook's original function.
#[cfg(target_arch = "x86_64")]
pub fn original_function_ptr() -> Option<core::ptr::NonNull<core::ffi::c_void>> {
    let mut orig_addr: *mut core::ffi::c_void = core::ptr::null_mut();
    let mut checksum = 0usize;
    unsafe {
        core::arch::asm!(
        "nop",
        lateout("r10") orig_addr,
        lateout("r11") checksum,
        );

        ((orig_addr as usize ^ ORIGINAL_FN_CHECKSUM_MAGIC) == checksum)
            .then(|| core::ptr::NonNull::new_unchecked(orig_addr))
    }
}