hooking 0.7.0

cross platform detour / hooking library in rust
Documentation
//! Hooks without a trampoline: the target jumps straight to the destination.

use std::ffi::{CStr, c_void};
use std::ptr::NonNull;

use super::patch_state::PatchState;
use super::{HookWriter, decodable_code};
use crate::asm;
use crate::error::{HookingError, Result};
use crate::sys;

/// A [`Hook`](super::Hook) without a trampoline: the target jumps straight
/// to the destination.
///
/// r10 and r11 are left untouched, so `original_function_ptr` returns `None`
/// in the destination. Use [`MiniHook::original_function`] to call the
/// original instead.
///
/// Prefer it over a `Hook` when the caller passes values in r10 or r11
/// (such as GCC's static chain pointer, or hidden arguments in JIT runtimes),
/// which a `Hook`'s trampoline would overwrite, or to save the trampoline's
/// jump and memory when `original_function_ptr` isn't needed.
#[derive(Debug)]
pub struct MiniHook<'a> {
    pub data: MiniHookData<'a>,
    state: PatchState<'a>,
}

#[derive(Debug)]
pub struct MiniHookData<'a> {
    pub symbol_address: NonNull<c_void>,
    /// A jump to the destination, placed in the arena near the target when
    /// the destination is out of rel32 range of it. `None` when the target
    /// jumps straight to the destination.
    pub thunk_data: Option<&'a [u8]>,
    /// The instructions the patch overwrites, relocated, then a jump back to
    /// the rest of the target.
    pub original_fn_call_stub_data: &'a [u8],
    /// The jump written over the target.
    pub patch_data: Vec<u8>,
    /// The bytes the patch overwrites.
    pub original_instructions: Vec<u8>,
}

impl MiniHook<'static> {
    /// Create a mini hook on `symbol` in `module`, or in any loaded module
    /// when `module` is `None`, using the default arena and patcher.
    ///
    /// # Safety
    /// As for [`MiniHook::create`], with `symbol` naming the target.
    pub unsafe fn by_name(
        module: Option<&CStr>,
        symbol: &CStr,
        destination: *mut u8,
    ) -> Result<Self> {
        let hook_writer = HookWriter::from_static();
        unsafe { hook_writer.create_mini_hook_by_name(module, symbol, destination) }
    }

    /// Create a mini hook on `target` using the default arena and patcher.
    ///
    /// # Safety
    /// As for [`Hook::create`](super::Hook::create).
    pub unsafe fn create(target: *mut u8, destination: *mut u8) -> Result<Self> {
        let hook_writer = HookWriter::from_static();
        unsafe {
            hook_writer.create_mini_hook(
                NonNull::new(target as *mut _)
                    .ok_or(HookingError::InvalidTarget(target as *const _))?,
                NonNull::new(destination as *mut _)
                    .ok_or(HookingError::InvalidDestination(destination as *const _))?,
            )
        }
    }
}

impl<'a> MiniHook<'a> {
    /// 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 destination. 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 bytes. 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)
        }
    }
}

impl<'a> HookWriter<'a> {
    /// Like [`MiniHook::by_name`], but uses this writer's arena and patcher.
    ///
    /// # Safety
    /// As for [`MiniHook::create`], with `symbol` naming the target.
    pub unsafe fn create_mini_hook_by_name(
        &self,
        module: Option<&CStr>,
        symbol: &CStr,
        destination: *mut u8,
    ) -> Result<MiniHook<'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_mini_hook(symbol_address, destination)
        }
    }

    /// Like [`MiniHook::create`], but uses this writer's arena and patcher.
    ///
    /// # Safety
    /// As for [`MiniHook::create`].
    pub unsafe fn create_mini_hook(
        &self,
        target: NonNull<c_void>,
        destination: NonNull<c_void>,
    ) -> Result<MiniHook<'a>> {
        let target_address = target.as_ptr() as usize;
        let target_code = unsafe { decodable_code(target) };
        let destination = destination.as_ptr() as usize;
        let near = sys::in_rel32_range(target_address, destination);

        // Placed in the arena: a thunk jumping on to the destination when it
        // is too far for the patch to reach, then the relocated original.
        // `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 thunk = if near {
                Vec::new()
            } else {
                asm::patch(at, destination)?
            };
            let patch = asm::patch(target_address, if near { destination } else { at })?;
            let original_at = at + thunk.len();
            let original =
                unsafe { asm::relocate(target_code, target_address, original_at, patch.len())? };

            let mut bytes = thunk;
            let thunk_len = bytes.len();
            bytes.extend_from_slice(&original);
            layout = Some((thunk_len, bytes.len(), patch));
            Ok(bytes)
        })?;
        let (thunk_len, len, patch_data) = layout.expect("place assembles the code it places");

        let placed = |start: usize, end: usize| unsafe {
            std::slice::from_raw_parts(placed_at.as_ptr().add(start), end - start)
        };
        let thunk_data = (!near).then(|| placed(0, thunk_len));
        let original_instructions = target_code[..patch_data.len()].to_vec();

        Ok(MiniHook {
            data: MiniHookData {
                symbol_address: target,
                thunk_data,
                original_fn_call_stub_data: placed(thunk_len, len),
                patch_data,
                original_instructions,
            },
            state: PatchState::new(self.patcher),
        })
    }
}