hooking 0.8.0

cross platform detour / hooking library in rust
Documentation
//! A hook doesn't have to call the original function. This one answers
//! lookups of one environment variable itself, and passes every other lookup
//! on to the real `getenv`.
//!
//! `std::env::var` calls libc's `getenv` on linux, so the hook also changes
//! what Rust code sees.

#[cfg(target_os = "linux")]
mod example {
    use std::ffi::CStr;

    use hooking::hook;

    const FAKED: &CStr = c"HOOKING_EXAMPLE";

    /// `#[hook]` copies these types into a generated module, so they are
    /// written as full paths.
    #[hook(method = "getenv")]
    unsafe extern "C" fn hooked_getenv(name: *const std::ffi::c_char) -> *mut std::ffi::c_char {
        if unsafe { CStr::from_ptr(name) } == FAKED {
            // Answer without calling the original.
            return c"set by the hook".as_ptr().cast_mut();
        }

        let original = unsafe { hooked_getenv::original_function().expect("the hook was created") };
        original(name)
    }

    fn show(when: &str) {
        let faked = FAKED.to_str().unwrap();
        println!("{when}:");
        println!("  {faked} = {:?}", std::env::var(faked));
        println!("  HOME = {:?}", std::env::var("HOME"));
    }

    pub fn main() {
        show("before hooking");

        unsafe { hooked_getenv::enable_hook().unwrap() };
        show("hooked");

        unsafe { hooked_getenv::disable_hook().unwrap() };
        show("unhooked");
    }
}

#[cfg(target_os = "linux")]
fn main() {
    example::main();
}

#[cfg(not(target_os = "linux"))]
fn main() {
    println!("this example needs linux");
}