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();
const MAX_INSTRUCTION_LEN: usize = 15;
struct HookLayout {
trampoline: Range<usize>,
original_fn: Range<usize>,
patch: Vec<u8>,
}
impl HookLayout {
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)?;
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)?;
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))
}
}
pub struct HookWriter<'a> {
pub(in crate::hooks) arena: &'a dyn CodeArena,
pub(in crate::hooks) patcher: &'a dyn PatchWriter,
}
impl HookWriter<'static> {
pub const fn from_static() -> Self {
Self::new(&DEFAULT_ARENA)
}
}
impl<'a> HookWriter<'a> {
pub const fn new(arena: &'a dyn CodeArena) -> Self {
Self {
arena,
patcher: &DEFAULT_PATCHER,
}
}
pub const fn with_patcher(self, patcher: &'a dyn PatchWriter) -> Self {
Self {
arena: self.arena,
patcher,
}
}
#[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],
)
}
}
#[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)) }
}
#[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],
)
}
}
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)
}
}
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) }
}
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))
}
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) }
}
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;
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,
})
}
}
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) }
}