hooking 0.8.0

cross platform detour / hooking library in rust
Documentation
//! Support used by the `#[hook]` and `#[mini_hook]` attribute macros to hold a
//! hook in a `static` and drive it. Not meant to be used directly.

use crate::error::{HookingError, Result};
use crate::{Hook, HookKind};
use std::ffi::{CStr, c_void};
use std::ops::{Deref, DerefMut};
use std::ptr::NonNull;
use std::sync::{Mutex, MutexGuard, OnceLock};

/// A hook wrapper that is `Send + Sync` so it can live in a `static`, derefing
/// to the wrapped hook.
#[derive(Debug)]
#[repr(transparent)]
pub struct MacroHook<H = Hook<'static>>(H);

unsafe impl<H> Send for MacroHook<H> {}
unsafe impl<H> Sync for MacroHook<H> {}
impl<H> DerefMut for MacroHook<H> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl<H> Deref for MacroHook<H> {
    type Target = H;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

/// The hook created by a `#[hook]` or `#[mini_hook]`, set once when the
/// program starts.
pub struct StaticHook<H = Hook<'static>>(OnceLock<Initialized<H>>);

struct Initialized<H> {
    hook: Mutex<MacroHook<H>>,
    /// Kept outside the mutex so hooks can read it without locking.
    original_function: NonNull<c_void>,
}

// The original function is only ever called, never written through.
unsafe impl<H> Send for Initialized<H> {}
unsafe impl<H> Sync for Initialized<H> {}

impl<H> StaticHook<H> {
    /// Creates an uninitialized static hook; it is filled in by `init_hook`.
    pub const fn new() -> Self {
        Self(OnceLock::new())
    }

    fn hook(&'static self) -> Result<StaticHookGuard<H>> {
        let initialized = self.0.get().ok_or(HookingError::NotHooked)?;
        Ok(initialized.hook.lock().unwrap())
    }
}

impl<H> Default for StaticHook<H> {
    fn default() -> Self {
        Self::new()
    }
}

/// A locked, mutable borrow of the hook inside a [`StaticHook`].
pub type StaticHookGuard<H = Hook<'static>> = MutexGuard<'static, MacroHook<H>>;

/// Called by `#[hook]` and `#[mini_hook]` when the program starts.
///
/// # Safety
/// As for [`HookKind::by_name`].
pub unsafe fn init_hook<H: HookKind>(
    static_hook: &StaticHook<H>,
    module: Option<&CStr>,
    symbol: &CStr,
    destination: *mut u8,
) {
    let hook = unsafe { H::by_name(module, symbol, destination).unwrap() };
    let initialized = Initialized {
        original_function: hook.original_function(),
        hook: Mutex::new(MacroHook(hook)),
    };

    if static_hook.0.set(initialized).is_err() {
        panic!("hook {symbol:?} was initialized twice");
    }
}

/// The address of the original (unhooked) function, or `None` if the hook has
/// not been initialized yet. Reads without locking.
pub fn original_function<H>(static_hook: &StaticHook<H>) -> Option<NonNull<c_void>> {
    Some(static_hook.0.get()?.original_function)
}

/// # Safety
/// As for [`Hook::apply_hook`].
pub unsafe fn enable_hook<H: HookKind>(static_hook: &'static StaticHook<H>) -> Result<()> {
    unsafe { static_hook.hook()?.apply_hook() }
}

/// # Safety
/// As for [`Hook::remove_hook`].
pub unsafe fn disable_hook<H: HookKind>(static_hook: &'static StaticHook<H>) -> Result<()> {
    unsafe { static_hook.hook()?.remove_hook() }
}

/// # Safety
/// The returned hook must not be applied or removed in ways that break the
/// requirements of [`Hook::apply_hook`] and [`Hook::remove_hook`].
pub unsafe fn get_hook<H>(static_hook: &'static StaticHook<H>) -> Result<StaticHookGuard<H>> {
    static_hook.hook()
}