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};
enum Target<'t> {
Address(*mut u8),
Symbol {
module: Option<&'t CStr>,
symbol: &'t CStr,
},
}
impl Target<'_> {
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)? }),
}
}
}
pub struct HookBuilder<'t, 'w> {
target: Target<'t>,
writer: HookWriter<'w>,
}
impl<'t> HookBuilder<'t, 'static> {
pub fn at(target: *mut u8) -> Self {
Self {
target: Target::Address(target),
writer: HookWriter::from_static(),
}
}
pub fn by_name(symbol: &'t CStr) -> Self {
Self {
target: Target::Symbol {
module: None,
symbol,
},
writer: HookWriter::from_static(),
}
}
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> {
pub fn with_writer(self, writer: HookWriter<'w>) -> Self {
Self { writer, ..self }
}
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) }
}
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) }
}
#[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))
}
#[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) => {
drop(unsafe { Box::from_raw(detour_ptr) });
Err(e)
}
}
}
}
#[cfg(target_arch = "x86_64")]
pub struct Dispatch<'a> {
pub original: usize,
pub regs: &'a SavedRegs,
}
#[cfg(target_arch = "x86_64")]
type BoxedDetour = Box<dyn Fn(Dispatch) -> DispatchResult + Send + Sync + 'static>;
#[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: ®s,
})
}
#[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))
}
#[cfg(target_arch = "x86_64")]
pub struct SavedRegisterHook<'a> {
hook: Hook<'a>,
context_at: usize,
arena: &'a dyn CodeArena,
detour: Option<*mut BoxedDetour>,
}
#[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,
}
}
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) });
}
}
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(())
}
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
}
}
#[cfg(target_arch = "x86_64")]
impl<'a> From<SavedRegisterHook<'a>> for Hook<'a> {
fn from(hook: SavedRegisterHook<'a>) -> Hook<'a> {
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) {
self.free_detour();
}
}