Skip to main content

hao_il2cpp_runtime/
lib.rs

1//! Hook and call into a Unity Il2Cpp game from inside its process, the way
2//! MelonLoader mods do.
3//!
4//! A mod is a `cdylib` loaded into the game (on Linux with `LD_PRELOAD`).
5//! [`on_init`] runs once the game's Il2Cpp runtime has started, and from there
6//! methods are found by name and hooked with ordinary closures. The closure's
7//! types are checked against the method's real signature when the hook is
8//! installed:
9//!
10//! ```no_run
11//! use hao_il2cpp_runtime::{Il2Cpp, Object, Original};
12//!
13//! hao_il2cpp_runtime::on_init(|il2cpp: &'static Il2Cpp| {
14//!     let health = il2cpp.class("Assembly-CSharp", "Assets.Scripts.Inventory__Items__Pickups", "PlayerHealth")?;
15//!     // `int Heal(float amount, bool allowOverheal)`: the instance comes first.
16//!     health.method("Heal", 2)?.hook(|this: Object, amount: f32, overheal: bool, original: Original<_, i32>| {
17//!         original.call((this, amount * 2.0, overheal))
18//!     })?;
19//!     Ok(())
20//! });
21//! ```
22
23mod api;
24mod error;
25#[cfg(unix)]
26mod loader;
27mod typed;
28#[cfg(feature = "reflect")]
29pub mod reflect;
30
31use std::{
32    ffi::{c_void, CStr, CString},
33    path::{Path, PathBuf},
34    sync::OnceLock,
35};
36
37use libloading::Library;
38
39pub use api::{Api, Ptr};
40pub use error::{Error, Result};
41#[cfg(unix)]
42pub use loader::on_init;
43pub use typed::{
44    element, HookCallback, Il2CppString, Il2CppValue, MethodArgs, Object, Original, Parameter,
45    Signature, TypeInfo, ValueCheck,
46};
47
48/// The hidden last argument of every Il2Cpp method (`const MethodInfo*`).
49pub type MethodInfo = Ptr;
50
51/// Whether `path` is a game binary: `GameAssembly.so`, `GameAssembly.dll` or any other `GameAssembly.*`.
52/// Both `/` and `\\` separate directories, as Windows paths can show up on Linux under Wine.
53pub fn is_game_assembly(path: impl AsRef<Path>) -> bool {
54    let path = path.as_ref().to_string_lossy();
55    path.rsplit(['/', '\\'])
56        .next()
57        .is_some_and(|name| name.starts_with("GameAssembly."))
58}
59
60/// The game binary in a game folder, whichever platform the game was built for.
61pub fn find_game_assembly(dir: impl AsRef<Path>) -> Option<PathBuf> {
62    std::fs::read_dir(dir)
63        .ok()?
64        .filter_map(|e| e.ok().map(|e| e.path()))
65        .find(|p| p.is_file() && is_game_assembly(p))
66}
67
68/// The game binary mapped into this process, if any.
69#[cfg(unix)]
70pub fn loaded_game_assembly() -> Option<PathBuf> {
71    let maps = std::fs::read_to_string("/proc/self/maps").ok()?;
72    game_assembly_in_maps(&maps)
73}
74
75#[cfg(unix)]
76fn game_assembly_in_maps(maps: &str) -> Option<PathBuf> {
77    maps.lines()
78        // /proc maps preserves whitespace inside absolute paths.
79        .filter_map(|line| line.find('/').map(|start| &line[start..]))
80        .map(PathBuf::from)
81        .find(|p| is_game_assembly(p))
82}
83
84/// The game binary mapped into this process, if any.
85#[cfg(windows)]
86pub fn loaded_game_assembly() -> Option<PathBuf> {
87    libloading::os::windows::Library::open_already_loaded("GameAssembly.dll")
88        .ok()
89        .map(|_| PathBuf::from("GameAssembly.dll"))
90}
91
92/// Errors unless `path` is a binary this build can load: ELF on Unix, PE on Windows.
93fn check_format(path: &Path) -> Result<()> {
94    use std::io::Read;
95    let mut magic = [0u8; 4];
96    let read = std::fs::File::open(path).and_then(|mut f| f.read_exact(&mut magic));
97    let (elf, pe) = (magic == *b"\x7fELF", magic.starts_with(b"MZ"));
98    match read {
99        Ok(()) if cfg!(unix) && pe => Err(Error::UnsupportedBinary(format!(
100            "{} is a Windows binary (a Windows build running under Wine/Proton), which a Linux mod can't load yet",
101            path.display()
102        ))),
103        Ok(()) if cfg!(windows) && elf => Err(Error::UnsupportedBinary(format!("{} is not a Windows binary", path.display()))),
104        _ => Ok(()),
105    }
106}
107
108static INSTANCE: OnceLock<Il2Cpp> = OnceLock::new();
109
110/// The game's Il2Cpp runtime.
111pub struct Il2Cpp {
112    api: Api,
113    _library: Library,
114}
115
116fn cstring(value: &str) -> Result<CString> {
117    CString::new(value).map_err(|_| Error::Nul(value.to_owned()))
118}
119
120pub(crate) unsafe fn c_str<'a>(value: *const std::ffi::c_char) -> &'a str {
121    if value.is_null() {
122        ""
123    } else {
124        unsafe { CStr::from_ptr(value) }.to_str().unwrap_or("")
125    }
126}
127
128impl Il2Cpp {
129    fn install(library: Library) -> Result<&'static Il2Cpp> {
130        let api = Api::load(&library)?;
131        tracing::debug!("loaded the il2cpp_* API from the game binary");
132        Ok(INSTANCE.get_or_init(|| Il2Cpp {
133            api,
134            _library: library,
135        }))
136    }
137
138    /// The runtime of the game binary already loaded in this process.
139    pub fn loaded() -> Result<&'static Il2Cpp> {
140        if let Some(il2cpp) = INSTANCE.get() {
141            return Ok(il2cpp);
142        }
143        let path = loaded_game_assembly()
144            .ok_or_else(|| Error::NotFound("a loaded GameAssembly".into()))?;
145        check_format(&path)?;
146        tracing::debug!(path = %path.display(), "using the loaded game binary");
147        #[cfg(unix)]
148        let library = unsafe {
149            libloading::os::unix::Library::open(Some(&path), libc::RTLD_NOW | libc::RTLD_NOLOAD)
150                .map(Library::from)
151        };
152        #[cfg(windows)]
153        let library =
154            libloading::os::windows::Library::open_already_loaded(&path).map(Library::from);
155        Self::install(library.map_err(Error::Load)?)
156    }
157
158    /// Loads a game binary into this process, e.g. to run a game's code without Unity.
159    pub fn load(path: impl AsRef<Path>) -> Result<&'static Il2Cpp> {
160        if let Some(il2cpp) = INSTANCE.get() {
161            return Ok(il2cpp);
162        }
163        check_format(path.as_ref())?;
164        tracing::debug!(path = %path.as_ref().display(), "loading the game binary");
165        let library = unsafe { Library::new(path.as_ref()) }.map_err(Error::Load)?;
166        Self::install(library)
167    }
168
169    /// The instance set up by [`Il2Cpp::loaded`] or [`Il2Cpp::load`].
170    pub fn get() -> Option<&'static Il2Cpp> {
171        INSTANCE.get()
172    }
173
174    pub fn api(&self) -> &Api {
175        &self.api
176    }
177
178    /// Starts the runtime without Unity, given the game's `<Game>_Data/il2cpp_data` folder.
179    /// Only the game's pure .NET code can run this way; anything calling into Unity will fail.
180    pub fn init_standalone(&self, data_dir: impl AsRef<Path>) -> Result<()> {
181        tracing::debug!(data_dir = %data_dir.as_ref().display(), "starting Il2Cpp without Unity");
182        let data_dir = cstring(&data_dir.as_ref().to_string_lossy())?;
183        unsafe {
184            (self.api.il2cpp_set_data_dir)(data_dir.as_ptr());
185            if (self.api.il2cpp_init)(c"hao".as_ptr()) == 0 {
186                return Err(Error::Init);
187            }
188        }
189        Ok(())
190    }
191
192    /// Lets the calling thread run managed code. Needed on threads the game didn't start.
193    pub fn attach_thread(&self) {
194        unsafe { (self.api.il2cpp_thread_attach)((self.api.il2cpp_domain_get)()) };
195    }
196
197    /// Finds a class, e.g. `class("Assembly-CSharp", "Game.Player", "Health")`.
198    pub fn class(&'static self, assembly: &str, namespace: &str, name: &str) -> Result<Class> {
199        let (assembly_c, namespace_c, name_c) =
200            (cstring(assembly)?, cstring(namespace)?, cstring(name)?);
201        let class = unsafe {
202            let domain = (self.api.il2cpp_domain_get)();
203            let opened = (self.api.il2cpp_domain_assembly_open)(domain, assembly_c.as_ptr());
204            if opened.is_null() {
205                return Err(Error::NotFound(format!("assembly {}", assembly)));
206            }
207            let image = (self.api.il2cpp_assembly_get_image)(opened);
208            (self.api.il2cpp_class_from_name)(image, namespace_c.as_ptr(), name_c.as_ptr())
209        };
210        if class.is_null() {
211            return Err(Error::NotFound(format!(
212                "class {}.{} in {}",
213                namespace, name, assembly
214            )));
215        }
216        tracing::trace!(assembly, namespace, name, "found class");
217        Ok(Class {
218            il2cpp: self,
219            ptr: class,
220        })
221    }
222
223    /// Finds a live method by the metadata `token` that `hao-il2cpp` emits as a
224    /// proxy's identity (and that `hao_il2cpp::Binary::method_pointer` maps to a
225    /// static code address offline). This is the online mirror: `(image, token)`
226    /// to a live `MethodInfo` you can [`Method::call`](crate::Method::call) or
227    /// [`Method::hook`](crate::Method::hook).
228    ///
229    /// `image_name` is matched with or without a `.dll` suffix (il2cpp reports
230    /// image names like `Assembly-CSharp.dll`). The image is opened on demand,
231    /// then its methods are scanned for a matching [`Method::token`].
232    pub fn method(&'static self, image_name: &str, token: u32) -> Result<Method> {
233        let assembly = cstring(image_name.strip_suffix(".dll").unwrap_or(image_name))?;
234        let image = unsafe {
235            let domain = (self.api.il2cpp_domain_get)();
236            let opened = (self.api.il2cpp_domain_assembly_open)(domain, assembly.as_ptr());
237            if opened.is_null() {
238                return Err(Error::NotFound(format!("assembly {image_name}")));
239            }
240            Image {
241                il2cpp: self,
242                ptr: (self.api.il2cpp_assembly_get_image)(opened),
243            }
244        };
245        for class in image.classes() {
246            if let Some(method) = class.methods().find(|m| m.token() == token) {
247                tracing::trace!(image = image_name, token, class = class.name(), "found method by token");
248                return Ok(method);
249            }
250        }
251        Err(Error::NotFound(format!(
252            "method with token {token:#x} in {image_name}"
253        )))
254    }
255
256    /// A new managed string.
257    pub fn string(&self, value: &str) -> Result<Il2CppString> {
258        let value = cstring(value)?;
259        Ok(Il2CppString(Object(unsafe {
260            (self.api.il2cpp_string_new)(value.as_ptr())
261        })))
262    }
263
264    /// A new managed `byte[]` holding a copy of `bytes`, e.g. to pass to
265    /// `Texture2D.LoadRawTextureData`.
266    pub fn byte_array(&'static self, bytes: &[u8]) -> Result<Object> {
267        let class = self.class("mscorlib", "System", "Byte")?;
268        let array = unsafe { (self.api.il2cpp_array_new)(class.as_ptr(), bytes.len()) };
269        if array.is_null() {
270            return Err(Error::NotFound("could not allocate a byte[]".into()));
271        }
272        // Array elements follow the header (object header, bounds, length): 4 pointers.
273        let base = 4 * std::mem::size_of::<usize>();
274        unsafe {
275            std::ptr::copy_nonoverlapping(bytes.as_ptr(), (array as *mut u8).add(base), bytes.len());
276        }
277        Ok(Object(array))
278    }
279
280    /// Reads a managed string, `None` for null.
281    ///
282    /// # Safety
283    /// `string` must be null or a live `System.String`.
284    pub unsafe fn read_string(&self, string: Object) -> Option<String> {
285        if string.is_null() {
286            return None;
287        }
288        unsafe {
289            let length = (self.api.il2cpp_string_length)(string.0).max(0) as usize;
290            let chars =
291                std::slice::from_raw_parts((self.api.il2cpp_string_chars)(string.0), length);
292            Some(String::from_utf16_lossy(chars))
293        }
294    }
295
296    /// Every assembly loaded in the current domain.
297    pub fn assemblies(&'static self) -> Vec<Image> {
298        let mut count: usize = 0;
299        let domain = unsafe { (self.api.il2cpp_domain_get)() };
300        let array = unsafe { (self.api.il2cpp_domain_get_assemblies)(domain, &mut count) };
301        if array.is_null() || count == 0 {
302            return Vec::new();
303        }
304        let ptrs = unsafe { std::slice::from_raw_parts(array, count) };
305        ptrs.iter()
306            .map(|&asm| {
307                let image = unsafe { (self.api.il2cpp_assembly_get_image)(asm) };
308                Image {
309                    il2cpp: self,
310                    ptr: image,
311                }
312            })
313            .collect()
314    }
315
316    /// The class of a managed object.
317    ///
318    /// # Safety
319    /// `object` must be a live managed object.
320    pub unsafe fn class_of(&'static self, object: Object) -> Class {
321        Class {
322            il2cpp: self,
323            ptr: unsafe { (self.api.il2cpp_object_get_class)(object.0) },
324        }
325    }
326
327    /// Extracts a human-readable message from a managed exception object by
328    /// calling its `ToString()` method. Falls back to the class name if
329    /// `ToString()` fails.
330    ///
331    /// # Safety
332    /// `exception` must be a non-null, live managed exception object.
333    pub unsafe fn exception_message(&self, exception: Ptr) -> String {
334        let cls = (self.api.il2cpp_object_get_class)(exception);
335        let class_name = if cls.is_null() {
336            "UnknownException"
337        } else {
338            c_str((self.api.il2cpp_class_get_name)(cls))
339        };
340
341        if !cls.is_null() {
342            if let Ok(to_string) = cstring("ToString") {
343                let method = (self.api.il2cpp_class_get_method_from_name)(
344                    cls,
345                    to_string.as_ptr(),
346                    0,
347                );
348                if !method.is_null() {
349                    let mut nested: Ptr = std::ptr::null_mut();
350                    let str_obj = (self.api.il2cpp_runtime_invoke)(
351                        method,
352                        exception,
353                        std::ptr::null_mut(),
354                        &mut nested,
355                    );
356                    if nested.is_null() && !str_obj.is_null() {
357                        if let Some(s) = self.read_string(Object(str_obj)) {
358                            return s;
359                        }
360                    }
361                }
362            }
363        }
364
365        format!("{class_name} (could not read exception message)")
366    }
367}
368
369/// A managed class (`Il2CppClass*`).
370#[derive(Clone, Copy)]
371pub struct Class {
372    il2cpp: &'static Il2Cpp,
373    ptr: Ptr,
374}
375
376unsafe impl Send for Class {}
377unsafe impl Sync for Class {}
378
379impl Class {
380    pub fn as_ptr(&self) -> Ptr {
381        self.ptr
382    }
383
384    pub fn name(&self) -> &'static str {
385        unsafe { c_str((self.il2cpp.api.il2cpp_class_get_name)(self.ptr)) }
386    }
387
388    pub fn namespace(&self) -> &'static str {
389        unsafe { c_str((self.il2cpp.api.il2cpp_class_get_namespace)(self.ptr)) }
390    }
391
392    /// Finds a method by name and parameter count (`-1` for any).
393    pub fn method(&self, name: &str, parameter_count: i32) -> Result<Method> {
394        let c_name = cstring(name)?;
395        let method = unsafe {
396            (self.il2cpp.api.il2cpp_class_get_method_from_name)(
397                self.ptr,
398                c_name.as_ptr(),
399                parameter_count,
400            )
401        };
402        if method.is_null() {
403            return Err(Error::NotFound(format!(
404                "method {}.{}({} parameters)",
405                self.name(),
406                name,
407                parameter_count
408            )));
409        }
410        tracing::trace!(class = self.name(), name, parameter_count, "found method");
411        Ok(Method {
412            il2cpp: self.il2cpp,
413            ptr: method,
414        })
415    }
416
417    /// Allocates an object of this class without running a constructor; call
418    /// `.ctor` on it with [`Method::call`].
419    pub fn new_object(&self) -> Object {
420        Object(unsafe { (self.il2cpp.api.il2cpp_object_new)(self.ptr) })
421    }
422
423    /// The class's `System.Type`, as `typeof` gives it.
424    pub fn type_object(&self) -> Object {
425        Object(unsafe {
426            (self.il2cpp.api.il2cpp_type_get_object)((self.il2cpp.api.il2cpp_class_get_type)(
427                self.ptr,
428            ))
429        })
430    }
431
432    /// Every method declared by the class, e.g. to pick an overload by [`Method::signature`].
433    pub fn methods(&self) -> impl Iterator<Item = Method> + '_ {
434        let mut iter: Ptr = std::ptr::null_mut();
435        std::iter::from_fn(move || {
436            let method = unsafe { (self.il2cpp.api.il2cpp_class_get_methods)(self.ptr, &mut iter) };
437            (!method.is_null()).then_some(Method {
438                il2cpp: self.il2cpp,
439                ptr: method,
440            })
441        })
442    }
443
444    /// A field by name, with its type, offset and whether it is static.
445    pub fn field(&self, name: &str) -> Result<Field> {
446        let c_name = cstring(name)?;
447        let field = unsafe {
448            (self.il2cpp.api.il2cpp_class_get_field_from_name)(self.ptr, c_name.as_ptr())
449        };
450        if field.is_null() {
451            return Err(Error::NotFound(format!("field {}.{}", self.name(), name)));
452        }
453        Ok(Field {
454            il2cpp: self.il2cpp,
455            ptr: field,
456        })
457    }
458
459    /// Every field declared by the class.
460    pub fn fields(&self) -> impl Iterator<Item = Field> + '_ {
461        let mut iter: Ptr = std::ptr::null_mut();
462        std::iter::from_fn(move || {
463            let field = unsafe { (self.il2cpp.api.il2cpp_class_get_fields)(self.ptr, &mut iter) };
464            (!field.is_null()).then_some(Field {
465                il2cpp: self.il2cpp,
466                ptr: field,
467            })
468        })
469    }
470
471    /// The byte offset of an instance field from the start of an object.
472    pub fn field_offset(&self, name: &str) -> Result<usize> {
473        Ok(self.field(name)?.offset())
474    }
475}
476
477/// A loaded assembly image, containing classes.
478#[derive(Clone, Copy)]
479pub struct Image {
480    il2cpp: &'static Il2Cpp,
481    ptr: Ptr,
482}
483
484unsafe impl Send for Image {}
485unsafe impl Sync for Image {}
486
487impl Image {
488    pub fn name(&self) -> &'static str {
489        unsafe { c_str((self.il2cpp.api.il2cpp_image_get_name)(self.ptr)) }
490    }
491
492    pub fn class_count(&self) -> usize {
493        unsafe { (self.il2cpp.api.il2cpp_image_get_class_count)(self.ptr) }
494    }
495
496    pub fn classes(&self) -> impl Iterator<Item = Class> + '_ {
497        let count = self.class_count();
498        (0..count).map(move |i| {
499            let ptr = unsafe { (self.il2cpp.api.il2cpp_image_get_class)(self.ptr, i) };
500            Class {
501                il2cpp: self.il2cpp,
502                ptr,
503            }
504        })
505    }
506}
507
508/// A managed field (`FieldInfo*`).
509#[derive(Clone, Copy)]
510pub struct Field {
511    il2cpp: &'static Il2Cpp,
512    ptr: Ptr,
513}
514
515unsafe impl Send for Field {}
516unsafe impl Sync for Field {}
517
518/// `FIELD_ATTRIBUTE_STATIC` in the field's flags.
519const FIELD_STATIC: i32 = 0x0010;
520
521impl Field {
522    pub fn as_ptr(&self) -> Ptr {
523        self.ptr
524    }
525
526    pub fn name(&self) -> &'static str {
527        unsafe { c_str((self.il2cpp.api.il2cpp_field_get_name)(self.ptr)) }
528    }
529
530    /// The managed type name, e.g. `System.Single`.
531    pub fn type_name(&self) -> String {
532        let ty = unsafe { (self.il2cpp.api.il2cpp_field_get_type)(self.ptr) };
533        unsafe { c_str((self.il2cpp.api.il2cpp_type_get_name)(ty)) }.to_owned()
534    }
535
536    /// The byte offset from the start of an object (for instance fields), with
537    /// [`read_field`]/[`write_field`].
538    pub fn offset(&self) -> usize {
539        unsafe { (self.il2cpp.api.il2cpp_field_get_offset)(self.ptr) }
540    }
541
542    pub fn is_static(&self) -> bool {
543        unsafe { (self.il2cpp.api.il2cpp_field_get_flags)(self.ptr) & FIELD_STATIC != 0 }
544    }
545
546    pub fn element_type(&self) -> typed::ElementType {
547        let ty = unsafe { (self.il2cpp.api.il2cpp_field_get_type)(self.ptr) };
548        let raw = unsafe { (self.il2cpp.api.il2cpp_type_get_type)(ty) };
549        typed::ElementType::from(raw)
550    }
551
552    /// Reads this instance field's value from `object`.
553    ///
554    /// # Safety
555    /// `T` must match the field's layout, and `object` must be an instance of
556    /// the field's class.
557    pub unsafe fn read<T: Copy>(&self, object: Object) -> T {
558        unsafe { read_field(object, self.offset()) }
559    }
560
561    /// Writes this instance field's value on `object`.
562    ///
563    /// # Safety
564    /// As for [`Field::read`].
565    pub unsafe fn write<T: Copy>(&self, object: Object, value: T) {
566        unsafe { write_field(object, self.offset(), value) }
567    }
568}
569
570/// Keeps an object alive and findable after the garbage collector moves or
571/// would free it. The collector doesn't scan Rust memory, so objects kept
572/// between calls (in statics or closures) need one. Freed on drop.
573pub struct GcHandle {
574    il2cpp: &'static Il2Cpp,
575    handle: Ptr,
576}
577
578unsafe impl Send for GcHandle {}
579unsafe impl Sync for GcHandle {}
580
581impl GcHandle {
582    pub fn new(il2cpp: &'static Il2Cpp, object: Object) -> Self {
583        Self {
584            il2cpp,
585            handle: unsafe { (il2cpp.api.il2cpp_gchandle_new)(object.0, false) },
586        }
587    }
588
589    pub fn target(&self) -> Object {
590        Object(unsafe { (self.il2cpp.api.il2cpp_gchandle_get_target)(self.handle) })
591    }
592}
593
594impl Drop for GcHandle {
595    fn drop(&mut self) {
596        unsafe { (self.il2cpp.api.il2cpp_gchandle_free)(self.handle) }
597    }
598}
599
600/// A managed method (`MethodInfo*`).
601#[derive(Clone, Copy)]
602pub struct Method {
603    il2cpp: &'static Il2Cpp,
604    ptr: Ptr,
605}
606
607unsafe impl Send for Method {}
608unsafe impl Sync for Method {}
609
610impl Method {
611    /// The `MethodInfo*`, passed as the last argument when calling the method.
612    pub fn as_ptr(&self) -> MethodInfo {
613        self.ptr
614    }
615
616    pub fn name(&self) -> &'static str {
617        unsafe { c_str((self.il2cpp.api.il2cpp_method_get_name)(self.ptr)) }
618    }
619
620    /// This method's metadata token: the `MethodDef` token (`0x06`-prefixed) that
621    /// `hao-il2cpp` emits as a proxy's identity and `Binary::method_pointer` maps
622    /// to a static code address. Resolve a token back to a live method with
623    /// [`Il2Cpp::method`].
624    pub fn token(&self) -> u32 {
625        unsafe { (self.il2cpp.api.il2cpp_method_get_token)(self.ptr) }
626    }
627
628    /// The method's compiled code. Call it with the instance first (for instance
629    /// methods), then the arguments, then [`Method::as_ptr`].
630    pub fn code(&self) -> *mut c_void {
631        // `methodPointer` is the first field of `MethodInfo`.
632        unsafe { *(self.ptr as *const *mut c_void) }
633    }
634
635    /// Calls the method through `il2cpp_runtime_invoke`, which catches managed
636    /// exceptions. Each element of `args` is a pointer to the argument value
637    /// (for value types) or the object pointer itself (for reference types).
638    pub fn runtime_invoke(&self, this: Object, args: &mut [Ptr]) -> Result<Object> {
639        let args_ptr = if args.is_empty() {
640            std::ptr::null_mut()
641        } else {
642            args.as_mut_ptr()
643        };
644        let mut exception: Ptr = std::ptr::null_mut();
645        let result = unsafe {
646            (self.il2cpp.api.il2cpp_runtime_invoke)(
647                self.ptr,
648                this.0,
649                args_ptr as *mut Ptr,
650                &mut exception,
651            )
652        };
653        if !exception.is_null() {
654            let msg = unsafe { self.il2cpp.exception_message(exception) };
655            return Err(Error::Exception(msg));
656        }
657        Ok(Object(result))
658    }
659
660    /// Redirects every call of the method to `detour`, which has the method's
661    /// signature as described on [`Method::code`]. Inside the detour, [`original!`]
662    /// gets a function that calls the original code. [`Method::hook`] is the safe,
663    /// typed version of this.
664    ///
665    /// The hook stays in place when the returned value is dropped.
666    ///
667    /// # Safety
668    /// `detour` must be an `extern "C"` function with exactly the method's signature.
669    pub unsafe fn hook_raw(&self, detour: *mut u8) -> Result<MethodHook> {
670        let mut hook = unsafe { hooking::Hook::create(self.code() as *mut u8, detour) }
671            .map_err(Error::Hook)?;
672        unsafe { hook.apply_hook() }.map_err(Error::Hook)?;
673        tracing::debug!(method = self.name(), code = ?self.code(), "hooked (raw)");
674        Ok(MethodHook(hook))
675    }
676}
677
678/// An applied method hook. Dropping it leaves the hook in place.
679pub struct MethodHook(pub(crate) hooking::Hook<'static>);
680
681impl MethodHook {
682    pub fn remove(mut self) -> Result<()> {
683        unsafe { self.0.remove_hook() }.map_err(Error::Hook)?;
684        tracing::debug!(code = ?self.0.data.symbol_address, "removed hook");
685        Ok(())
686    }
687}
688
689pub use typed::{ElementType, VoidBlockHook};
690#[cfg(target_arch = "x86_64")]
691pub use typed::{GenericHookMeta, GenericParam, ParamSlot};
692
693/// Reads a managed object's field at `offset` (from [`Class::field_offset`]).
694///
695/// # Safety
696/// `object` must be a live object with a field of type `T` at `offset`.
697pub unsafe fn read_field<T: Copy>(object: Object, offset: usize) -> T {
698    unsafe { std::ptr::read_unaligned((object.0 as *const u8).add(offset) as *const T) }
699}
700
701/// Writes a managed object's field at `offset`. Only for fields that don't hold references.
702///
703/// # Safety
704/// `object` must be a live object with a field of type `T` at `offset`.
705pub unsafe fn write_field<T: Copy>(object: Object, offset: usize, value: T) {
706    unsafe { std::ptr::write_unaligned((object.0 as *mut u8).add(offset) as *mut T, value) }
707}
708
709/// Inside a detour from [`Method::hook_raw`], gets the function that calls the
710/// original method. Must be the first thing the detour does.
711#[macro_export]
712macro_rules! original {
713    ($fn_type:ty) => {{
714        let original =
715            $crate::__original_function_ptr().expect("original! must be used inside a hook");
716        unsafe { ::core::mem::transmute::<*mut ::core::ffi::c_void, $fn_type>(original.as_ptr()) }
717    }};
718}
719
720#[doc(hidden)]
721pub use hooking::original_function_ptr as __original_function_ptr;
722
723#[cfg(test)]
724mod tests {
725    use super::*;
726
727    #[cfg(unix)]
728    #[test]
729    fn mapped_game_assembly_paths() {
730        for path in [
731            "/games/Example/GameAssembly.so",
732            "/games/Idle Slayer/GameAssembly.so",
733        ] {
734            let maps = format!(
735                "1000-2000 r-xp 00000000 08:01 1 /games/Idle Slayer/UnityPlayer.so\n\
736                 2000-3000 r-xp 00000000 08:01 2 {path}\n"
737            );
738            assert_eq!(game_assembly_in_maps(&maps), Some(PathBuf::from(path)));
739        }
740    }
741
742    #[cfg(unix)]
743    #[test]
744    fn maps_without_game_assembly() {
745        let maps = "1000-2000 r-xp 00000000 08:01 1 /games/Example/UnityPlayer.so\n\
746                    2000-3000 rw-p 00000000 00:00 0 [heap]\n\
747                    3000-4000 rw-p 00000000 00:00 0\n";
748        assert_eq!(game_assembly_in_maps(maps), None);
749        assert_eq!(game_assembly_in_maps(""), None);
750    }
751
752    #[test]
753    fn game_assembly_names() {
754        assert!(is_game_assembly("/games/Example/GameAssembly.so"));
755        assert!(is_game_assembly("C:\\Games\\Example\\GameAssembly.dll"));
756        assert!(!is_game_assembly("/games/Example/UnityPlayer.so"));
757        assert!(!is_game_assembly("/games/Example/NotGameAssembly.dll"));
758    }
759
760    #[test]
761    fn finds_and_checks_the_game_binary() {
762        let dir = std::env::temp_dir().join(format!("hao-il2cpp-runtime-{}", std::process::id()));
763        std::fs::create_dir_all(&dir).unwrap();
764        std::fs::write(dir.join("UnityPlayer.dll"), b"MZ\x90\x00").unwrap();
765        std::fs::write(dir.join("GameAssembly.dll"), b"MZ\x90\x00").unwrap();
766        let found = find_game_assembly(&dir).unwrap();
767        assert_eq!(found, dir.join("GameAssembly.dll"));
768        if cfg!(unix) {
769            assert!(matches!(
770                check_format(&found),
771                Err(Error::UnsupportedBinary(_))
772            ));
773        }
774        std::fs::remove_dir_all(dir).unwrap();
775    }
776}