Skip to main content

hao_il2cpp_runtime/
typed.rs

1//! Typed values, hooks and calls, checked against the game's method signatures.
2
3use std::{any::Any, ffi::c_void, marker::PhantomData, sync::RwLock};
4
5use crate::{Error, Il2Cpp, Method, MethodInfo, Ptr, Result};
6
7/// Managed element types (`Il2CppTypeEnum`).
8pub mod element {
9    pub const VOID: i32 = 0x01;
10    pub const BOOLEAN: i32 = 0x02;
11    pub const CHAR: i32 = 0x03;
12    pub const I1: i32 = 0x04;
13    pub const U1: i32 = 0x05;
14    pub const I2: i32 = 0x06;
15    pub const U2: i32 = 0x07;
16    pub const I4: i32 = 0x08;
17    pub const U4: i32 = 0x09;
18    pub const I8: i32 = 0x0A;
19    pub const U8: i32 = 0x0B;
20    pub const R4: i32 = 0x0C;
21    pub const R8: i32 = 0x0D;
22    pub const STRING: i32 = 0x0E;
23    pub const PTR: i32 = 0x0F;
24    pub const VALUETYPE: i32 = 0x11;
25    pub const CLASS: i32 = 0x12;
26    pub const VAR: i32 = 0x13;
27    pub const ARRAY: i32 = 0x14;
28    pub const GENERICINST: i32 = 0x15;
29    pub const I: i32 = 0x18;
30    pub const U: i32 = 0x19;
31    pub const OBJECT: i32 = 0x1C;
32    pub const SZARRAY: i32 = 0x1D;
33    pub const MVAR: i32 = 0x1E;
34}
35
36/// The managed element type of a field, parameter, or return value.
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
38pub enum ElementType {
39    Void,
40    Boolean,
41    Char,
42    I1,
43    U1,
44    I2,
45    U2,
46    I4,
47    U4,
48    I8,
49    U8,
50    R4,
51    R8,
52    String,
53    Ptr,
54    ValueType,
55    Class,
56    Var,
57    Array,
58    GenericInst,
59    I,
60    U,
61    Object,
62    SzArray,
63    MVar,
64    Unknown(i32),
65}
66
67impl ElementType {
68    pub fn is_float(self) -> bool {
69        matches!(self, Self::R4 | Self::R8)
70    }
71
72    pub fn is_integer(self) -> bool {
73        matches!(
74            self,
75            Self::Boolean | Self::Char | Self::I1 | Self::U1 | Self::I2 | Self::U2
76                | Self::I4 | Self::U4 | Self::I8 | Self::U8 | Self::I | Self::U
77        )
78    }
79
80    pub fn is_reference(self) -> bool {
81        matches!(
82            self,
83            Self::String | Self::Class | Self::Object | Self::GenericInst
84                | Self::Array | Self::SzArray
85        )
86    }
87
88    pub fn raw(self) -> i32 {
89        match self {
90            Self::Void => element::VOID,
91            Self::Boolean => element::BOOLEAN,
92            Self::Char => element::CHAR,
93            Self::I1 => element::I1,
94            Self::U1 => element::U1,
95            Self::I2 => element::I2,
96            Self::U2 => element::U2,
97            Self::I4 => element::I4,
98            Self::U4 => element::U4,
99            Self::I8 => element::I8,
100            Self::U8 => element::U8,
101            Self::R4 => element::R4,
102            Self::R8 => element::R8,
103            Self::String => element::STRING,
104            Self::Ptr => element::PTR,
105            Self::ValueType => element::VALUETYPE,
106            Self::Class => element::CLASS,
107            Self::Var => element::VAR,
108            Self::Array => element::ARRAY,
109            Self::GenericInst => element::GENERICINST,
110            Self::I => element::I,
111            Self::U => element::U,
112            Self::Object => element::OBJECT,
113            Self::SzArray => element::SZARRAY,
114            Self::MVar => element::MVAR,
115            Self::Unknown(v) => v,
116        }
117    }
118}
119
120impl From<i32> for ElementType {
121    fn from(v: i32) -> Self {
122        match v {
123            element::VOID => Self::Void,
124            element::BOOLEAN => Self::Boolean,
125            element::CHAR => Self::Char,
126            element::I1 => Self::I1,
127            element::U1 => Self::U1,
128            element::I2 => Self::I2,
129            element::U2 => Self::U2,
130            element::I4 => Self::I4,
131            element::U4 => Self::U4,
132            element::I8 => Self::I8,
133            element::U8 => Self::U8,
134            element::R4 => Self::R4,
135            element::R8 => Self::R8,
136            element::STRING => Self::String,
137            element::PTR => Self::Ptr,
138            element::VALUETYPE => Self::ValueType,
139            element::CLASS => Self::Class,
140            element::VAR => Self::Var,
141            element::ARRAY => Self::Array,
142            element::GENERICINST => Self::GenericInst,
143            element::I => Self::I,
144            element::U => Self::U,
145            element::OBJECT => Self::Object,
146            element::SZARRAY => Self::SzArray,
147            element::MVAR => Self::MVar,
148            other => Self::Unknown(other),
149        }
150    }
151}
152
153impl std::fmt::Display for ElementType {
154    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
155        match self {
156            Self::Void => f.write_str("void"),
157            Self::Boolean => f.write_str("bool"),
158            Self::Char => f.write_str("char"),
159            Self::I1 => f.write_str("i8"),
160            Self::U1 => f.write_str("u8"),
161            Self::I2 => f.write_str("i16"),
162            Self::U2 => f.write_str("u16"),
163            Self::I4 => f.write_str("i32"),
164            Self::U4 => f.write_str("u32"),
165            Self::I8 => f.write_str("i64"),
166            Self::U8 => f.write_str("u64"),
167            Self::R4 => f.write_str("f32"),
168            Self::R8 => f.write_str("f64"),
169            Self::String => f.write_str("string"),
170            Self::Ptr => f.write_str("ptr"),
171            Self::ValueType => f.write_str("valuetype"),
172            Self::Class => f.write_str("class"),
173            Self::Var => f.write_str("var"),
174            Self::Array => f.write_str("array"),
175            Self::GenericInst => f.write_str("generic"),
176            Self::I => f.write_str("nint"),
177            Self::U => f.write_str("nuint"),
178            Self::Object => f.write_str("object"),
179            Self::SzArray => f.write_str("szarray"),
180            Self::MVar => f.write_str("mvar"),
181            Self::Unknown(v) => write!(f, "unknown(0x{v:02X})"),
182        }
183    }
184}
185
186/// The managed type of a parameter or return value.
187#[derive(Debug, Clone, Copy, PartialEq, Eq)]
188#[cfg_attr(feature = "reflect", derive(facet::Facet))]
189pub struct TypeInfo {
190    /// The `Il2CppTypeEnum` value. For enums, the element type of the underlying integer.
191    pub element: i32,
192    pub value_type: bool,
193    pub is_enum: bool,
194    pub byref: bool,
195    pub namespace: &'static str,
196    pub name: &'static str,
197}
198
199impl TypeInfo {
200    /// Whether this is the value type `namespace.name`, passed by value. For
201    /// [`Il2CppValue`] impls of `#[repr(C)]` structs mirroring a managed struct.
202    pub fn is_value_type(&self, namespace: &str, name: &str) -> bool {
203        !self.byref
204            && self.value_type
205            && !self.is_enum
206            && self.namespace == namespace
207            && self.name == name
208    }
209}
210
211/// A method parameter's name and managed type name, from [`Method::parameters`].
212#[derive(Debug, Clone, PartialEq, Eq)]
213#[cfg_attr(feature = "reflect", derive(facet::Facet))]
214pub struct Parameter {
215    /// The declared name, e.g. `amount` (often `arg0` in release builds).
216    pub name: String,
217    /// The managed type name, e.g. `System.Single`.
218    pub type_name: String,
219}
220
221/// A managed object reference (`Il2CppObject*`), possibly null.
222#[repr(transparent)]
223#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
224pub struct Object(pub Ptr);
225
226unsafe impl Send for Object {}
227unsafe impl Sync for Object {}
228
229impl Object {
230    pub const NULL: Object = Object(std::ptr::null_mut());
231
232    pub fn is_null(&self) -> bool {
233        self.0.is_null()
234    }
235
236    pub fn as_ptr(&self) -> Ptr {
237        self.0
238    }
239}
240
241/// A managed string (`Il2CppString*`), possibly null.
242#[repr(transparent)]
243#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
244pub struct Il2CppString(pub Object);
245
246impl Il2CppString {
247    pub fn new(il2cpp: &Il2Cpp, value: &str) -> Result<Self> {
248        il2cpp.string(value)
249    }
250
251    pub fn is_null(&self) -> bool {
252        self.0.is_null()
253    }
254
255    /// The string's contents, or `None` for null.
256    pub fn to_rust(&self) -> Option<String> {
257        let il2cpp = Il2Cpp::get()?;
258        // Values of this type only come from string typed arguments and returns.
259        unsafe { il2cpp.read_string(self.0) }
260    }
261}
262
263/// A Rust type that has the same representation as some managed types when
264/// passed to and from compiled Il2Cpp code.
265///
266/// # Safety
267/// `matches` may only accept managed types whose values are passed exactly like `Self`.
268pub unsafe trait Il2CppValue: Copy + 'static {
269    fn matches(ty: TypeInfo) -> bool;
270
271    fn describe() -> &'static str {
272        std::any::type_name::<Self>()
273    }
274
275    /// Whether this is a pointer to an object, so it can be the instance (`this`).
276    fn is_reference() -> bool {
277        false
278    }
279}
280
281macro_rules! primitive {
282    ($($t:ty => [$($e:ident),+];)*) => {$(
283        unsafe impl Il2CppValue for $t {
284            fn matches(ty: TypeInfo) -> bool {
285                !ty.byref && [$(element::$e),+].contains(&ty.element)
286            }
287        }
288    )*};
289}
290
291primitive! {
292    () => [VOID];
293    bool => [BOOLEAN];
294    u16 => [CHAR, U2];
295    i8 => [I1];
296    u8 => [U1];
297    i16 => [I2];
298    i32 => [I4];
299    u32 => [U4];
300    i64 => [I8];
301    u64 => [U8];
302    f32 => [R4];
303    f64 => [R8];
304    isize => [I];
305    usize => [U];
306}
307
308unsafe impl Il2CppValue for Object {
309    fn is_reference() -> bool {
310        true
311    }
312
313    fn matches(ty: TypeInfo) -> bool {
314        !ty.byref
315            && !ty.value_type
316            && [
317                element::STRING,
318                element::CLASS,
319                element::OBJECT,
320                element::SZARRAY,
321                element::ARRAY,
322                element::GENERICINST,
323                element::VAR,
324                element::MVAR,
325            ]
326            .contains(&ty.element)
327    }
328}
329
330unsafe impl Il2CppValue for Il2CppString {
331    fn is_reference() -> bool {
332        true
333    }
334
335    fn matches(ty: TypeInfo) -> bool {
336        !ty.byref && ty.element == element::STRING
337    }
338}
339
340/// `ref`/`out` parameters and pointers.
341unsafe impl Il2CppValue for *mut c_void {
342    fn is_reference() -> bool {
343        true
344    }
345
346    fn matches(ty: TypeInfo) -> bool {
347        ty.byref || ty.element == element::PTR
348    }
349}
350
351/// Calls the original code of a hooked method.
352pub struct Original<Args, R> {
353    code: *const c_void,
354    method: MethodInfo,
355    _marker: PhantomData<fn(Args) -> R>,
356}
357
358/// How a Rust type is checked against a managed parameter or return type.
359#[derive(Clone, Copy)]
360pub struct ValueCheck {
361    pub matches: fn(TypeInfo) -> bool,
362    pub name: &'static str,
363    pub reference: bool,
364}
365
366impl ValueCheck {
367    pub fn of<T: Il2CppValue>() -> Self {
368        Self {
369            matches: T::matches,
370            name: T::describe(),
371            reference: T::is_reference(),
372        }
373    }
374}
375
376/// The Rust types of a hook or call, checked against the method before use.
377pub struct Signature {
378    pub parameters: Vec<ValueCheck>,
379    pub ret: ValueCheck,
380}
381
382impl<Args: MethodArgs, R: Il2CppValue> Original<Args, R> {
383    /// Calls the original code with `args`, a tuple like the callback's arguments.
384    pub fn call(&self, args: Args) -> R {
385        unsafe { args.invoke(self.code, self.method) }
386    }
387}
388
389/// A closure usable as a hook for a method with parameters `Args` returning `R`.
390/// Implemented for `Fn(args..., Original<(args...), R>) -> R`.
391pub trait HookCallback<Args, R>: Send + Sync + 'static {
392    #[doc(hidden)]
393    fn trampoline() -> *mut u8;
394    #[doc(hidden)]
395    fn signature() -> Signature;
396}
397
398/// Argument tuples for [`Method::call`].
399pub trait MethodArgs {
400    #[doc(hidden)]
401    fn parameters() -> Vec<ValueCheck>;
402    #[doc(hidden)]
403    unsafe fn invoke<R: Il2CppValue>(self, code: *const c_void, method: MethodInfo) -> R;
404}
405
406type Callbacks = RwLock<Vec<(usize, &'static (dyn Any + Send + Sync))>>;
407
408/// Hook closures by the address of their hook's original-function stub.
409static CALLBACKS: Callbacks = RwLock::new(Vec::new());
410
411pub(crate) fn register<F: Any + Send + Sync>(stub: usize, callback: F) {
412    let callback: &'static (dyn Any + Send + Sync) = Box::leak(Box::new(callback));
413    CALLBACKS
414        .write()
415        .unwrap_or_else(|e| e.into_inner())
416        .push((stub, callback));
417}
418
419fn callback<F: Any>(stub: usize) -> &'static F {
420    let callbacks = CALLBACKS.read().unwrap_or_else(|e| e.into_inner());
421    callbacks
422        .iter()
423        .rev()
424        .find(|(s, _)| *s == stub)
425        .and_then(|(_, c)| c.downcast_ref::<F>())
426        .unwrap_or_else(|| {
427            tracing::error!("no callback registered for hook {:#x}, aborting", stub);
428            eprintln!("[hao] no callback registered for hook {:#x}", stub);
429            std::process::abort()
430        })
431}
432
433macro_rules! arity {
434    ($trampoline:ident; $($t:ident $v:ident),*) => {
435        impl<F, $($t: Il2CppValue,)* R: Il2CppValue> HookCallback<($($t,)*), R> for F
436        where
437            F: Fn($($t,)* Original<($($t,)*), R>) -> R + Send + Sync + 'static,
438        {
439            fn trampoline() -> *mut u8 {
440                $trampoline::<F, $($t,)* R> as *mut u8
441            }
442
443            fn signature() -> Signature {
444                Signature {
445                    parameters: vec![$(ValueCheck::of::<$t>(),)*],
446                    ret: ValueCheck::of::<R>(),
447                }
448            }
449        }
450
451        #[allow(clippy::too_many_arguments)]
452        extern "C-unwind" fn $trampoline<F, $($t,)* R>($($v: $t,)* method: MethodInfo) -> R
453        where
454            F: Fn($($t,)* Original<($($t,)*), R>) -> R + Send + Sync + 'static,
455        {
456            // Must come first: the hook passes the original code in registers.
457            let code = hooking::original_function_ptr().map_or(std::ptr::null_mut(), |p| p.as_ptr());
458            let callback = callback::<F>(code as usize);
459            callback($($v,)* Original { code, method, _marker: PhantomData })
460        }
461
462        impl<$($t: Il2CppValue,)*> MethodArgs for ($($t,)*) {
463            fn parameters() -> Vec<ValueCheck> {
464                vec![$(ValueCheck::of::<$t>(),)*]
465            }
466
467            #[allow(clippy::unused_unit)]
468            unsafe fn invoke<R: Il2CppValue>(self, code: *const c_void, method: MethodInfo) -> R {
469                let ($($v,)*) = self;
470                let f: extern "C-unwind" fn($($t,)* MethodInfo) -> R = unsafe { std::mem::transmute(code) };
471                f($($v,)* method)
472            }
473        }
474    };
475}
476
477arity!(trampoline0;);
478arity!(trampoline1; A a);
479arity!(trampoline2; A a, B b);
480arity!(trampoline3; A a, B b, C c);
481arity!(trampoline4; A a, B b, C c, D d);
482arity!(trampoline5; A a, B b, C c, D d, E e);
483arity!(trampoline6; A a, B b, C c, D d, E e, G g);
484arity!(trampoline7; A a, B b, C c, D d, E e, G g, H h);
485arity!(trampoline8; A a, B b, C c, D d, E e, G g, H h, I i);
486
487impl Method {
488    fn type_info(&self, ty: Ptr) -> TypeInfo {
489        let api = &self.il2cpp.api;
490        unsafe {
491            let mut element = (api.il2cpp_type_get_type)(ty);
492            let byref = (api.il2cpp_type_is_byref)(ty);
493            let class = (api.il2cpp_type_get_class_or_element_class)(ty);
494            let value_type = match element {
495                element::VALUETYPE => true,
496                element::GENERICINST => !class.is_null() && (api.il2cpp_class_is_valuetype)(class),
497                _ => false,
498            };
499            let is_enum = element == element::VALUETYPE
500                && !class.is_null()
501                && (api.il2cpp_class_is_enum)(class);
502            if is_enum {
503                element = (api.il2cpp_type_get_type)((api.il2cpp_class_enum_basetype)(class));
504            }
505            let (namespace, name) = if class.is_null() {
506                ("", "")
507            } else {
508                (
509                    crate::c_str((api.il2cpp_class_get_namespace)(class)),
510                    crate::c_str((api.il2cpp_class_get_name)(class)),
511                )
512            };
513            TypeInfo {
514                element,
515                value_type,
516                is_enum,
517                byref,
518                namespace,
519                name,
520            }
521        }
522    }
523
524    fn type_name(&self, ty: Ptr) -> String {
525        unsafe {
526            let name = (self.il2cpp.api.il2cpp_type_get_name)(ty);
527            if name.is_null() {
528                return "?".into();
529            }
530            std::ffi::CStr::from_ptr(name)
531                .to_string_lossy()
532                .into_owned()
533        }
534    }
535
536    pub fn is_instance(&self) -> bool {
537        unsafe { (self.il2cpp.api.il2cpp_method_is_instance)(self.ptr) }
538    }
539
540    pub fn parameter_count(&self) -> u32 {
541        unsafe { (self.il2cpp.api.il2cpp_method_get_param_count)(self.ptr) }
542    }
543
544    /// The managed name of the return type, e.g. `System.Int32`.
545    pub fn return_type_name(&self) -> String {
546        self.type_name(unsafe { (self.il2cpp.api.il2cpp_method_get_return_type)(self.ptr) })
547    }
548
549    /// The managed type name of parameter `index`, e.g. `System.Single`.
550    pub fn parameter_type_name(&self, index: u32) -> String {
551        self.type_name(unsafe { (self.il2cpp.api.il2cpp_method_get_param)(self.ptr, index) })
552    }
553
554    /// The declared name of parameter `index`, e.g. `amount`. Release builds
555    /// often strip these to `arg0`, `arg1`, ...
556    pub fn parameter_name(&self, index: u32) -> String {
557        let name = unsafe { (self.il2cpp.api.il2cpp_method_get_param_name)(self.ptr, index) };
558        unsafe { crate::c_str(name) }.to_owned()
559    }
560
561    /// The parameters, each with its name and type name.
562    pub fn parameters(&self) -> impl Iterator<Item = Parameter> + '_ {
563        (0..self.parameter_count()).map(move |i| Parameter {
564            name: self.parameter_name(i),
565            type_name: self.parameter_type_name(i),
566        })
567    }
568
569    /// The managed signature, e.g. `System.Int32 Heal(System.Single, System.Boolean)`,
570    /// built from [`Method::return_type_name`], [`Method::name`] and [`Method::parameters`].
571    pub fn signature(&self) -> String {
572        let params: Vec<String> = self.parameters().map(|p| p.type_name).collect();
573        format!(
574            "{}{} {}({})",
575            if self.is_instance() { "" } else { "static " },
576            self.return_type_name(),
577            self.name(),
578            params.join(", ")
579        )
580    }
581
582    /// Checks `params` (with the instance first for instance methods) and `ret` against the method.
583    fn check(&self, params: &[ValueCheck], ret: ValueCheck) -> Result<()> {
584        let api = &self.il2cpp.api;
585        let instance = self.is_instance() as usize;
586        let count = self.parameter_count() as usize;
587        let mismatch =
588            |detail: String| Error::Signature(format!("{}: {}", self.signature(), detail));
589        if params.len() != count + instance {
590            return Err(mismatch(format!(
591                "expected {} arguments{}, got {}",
592                count + instance,
593                if instance == 1 {
594                    " including the instance"
595                } else {
596                    ""
597                },
598                params.len()
599            )));
600        }
601        if instance == 1 && !params[0].reference {
602            return Err(mismatch(format!(
603                "the instance can't be passed as {}",
604                params[0].name
605            )));
606        }
607        for (i, check) in params[instance..].iter().enumerate() {
608            let ty = unsafe { (api.il2cpp_method_get_param)(self.ptr, i as u32) };
609            if !(check.matches)(self.type_info(ty)) {
610                return Err(mismatch(format!(
611                    "parameter {} is {}, not {}",
612                    i,
613                    self.type_name(ty),
614                    check.name
615                )));
616            }
617        }
618        let ty = unsafe { (api.il2cpp_method_get_return_type)(self.ptr) };
619        if !(ret.matches)(self.type_info(ty)) {
620            return Err(mismatch(format!(
621                "returns {}, not {}",
622                self.type_name(ty),
623                ret.name
624            )));
625        }
626        Ok(())
627    }
628
629    /// Checks argument types `Args` (a tuple, with the instance first for
630    /// instance methods) and return type `R` against the method's signature, as
631    /// [`Method::hook`] and [`Method::call`] do.
632    pub fn check_types<Args: MethodArgs, R: Il2CppValue>(&self) -> Result<()> {
633        self.check(&Args::parameters(), ValueCheck::of::<R>())
634    }
635
636    /// Redirects calls of this method to `callback`, after checking its types
637    /// against the method's signature. The callback gets the arguments (the
638    /// instance first for instance methods) and an [`Original`] to call the
639    /// original code with.
640    ///
641    /// ```no_run
642    /// # use hao_il2cpp_runtime::{Il2Cpp, Object, Original};
643    /// # fn f(il2cpp: &'static Il2Cpp) -> hao_il2cpp_runtime::Result<()> {
644    /// let heal = il2cpp.class("Assembly-CSharp", "Game", "PlayerHealth")?.method("Heal", 2)?;
645    /// heal.hook(|this: Object, amount: f32, overheal: bool, original: Original<_, i32>| {
646    ///     original.call((this, amount * 2.0, overheal))
647    /// })?;
648    /// # Ok(()) }
649    /// ```
650    pub fn hook<Args, R, F: HookCallback<Args, R>>(
651        &self,
652        callback: F,
653    ) -> Result<crate::MethodHook> {
654        let signature = F::signature();
655        self.check(&signature.parameters, signature.ret)?;
656        let mut hook = unsafe { hooking::Hook::create(self.code() as *mut u8, F::trampoline()) }
657            .map_err(Error::Hook)?;
658        register(
659            hook.data.original_fn_call_stub_data.as_ptr() as usize,
660            callback,
661        );
662        unsafe { hook.apply_hook() }.map_err(Error::Hook)?;
663        tracing::debug!(method = %self.signature(), code = ?self.code(), "hooked");
664        Ok(crate::MethodHook(hook))
665    }
666
667    /// Calls the method's compiled code after checking the argument and return
668    /// types. `args` is a tuple, with the instance first for instance methods.
669    ///
670    /// Managed exceptions thrown by the method unwind through the caller.
671    pub fn call<Args: MethodArgs, R: Il2CppValue>(&self, args: Args) -> Result<R> {
672        self.check(&Args::parameters(), ValueCheck::of::<R>())?;
673        Ok(unsafe { args.invoke(self.code(), self.ptr) })
674    }
675
676    /// [`Method::call`] without the type check, for calls made often after
677    /// [`Method::check_types`] has passed once.
678    ///
679    /// # Safety
680    /// `Args` and `R` must pass [`Method::check_types`] for this method.
681    pub unsafe fn call_unchecked<Args: MethodArgs, R: Il2CppValue>(&self, args: Args) -> R {
682        unsafe { args.invoke(self.code(), self.ptr) }
683    }
684
685    /// Hooks a **void** method with a conditional block: when
686    /// [`VoidBlockHook::set_blocked(true)`] is active, calls to the method
687    /// return immediately without running the original code.
688    ///
689    /// Works for any void method regardless of its parameter types — the
690    /// trampoline preserves all argument registers and either tail-calls the
691    /// original or returns.
692    ///
693    /// ```no_run
694    /// # use hao_il2cpp_runtime::Il2Cpp;
695    /// # fn f(il2cpp: &'static Il2Cpp) -> hao_il2cpp_runtime::Result<()> {
696    /// let damage = il2cpp
697    ///     .class("Assembly-CSharp", "Actors", "PlayerHealth")?
698    ///     .method("DamagePlayer", 3)?;
699    /// let hook = damage.hook_void_block()?;
700    /// hook.set_blocked(true); // godmode — DamagePlayer is now a no-op
701    /// # Ok(()) }
702    /// ```
703    #[cfg(target_arch = "x86_64")]
704    pub fn hook_void_block(&self) -> Result<VoidBlockHook> {
705        let ret = self.return_type_name();
706        if ret != "System.Void" {
707            return Err(Error::Signature(format!(
708                "hook_void_block requires a void method, but `{}` returns {}",
709                self.name(),
710                ret,
711            )));
712        }
713
714        let state = Box::leak(Box::new(std::sync::atomic::AtomicBool::new(false)));
715        let state_ptr = state as *const std::sync::atomic::AtomicBool;
716
717        let mut hook =
718            unsafe { hooking::Hook::create(self.code() as *mut u8, void_block_trampoline as *mut u8) }
719                .map_err(Error::Hook)?;
720        let original = hook.data.original_fn_call_stub_data.as_ptr() as usize;
721        register(original, state_ptr as usize);
722        unsafe { hook.apply_hook() }.map_err(Error::Hook)?;
723
724        tracing::debug!(method = %self.signature(), code = ?self.code(), "hooked (void block)");
725
726        Ok(VoidBlockHook {
727            state,
728            _hook: crate::MethodHook(hook),
729        })
730    }
731}
732
733/// A hook that conditionally blocks a void method. Created by
734/// [`Method::hook_void_block`].
735pub struct VoidBlockHook {
736    /// The flag that controls whether the method is blocked.
737    pub state: &'static std::sync::atomic::AtomicBool,
738    _hook: crate::MethodHook,
739}
740
741impl VoidBlockHook {
742    /// When `true`, calls to the hooked method return immediately.
743    pub fn set_blocked(&self, blocked: bool) {
744        self.state.store(blocked, std::sync::atomic::Ordering::Relaxed);
745    }
746
747    pub fn is_blocked(&self) -> bool {
748        self.state.load(std::sync::atomic::Ordering::Relaxed)
749    }
750}
751
752// ── Generic hooks ───────────────────────────────────────────────────
753
754/// How a method parameter maps to the System V AMD64 ABI.
755#[cfg(target_arch = "x86_64")]
756#[derive(Debug, Clone, Copy)]
757pub enum ParamSlot {
758    /// Integer/pointer in register index 0..5 (rdi, rsi, rdx, rcx, r8, r9).
759    IntReg(u8),
760    /// Float in SSE register index 0..7 (xmm0..xmm7).
761    FloatReg(u8),
762}
763
764/// One parameter of a hooked method, mapped to its ABI slot at install time.
765#[cfg(target_arch = "x86_64")]
766#[derive(Debug, Clone)]
767pub struct GenericParam {
768    pub slot: ParamSlot,
769    pub type_info: TypeInfo,
770    pub name: String,
771}
772
773/// Metadata about a generically-hooked method, built once at install time.
774///
775/// The `params` list includes the instance pointer (if any) as the first
776/// entry, followed by the declared parameters. Each is mapped to its ABI
777/// register slot.
778#[cfg(target_arch = "x86_64")]
779#[derive(Debug, Clone)]
780pub struct GenericHookMeta {
781    pub params: Vec<GenericParam>,
782    pub return_type: TypeInfo,
783    pub is_instance: bool,
784    pub signature: String,
785}
786
787#[cfg(target_arch = "x86_64")]
788struct GenericHookEntry {
789    meta: GenericHookMeta,
790    callback: Box<dyn Fn(usize, &GenericHookMeta, &mut hooking::SavedRegs) -> hooking::HookAction + Send + Sync>,
791}
792
793#[cfg(target_arch = "x86_64")]
794impl Method {
795    /// Hooks this method with a generic callback that receives the saved
796    /// argument registers and metadata about each parameter's type and ABI
797    /// slot. The callback inspects or modifies arguments through
798    /// [`hooking::SavedRegs`] and returns a [`hooking::HookAction`] to pass
799    /// through to the original or override the return value.
800    ///
801    /// Unlike [`Method::hook`], the callback doesn't need to declare the
802    /// method's parameter types at compile time — they are mapped to ABI
803    /// registers at install time using Il2Cpp metadata.
804    ///
805    /// ```no_run
806    /// # use hao_il2cpp_runtime::Il2Cpp;
807    /// # fn f(il2cpp: &'static Il2Cpp) -> hao_il2cpp_runtime::Result<()> {
808    /// let heal = il2cpp
809    ///     .class("Assembly-CSharp", "Game", "PlayerHealth")?
810    ///     .method("Heal", 2)?;
811    /// heal.hook_generic(|original, meta, regs| {
812    ///     // Read the second declared parameter (index 1 if instance method,
813    ///     // since index 0 is `this`).
814    ///     let amount = regs.read_int(1);
815    ///     // Double it and pass through to the original.
816    ///     regs.write_int(1, amount * 2);
817    ///     hooking::HookAction::Passthrough
818    /// })?;
819    /// # Ok(()) }
820    /// ```
821    pub fn hook_generic(
822        &self,
823        callback: impl Fn(usize, &GenericHookMeta, &mut hooking::SavedRegs) -> hooking::HookAction + Send + Sync + 'static,
824    ) -> Result<crate::MethodHook> {
825        let meta = self.build_generic_meta();
826        let entry = GenericHookEntry {
827            meta,
828            callback: Box::new(callback),
829        };
830
831        let mut hook = unsafe {
832            hooking::Hook::create_save_registers(
833                self.code() as *mut u8,
834                generic_hook_dispatch,
835            )
836        }
837        .map_err(Error::Hook)?;
838
839        let stub_addr = hook.data.original_fn_call_stub_data.as_ptr() as usize;
840        register(stub_addr, entry);
841
842        unsafe { hook.apply_hook() }.map_err(Error::Hook)?;
843        tracing::debug!(method = %self.signature(), code = ?self.code(), "hooked (generic)");
844        Ok(crate::MethodHook(hook))
845    }
846
847    fn build_generic_meta(&self) -> GenericHookMeta {
848        let is_instance = self.is_instance();
849        let param_count = self.parameter_count();
850
851        let mut params = Vec::new();
852        let mut int_idx: u8 = 0;
853        let mut float_idx: u8 = 0;
854
855        if is_instance {
856            params.push(GenericParam {
857                slot: ParamSlot::IntReg(int_idx),
858                type_info: TypeInfo {
859                    element: element::OBJECT,
860                    value_type: false,
861                    is_enum: false,
862                    byref: false,
863                    namespace: "",
864                    name: "",
865                },
866                name: "this".to_owned(),
867            });
868            int_idx += 1;
869        }
870
871        for i in 0..param_count {
872            let ty = unsafe { (self.il2cpp.api.il2cpp_method_get_param)(self.ptr, i) };
873            let info = self.type_info(ty);
874            let name = self.parameter_name(i);
875
876            let is_float = matches!(info.element, element::R4 | element::R8) && !info.byref;
877            let slot = if is_float {
878                if float_idx < 8 {
879                    let s = ParamSlot::FloatReg(float_idx);
880                    float_idx += 1;
881                    s
882                } else {
883                    continue;
884                }
885            } else if int_idx < 6 {
886                let s = ParamSlot::IntReg(int_idx);
887                int_idx += 1;
888                s
889            } else {
890                continue;
891            };
892
893            params.push(GenericParam { slot, type_info: info, name });
894        }
895
896        let ret_ty = unsafe { (self.il2cpp.api.il2cpp_method_get_return_type)(self.ptr) };
897
898        GenericHookMeta {
899            params,
900            return_type: self.type_info(ret_ty),
901            is_instance,
902            signature: self.signature(),
903        }
904    }
905}
906
907/// Called from hooking's `save_registers_trampoline` via the dispatch shim.
908#[cfg(target_arch = "x86_64")]
909extern "C" fn generic_hook_dispatch(
910    original: usize,
911    int_regs: *mut u64,
912    sse_regs: *mut [u8; 16],
913    result: *mut hooking::DispatchResult,
914) {
915    let entry = callback::<GenericHookEntry>(original);
916    let mut regs = hooking::SavedRegs { int_regs, sse_regs };
917
918    let action = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
919        (entry.callback)(original, &entry.meta, &mut regs)
920    }));
921
922    let action = match action {
923        Ok(a) => a,
924        Err(_) => {
925            tracing::error!("generic hook callback panicked, calling original");
926            hooking::HookAction::Passthrough
927        }
928    };
929
930    unsafe { *result = hooking::DispatchResult::from(action) };
931}
932
933/// Looks up the block flag for the hook whose original function stub is at
934/// `original`. Called from the naked trampoline.
935extern "C" fn void_block_check(original: usize) -> bool {
936    let state_ptr = callback::<usize>(original);
937    let state = unsafe { &*(*state_ptr as *const std::sync::atomic::AtomicBool) };
938    state.load(std::sync::atomic::Ordering::Relaxed)
939}
940
941/// Generic trampoline for [`Method::hook_void_block`]. Preserves all
942/// argument registers (integer and SSE) so it works for any void method
943/// regardless of parameter types.
944#[unsafe(naked)]
945#[cfg(target_arch = "x86_64")]
946unsafe extern "C" fn void_block_trampoline() {
947    // The hooking crate's redirect stub puts the original function pointer
948    // in r10 and a checksum in r11 before jumping here.
949    core::arch::naked_asm!(
950        // Save callee-saved register we'll use to hold the original ptr.
951        "push rbx",
952
953        // Verify and capture the original function pointer from r10/r11.
954        "mov rbx, r10",
955        "movabs rax, 0xDEADBEEFCAFEBABE",
956        "xor rax, r10",
957        "cmp rax, r11",
958        "jne 9f",
959
960        // Save all integer argument registers.
961        "push rdi",
962        "push rsi",
963        "push rdx",
964        "push rcx",
965        "push r8",
966        "push r9",
967
968        // Save all SSE argument registers (8 × 16 = 128 bytes).
969        "sub rsp, 0x80",
970        "movdqu [rsp+0x00], xmm0",
971        "movdqu [rsp+0x10], xmm1",
972        "movdqu [rsp+0x20], xmm2",
973        "movdqu [rsp+0x30], xmm3",
974        "movdqu [rsp+0x40], xmm4",
975        "movdqu [rsp+0x50], xmm5",
976        "movdqu [rsp+0x60], xmm6",
977        "movdqu [rsp+0x70], xmm7",
978
979        // Check if this hook is blocked.
980        // void_block_check(original: usize) -> bool
981        "mov rdi, rbx",
982        "call {check}",
983        "test al, al",
984        "jnz 2f",
985
986        // Not blocked — restore registers and tail-call original.
987        "movdqu xmm0, [rsp+0x00]",
988        "movdqu xmm1, [rsp+0x10]",
989        "movdqu xmm2, [rsp+0x20]",
990        "movdqu xmm3, [rsp+0x30]",
991        "movdqu xmm4, [rsp+0x40]",
992        "movdqu xmm5, [rsp+0x50]",
993        "movdqu xmm6, [rsp+0x60]",
994        "movdqu xmm7, [rsp+0x70]",
995        "add rsp, 0x80",
996        "pop r9",
997        "pop r8",
998        "pop rcx",
999        "pop rdx",
1000        "pop rsi",
1001        "pop rdi",
1002        "mov rax, rbx",
1003        "pop rbx",
1004        "jmp rax",
1005
1006        "2:",
1007        // Blocked — clean up and return (method is void).
1008        "add rsp, 0x80",
1009        "pop r9",
1010        "pop r8",
1011        "pop rcx",
1012        "pop rdx",
1013        "pop rsi",
1014        "pop rdi",
1015        "pop rbx",
1016        "ret",
1017
1018        "9:",
1019        // Checksum mismatch — not in a hook, just return.
1020        "pop rbx",
1021        "ret",
1022
1023        check = sym void_block_check,
1024    );
1025}