use std::{
arch::asm,
fmt, mem,
ops::{Bound, Deref, DerefMut},
ptr::{self, NonNull},
sync::{
Arc, LazyLock, OnceLock,
atomic::{AtomicBool, AtomicI64, AtomicPtr, AtomicU32, AtomicU64, Ordering},
},
};
use closure_ffi::{
BareFnSync, UntypedBareFn, thunk_factory,
traits::{FnPtr, FnThunk},
};
use parking_lot::Mutex;
use crate::hook::alloc::HookAllocator;
pub mod alloc;
mod asm;
mod cas;
pub mod installer;
pub const MIN_HOOKABLE_REGION_LEN: usize = cas::CMPXCHG64_LEN;
static STATIC_ALLOCATOR: LazyLock<HookAllocator> = LazyLock::new(HookAllocator::new);
#[repr(transparent)]
pub struct HookHandle {
inner: NonNull<HookInstance>,
}
#[repr(C)]
struct HookGroup {
lock: CachePaddedU32,
data: HookGroupData,
}
#[derive(Default)]
#[repr(C, align(64))]
struct CachePaddedU32(AtomicU32);
#[derive(Clone, Copy)]
#[repr(transparent)]
struct ScopedFnPtr(*const ());
#[repr(C)]
struct HookGroupData {
scope_count: AtomicU64,
next_fn_ptr: ScopedFnPtr,
scoped_trampoline_fn_ptr: ScopedFnPtr,
trampoline_fn_ptr: *const (),
scoped_trampoline_fn: Option<UntypedBareFn<dyn Send + Sync>>,
hooks: Vec<(i64, NonNull<HookInstance>)>,
next_neg_uid: AtomicI64,
next_pos_uid: AtomicI64,
#[allow(clippy::vec_box)]
free_queue: Mutex<Vec<Box<HookInstance>>>,
is_queued: AtomicBool,
}
#[repr(C)]
struct HookInstance {
scoped_fn_ptr: ScopedFnPtr,
next_fn_ptr: AtomicPtr<()>,
hook_fn_ptr: *const (),
hook_fn: UntypedBareFn<dyn Send + Sync>,
scoped_fn: UntypedBareFn<dyn Send + Sync>,
trampoline_fn: UntypedBareFn<dyn Send + Sync>,
uid: i64,
group: NonNull<HookGroup>,
ref_count: AtomicU64,
is_enabled: AtomicBool,
}
impl HookGroupData {
const fn new() -> Self {
Self {
scope_count: AtomicU64::new(0),
next_fn_ptr: ScopedFnPtr(ptr::null()),
scoped_trampoline_fn_ptr: ScopedFnPtr(ptr::null()),
trampoline_fn_ptr: ptr::null(),
scoped_trampoline_fn: None,
hooks: vec![],
next_neg_uid: AtomicI64::new(-1),
next_pos_uid: AtomicI64::new(0),
free_queue: Mutex::new(vec![]),
is_queued: AtomicBool::new(false),
}
}
}
impl HookGroup {
pub unsafe fn write<B>(ptr: NonNull<Self>, trampoline: B)
where
B: FnPtr + 'static,
{
let send_ptr = ptr.expose_provenance();
let scoped_trampoline =
BareFnSync::with_thunk(thunk_factory::make_send_sync::<B, _>(move |args| unsafe {
let _scope = ScopeGuard(NonNull::with_exposed_provenance(send_ptr));
trampoline.call(args)
}))
.into_untyped();
let value = Self {
lock: CachePaddedU32(AtomicU32::new(1)),
data: HookGroupData {
next_fn_ptr: ScopedFnPtr(scoped_trampoline.bare()),
scoped_trampoline_fn_ptr: ScopedFnPtr(scoped_trampoline.bare()),
trampoline_fn_ptr: trampoline.to_ptr(),
scoped_trampoline_fn: Some(scoped_trampoline),
..const { HookGroupData::new() }
},
};
unsafe {
ptr.write(value);
}
}
pub unsafe fn push_hook<F, H, C>(
ptr: NonNull<Self>,
starts_enabled: bool,
push_front: bool,
c: C,
) -> HookHandle
where
C: FnOnce(F) -> H,
F: FnPtr + 'static,
H: FnThunk<F> + Send + Sync + 'static,
{
let hook = Box::new(OnceLock::<HookInstance>::new());
let hook = unsafe { &*Box::into_raw(Box::new(hook)) };
let trampoline_fn =
BareFnSync::with_thunk(thunk_factory::make_send_sync::<F, _>(move |args| unsafe {
let next_fn_ptr = hook.get().unwrap().next_fn_ptr.load(Ordering::Relaxed);
F::from_ptr(next_fn_ptr).call(args)
}));
let (hook_fn, scoped_fn) = {
let hook = c(trampoline_fn.bare());
let send_ptr = ptr.expose_provenance();
if const { size_of::<H>() == 0 } {
let hook_fn = BareFnSync::with_thunk(unsafe { mem::zeroed::<H>() });
let hook = unsafe { mem::zeroed::<H>() };
let scoped_fn = BareFnSync::with_thunk(thunk_factory::make_send_sync::<F, _>(
move |args| unsafe {
let _scope = ScopeGuard(NonNull::with_exposed_provenance(send_ptr));
hook.call(args)
},
));
(hook_fn.into_untyped(), scoped_fn.into_untyped())
} else {
let hook = Arc::new(hook);
let hook_fn = BareFnSync::with_thunk(thunk_factory::make_send_sync::<F, _>({
let hook = hook.clone();
move |args| unsafe { hook.call(args) }
}));
let scoped_fn = BareFnSync::with_thunk(thunk_factory::make_send_sync::<F, _>(
move |args| unsafe {
let _scope = ScopeGuard(NonNull::with_exposed_provenance(send_ptr));
hook.call(args)
},
));
(hook_fn.into_untyped(), scoped_fn.into_untyped())
}
};
let scoped_fn_ptr = ScopedFnPtr(scoped_fn.bare());
let hook_fn_ptr = hook_fn.bare();
let uid = unsafe {
let group = &ptr.as_ref().data;
if push_front {
group.next_neg_uid.fetch_sub(1, Ordering::Relaxed)
} else {
group.next_pos_uid.fetch_add(1, Ordering::Relaxed)
}
};
let mut lock_guard = unsafe { Self::acquire_lock(ptr) };
let group = &mut *lock_guard;
let next_fn_ptr = if push_front && let Some((_, first)) = group.hooks.first() {
unsafe { first.as_ref().hook_fn_ptr }
} else {
group.trampoline_fn_ptr
};
let hook = hook.get_or_init(|| HookInstance {
scoped_fn_ptr,
next_fn_ptr: AtomicPtr::new(next_fn_ptr as *mut ()),
hook_fn_ptr,
hook_fn,
scoped_fn,
trampoline_fn: trampoline_fn.into_untyped(),
uid,
group: ptr,
ref_count: 0.into(),
is_enabled: starts_enabled.into(),
});
let handle = unsafe { hook.make_handle() };
if push_front {
if starts_enabled {
group.next_fn_ptr = scoped_fn_ptr;
}
group.hooks.insert(0, (uid, hook.into()));
} else {
if starts_enabled && let Some((_, last)) = group.hooks.last_mut() {
unsafe {
last.as_mut()
.next_fn_ptr
.store(hook_fn_ptr as *mut (), Ordering::Relaxed);
};
}
group.hooks.push((uid, hook.into()));
}
handle
}
pub unsafe fn acquire_lock(ptr: NonNull<Self>) -> impl DerefMut<Target = HookGroupData> {
struct LockGuard(NonNull<HookGroup>);
impl Deref for LockGuard {
type Target = HookGroupData;
fn deref(&self) -> &Self::Target {
unsafe { &self.0.as_ref().data }
}
}
impl DerefMut for LockGuard {
fn deref_mut(&mut self) -> &mut Self::Target {
unsafe { &mut self.0.as_mut().data }
}
}
impl Drop for LockGuard {
fn drop(&mut self) {
unsafe {
self.0.as_ref().lock.0.store(1, Ordering::Release);
}
}
}
let lock = unsafe { &raw const ptr.as_ref().lock.0 };
unsafe {
asm! {
"lock btr dword ptr [{0}],0",
"jnc 2f",
"jmp 3f",
"2:",
"pause",
"mov {1:e},[{0}]",
"test {1:l},{1:l}",
"je 2b",
"lock btr dword ptr [{0}],0",
"jnc 2b",
"3:",
in(reg) lock,
out(reg) _,
options(nostack),
}
}
LockGuard(ptr)
}
}
impl HookInstance {
pub unsafe fn make_handle(&self) -> HookHandle {
self.ref_count.fetch_add(1, Ordering::Relaxed);
HookHandle { inner: self.into() }
}
}
impl HookHandle {
pub unsafe fn enable(&self, new_state: bool) {
if self.is_enabled() == new_state {
return;
}
let mut lock_guard = unsafe { HookGroup::acquire_lock(self.inner.as_ref().group) };
let group = &mut *lock_guard;
if self.is_enabled() == new_state {
return;
}
let hook = unsafe { self.inner.clone().as_mut() };
hook.is_enabled.store(new_state, Ordering::Relaxed);
let index = group
.hooks
.binary_search_by_key(&hook.uid, |(uid, _)| *uid)
.expect("BUG: hook is missing");
let prev_enabled = group.hooks[..index]
.iter_mut()
.rev()
.find_map(|(_, prev)| unsafe {
let prev = prev.as_mut();
prev.is_enabled.load(Ordering::Relaxed).then_some(prev)
});
let next_enabled = group.hooks[(Bound::Excluded(index), Bound::Unbounded)]
.iter_mut()
.find_map(|(_, next)| unsafe {
let next = next.as_mut();
next.is_enabled.load(Ordering::Relaxed).then_some(next)
});
let next_fn_ptr = next_enabled
.as_ref()
.map(|next| next.hook_fn_ptr)
.unwrap_or_else(|| group.trampoline_fn_ptr);
if new_state {
hook.next_fn_ptr
.store(next_fn_ptr as *mut (), Ordering::Relaxed);
if let Some(prev_enabled) = prev_enabled {
prev_enabled
.next_fn_ptr
.store(hook.hook_fn_ptr as *mut (), Ordering::Relaxed);
} else {
group.next_fn_ptr = hook.scoped_fn_ptr;
}
} else if let Some(prev_enabled) = prev_enabled {
prev_enabled
.next_fn_ptr
.store(next_fn_ptr as *mut (), Ordering::Relaxed);
} else {
group.next_fn_ptr = next_enabled
.map(|next| next.scoped_fn_ptr)
.unwrap_or_else(|| group.scoped_trampoline_fn_ptr);
}
}
pub fn is_enabled(&self) -> bool {
unsafe { self.inner.as_ref().is_enabled.load(Ordering::Relaxed) }
}
pub fn into_raw(self) -> NonNull<()> {
self.inner.cast()
}
pub unsafe fn from_raw(raw: NonNull<()>) -> Self {
Self { inner: raw.cast() }
}
}
impl Clone for HookHandle {
fn clone(&self) -> Self {
unsafe {
self.inner
.as_ref()
.ref_count
.fetch_add(1, Ordering::Relaxed);
}
Self { inner: self.inner }
}
}
impl Drop for HookHandle {
fn drop(&mut self) {
let not_last = {
let ref_count = unsafe { &self.inner.as_ref().ref_count };
ref_count.fetch_sub(1, Ordering::Release) != 1
};
if not_last {
return;
}
{
let mut lock_guard = unsafe { HookGroup::acquire_lock(self.inner.as_ref().group) };
let group = &mut *lock_guard;
let hook = unsafe { self.inner.clone().as_mut() };
hook.is_enabled.store(false, Ordering::Relaxed);
let index = group
.hooks
.binary_search_by_key(&hook.uid, |(uid, _)| *uid)
.expect("BUG: hook is missing");
let next_enabled = group.hooks[(Bound::Excluded(index), Bound::Unbounded)]
.iter_mut()
.find_map(|(_, next)| unsafe {
let next = next.as_mut();
next.is_enabled.load(Ordering::Relaxed).then_some(next)
});
if let Some(prev_enabled) =
group.hooks[..index]
.iter_mut()
.rev()
.find_map(|(_, prev)| unsafe {
let prev = prev.as_mut();
prev.is_enabled.load(Ordering::Relaxed).then_some(prev)
})
{
let next_fn_ptr = next_enabled
.map(|next| next.hook_fn_ptr)
.unwrap_or_else(|| group.trampoline_fn_ptr);
prev_enabled
.next_fn_ptr
.store(next_fn_ptr as *mut (), Ordering::Relaxed);
} else {
group.next_fn_ptr = next_enabled
.map(|next| next.scoped_fn_ptr)
.unwrap_or_else(|| group.scoped_trampoline_fn_ptr);
}
let _ = group.hooks.remove(index);
}
{
let group = unsafe { &self.inner.as_ref().group.as_ref().data };
if group.scope_count.load(Ordering::Acquire) != 0 {
let boxed = unsafe { Box::from_raw(self.inner.as_ptr()) };
group.free_queue.lock().push(boxed);
return;
}
}
unsafe {
drop(Box::from_raw(self.inner.as_ptr()));
}
}
}
struct ScopeGuard(NonNull<HookGroup>);
impl Drop for ScopeGuard {
#[inline(always)]
fn drop(&mut self) {
let control = unsafe { self.0.as_ref() };
if control.data.scope_count.fetch_sub(1, Ordering::Release) != 1 {
return;
}
if !control.data.is_queued.load(Ordering::Acquire) {
return;
}
#[cold]
#[inline(never)]
fn drop_queued(control: &HookGroup) {
let mut queue_lock = control.data.free_queue.lock();
control.data.is_queued.store(false, Ordering::Relaxed);
let queued = mem::take(&mut *queue_lock);
drop(queue_lock);
drop(queued);
}
drop_queued(control);
}
}
impl fmt::Debug for HookHandle {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("HookHandle")
.field("is_enabled", &self.is_enabled())
.finish_non_exhaustive()
}
}
unsafe impl Send for HookInstance {}
unsafe impl Sync for HookInstance {}
unsafe impl Send for HookHandle {}
unsafe impl Sync for HookHandle {}