interpose 0.1.0

interpose extern c function
Documentation
#[doc(hidden)]
pub use paste as __paste;

/// Macro to interpose C functions with custom logic
/// 
/// # Example
/// ```
/// interpose! {
///     malloc(size: libc::size_t) -> *mut libc::c_void {
///         println!("malloc!");
///         let result = real_malloc(size);
///         result
///     }
/// }
/// ```
#[macro_export]
macro_rules! interpose {
    (
        $name:ident($($arg:ident: $arg_ty:ty),*) -> $ret:ty $body:block
    ) => {
        $crate::__paste::paste! {
            type [<$name:camel Fn>] = unsafe extern "C" fn($($arg_ty),*) -> $ret;
            static [<REAL_ $name:upper>]: ::std::sync::OnceLock<[<$name:camel Fn>]> = 
                ::std::sync::OnceLock::new();

            unsafe fn [<get_real_ $name>]() -> [<$name:camel Fn>] {
                *[<REAL_ $name:upper>].get_or_init(|| {
                    let sym_name = concat!(stringify!($name), "\0");
                    let sym = unsafe { 
                        libc::dlsym(
                            libc::RTLD_NEXT, 
                            sym_name.as_ptr() as *const libc::c_char
                        ) 
                    };
                    if sym.is_null() {
                        panic!("Could not find real {}", stringify!($name));
                    }
                    unsafe { std::mem::transmute(sym) }
                })
            }

            #[unsafe(no_mangle)]
            pub unsafe extern "C" fn $name($($arg: $arg_ty),*) -> $ret {
                let [<real_ $name>] = unsafe { [<get_real_ $name>]() };
                $body
            }
        }
    };
}

/// Call the real (original) function found by `dlsym`.
///
/// Usage: `real!(malloc(size))` or `let p = real!(malloc)(size);`
#[macro_export]
macro_rules! real {
    ($name:ident ( $($args:expr),* $(,)? )) => {{
        $crate::__paste::paste! {{
            let __f = unsafe { [<get_real_ $name>]() };
            unsafe { __f($($args),*) }
        }}
    }};
    ($name:ident) => {{
        $crate::__paste::paste! {
            unsafe { [<get_real_ $name>]() }
        }
    }};
}

/// Get just the real function pointer: `let f = real_fn!(malloc);`
#[macro_export]
macro_rules! real_fn {
    ($name:ident) => {{
        $crate::__paste::paste! {
            unsafe { [<get_real_ $name>]() }
        }
    }};
}