Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
KiraCoding committed Sep 15, 2024
1 parent d123874 commit 0c99206
Show file tree
Hide file tree
Showing 5 changed files with 83 additions and 2 deletions.
16 changes: 16 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ description = "todo"

[dependencies]
rayon = "1.10.0"
sharded-slab = "0.1.7"

[target.'cfg(windows)'.dependencies.pelite]
version = "0.10.0"
Expand Down
11 changes: 9 additions & 2 deletions examples/sections.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
use inka::program;
use inka::Hook;

fn main() {
dbg!(program());
unsafe extern "C" fn hook_me() {
println!("Original");
}

let _guard = (hook_me as unsafe extern "C" fn()).hook(|| println!("Hooked"));
dbg!(_guard);

unsafe { hook_me() };
}
55 changes: 55 additions & 0 deletions src/hook.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
use core::any::Any;
use sharded_slab::Slab;
use std::{
ptr::NonNull,
sync::{LazyLock, Mutex},
};

static HOOKS: LazyLock<Slab<Mutex<Box<dyn Any + Send>>>> = LazyLock::new(Slab::new);

pub trait Hook<F>: Copy {
fn hook(self, f: F) -> HookGuard;
fn as_ptr_u8(self) -> NonNull<u8>;
}

#[derive(Debug)]
pub struct HookGuard {
ptr: NonNull<u8>,
bytes: [u8; 10], // used to restore original function prologue
index: usize,
}

impl HookGuard {
pub fn unhook(&mut self) {
HOOKS.remove(self.index);
}
}

impl Drop for HookGuard {
fn drop(&mut self) {
self.unhook();
}
}

impl<F> Hook<F> for unsafe extern "C" fn()
where
F: FnMut() + 'static + Send,
{
fn hook(self, f: F) -> HookGuard {
let ptr = <unsafe extern "C" fn() as Hook<F>>::as_ptr_u8(self);

let index = HOOKS
.insert(Mutex::new(Box::new(f)))
.expect("Max shards reached");

HookGuard {
ptr,
bytes: [0; 10],
index,
}
}

fn as_ptr_u8(self) -> NonNull<u8> {
unsafe { NonNull::new_unchecked(self as *mut u8) }
}
}
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@
mod base;
mod find;
mod hook;
mod program;
mod section;
mod symbol;

pub use base::Base;
pub use find::Find;
pub use hook::{Hook, HookGuard};
pub use program::{program, Program};
pub use section::Section;
pub use symbol::Symbol;
Expand Down

0 comments on commit 0c99206

Please sign in to comment.