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