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    /// The class of a managed object.
258    ///
259    /// # Safety
260    /// `object` must be a live managed object.
261    pub unsafe fn class_of(&'static self, object: Object) -> Class {
262        Class {
263            il2cpp: self,
264            ptr: unsafe { (self.api.il2cpp_object_get_class)(object.0) },
265        }
266    }
267}
268
269/// A managed class (`Il2CppClass*`).
270#[derive(Clone, Copy)]
271pub struct Class {
272    il2cpp: &'static Il2Cpp,
273    ptr: Ptr,
274}
275
276unsafe impl Send for Class {}
277unsafe impl Sync for Class {}
278
279impl Class {
280    pub fn as_ptr(&self) -> Ptr {
281        self.ptr
282    }
283
284    pub fn name(&self) -> &'static str {
285        unsafe { c_str((self.il2cpp.api.il2cpp_class_get_name)(self.ptr)) }
286    }
287
288    pub fn namespace(&self) -> &'static str {
289        unsafe { c_str((self.il2cpp.api.il2cpp_class_get_namespace)(self.ptr)) }
290    }
291
292    /// Finds a method by name and parameter count (`-1` for any).
293    pub fn method(&self, name: &str, parameter_count: i32) -> Result<Method> {
294        let c_name = cstring(name)?;
295        let method = unsafe {
296            (self.il2cpp.api.il2cpp_class_get_method_from_name)(
297                self.ptr,
298                c_name.as_ptr(),
299                parameter_count,
300            )
301        };
302        if method.is_null() {
303            return Err(Error::NotFound(format!(
304                "method {}.{}({} parameters)",
305                self.name(),
306                name,
307                parameter_count
308            )));
309        }
310        tracing::trace!(class = self.name(), name, parameter_count, "found method");
311        Ok(Method {
312            il2cpp: self.il2cpp,
313            ptr: method,
314        })
315    }
316
317    /// Allocates an object of this class without running a constructor; call
318    /// `.ctor` on it with [`Method::call`].
319    pub fn new_object(&self) -> Object {
320        Object(unsafe { (self.il2cpp.api.il2cpp_object_new)(self.ptr) })
321    }
322
323    /// The class's `System.Type`, as `typeof` gives it.
324    pub fn type_object(&self) -> Object {
325        Object(unsafe {
326            (self.il2cpp.api.il2cpp_type_get_object)((self.il2cpp.api.il2cpp_class_get_type)(
327                self.ptr,
328            ))
329        })
330    }
331
332    /// Every method declared by the class, e.g. to pick an overload by [`Method::signature`].
333    pub fn methods(&self) -> impl Iterator<Item = Method> + '_ {
334        let mut iter: Ptr = std::ptr::null_mut();
335        std::iter::from_fn(move || {
336            let method = unsafe { (self.il2cpp.api.il2cpp_class_get_methods)(self.ptr, &mut iter) };
337            (!method.is_null()).then_some(Method {
338                il2cpp: self.il2cpp,
339                ptr: method,
340            })
341        })
342    }
343
344    /// A field by name, with its type, offset and whether it is static.
345    pub fn field(&self, name: &str) -> Result<Field> {
346        let c_name = cstring(name)?;
347        let field = unsafe {
348            (self.il2cpp.api.il2cpp_class_get_field_from_name)(self.ptr, c_name.as_ptr())
349        };
350        if field.is_null() {
351            return Err(Error::NotFound(format!("field {}.{}", self.name(), name)));
352        }
353        Ok(Field {
354            il2cpp: self.il2cpp,
355            ptr: field,
356        })
357    }
358
359    /// Every field declared by the class.
360    pub fn fields(&self) -> impl Iterator<Item = Field> + '_ {
361        let mut iter: Ptr = std::ptr::null_mut();
362        std::iter::from_fn(move || {
363            let field = unsafe { (self.il2cpp.api.il2cpp_class_get_fields)(self.ptr, &mut iter) };
364            (!field.is_null()).then_some(Field {
365                il2cpp: self.il2cpp,
366                ptr: field,
367            })
368        })
369    }
370
371    /// The byte offset of an instance field from the start of an object.
372    pub fn field_offset(&self, name: &str) -> Result<usize> {
373        Ok(self.field(name)?.offset())
374    }
375}
376
377/// A managed field (`FieldInfo*`).
378#[derive(Clone, Copy)]
379pub struct Field {
380    il2cpp: &'static Il2Cpp,
381    ptr: Ptr,
382}
383
384unsafe impl Send for Field {}
385unsafe impl Sync for Field {}
386
387/// `FIELD_ATTRIBUTE_STATIC` in the field's flags.
388const FIELD_STATIC: i32 = 0x0010;
389
390impl Field {
391    pub fn as_ptr(&self) -> Ptr {
392        self.ptr
393    }
394
395    pub fn name(&self) -> &'static str {
396        unsafe { c_str((self.il2cpp.api.il2cpp_field_get_name)(self.ptr)) }
397    }
398
399    /// The managed type name, e.g. `System.Single`.
400    pub fn type_name(&self) -> String {
401        let ty = unsafe { (self.il2cpp.api.il2cpp_field_get_type)(self.ptr) };
402        unsafe { c_str((self.il2cpp.api.il2cpp_type_get_name)(ty)) }.to_owned()
403    }
404
405    /// The byte offset from the start of an object (for instance fields), with
406    /// [`read_field`]/[`write_field`].
407    pub fn offset(&self) -> usize {
408        unsafe { (self.il2cpp.api.il2cpp_field_get_offset)(self.ptr) }
409    }
410
411    pub fn is_static(&self) -> bool {
412        unsafe { (self.il2cpp.api.il2cpp_field_get_flags)(self.ptr) & FIELD_STATIC != 0 }
413    }
414
415    /// Reads this instance field's value from `object`.
416    ///
417    /// # Safety
418    /// `T` must match the field's layout, and `object` must be an instance of
419    /// the field's class.
420    pub unsafe fn read<T: Copy>(&self, object: Object) -> T {
421        unsafe { read_field(object, self.offset()) }
422    }
423
424    /// Writes this instance field's value on `object`.
425    ///
426    /// # Safety
427    /// As for [`Field::read`].
428    pub unsafe fn write<T: Copy>(&self, object: Object, value: T) {
429        unsafe { write_field(object, self.offset(), value) }
430    }
431}
432
433/// Keeps an object alive and findable after the garbage collector moves or
434/// would free it. The collector doesn't scan Rust memory, so objects kept
435/// between calls (in statics or closures) need one. Freed on drop.
436pub struct GcHandle {
437    il2cpp: &'static Il2Cpp,
438    handle: Ptr,
439}
440
441unsafe impl Send for GcHandle {}
442unsafe impl Sync for GcHandle {}
443
444impl GcHandle {
445    pub fn new(il2cpp: &'static Il2Cpp, object: Object) -> Self {
446        Self {
447            il2cpp,
448            handle: unsafe { (il2cpp.api.il2cpp_gchandle_new)(object.0, false) },
449        }
450    }
451
452    pub fn target(&self) -> Object {
453        Object(unsafe { (self.il2cpp.api.il2cpp_gchandle_get_target)(self.handle) })
454    }
455}
456
457impl Drop for GcHandle {
458    fn drop(&mut self) {
459        unsafe { (self.il2cpp.api.il2cpp_gchandle_free)(self.handle) }
460    }
461}
462
463/// A managed method (`MethodInfo*`).
464#[derive(Clone, Copy)]
465pub struct Method {
466    il2cpp: &'static Il2Cpp,
467    ptr: Ptr,
468}
469
470unsafe impl Send for Method {}
471unsafe impl Sync for Method {}
472
473impl Method {
474    /// The `MethodInfo*`, passed as the last argument when calling the method.
475    pub fn as_ptr(&self) -> MethodInfo {
476        self.ptr
477    }
478
479    pub fn name(&self) -> &'static str {
480        unsafe { c_str((self.il2cpp.api.il2cpp_method_get_name)(self.ptr)) }
481    }
482
483    /// The method's compiled code. Call it with the instance first (for instance
484    /// methods), then the arguments, then [`Method::as_ptr`].
485    pub fn code(&self) -> *mut c_void {
486        // `methodPointer` is the first field of `MethodInfo`.
487        unsafe { *(self.ptr as *const *mut c_void) }
488    }
489
490    /// Redirects every call of the method to `detour`, which has the method's
491    /// signature as described on [`Method::code`]. Inside the detour, [`original!`]
492    /// gets a function that calls the original code. [`Method::hook`] is the safe,
493    /// typed version of this.
494    ///
495    /// The hook stays in place when the returned value is dropped.
496    ///
497    /// # Safety
498    /// `detour` must be an `extern "C"` function with exactly the method's signature.
499    pub unsafe fn hook_raw(&self, detour: *mut u8) -> Result<MethodHook> {
500        let mut hook = unsafe { hooking::Hook::create(self.code() as *mut u8, detour) }
501            .map_err(Error::Hook)?;
502        unsafe { hook.apply_hook() }.map_err(Error::Hook)?;
503        tracing::debug!(method = self.name(), code = ?self.code(), "hooked (raw)");
504        Ok(MethodHook(hook))
505    }
506}
507
508/// An applied method hook. Dropping it leaves the hook in place.
509pub struct MethodHook(pub(crate) hooking::Hook<'static>);
510
511impl MethodHook {
512    pub fn remove(mut self) -> Result<()> {
513        unsafe { self.0.remove_hook() }.map_err(Error::Hook)?;
514        tracing::debug!(code = ?self.0.data.symbol_address, "removed hook");
515        Ok(())
516    }
517}
518
519/// Reads a managed object's field at `offset` (from [`Class::field_offset`]).
520///
521/// # Safety
522/// `object` must be a live object with a field of type `T` at `offset`.
523pub unsafe fn read_field<T: Copy>(object: Object, offset: usize) -> T {
524    unsafe { std::ptr::read_unaligned((object.0 as *const u8).add(offset) as *const T) }
525}
526
527/// Writes a managed object's field at `offset`. Only for fields that don't hold references.
528///
529/// # Safety
530/// `object` must be a live object with a field of type `T` at `offset`.
531pub unsafe fn write_field<T: Copy>(object: Object, offset: usize, value: T) {
532    unsafe { std::ptr::write_unaligned((object.0 as *mut u8).add(offset) as *mut T, value) }
533}
534
535/// Inside a detour from [`Method::hook_raw`], gets the function that calls the
536/// original method. Must be the first thing the detour does.
537#[macro_export]
538macro_rules! original {
539    ($fn_type:ty) => {{
540        let original =
541            $crate::__original_function_ptr().expect("original! must be used inside a hook");
542        unsafe { ::core::mem::transmute::<*mut ::core::ffi::c_void, $fn_type>(original.as_ptr()) }
543    }};
544}
545
546#[doc(hidden)]
547pub use hooking::original_function_ptr as __original_function_ptr;
548
549#[cfg(test)]
550mod tests {
551    use super::*;
552
553    #[test]
554    fn game_assembly_names() {
555        assert!(is_game_assembly("/games/Example/GameAssembly.so"));
556        assert!(is_game_assembly("C:\\Games\\Example\\GameAssembly.dll"));
557        assert!(!is_game_assembly("/games/Example/UnityPlayer.so"));
558        assert!(!is_game_assembly("/games/Example/NotGameAssembly.dll"));
559    }
560
561    #[test]
562    fn finds_and_checks_the_game_binary() {
563        let dir = std::env::temp_dir().join(format!("hao-il2cpp-runtime-{}", std::process::id()));
564        std::fs::create_dir_all(&dir).unwrap();
565        std::fs::write(dir.join("UnityPlayer.dll"), b"MZ\x90\x00").unwrap();
566        std::fs::write(dir.join("GameAssembly.dll"), b"MZ\x90\x00").unwrap();
567        let found = find_game_assembly(&dir).unwrap();
568        assert_eq!(found, dir.join("GameAssembly.dll"));
569        if cfg!(unix) {
570            assert!(matches!(
571                check_format(&found),
572                Err(Error::UnsupportedBinary(_))
573            ));
574        }
575        std::fs::remove_dir_all(dir).unwrap();
576    }
577}