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