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 type of a parameter or return value.
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38#[cfg_attr(feature = "reflect", derive(facet::Facet))]
39pub struct TypeInfo {
40    /// The `Il2CppTypeEnum` value. For enums, the element type of the underlying integer.
41    pub element: i32,
42    pub value_type: bool,
43    pub is_enum: bool,
44    pub byref: bool,
45    pub namespace: &'static str,
46    pub name: &'static str,
47}
48
49impl TypeInfo {
50    /// Whether this is the value type `namespace.name`, passed by value. For
51    /// [`Il2CppValue`] impls of `#[repr(C)]` structs mirroring a managed struct.
52    pub fn is_value_type(&self, namespace: &str, name: &str) -> bool {
53        !self.byref
54            && self.value_type
55            && !self.is_enum
56            && self.namespace == namespace
57            && self.name == name
58    }
59}
60
61/// A method parameter's name and managed type name, from [`Method::parameters`].
62#[derive(Debug, Clone, PartialEq, Eq)]
63#[cfg_attr(feature = "reflect", derive(facet::Facet))]
64pub struct Parameter {
65    /// The declared name, e.g. `amount` (often `arg0` in release builds).
66    pub name: String,
67    /// The managed type name, e.g. `System.Single`.
68    pub type_name: String,
69}
70
71/// A managed object reference (`Il2CppObject*`), possibly null.
72#[repr(transparent)]
73#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
74pub struct Object(pub Ptr);
75
76unsafe impl Send for Object {}
77unsafe impl Sync for Object {}
78
79impl Object {
80    pub const NULL: Object = Object(std::ptr::null_mut());
81
82    pub fn is_null(&self) -> bool {
83        self.0.is_null()
84    }
85
86    pub fn as_ptr(&self) -> Ptr {
87        self.0
88    }
89}
90
91/// A managed string (`Il2CppString*`), possibly null.
92#[repr(transparent)]
93#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
94pub struct Il2CppString(pub Object);
95
96impl Il2CppString {
97    pub fn new(il2cpp: &Il2Cpp, value: &str) -> Result<Self> {
98        il2cpp.string(value)
99    }
100
101    pub fn is_null(&self) -> bool {
102        self.0.is_null()
103    }
104
105    /// The string's contents, or `None` for null.
106    pub fn to_rust(&self) -> Option<String> {
107        let il2cpp = Il2Cpp::get()?;
108        // Values of this type only come from string typed arguments and returns.
109        unsafe { il2cpp.read_string(self.0) }
110    }
111}
112
113/// A Rust type that has the same representation as some managed types when
114/// passed to and from compiled Il2Cpp code.
115///
116/// # Safety
117/// `matches` may only accept managed types whose values are passed exactly like `Self`.
118pub unsafe trait Il2CppValue: Copy + 'static {
119    fn matches(ty: TypeInfo) -> bool;
120
121    fn describe() -> &'static str {
122        std::any::type_name::<Self>()
123    }
124
125    /// Whether this is a pointer to an object, so it can be the instance (`this`).
126    fn is_reference() -> bool {
127        false
128    }
129}
130
131macro_rules! primitive {
132    ($($t:ty => [$($e:ident),+];)*) => {$(
133        unsafe impl Il2CppValue for $t {
134            fn matches(ty: TypeInfo) -> bool {
135                !ty.byref && [$(element::$e),+].contains(&ty.element)
136            }
137        }
138    )*};
139}
140
141primitive! {
142    () => [VOID];
143    bool => [BOOLEAN];
144    u16 => [CHAR, U2];
145    i8 => [I1];
146    u8 => [U1];
147    i16 => [I2];
148    i32 => [I4];
149    u32 => [U4];
150    i64 => [I8];
151    u64 => [U8];
152    f32 => [R4];
153    f64 => [R8];
154    isize => [I];
155    usize => [U];
156}
157
158unsafe impl Il2CppValue for Object {
159    fn is_reference() -> bool {
160        true
161    }
162
163    fn matches(ty: TypeInfo) -> bool {
164        !ty.byref
165            && !ty.value_type
166            && [
167                element::STRING,
168                element::CLASS,
169                element::OBJECT,
170                element::SZARRAY,
171                element::ARRAY,
172                element::GENERICINST,
173                element::VAR,
174                element::MVAR,
175            ]
176            .contains(&ty.element)
177    }
178}
179
180unsafe impl Il2CppValue for Il2CppString {
181    fn is_reference() -> bool {
182        true
183    }
184
185    fn matches(ty: TypeInfo) -> bool {
186        !ty.byref && ty.element == element::STRING
187    }
188}
189
190/// `ref`/`out` parameters and pointers.
191unsafe impl Il2CppValue for *mut c_void {
192    fn is_reference() -> bool {
193        true
194    }
195
196    fn matches(ty: TypeInfo) -> bool {
197        ty.byref || ty.element == element::PTR
198    }
199}
200
201/// Calls the original code of a hooked method.
202pub struct Original<Args, R> {
203    code: *const c_void,
204    method: MethodInfo,
205    _marker: PhantomData<fn(Args) -> R>,
206}
207
208/// How a Rust type is checked against a managed parameter or return type.
209#[derive(Clone, Copy)]
210pub struct ValueCheck {
211    pub matches: fn(TypeInfo) -> bool,
212    pub name: &'static str,
213    pub reference: bool,
214}
215
216impl ValueCheck {
217    pub fn of<T: Il2CppValue>() -> Self {
218        Self {
219            matches: T::matches,
220            name: T::describe(),
221            reference: T::is_reference(),
222        }
223    }
224}
225
226/// The Rust types of a hook or call, checked against the method before use.
227pub struct Signature {
228    pub parameters: Vec<ValueCheck>,
229    pub ret: ValueCheck,
230}
231
232impl<Args: MethodArgs, R: Il2CppValue> Original<Args, R> {
233    /// Calls the original code with `args`, a tuple like the callback's arguments.
234    pub fn call(&self, args: Args) -> R {
235        unsafe { args.invoke(self.code, self.method) }
236    }
237}
238
239/// A closure usable as a hook for a method with parameters `Args` returning `R`.
240/// Implemented for `Fn(args..., Original<(args...), R>) -> R`.
241pub trait HookCallback<Args, R>: Send + Sync + 'static {
242    #[doc(hidden)]
243    fn trampoline() -> *mut u8;
244    #[doc(hidden)]
245    fn signature() -> Signature;
246}
247
248/// Argument tuples for [`Method::call`].
249pub trait MethodArgs {
250    #[doc(hidden)]
251    fn parameters() -> Vec<ValueCheck>;
252    #[doc(hidden)]
253    unsafe fn invoke<R: Il2CppValue>(self, code: *const c_void, method: MethodInfo) -> R;
254}
255
256type Callbacks = RwLock<Vec<(usize, &'static (dyn Any + Send + Sync))>>;
257
258/// Hook closures by the address of their hook's original-function stub.
259static CALLBACKS: Callbacks = RwLock::new(Vec::new());
260
261pub(crate) fn register<F: Any + Send + Sync>(stub: usize, callback: F) {
262    let callback: &'static (dyn Any + Send + Sync) = Box::leak(Box::new(callback));
263    CALLBACKS
264        .write()
265        .unwrap_or_else(|e| e.into_inner())
266        .push((stub, callback));
267}
268
269fn callback<F: Any>(stub: usize) -> &'static F {
270    let callbacks = CALLBACKS.read().unwrap_or_else(|e| e.into_inner());
271    callbacks
272        .iter()
273        .rev()
274        .find(|(s, _)| *s == stub)
275        .and_then(|(_, c)| c.downcast_ref::<F>())
276        .unwrap_or_else(|| {
277            tracing::error!("no callback registered for hook {:#x}, aborting", stub);
278            eprintln!("[hao] no callback registered for hook {:#x}", stub);
279            std::process::abort()
280        })
281}
282
283macro_rules! arity {
284    ($trampoline:ident; $($t:ident $v:ident),*) => {
285        impl<F, $($t: Il2CppValue,)* R: Il2CppValue> HookCallback<($($t,)*), R> for F
286        where
287            F: Fn($($t,)* Original<($($t,)*), R>) -> R + Send + Sync + 'static,
288        {
289            fn trampoline() -> *mut u8 {
290                $trampoline::<F, $($t,)* R> as *mut u8
291            }
292
293            fn signature() -> Signature {
294                Signature {
295                    parameters: vec![$(ValueCheck::of::<$t>(),)*],
296                    ret: ValueCheck::of::<R>(),
297                }
298            }
299        }
300
301        #[allow(clippy::too_many_arguments)]
302        extern "C-unwind" fn $trampoline<F, $($t,)* R>($($v: $t,)* method: MethodInfo) -> R
303        where
304            F: Fn($($t,)* Original<($($t,)*), R>) -> R + Send + Sync + 'static,
305        {
306            // Must come first: the hook passes the original code in registers.
307            let code = hooking::original_function_ptr().map_or(std::ptr::null_mut(), |p| p.as_ptr());
308            let callback = callback::<F>(code as usize);
309            callback($($v,)* Original { code, method, _marker: PhantomData })
310        }
311
312        impl<$($t: Il2CppValue,)*> MethodArgs for ($($t,)*) {
313            fn parameters() -> Vec<ValueCheck> {
314                vec![$(ValueCheck::of::<$t>(),)*]
315            }
316
317            #[allow(clippy::unused_unit)]
318            unsafe fn invoke<R: Il2CppValue>(self, code: *const c_void, method: MethodInfo) -> R {
319                let ($($v,)*) = self;
320                let f: extern "C-unwind" fn($($t,)* MethodInfo) -> R = unsafe { std::mem::transmute(code) };
321                f($($v,)* method)
322            }
323        }
324    };
325}
326
327arity!(trampoline0;);
328arity!(trampoline1; A a);
329arity!(trampoline2; A a, B b);
330arity!(trampoline3; A a, B b, C c);
331arity!(trampoline4; A a, B b, C c, D d);
332arity!(trampoline5; A a, B b, C c, D d, E e);
333arity!(trampoline6; A a, B b, C c, D d, E e, G g);
334arity!(trampoline7; A a, B b, C c, D d, E e, G g, H h);
335arity!(trampoline8; A a, B b, C c, D d, E e, G g, H h, I i);
336
337impl Method {
338    fn type_info(&self, ty: Ptr) -> TypeInfo {
339        let api = &self.il2cpp.api;
340        unsafe {
341            let mut element = (api.il2cpp_type_get_type)(ty);
342            let byref = (api.il2cpp_type_is_byref)(ty);
343            let class = (api.il2cpp_type_get_class_or_element_class)(ty);
344            let value_type = match element {
345                element::VALUETYPE => true,
346                element::GENERICINST => !class.is_null() && (api.il2cpp_class_is_valuetype)(class),
347                _ => false,
348            };
349            let is_enum = element == element::VALUETYPE
350                && !class.is_null()
351                && (api.il2cpp_class_is_enum)(class);
352            if is_enum {
353                element = (api.il2cpp_type_get_type)((api.il2cpp_class_enum_basetype)(class));
354            }
355            let (namespace, name) = if class.is_null() {
356                ("", "")
357            } else {
358                (
359                    crate::c_str((api.il2cpp_class_get_namespace)(class)),
360                    crate::c_str((api.il2cpp_class_get_name)(class)),
361                )
362            };
363            TypeInfo {
364                element,
365                value_type,
366                is_enum,
367                byref,
368                namespace,
369                name,
370            }
371        }
372    }
373
374    fn type_name(&self, ty: Ptr) -> String {
375        unsafe {
376            let name = (self.il2cpp.api.il2cpp_type_get_name)(ty);
377            if name.is_null() {
378                return "?".into();
379            }
380            std::ffi::CStr::from_ptr(name)
381                .to_string_lossy()
382                .into_owned()
383        }
384    }
385
386    pub fn is_instance(&self) -> bool {
387        unsafe { (self.il2cpp.api.il2cpp_method_is_instance)(self.ptr) }
388    }
389
390    pub fn parameter_count(&self) -> u32 {
391        unsafe { (self.il2cpp.api.il2cpp_method_get_param_count)(self.ptr) }
392    }
393
394    /// The managed name of the return type, e.g. `System.Int32`.
395    pub fn return_type_name(&self) -> String {
396        self.type_name(unsafe { (self.il2cpp.api.il2cpp_method_get_return_type)(self.ptr) })
397    }
398
399    /// The managed type name of parameter `index`, e.g. `System.Single`.
400    pub fn parameter_type_name(&self, index: u32) -> String {
401        self.type_name(unsafe { (self.il2cpp.api.il2cpp_method_get_param)(self.ptr, index) })
402    }
403
404    /// The declared name of parameter `index`, e.g. `amount`. Release builds
405    /// often strip these to `arg0`, `arg1`, ...
406    pub fn parameter_name(&self, index: u32) -> String {
407        let name = unsafe { (self.il2cpp.api.il2cpp_method_get_param_name)(self.ptr, index) };
408        unsafe { crate::c_str(name) }.to_owned()
409    }
410
411    /// The parameters, each with its name and type name.
412    pub fn parameters(&self) -> impl Iterator<Item = Parameter> + '_ {
413        (0..self.parameter_count()).map(move |i| Parameter {
414            name: self.parameter_name(i),
415            type_name: self.parameter_type_name(i),
416        })
417    }
418
419    /// The managed signature, e.g. `System.Int32 Heal(System.Single, System.Boolean)`,
420    /// built from [`Method::return_type_name`], [`Method::name`] and [`Method::parameters`].
421    pub fn signature(&self) -> String {
422        let params: Vec<String> = self.parameters().map(|p| p.type_name).collect();
423        format!(
424            "{}{} {}({})",
425            if self.is_instance() { "" } else { "static " },
426            self.return_type_name(),
427            self.name(),
428            params.join(", ")
429        )
430    }
431
432    /// Checks `params` (with the instance first for instance methods) and `ret` against the method.
433    fn check(&self, params: &[ValueCheck], ret: ValueCheck) -> Result<()> {
434        let api = &self.il2cpp.api;
435        let instance = self.is_instance() as usize;
436        let count = self.parameter_count() as usize;
437        let mismatch =
438            |detail: String| Error::Signature(format!("{}: {}", self.signature(), detail));
439        if params.len() != count + instance {
440            return Err(mismatch(format!(
441                "expected {} arguments{}, got {}",
442                count + instance,
443                if instance == 1 {
444                    " including the instance"
445                } else {
446                    ""
447                },
448                params.len()
449            )));
450        }
451        if instance == 1 && !params[0].reference {
452            return Err(mismatch(format!(
453                "the instance can't be passed as {}",
454                params[0].name
455            )));
456        }
457        for (i, check) in params[instance..].iter().enumerate() {
458            let ty = unsafe { (api.il2cpp_method_get_param)(self.ptr, i as u32) };
459            if !(check.matches)(self.type_info(ty)) {
460                return Err(mismatch(format!(
461                    "parameter {} is {}, not {}",
462                    i,
463                    self.type_name(ty),
464                    check.name
465                )));
466            }
467        }
468        let ty = unsafe { (api.il2cpp_method_get_return_type)(self.ptr) };
469        if !(ret.matches)(self.type_info(ty)) {
470            return Err(mismatch(format!(
471                "returns {}, not {}",
472                self.type_name(ty),
473                ret.name
474            )));
475        }
476        Ok(())
477    }
478
479    /// Checks argument types `Args` (a tuple, with the instance first for
480    /// instance methods) and return type `R` against the method's signature, as
481    /// [`Method::hook`] and [`Method::call`] do.
482    pub fn check_types<Args: MethodArgs, R: Il2CppValue>(&self) -> Result<()> {
483        self.check(&Args::parameters(), ValueCheck::of::<R>())
484    }
485
486    /// Redirects calls of this method to `callback`, after checking its types
487    /// against the method's signature. The callback gets the arguments (the
488    /// instance first for instance methods) and an [`Original`] to call the
489    /// original code with.
490    ///
491    /// ```no_run
492    /// # use hao_il2cpp_runtime::{Il2Cpp, Object, Original};
493    /// # fn f(il2cpp: &'static Il2Cpp) -> hao_il2cpp_runtime::Result<()> {
494    /// let heal = il2cpp.class("Assembly-CSharp", "Game", "PlayerHealth")?.method("Heal", 2)?;
495    /// heal.hook(|this: Object, amount: f32, overheal: bool, original: Original<_, i32>| {
496    ///     original.call((this, amount * 2.0, overheal))
497    /// })?;
498    /// # Ok(()) }
499    /// ```
500    pub fn hook<Args, R, F: HookCallback<Args, R>>(
501        &self,
502        callback: F,
503    ) -> Result<crate::MethodHook> {
504        let signature = F::signature();
505        self.check(&signature.parameters, signature.ret)?;
506        let mut hook = unsafe { hooking::Hook::create(self.code() as *mut u8, F::trampoline()) }
507            .map_err(Error::Hook)?;
508        register(
509            hook.data.original_fn_call_stub_data.as_ptr() as usize,
510            callback,
511        );
512        unsafe { hook.apply_hook() }.map_err(Error::Hook)?;
513        tracing::debug!(method = %self.signature(), code = ?self.code(), "hooked");
514        Ok(crate::MethodHook(hook))
515    }
516
517    /// Calls the method's compiled code after checking the argument and return
518    /// types. `args` is a tuple, with the instance first for instance methods.
519    ///
520    /// Managed exceptions thrown by the method unwind through the caller.
521    pub fn call<Args: MethodArgs, R: Il2CppValue>(&self, args: Args) -> Result<R> {
522        self.check(&Args::parameters(), ValueCheck::of::<R>())?;
523        Ok(unsafe { args.invoke(self.code(), self.ptr) })
524    }
525
526    /// [`Method::call`] without the type check, for calls made often after
527    /// [`Method::check_types`] has passed once.
528    ///
529    /// # Safety
530    /// `Args` and `R` must pass [`Method::check_types`] for this method.
531    pub unsafe fn call_unchecked<Args: MethodArgs, R: Il2CppValue>(&self, args: Args) -> R {
532        unsafe { args.invoke(self.code(), self.ptr) }
533    }
534}