use std::{
cmp::Ordering,
collections::BTreeMap,
ffi::c_void,
fmt,
hash::BuildHasherDefault,
mem,
ptr::{self, NonNull},
slice,
sync::{
Arc,
atomic::{AtomicPtr, Ordering as AtomicOrdering},
},
};
use fxhash::{FxBuildHasher, FxHashMap};
use parking_lot::Mutex;
use windows_sys::Win32::{
Foundation::STATUS_SUCCESS,
System::Memory::{
MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_EXECUTE_READWRITE, PAGE_READWRITE, VirtualAlloc,
VirtualFree,
},
};
use crate::{
address::AsAddress,
hook::{HookGroup, asm},
system::{
self,
alloc::{AllocBounds, try_alloc_in_bounds_unchecked},
module::Module,
nt::{
LDR_DLL_NOTIFICATION_DATA, LDR_DLL_NOTIFICATION_REASON_LOADED,
LDR_DLL_NOTIFICATION_REASON_UNLOADED, LdrRegisterDllNotification,
LdrUnregisterDllNotification,
},
},
};
const CALL_REL32_DATA_LEN: usize = 1 + size_of::<i32>() + size_of::<usize>() - 1;
const LANDING_PAD_LEN: usize = LANDING_PAD_TEMPLATE.len();
const LANDING_PAD_EXCLUDE_LEN: usize = 18;
const LANDING_PAD_INCLUDE_LEN: usize = LANDING_PAD_LEN - LANDING_PAD_EXCLUDE_LEN + 1;
const LANDING_PAD_OFFSET_START: usize = LANDING_PAD_INCLUDE_LEN + 2;
#[derive(Clone)]
pub struct HookAllocator {
inner: Arc<(RawHookAllocator, Module)>,
}
struct RawHookAllocator {
module_mapping: Mutex<FxHashMap<Module, HookModuleGroup>>,
memory_mapping: Mutex<BTreeMap<usize, Box<[Option<Module>]>>>,
loader_cookie: AtomicPtr<c_void>,
alloc_granularity: usize,
pages_per_alloc: usize,
page_size: usize,
}
struct HookModuleGroup {
base_address: *mut u8,
address_ranges: Vec<(u32, u32)>,
group_allocator: HookGroupBumpAllocator,
groups_by_ptr: FxHashMap<*const (), NonNull<HookGroup>>,
}
struct HookGroupBumpAllocator(Vec<(NonNull<HookGroup>, NonNull<HookGroup>)>);
impl HookAllocator {
pub fn new() -> Self {
let system_info = system::get_info();
let alloc_granularity = system_info.dwAllocationGranularity as usize;
let page_size = system_info.dwPageSize as usize;
assert!(page_size.is_power_of_two(), "page size is not a power of 2");
assert!(
alloc_granularity.is_power_of_two(),
"allocation granularity is not a power of 2"
);
assert!(
page_size <= alloc_granularity,
"page size is greater than the allocation granularity"
);
assert!(
page_size >= LANDING_PAD_LEN,
"page size is smaller than `LANDING_PAD_LEN` bytes"
);
let pages_per_alloc = alloc_granularity / page_size;
let owning_module =
Module::try_from_address(Self::new as *const ()).expect("failed to get owning module");
let inner = Arc::new((
RawHookAllocator {
alloc_granularity,
pages_per_alloc,
page_size,
..const { RawHookAllocator::new() }
},
owning_module,
));
let mut loader_cookie = ptr::null_mut();
if unsafe {
LdrRegisterDllNotification(
0,
Some(Self::loader_notification),
Arc::into_raw(inner.clone()) as *mut _,
&mut loader_cookie,
) != STATUS_SUCCESS
} {
panic!("LdrRegisterDllNotification failed");
}
inner
.0
.loader_cookie
.store(loader_cookie, AtomicOrdering::Relaxed);
Self { inner }
}
pub(super) fn get_existing(
&self,
module: Module,
fn_ptr: *const (),
) -> Option<NonNull<HookGroup>> {
self.inner.0.get_existing(module, fn_ptr)
}
pub(super) unsafe fn try_alloc_in_bounds<B: AllocBounds<A>, A: AsAddress>(
&self,
bounds: B,
module: Module,
fn_ptr: *const (),
code_offset: u32,
code: &[u8],
f: &dyn Fn(NonNull<HookGroup>),
) -> Option<(*const (), NonNull<HookGroup>)> {
unsafe {
self.inner
.0
.try_alloc_in_bounds(bounds, module, fn_ptr, code_offset, code, f)
}
}
pub(super) unsafe fn dealloc_failed_hook(&self, module: Module, fn_ptr: *const ()) {
unsafe {
self.inner.0.dealloc_failed_hook(module, fn_ptr);
}
}
unsafe extern "system" fn loader_notification(
reason: u32,
data: *const LDR_DLL_NOTIFICATION_DATA,
context: *mut c_void,
) {
match reason {
LDR_DLL_NOTIFICATION_REASON_LOADED => {
}
LDR_DLL_NOTIFICATION_REASON_UNLOADED => {
let data = unsafe { &(*data).Unloaded };
let context = unsafe { &(*context.cast::<(RawHookAllocator, Module)>()) };
let Some(unloaded_module_base) = NonNull::new(data.DllBase as *mut u8) else {
return;
};
let unloaded_module =
unsafe { Module::from_raw_parts(unloaded_module_base, data.SizeOfImage) };
drop(context.0.module_mapping.lock().remove(&unloaded_module));
const PLUS_MINUS_2GB: usize = 0x80000000;
let module_address_space = unloaded_module.address_space();
let low_address_bound = module_address_space
.start
.addr()
.saturating_sub(PLUS_MINUS_2GB);
let high_address_bound = module_address_space
.end
.addr()
.saturating_add(PLUS_MINUS_2GB);
{
let mut memory_mapping = context.0.memory_mapping.lock();
let mut cleared_pages = vec![];
for (&page_addr, owners) in
memory_mapping.range_mut(low_address_bound..high_address_bound)
{
if owners.iter_mut().fold(true, |mut all_cleared, owner| {
all_cleared &=
owner.take_if(|module| *module == unloaded_module).is_some();
all_cleared
}) {
cleared_pages.push(page_addr);
}
}
for page in cleared_pages {
memory_mapping.remove(&page);
unsafe {
VirtualFree(page as _, 0, MEM_RELEASE);
}
}
}
if unloaded_module == context.1 {
let cookie = context.0.loader_cookie.load(AtomicOrdering::Relaxed);
unsafe {
LdrUnregisterDllNotification(cookie);
drop(Arc::from_raw(context));
}
}
}
_ => {}
}
}
}
impl RawHookAllocator {
fn get_existing(&self, module: Module, fn_ptr: *const ()) -> Option<NonNull<HookGroup>> {
self.module_mapping
.lock()
.get(&module)
.and_then(|group| group.groups_by_ptr.get(&fn_ptr).cloned())
}
unsafe fn try_alloc_in_bounds<B: AllocBounds<A>, A: AsAddress>(
&self,
bounds: B,
module: Module,
fn_ptr: *const (),
code_offset: u32,
code: &[u8],
f: &dyn Fn(NonNull<HookGroup>),
) -> Option<(*const (), NonNull<HookGroup>)> {
let (mut low_addr, mut high_addr) = bounds.as_alloc_bounds();
if high_addr - low_addr <= LANDING_PAD_EXCLUDE_LEN {
let high_rem = high_addr % LANDING_PAD_LEN;
high_addr = high_addr - high_rem + high_rem.min(LANDING_PAD_INCLUDE_LEN);
let low_rem = low_addr % LANDING_PAD_LEN;
if low_rem >= LANDING_PAD_INCLUDE_LEN {
low_addr = low_addr - low_rem + LANDING_PAD_LEN;
}
if low_addr >= high_addr {
return None;
}
}
let mut module_mapping = self.module_mapping.lock();
let hook_module_group = module_mapping.entry(module).or_insert_with(|| {
let new_address_space = module
.dupe_module_address_space()
.expect("could not duplicate module address space; out of memory");
let entry_thunk = asm::hook_entry_thunk();
let entry_thunk_len = entry_thunk.len();
unsafe {
let page = VirtualAlloc(
new_address_space.start as _,
entry_thunk_len,
MEM_COMMIT,
PAGE_EXECUTE_READWRITE,
) as *mut u8;
assert!(
!page.is_null(),
"failed to commit page at {:?}",
new_address_space.start
);
ptr::copy_nonoverlapping(entry_thunk.as_ptr(), page, entry_thunk_len);
}
HookModuleGroup {
base_address: new_address_space.start,
address_ranges: vec![(0, entry_thunk_len as u32)],
group_allocator: HookGroupBumpAllocator(vec![]),
groups_by_ptr: FxHashMap::with_hasher(BuildHasherDefault::new()),
}
});
if hook_module_group.groups_by_ptr.contains_key(&fn_ptr) {
panic!("tried to allocate new hook for a hooked function");
}
let next_address_range_index = hook_module_group
.address_ranges
.binary_search_by(|(start, _)| start.cmp(&code_offset).then(Ordering::Less))
.unwrap_err();
let address_range_upper = hook_module_group
.address_ranges
.get(next_address_range_index)
.map_or(u32::MAX, |(start, _)| *start);
let address_range_lower = next_address_range_index
.checked_sub(1)
.map(|prev_index| hook_module_group.address_ranges[prev_index].1)
.unwrap_or(0);
if code_offset < address_range_lower
|| code
.len()
.saturating_add(code_offset as usize + CALL_REL32_DATA_LEN)
> address_range_upper as usize
{
return None;
}
let alloc_granularity = self.alloc_granularity;
let page_size = self.page_size;
let mut low_alloc_bound = low_addr
.saturating_sub(alloc_granularity - 1)
.next_multiple_of(alloc_granularity);
if low_alloc_bound + alloc_granularity - low_addr <= LANDING_PAD_EXCLUDE_LEN {
low_alloc_bound += alloc_granularity;
}
let high_alloc_bound = high_addr.next_multiple_of(alloc_granularity);
if low_alloc_bound == high_alloc_bound {
return None;
}
let mut memory_mapping = self.memory_mapping.lock();
let maybe_available_page = memory_mapping
.range_mut(low_alloc_bound..high_alloc_bound)
.find_map(|(addr, pages)| {
let mut page_addr = *addr;
let mut reused_page = None;
let mut empty_page = None;
for page in pages {
if high_addr > page_addr && low_addr < page_addr + page_size {
let mut low_addr = Ord::max(low_addr, page_addr);
let high_addr = Ord::min(high_addr, page_addr + page_size);
if high_addr - low_addr <= LANDING_PAD_EXCLUDE_LEN
&& low_addr % LANDING_PAD_LEN >= LANDING_PAD_INCLUDE_LEN
{
low_addr = low_addr.next_multiple_of(256);
if low_addr >= high_addr {
continue;
}
}
if page.is_some_and(|owner| owner == module) {
reused_page = Some((page_addr, page));
break;
}
if page.is_none() && empty_page.is_none() {
empty_page = Some((page_addr, page));
}
}
page_addr += page_size;
}
reused_page.or(empty_page)
});
let (page_addr, page_owner) = match maybe_available_page {
Some(available_page) => available_page,
None => {
let alloc = unsafe {
try_alloc_in_bounds_unchecked(
low_alloc_bound..high_alloc_bound,
alloc_granularity,
MEM_RESERVE,
PAGE_EXECUTE_READWRITE,
alloc_granularity,
page_size,
)?
.start
};
let mut occupied_pages = Vec::with_capacity(self.pages_per_alloc);
occupied_pages.resize(self.pages_per_alloc, None);
let pages = memory_mapping
.entry(alloc.addr())
.or_insert(occupied_pages.into_boxed_slice());
let mut page_addr = low_addr
.max(alloc.addr())
.saturating_sub(page_size - 1)
.next_multiple_of(page_size);
if page_addr + page_size - low_addr <= LANDING_PAD_EXCLUDE_LEN {
page_addr += page_size;
}
let page = pages.get_mut((page_addr - alloc.addr()) / page_size)?;
(high_addr > page_addr).then_some((page_addr, page))?
}
};
let _ = page_owner.get_or_insert_with(|| unsafe {
let page = VirtualAlloc(
page_addr as _,
page_size,
MEM_COMMIT,
PAGE_EXECUTE_READWRITE,
) as *mut u8;
assert!(!page.is_null(), "failed to commit page at {page_addr:x}");
let module_delta = hook_module_group
.base_address
.addr()
.wrapping_sub(module.image_base().addr());
Self::fill_landing_pad_page(page, page_size, module_delta);
module
});
let mut addr = Ord::max(low_addr, page_addr);
let high_addr = Ord::min(high_addr, page_addr + page_size);
let low_rem = addr % LANDING_PAD_LEN;
if low_rem >= LANDING_PAD_INCLUDE_LEN {
addr = addr - low_rem + LANDING_PAD_LEN;
}
assert!(addr < high_addr, "allocated an invalid address range");
let hook_group = unsafe {
let hook_group = hook_module_group.group_allocator.alloc(alloc_granularity);
f(hook_group);
hook_module_group.groups_by_ptr.insert(fn_ptr, hook_group);
hook_group
};
unsafe {
Self::write_code_region(hook_module_group, hook_group, code, code_offset);
}
Some((addr as *const (), hook_group))
}
unsafe fn dealloc_failed_hook(&self, module: Module, fn_ptr: *const ()) {
let mut module_mapping = self.module_mapping.lock();
if let Some(hook_module_group) = module_mapping.get_mut(&module)
&& let Some(hook_group) = hook_module_group.groups_by_ptr.remove(&fn_ptr)
{
unsafe {
ptr::drop_in_place(hook_group.as_ptr());
hook_module_group
.group_allocator
.try_dealloc(self.alloc_granularity, hook_group);
}
}
}
unsafe fn fill_landing_pad_page(page: *mut u8, page_size: usize, module_delta: usize) {
let module_offset = (module_delta as u64).to_le_bytes();
let mut landing_pad = LANDING_PAD_TEMPLATE;
landing_pad[LANDING_PAD_OFFSET_START..LANDING_PAD_OFFSET_START + 8]
.copy_from_slice(&module_offset[..]);
let page = unsafe { slice::from_raw_parts_mut(page, page_size) };
for page_chunk in page.chunks_exact_mut(LANDING_PAD_LEN) {
page_chunk.copy_from_slice(&landing_pad);
}
}
unsafe fn write_code_region(
hook_module_group: &mut HookModuleGroup,
hook_group: NonNull<HookGroup>,
code: &[u8],
code_offset: u32,
) {
assert!(
hook_group.addr().get().is_multiple_of(256),
"bump allocator alignment failure"
);
let code_start = unsafe { hook_module_group.base_address.add(code_offset as usize) };
let code_len = code.len() + CALL_REL32_DATA_LEN;
let page = unsafe {
VirtualAlloc(
code_start as _,
code_len,
MEM_COMMIT,
PAGE_EXECUTE_READWRITE,
)
};
assert!(!page.is_null(), "failed to commit page at {code_start:?}");
let hook_group_addr = hook_group.addr().get().to_le_bytes();
let disp32 = unsafe {
hook_module_group
.base_address
.offset_from(code_start.add(code.len() + 5)) as i32
}
.to_le_bytes();
let mut buf = Vec::with_capacity(code_len);
buf.extend_from_slice(code);
buf.push(0xe8);
buf.extend_from_slice(&disp32);
buf.extend_from_slice(&hook_group_addr[1..]);
unsafe {
ptr::copy_nonoverlapping(buf.as_ptr(), code_start, buf.len());
}
let index = hook_module_group
.address_ranges
.binary_search_by_key(&code_offset, |(start, _)| *start)
.expect_err("BUG: range already occupied");
hook_module_group
.address_ranges
.insert(index, (code_offset, code_offset + code_len as u32));
}
}
impl RawHookAllocator {
const fn new() -> Self {
Self {
module_mapping: Mutex::new(FxHashMap::with_hasher(FxBuildHasher::new())),
memory_mapping: Mutex::new(BTreeMap::new()),
loader_cookie: AtomicPtr::new(ptr::null_mut()),
alloc_granularity: 4096 * 16,
pages_per_alloc: 16,
page_size: 4096,
}
}
}
impl HookGroupBumpAllocator {
unsafe fn alloc(&mut self, alloc_granularity: usize) -> NonNull<HookGroup> {
const _HOOK_GROUP_SIZE: () = assert!(size_of::<HookGroup>() == 256);
let next = match self
.0
.last_mut()
.filter(|(start, end)| unsafe { start.byte_add(alloc_granularity) != *end })
{
Some((_, next)) => next,
None => {
let alloc = unsafe {
VirtualAlloc(
ptr::null(),
alloc_granularity,
MEM_COMMIT | MEM_RESERVE,
PAGE_READWRITE,
) as *mut HookGroup
};
let ptr = NonNull::new(alloc).expect("VirtualAlloc failed");
self.0.push((ptr, ptr));
let (_, next) = self.0.last_mut().unwrap();
next
}
};
let result = next.cast::<HookGroup>();
*next = unsafe { next.add(1) };
result
}
unsafe fn try_dealloc(&mut self, alloc_granularity: usize, ptr: NonNull<HookGroup>) {
if let Some((_, end)) = self
.0
.last_mut()
.filter(|(start, end)| unsafe { start.byte_add(alloc_granularity) != *end })
{
let prev = unsafe { end.sub(1) };
if prev == ptr {
*end = prev;
}
}
}
}
impl Drop for HookModuleGroup {
fn drop(&mut self) {
unsafe {
for hook_group in self.groups_by_ptr.values() {
ptr::drop_in_place(hook_group.as_ptr());
}
VirtualFree(self.base_address as _, 0, MEM_RELEASE);
}
}
}
impl Drop for HookGroupBumpAllocator {
fn drop(&mut self) {
for (shard, _) in mem::take(&mut self.0) {
unsafe {
VirtualFree(shard.as_ptr() as _, 0, MEM_RELEASE);
}
}
}
}
unsafe impl Send for RawHookAllocator {}
unsafe impl Sync for RawHookAllocator {}
impl fmt::Debug for HookAllocator {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("HookAllocator").finish()
}
}
static LANDING_PAD_TEMPLATE: [u8; 256] = [
0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e,
0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e,
0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e,
0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e,
0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e,
0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e,
0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e,
0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e,
0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e,
0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e,
0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e,
0x66, 0x90, 0xeb, 0x2e, 0xeb, 0x2e, 0xeb, 0x2e, 0xeb, 0x2e, 0xeb, 0x2e, 0xeb, 0x2e, 0xeb, 0x2e,
0x66, 0x90, 0xeb, 0x26, 0xeb, 0x26, 0xeb, 0x26, 0x66, 0x90, 0x66, 0x90, 0x66, 0x90, 0x66, 0x90,
0x66, 0x90, 0x66, 0x90, 0x66, 0x90, 0x66, 0x90, 0x66, 0x90, 0x66, 0x90, 0x66, 0x90, 0x66, 0x90,
0x66, 0x90, 0x66, 0x90, 0x66, 0x90, 0x66, 0x90, 0x66, 0x90, 0x66, 0x90, 0x66, 0x90, 0x50, 0x48,
0xb8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x48, 0x01, 0x44, 0x24, 0x08, 0x58, 0xc3,
];