diff --git a/src/hook.rs b/src/hook.rs index b836588..de3a220 100644 --- a/src/hook.rs +++ b/src/hook.rs @@ -1,4 +1,14 @@ +use core::sync::atomic::{AtomicPtr, Ordering}; +use core::ptr::null_mut; + pub trait Hook: Copy { + + fn hook(&self) -> HookGuard { + let self_ptr = self.as_ptr_u8(); + + HookGuard { bytes: [0; 16] } + } + fn as_ptr_u8(self) -> *mut u8; fn trampoline(f: F) -> Closure; } @@ -11,9 +21,8 @@ impl HookGuard { pub fn unhook(&self) {} } - pub struct Closure { - inner: Box> + inner: Box>, } #[repr(C)] @@ -22,3 +31,30 @@ struct ClosureInner { data: F, } +static STATIC_CONTEXT: AtomicPtr<()> = AtomicPtr::new(null_mut()); + +impl Hook for unsafe extern "C" fn() -> R +where + F: FnMut() + 'static, +{ + fn as_ptr_u8(self) -> *mut u8 { + self as *mut u8 + } + + fn trampoline(f: F) -> Closure { + unsafe extern "C" fn thunk() + where + F: FnMut(), + { + let p = STATIC_CONTEXT.swap(null_mut(), Ordering::Relaxed) as *mut ClosureInner; + ((*p).data)(); + } + + Closure { + inner: Box::new(ClosureInner { + ptr: thunk:: as *const (), + data: f, + }), + } + } +}