Skip to main content

write_hook_table/
write_hook_table.rs

1use std::arch::asm;
2
3use core::ptr::NonNull;
4use hooking::{HookData, HookWriter};
5
6#[unsafe(no_mangle)]
7pub unsafe extern "C" fn add_two_numbers_together(a: i32, b: i32) -> i32 {
8    println!("adding {a} + {b}");
9    a + b
10}
11
12unsafe extern "C" fn hook(a: i32, b: i32) -> i32 {
13    let original_add: extern "C" fn(a: i32, b: i32) -> i32 = unsafe {
14        std::mem::transmute(
15            hooking::original_function_ptr()
16                .expect("invoked from hook")
17                .as_ptr(),
18        )
19    };
20
21    println!("Hooked with params: ({a}, {b})");
22
23    original_add(5, 6)
24}
25
26fn main() {
27    let hook_writer = HookWriter::from_static();
28    let hook = unsafe {
29        hook_writer
30            .create_hook(
31                NonNull::new(add_two_numbers_together as *mut _).unwrap(),
32                NonNull::new(hook as *mut _).unwrap(),
33            )
34            .unwrap()
35    };
36
37    let HookData {
38        trampoline_data, ..
39    } = hook.data;
40
41    println!("about to run hook");
42
43    unsafe {
44        #[cfg(target_os = "linux")]
45        asm! {
46            "mov rdi, 6",
47            "mov rsi, 7",
48            "call {}",
49            in(reg)trampoline_data.as_ptr()
50        }
51        #[cfg(target_os = "windows")]
52        asm! {
53            "mov rcx, 6",
54            "mov rdx, 7",
55            "call {}",
56            in(reg)trampoline_data.as_ptr()
57        }
58    }
59}