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