winhook 0.1.0

x86_64 function hooking library for Windows and Wine
use closure_ffi_iced_x86::Register;

mod private {
    pub trait Sealed {}
}

pub trait CConv: private::Sealed {
    fn called_with() -> &'static [Register];
}

pub static X64_CCONV_VOLATILE: [Register; 13] = [
    Register::RAX,
    Register::RCX,
    Register::RDX,
    Register::R8,
    Register::R9,
    Register::R10,
    Register::R11,
    Register::ZMM0,
    Register::ZMM1,
    Register::ZMM2,
    Register::ZMM3,
    Register::ZMM4,
    Register::ZMM5,
];

pub const X64_STACK_SCRATCH_SPACE: (usize, usize) = (32, 0);

static X64_CCONV_USES: [Register; 8] = [
    Register::RCX,
    Register::ZMM0,
    Register::RDX,
    Register::ZMM1,
    Register::R8,
    Register::ZMM2,
    Register::R9,
    Register::ZMM3,
];

// https://lukaswirth.dev/tlborm/decl-macros/building-blocks/counting.html#bit-twiddling
macro_rules! count_idents {
    (@tt) => { 0usize };
    (@tt $odd:tt $($a:tt $b:tt)*) => { (count_idents!(@tt $($a)*) << 1usize) | 1usize };
    (@tt $($a:tt $even:tt)*) => { count_idents!(@tt $($a)*) << 1usize };
    (@ident ($($count:tt)*),) => { count_idents!(@tt $($count)*) };
    (@ident ($($count:tt)*), $first:ident, $($rest:ident,)*) =>
        { count_idents!(@ident ($($count)* 0usize), $($rest,)*) };
    ($($all:ident,)*) => { count_idents!(@ident (), $($all,)*) };
}

macro_rules! impl_x64_cconv {
    () => {
        impl_x64_cconv!(@impl_all);
    };
    ($first:ident, $($rest:ident,)*) => {
        impl_x64_cconv!(@impl_all $first, $($rest,)*);
        impl_x64_cconv!($($rest,)*);
    };
    (@impl_all $($all:ident,)*) => {
        impl_x64_cconv!(@impl_one "C", $($all,)*);
        impl_x64_cconv!(@impl_one "C-unwind", $($all,)*);
        impl_x64_cconv!(@impl_one "system", $($all,)*);
        impl_x64_cconv!(@impl_one "system-unwind", $($all,)*);
        impl_x64_cconv!(@impl_one "win64", $($all,)*);
        impl_x64_cconv!(@impl_one "win64-unwind",  $($all,)*);
    };
    (@impl_one $cc:tt, $($all:ident,)*) => {
        impl<R, $($all,)*> private::Sealed for unsafe extern $cc fn($($all,)*) -> R {}
        impl<R, $($all,)*> CConv for unsafe extern $cc fn($($all,)*) -> R {
            #[inline]
            fn called_with() -> &'static [Register] {
                const COUNT: usize = (count_idents!($($all,)*)) * 2;
                const INDEX: usize = if COUNT < 8 { COUNT } else { 8 };
                &X64_CCONV_USES[..INDEX]
            }
        }
    };
}

impl_x64_cconv! { L, K, J, I, H, G, F, E, D, C, B, A, }