Skip to main content

hook

Attribute Macro hook 

Source
#[hook]
Expand description

Defines a function hook at a fixed offset from a base address.

The annotated function becomes a module of the same name that holds the hook’s static state and can be installed via forge::install_hook!.

Inside the body the following pseudo-macros are available:

  • original!(args) — call the original function (zero or more args).
  • original!() — call the original function with no arguments.
  • original_function!() — obtain the raw function pointer without calling it.
  • context!(T) — borrow the context as &mut T (requires context variant of install).
  • context!() — obtain the raw *const c_void context pointer.

§Example

#[forge::hook(offset = 0x1234)]
fn my_hook(param: u32) -> u32 {
    let result = original!(param);
    result * 2
}

// Context must outlive the hook (static or Box::leak with "allocator" feature).
static mut MULTIPLIER: u32 = 2;

#[forge::hook(offset = 0x5678)]
fn ctx_hook(value: u32) -> u32 {
    let m = context!(u32);
    original!(value) * *m
}

#[forge::entry]
fn main() {
    let base = forge::mem::text_addr();
    forge::install_hook!(base, my_hook);
    forge::install_hook!(base, ctx_hook, unsafe { &raw mut MULTIPLIER });
}