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