A minimalistic, high-performance trampoline hooking library implemented in Rust. Designed for low-level system instrumentation and binary analysis using raw pointers for direct memory control and zero overhead.
This library utilizes Inline Trampoline Hooking to intercept function execution flow. It safely overwrites the prologue of a target function with a jump instruction redirecting to your hook, while preserving the original instructions inside a dynamically allocated execution bridge (the trampoline).
Based on the architecture illustrated above, the hooking process executes the following steps:
- Instruction Boundary Alignment: The library decodes the initial bytes of the
originalfunction to determine a safe instruction boundary (stating at least 5 bytes for a relative jump). It avoids slicing instructions in half, ensuring the application won't crash when executing relocated code. - Trampoline Allocation: A separate executable memory stub (
trampoline) is allocated. The stolen instructions from the original function prologue are cloned into it:mov edi, edipush ebpmov ebp, esp
- Jump Back Append: Immediately following these cloned instructions, a
JMP original + N bytesinstruction is appended to smoothly resume uninhibited execution flow. - Function Patching: The original function's prologue is hot-patched in memory, replacing the stolen instructions with a direct
JMP hookto transfer control to your custom function.
use rusthook::hook;
fn main() {
hook(function_to_hook as *mut u8, hooked_function as *mut u8);
function_to_hook();
}
fn hooked_function() {
println!("you got hooked buddy");
}
fn function_to_hook() {
println!("Hello!");
}