hao-il2cpp-runtime 0.0.6

Hook and call into Unity Il2Cpp games from inside the game process
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
//! Hook and call into a Unity Il2Cpp game from inside its process, the way
//! MelonLoader mods do.
//!
//! A mod is a `cdylib` loaded into the game (on Linux with `LD_PRELOAD`).
//! [`on_init`] runs once the game's Il2Cpp runtime has started, and from there
//! methods are found by name and hooked with ordinary closures. The closure's
//! types are checked against the method's real signature when the hook is
//! installed:
//!
//! ```no_run
//! use hao_il2cpp_runtime::{Il2Cpp, Object, Original};
//!
//! hao_il2cpp_runtime::on_init(|il2cpp: &'static Il2Cpp| {
//!     let health = il2cpp.class("Assembly-CSharp", "Assets.Scripts.Inventory__Items__Pickups", "PlayerHealth")?;
//!     // `int Heal(float amount, bool allowOverheal)`: the instance comes first.
//!     health.method("Heal", 2)?.hook(|this: Object, amount: f32, overheal: bool, original: Original<_, i32>| {
//!         original.call((this, amount * 2.0, overheal))
//!     })?;
//!     Ok(())
//! });
//! ```

mod api;
mod error;
#[cfg(unix)]
mod loader;
mod typed;
#[cfg(feature = "reflect")]
pub mod reflect;

use std::{
    ffi::{c_void, CStr, CString},
    path::{Path, PathBuf},
    sync::OnceLock,
};

use libloading::Library;

pub use api::{Api, Ptr};
pub use error::{Error, Result};
#[cfg(unix)]
pub use loader::on_init;
pub use typed::{
    element, HookCallback, Il2CppString, Il2CppValue, MethodArgs, Object, Original, Parameter,
    Signature, TypeInfo, ValueCheck,
};

/// The hidden last argument of every Il2Cpp method (`const MethodInfo*`).
pub type MethodInfo = Ptr;

/// Whether `path` is a game binary: `GameAssembly.so`, `GameAssembly.dll` or any other `GameAssembly.*`.
/// Both `/` and `\\` separate directories, as Windows paths can show up on Linux under Wine.
pub fn is_game_assembly(path: impl AsRef<Path>) -> bool {
    let path = path.as_ref().to_string_lossy();
    path.rsplit(['/', '\\'])
        .next()
        .is_some_and(|name| name.starts_with("GameAssembly."))
}

/// The game binary in a game folder, whichever platform the game was built for.
pub fn find_game_assembly(dir: impl AsRef<Path>) -> Option<PathBuf> {
    std::fs::read_dir(dir)
        .ok()?
        .filter_map(|e| e.ok().map(|e| e.path()))
        .find(|p| p.is_file() && is_game_assembly(p))
}

/// The game binary mapped into this process, if any.
#[cfg(unix)]
pub fn loaded_game_assembly() -> Option<PathBuf> {
    let maps = std::fs::read_to_string("/proc/self/maps").ok()?;
    game_assembly_in_maps(&maps)
}

#[cfg(unix)]
fn game_assembly_in_maps(maps: &str) -> Option<PathBuf> {
    maps.lines()
        // /proc maps preserves whitespace inside absolute paths.
        .filter_map(|line| line.find('/').map(|start| &line[start..]))
        .map(PathBuf::from)
        .find(|p| is_game_assembly(p))
}

/// The game binary mapped into this process, if any.
#[cfg(windows)]
pub fn loaded_game_assembly() -> Option<PathBuf> {
    libloading::os::windows::Library::open_already_loaded("GameAssembly.dll")
        .ok()
        .map(|_| PathBuf::from("GameAssembly.dll"))
}

/// Errors unless `path` is a binary this build can load: ELF on Unix, PE on Windows.
fn check_format(path: &Path) -> Result<()> {
    use std::io::Read;
    let mut magic = [0u8; 4];
    let read = std::fs::File::open(path).and_then(|mut f| f.read_exact(&mut magic));
    let (elf, pe) = (magic == *b"\x7fELF", magic.starts_with(b"MZ"));
    match read {
        Ok(()) if cfg!(unix) && pe => Err(Error::UnsupportedBinary(format!(
            "{} is a Windows binary (a Windows build running under Wine/Proton), which a Linux mod can't load yet",
            path.display()
        ))),
        Ok(()) if cfg!(windows) && elf => Err(Error::UnsupportedBinary(format!("{} is not a Windows binary", path.display()))),
        _ => Ok(()),
    }
}

static INSTANCE: OnceLock<Il2Cpp> = OnceLock::new();

/// The game's Il2Cpp runtime.
pub struct Il2Cpp {
    api: Api,
    _library: Library,
}

fn cstring(value: &str) -> Result<CString> {
    CString::new(value).map_err(|_| Error::Nul(value.to_owned()))
}

pub(crate) unsafe fn c_str<'a>(value: *const std::ffi::c_char) -> &'a str {
    if value.is_null() {
        ""
    } else {
        unsafe { CStr::from_ptr(value) }.to_str().unwrap_or("")
    }
}

impl Il2Cpp {
    fn install(library: Library) -> Result<&'static Il2Cpp> {
        let api = Api::load(&library)?;
        tracing::debug!("loaded the il2cpp_* API from the game binary");
        Ok(INSTANCE.get_or_init(|| Il2Cpp {
            api,
            _library: library,
        }))
    }

    /// The runtime of the game binary already loaded in this process.
    pub fn loaded() -> Result<&'static Il2Cpp> {
        if let Some(il2cpp) = INSTANCE.get() {
            return Ok(il2cpp);
        }
        let path = loaded_game_assembly()
            .ok_or_else(|| Error::NotFound("a loaded GameAssembly".into()))?;
        check_format(&path)?;
        tracing::debug!(path = %path.display(), "using the loaded game binary");
        #[cfg(unix)]
        let library = unsafe {
            libloading::os::unix::Library::open(Some(&path), libc::RTLD_NOW | libc::RTLD_NOLOAD)
                .map(Library::from)
        };
        #[cfg(windows)]
        let library =
            libloading::os::windows::Library::open_already_loaded(&path).map(Library::from);
        Self::install(library.map_err(Error::Load)?)
    }

    /// Loads a game binary into this process, e.g. to run a game's code without Unity.
    pub fn load(path: impl AsRef<Path>) -> Result<&'static Il2Cpp> {
        if let Some(il2cpp) = INSTANCE.get() {
            return Ok(il2cpp);
        }
        check_format(path.as_ref())?;
        tracing::debug!(path = %path.as_ref().display(), "loading the game binary");
        let library = unsafe { Library::new(path.as_ref()) }.map_err(Error::Load)?;
        Self::install(library)
    }

    /// The instance set up by [`Il2Cpp::loaded`] or [`Il2Cpp::load`].
    pub fn get() -> Option<&'static Il2Cpp> {
        INSTANCE.get()
    }

    pub fn api(&self) -> &Api {
        &self.api
    }

    /// Starts the runtime without Unity, given the game's `<Game>_Data/il2cpp_data` folder.
    /// Only the game's pure .NET code can run this way; anything calling into Unity will fail.
    pub fn init_standalone(&self, data_dir: impl AsRef<Path>) -> Result<()> {
        tracing::debug!(data_dir = %data_dir.as_ref().display(), "starting Il2Cpp without Unity");
        let data_dir = cstring(&data_dir.as_ref().to_string_lossy())?;
        unsafe {
            (self.api.il2cpp_set_data_dir)(data_dir.as_ptr());
            if (self.api.il2cpp_init)(c"hao".as_ptr()) == 0 {
                return Err(Error::Init);
            }
        }
        Ok(())
    }

    /// Lets the calling thread run managed code. Needed on threads the game didn't start.
    pub fn attach_thread(&self) {
        unsafe { (self.api.il2cpp_thread_attach)((self.api.il2cpp_domain_get)()) };
    }

    /// Finds a class, e.g. `class("Assembly-CSharp", "Game.Player", "Health")`.
    pub fn class(&'static self, assembly: &str, namespace: &str, name: &str) -> Result<Class> {
        let (assembly_c, namespace_c, name_c) =
            (cstring(assembly)?, cstring(namespace)?, cstring(name)?);
        let class = unsafe {
            let domain = (self.api.il2cpp_domain_get)();
            let opened = (self.api.il2cpp_domain_assembly_open)(domain, assembly_c.as_ptr());
            if opened.is_null() {
                return Err(Error::NotFound(format!("assembly {}", assembly)));
            }
            let image = (self.api.il2cpp_assembly_get_image)(opened);
            (self.api.il2cpp_class_from_name)(image, namespace_c.as_ptr(), name_c.as_ptr())
        };
        if class.is_null() {
            return Err(Error::NotFound(format!(
                "class {}.{} in {}",
                namespace, name, assembly
            )));
        }
        tracing::trace!(assembly, namespace, name, "found class");
        Ok(Class {
            il2cpp: self,
            ptr: class,
        })
    }

    /// Finds a live method by the metadata `token` that `hao-il2cpp` emits as a
    /// proxy's identity (and that `hao_il2cpp::Binary::method_pointer` maps to a
    /// static code address offline). This is the online mirror: `(image, token)`
    /// to a live `MethodInfo` you can [`Method::call`](crate::Method::call) or
    /// [`Method::hook`](crate::Method::hook).
    ///
    /// `image_name` is matched with or without a `.dll` suffix (il2cpp reports
    /// image names like `Assembly-CSharp.dll`). The image is opened on demand,
    /// then its methods are scanned for a matching [`Method::token`].
    pub fn method(&'static self, image_name: &str, token: u32) -> Result<Method> {
        let assembly = cstring(image_name.strip_suffix(".dll").unwrap_or(image_name))?;
        let image = unsafe {
            let domain = (self.api.il2cpp_domain_get)();
            let opened = (self.api.il2cpp_domain_assembly_open)(domain, assembly.as_ptr());
            if opened.is_null() {
                return Err(Error::NotFound(format!("assembly {image_name}")));
            }
            Image {
                il2cpp: self,
                ptr: (self.api.il2cpp_assembly_get_image)(opened),
            }
        };
        for class in image.classes() {
            if let Some(method) = class.methods().find(|m| m.token() == token) {
                tracing::trace!(image = image_name, token, class = class.name(), "found method by token");
                return Ok(method);
            }
        }
        Err(Error::NotFound(format!(
            "method with token {token:#x} in {image_name}"
        )))
    }

    /// A new managed string.
    pub fn string(&self, value: &str) -> Result<Il2CppString> {
        let value = cstring(value)?;
        Ok(Il2CppString(Object(unsafe {
            (self.api.il2cpp_string_new)(value.as_ptr())
        })))
    }

    /// A new managed `byte[]` holding a copy of `bytes`, e.g. to pass to
    /// `Texture2D.LoadRawTextureData`.
    pub fn byte_array(&'static self, bytes: &[u8]) -> Result<Object> {
        let class = self.class("mscorlib", "System", "Byte")?;
        let array = unsafe { (self.api.il2cpp_array_new)(class.as_ptr(), bytes.len()) };
        if array.is_null() {
            return Err(Error::NotFound("could not allocate a byte[]".into()));
        }
        // Array elements follow the header (object header, bounds, length): 4 pointers.
        let base = 4 * std::mem::size_of::<usize>();
        unsafe {
            std::ptr::copy_nonoverlapping(bytes.as_ptr(), (array as *mut u8).add(base), bytes.len());
        }
        Ok(Object(array))
    }

    /// Reads a managed string, `None` for null.
    ///
    /// # Safety
    /// `string` must be null or a live `System.String`.
    pub unsafe fn read_string(&self, string: Object) -> Option<String> {
        if string.is_null() {
            return None;
        }
        unsafe {
            let length = (self.api.il2cpp_string_length)(string.0).max(0) as usize;
            let chars =
                std::slice::from_raw_parts((self.api.il2cpp_string_chars)(string.0), length);
            Some(String::from_utf16_lossy(chars))
        }
    }

    /// Every assembly loaded in the current domain.
    pub fn assemblies(&'static self) -> Vec<Image> {
        let mut count: usize = 0;
        let domain = unsafe { (self.api.il2cpp_domain_get)() };
        let array = unsafe { (self.api.il2cpp_domain_get_assemblies)(domain, &mut count) };
        if array.is_null() || count == 0 {
            return Vec::new();
        }
        let ptrs = unsafe { std::slice::from_raw_parts(array, count) };
        ptrs.iter()
            .map(|&asm| {
                let image = unsafe { (self.api.il2cpp_assembly_get_image)(asm) };
                Image {
                    il2cpp: self,
                    ptr: image,
                }
            })
            .collect()
    }

    /// The class of a managed object.
    ///
    /// # Safety
    /// `object` must be a live managed object.
    pub unsafe fn class_of(&'static self, object: Object) -> Class {
        Class {
            il2cpp: self,
            ptr: unsafe { (self.api.il2cpp_object_get_class)(object.0) },
        }
    }

    /// Extracts a human-readable message from a managed exception object by
    /// calling its `ToString()` method. Falls back to the class name if
    /// `ToString()` fails.
    ///
    /// # Safety
    /// `exception` must be a non-null, live managed exception object.
    pub unsafe fn exception_message(&self, exception: Ptr) -> String {
        let cls = (self.api.il2cpp_object_get_class)(exception);
        let class_name = if cls.is_null() {
            "UnknownException"
        } else {
            c_str((self.api.il2cpp_class_get_name)(cls))
        };

        if !cls.is_null() {
            if let Ok(to_string) = cstring("ToString") {
                let method = (self.api.il2cpp_class_get_method_from_name)(
                    cls,
                    to_string.as_ptr(),
                    0,
                );
                if !method.is_null() {
                    let mut nested: Ptr = std::ptr::null_mut();
                    let str_obj = (self.api.il2cpp_runtime_invoke)(
                        method,
                        exception,
                        std::ptr::null_mut(),
                        &mut nested,
                    );
                    if nested.is_null() && !str_obj.is_null() {
                        if let Some(s) = self.read_string(Object(str_obj)) {
                            return s;
                        }
                    }
                }
            }
        }

        format!("{class_name} (could not read exception message)")
    }
}

/// A managed class (`Il2CppClass*`).
#[derive(Clone, Copy)]
pub struct Class {
    il2cpp: &'static Il2Cpp,
    ptr: Ptr,
}

unsafe impl Send for Class {}
unsafe impl Sync for Class {}

impl Class {
    pub fn as_ptr(&self) -> Ptr {
        self.ptr
    }

    pub fn name(&self) -> &'static str {
        unsafe { c_str((self.il2cpp.api.il2cpp_class_get_name)(self.ptr)) }
    }

    pub fn namespace(&self) -> &'static str {
        unsafe { c_str((self.il2cpp.api.il2cpp_class_get_namespace)(self.ptr)) }
    }

    /// Finds a method by name and parameter count (`-1` for any).
    pub fn method(&self, name: &str, parameter_count: i32) -> Result<Method> {
        let c_name = cstring(name)?;
        let method = unsafe {
            (self.il2cpp.api.il2cpp_class_get_method_from_name)(
                self.ptr,
                c_name.as_ptr(),
                parameter_count,
            )
        };
        if method.is_null() {
            return Err(Error::NotFound(format!(
                "method {}.{}({} parameters)",
                self.name(),
                name,
                parameter_count
            )));
        }
        tracing::trace!(class = self.name(), name, parameter_count, "found method");
        Ok(Method {
            il2cpp: self.il2cpp,
            ptr: method,
        })
    }

    /// Allocates an object of this class without running a constructor; call
    /// `.ctor` on it with [`Method::call`].
    pub fn new_object(&self) -> Object {
        Object(unsafe { (self.il2cpp.api.il2cpp_object_new)(self.ptr) })
    }

    /// The class's `System.Type`, as `typeof` gives it.
    pub fn type_object(&self) -> Object {
        Object(unsafe {
            (self.il2cpp.api.il2cpp_type_get_object)((self.il2cpp.api.il2cpp_class_get_type)(
                self.ptr,
            ))
        })
    }

    /// Every method declared by the class, e.g. to pick an overload by [`Method::signature`].
    pub fn methods(&self) -> impl Iterator<Item = Method> + '_ {
        let mut iter: Ptr = std::ptr::null_mut();
        std::iter::from_fn(move || {
            let method = unsafe { (self.il2cpp.api.il2cpp_class_get_methods)(self.ptr, &mut iter) };
            (!method.is_null()).then_some(Method {
                il2cpp: self.il2cpp,
                ptr: method,
            })
        })
    }

    /// A field by name, with its type, offset and whether it is static.
    pub fn field(&self, name: &str) -> Result<Field> {
        let c_name = cstring(name)?;
        let field = unsafe {
            (self.il2cpp.api.il2cpp_class_get_field_from_name)(self.ptr, c_name.as_ptr())
        };
        if field.is_null() {
            return Err(Error::NotFound(format!("field {}.{}", self.name(), name)));
        }
        Ok(Field {
            il2cpp: self.il2cpp,
            ptr: field,
        })
    }

    /// Every field declared by the class.
    pub fn fields(&self) -> impl Iterator<Item = Field> + '_ {
        let mut iter: Ptr = std::ptr::null_mut();
        std::iter::from_fn(move || {
            let field = unsafe { (self.il2cpp.api.il2cpp_class_get_fields)(self.ptr, &mut iter) };
            (!field.is_null()).then_some(Field {
                il2cpp: self.il2cpp,
                ptr: field,
            })
        })
    }

    /// The byte offset of an instance field from the start of an object.
    pub fn field_offset(&self, name: &str) -> Result<usize> {
        Ok(self.field(name)?.offset())
    }
}

/// A loaded assembly image, containing classes.
#[derive(Clone, Copy)]
pub struct Image {
    il2cpp: &'static Il2Cpp,
    ptr: Ptr,
}

unsafe impl Send for Image {}
unsafe impl Sync for Image {}

impl Image {
    pub fn name(&self) -> &'static str {
        unsafe { c_str((self.il2cpp.api.il2cpp_image_get_name)(self.ptr)) }
    }

    pub fn class_count(&self) -> usize {
        unsafe { (self.il2cpp.api.il2cpp_image_get_class_count)(self.ptr) }
    }

    pub fn classes(&self) -> impl Iterator<Item = Class> + '_ {
        let count = self.class_count();
        (0..count).map(move |i| {
            let ptr = unsafe { (self.il2cpp.api.il2cpp_image_get_class)(self.ptr, i) };
            Class {
                il2cpp: self.il2cpp,
                ptr,
            }
        })
    }
}

/// A managed field (`FieldInfo*`).
#[derive(Clone, Copy)]
pub struct Field {
    il2cpp: &'static Il2Cpp,
    ptr: Ptr,
}

unsafe impl Send for Field {}
unsafe impl Sync for Field {}

/// `FIELD_ATTRIBUTE_STATIC` in the field's flags.
const FIELD_STATIC: i32 = 0x0010;

impl Field {
    pub fn as_ptr(&self) -> Ptr {
        self.ptr
    }

    pub fn name(&self) -> &'static str {
        unsafe { c_str((self.il2cpp.api.il2cpp_field_get_name)(self.ptr)) }
    }

    /// The managed type name, e.g. `System.Single`.
    pub fn type_name(&self) -> String {
        let ty = unsafe { (self.il2cpp.api.il2cpp_field_get_type)(self.ptr) };
        unsafe { c_str((self.il2cpp.api.il2cpp_type_get_name)(ty)) }.to_owned()
    }

    /// The byte offset from the start of an object (for instance fields), with
    /// [`read_field`]/[`write_field`].
    pub fn offset(&self) -> usize {
        unsafe { (self.il2cpp.api.il2cpp_field_get_offset)(self.ptr) }
    }

    pub fn is_static(&self) -> bool {
        unsafe { (self.il2cpp.api.il2cpp_field_get_flags)(self.ptr) & FIELD_STATIC != 0 }
    }

    pub fn element_type(&self) -> typed::ElementType {
        let ty = unsafe { (self.il2cpp.api.il2cpp_field_get_type)(self.ptr) };
        let raw = unsafe { (self.il2cpp.api.il2cpp_type_get_type)(ty) };
        typed::ElementType::from(raw)
    }

    /// Reads this instance field's value from `object`.
    ///
    /// # Safety
    /// `T` must match the field's layout, and `object` must be an instance of
    /// the field's class.
    pub unsafe fn read<T: Copy>(&self, object: Object) -> T {
        unsafe { read_field(object, self.offset()) }
    }

    /// Writes this instance field's value on `object`.
    ///
    /// # Safety
    /// As for [`Field::read`].
    pub unsafe fn write<T: Copy>(&self, object: Object, value: T) {
        unsafe { write_field(object, self.offset(), value) }
    }
}

/// Keeps an object alive and findable after the garbage collector moves or
/// would free it. The collector doesn't scan Rust memory, so objects kept
/// between calls (in statics or closures) need one. Freed on drop.
pub struct GcHandle {
    il2cpp: &'static Il2Cpp,
    handle: Ptr,
}

unsafe impl Send for GcHandle {}
unsafe impl Sync for GcHandle {}

impl GcHandle {
    pub fn new(il2cpp: &'static Il2Cpp, object: Object) -> Self {
        Self {
            il2cpp,
            handle: unsafe { (il2cpp.api.il2cpp_gchandle_new)(object.0, false) },
        }
    }

    pub fn target(&self) -> Object {
        Object(unsafe { (self.il2cpp.api.il2cpp_gchandle_get_target)(self.handle) })
    }
}

impl Drop for GcHandle {
    fn drop(&mut self) {
        unsafe { (self.il2cpp.api.il2cpp_gchandle_free)(self.handle) }
    }
}

/// A managed method (`MethodInfo*`).
#[derive(Clone, Copy)]
pub struct Method {
    il2cpp: &'static Il2Cpp,
    ptr: Ptr,
}

unsafe impl Send for Method {}
unsafe impl Sync for Method {}

impl Method {
    /// The `MethodInfo*`, passed as the last argument when calling the method.
    pub fn as_ptr(&self) -> MethodInfo {
        self.ptr
    }

    pub fn name(&self) -> &'static str {
        unsafe { c_str((self.il2cpp.api.il2cpp_method_get_name)(self.ptr)) }
    }

    /// This method's metadata token: the `MethodDef` token (`0x06`-prefixed) that
    /// `hao-il2cpp` emits as a proxy's identity and `Binary::method_pointer` maps
    /// to a static code address. Resolve a token back to a live method with
    /// [`Il2Cpp::method`].
    pub fn token(&self) -> u32 {
        unsafe { (self.il2cpp.api.il2cpp_method_get_token)(self.ptr) }
    }

    /// The method's compiled code. Call it with the instance first (for instance
    /// methods), then the arguments, then [`Method::as_ptr`].
    pub fn code(&self) -> *mut c_void {
        // `methodPointer` is the first field of `MethodInfo`.
        unsafe { *(self.ptr as *const *mut c_void) }
    }

    /// Calls the method through `il2cpp_runtime_invoke`, which catches managed
    /// exceptions. Each element of `args` is a pointer to the argument value
    /// (for value types) or the object pointer itself (for reference types).
    pub fn runtime_invoke(&self, this: Object, args: &mut [Ptr]) -> Result<Object> {
        let args_ptr = if args.is_empty() {
            std::ptr::null_mut()
        } else {
            args.as_mut_ptr()
        };
        let mut exception: Ptr = std::ptr::null_mut();
        let result = unsafe {
            (self.il2cpp.api.il2cpp_runtime_invoke)(
                self.ptr,
                this.0,
                args_ptr as *mut Ptr,
                &mut exception,
            )
        };
        if !exception.is_null() {
            let msg = unsafe { self.il2cpp.exception_message(exception) };
            return Err(Error::Exception(msg));
        }
        Ok(Object(result))
    }

    /// Redirects every call of the method to `detour`, which has the method's
    /// signature as described on [`Method::code`]. Inside the detour, [`original!`]
    /// gets a function that calls the original code. [`Method::hook`] is the safe,
    /// typed version of this.
    ///
    /// The hook stays in place when the returned value is dropped.
    ///
    /// # Safety
    /// `detour` must be an `extern "C"` function with exactly the method's signature.
    pub unsafe fn hook_raw(&self, detour: *mut u8) -> Result<MethodHook> {
        let mut hook = unsafe { hooking::Hook::create(self.code() as *mut u8, detour) }
            .map_err(Error::Hook)?;
        unsafe { hook.apply_hook() }.map_err(Error::Hook)?;
        tracing::debug!(method = self.name(), code = ?self.code(), "hooked (raw)");
        Ok(MethodHook(hook))
    }
}

/// An applied method hook. Dropping it leaves the hook in place.
pub struct MethodHook(pub(crate) hooking::Hook<'static>);

impl MethodHook {
    pub fn remove(mut self) -> Result<()> {
        unsafe { self.0.remove_hook() }.map_err(Error::Hook)?;
        tracing::debug!(code = ?self.0.data.symbol_address, "removed hook");
        Ok(())
    }
}

pub use typed::{ElementType, VoidBlockHook};
#[cfg(target_arch = "x86_64")]
pub use typed::{GenericHookMeta, GenericParam, ParamSlot};

/// Reads a managed object's field at `offset` (from [`Class::field_offset`]).
///
/// # Safety
/// `object` must be a live object with a field of type `T` at `offset`.
pub unsafe fn read_field<T: Copy>(object: Object, offset: usize) -> T {
    unsafe { std::ptr::read_unaligned((object.0 as *const u8).add(offset) as *const T) }
}

/// Writes a managed object's field at `offset`. Only for fields that don't hold references.
///
/// # Safety
/// `object` must be a live object with a field of type `T` at `offset`.
pub unsafe fn write_field<T: Copy>(object: Object, offset: usize, value: T) {
    unsafe { std::ptr::write_unaligned((object.0 as *mut u8).add(offset) as *mut T, value) }
}

/// Inside a detour from [`Method::hook_raw`], gets the function that calls the
/// original method. Must be the first thing the detour does.
#[macro_export]
macro_rules! original {
    ($fn_type:ty) => {{
        let original =
            $crate::__original_function_ptr().expect("original! must be used inside a hook");
        unsafe { ::core::mem::transmute::<*mut ::core::ffi::c_void, $fn_type>(original.as_ptr()) }
    }};
}

#[doc(hidden)]
pub use hooking::original_function_ptr as __original_function_ptr;

#[cfg(test)]
mod tests {
    use super::*;

    #[cfg(unix)]
    #[test]
    fn mapped_game_assembly_paths() {
        for path in [
            "/games/Example/GameAssembly.so",
            "/games/Idle Slayer/GameAssembly.so",
        ] {
            let maps = format!(
                "1000-2000 r-xp 00000000 08:01 1 /games/Idle Slayer/UnityPlayer.so\n\
                 2000-3000 r-xp 00000000 08:01 2 {path}\n"
            );
            assert_eq!(game_assembly_in_maps(&maps), Some(PathBuf::from(path)));
        }
    }

    #[cfg(unix)]
    #[test]
    fn maps_without_game_assembly() {
        let maps = "1000-2000 r-xp 00000000 08:01 1 /games/Example/UnityPlayer.so\n\
                    2000-3000 rw-p 00000000 00:00 0 [heap]\n\
                    3000-4000 rw-p 00000000 00:00 0\n";
        assert_eq!(game_assembly_in_maps(maps), None);
        assert_eq!(game_assembly_in_maps(""), None);
    }

    #[test]
    fn game_assembly_names() {
        assert!(is_game_assembly("/games/Example/GameAssembly.so"));
        assert!(is_game_assembly("C:\\Games\\Example\\GameAssembly.dll"));
        assert!(!is_game_assembly("/games/Example/UnityPlayer.so"));
        assert!(!is_game_assembly("/games/Example/NotGameAssembly.dll"));
    }

    #[test]
    fn finds_and_checks_the_game_binary() {
        let dir = std::env::temp_dir().join(format!("hao-il2cpp-runtime-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("UnityPlayer.dll"), b"MZ\x90\x00").unwrap();
        std::fs::write(dir.join("GameAssembly.dll"), b"MZ\x90\x00").unwrap();
        let found = find_game_assembly(&dir).unwrap();
        assert_eq!(found, dir.join("GameAssembly.dll"));
        if cfg!(unix) {
            assert!(matches!(
                check_format(&found),
                Err(Error::UnsupportedBinary(_))
            ));
        }
        std::fs::remove_dir_all(dir).unwrap();
    }
}