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
29use std::{
30    ffi::{c_void, CStr, CString},
31    path::{Path, PathBuf},
32    sync::OnceLock,
33};
34
35use libloading::Library;
36
37pub use api::{Api, Ptr};
38pub use error::{Error, Result};
39#[cfg(unix)]
40pub use loader::on_init;
41pub use typed::{
42    element, HookCallback, Il2CppString, Il2CppValue, MethodArgs, Object, Original, Parameter,
43    Signature, TypeInfo, ValueCheck,
44};
45
46/// The hidden last argument of every Il2Cpp method (`const MethodInfo*`).
47pub type MethodInfo = Ptr;
48
49/// Whether `path` is a game binary: `GameAssembly.so`, `GameAssembly.dll` or any other `GameAssembly.*`.
50/// Both `/` and `\\` separate directories, as Windows paths can show up on Linux under Wine.
51pub fn is_game_assembly(path: impl AsRef<Path>) -> bool {
52    let path = path.as_ref().to_string_lossy();
53    path.rsplit(['/', '\\'])
54        .next()
55        .is_some_and(|name| name.starts_with("GameAssembly."))
56}
57
58/// The game binary in a game folder, whichever platform the game was built for.
59pub fn find_game_assembly(dir: impl AsRef<Path>) -> Option<PathBuf> {
60    std::fs::read_dir(dir)
61        .ok()?
62        .filter_map(|e| e.ok().map(|e| e.path()))
63        .find(|p| p.is_file() && is_game_assembly(p))
64}
65
66/// The game binary mapped into this process, if any.
67#[cfg(unix)]
68pub fn loaded_game_assembly() -> Option<PathBuf> {
69    let maps = std::fs::read_to_string("/proc/self/maps").ok()?;
70    maps.lines()
71        .filter_map(|line| line.split_whitespace().nth(5))
72        .map(PathBuf::from)
73        .find(|p| is_game_assembly(p))
74}
75
76/// The game binary mapped into this process, if any.
77#[cfg(windows)]
78pub fn loaded_game_assembly() -> Option<PathBuf> {
79    libloading::os::windows::Library::open_already_loaded("GameAssembly.dll")
80        .ok()
81        .map(|_| PathBuf::from("GameAssembly.dll"))
82}
83
84/// Errors unless `path` is a binary this build can load: ELF on Unix, PE on Windows.
85fn check_format(path: &Path) -> Result<()> {
86    use std::io::Read;
87    let mut magic = [0u8; 4];
88    let read = std::fs::File::open(path).and_then(|mut f| f.read_exact(&mut magic));
89    let (elf, pe) = (magic == *b"\x7fELF", magic.starts_with(b"MZ"));
90    match read {
91        Ok(()) if cfg!(unix) && pe => Err(Error::UnsupportedBinary(format!(
92            "{} is a Windows binary (a Windows build running under Wine/Proton), which a Linux mod can't load yet",
93            path.display()
94        ))),
95        Ok(()) if cfg!(windows) && elf => Err(Error::UnsupportedBinary(format!("{} is not a Windows binary", path.display()))),
96        _ => Ok(()),
97    }
98}
99
100static INSTANCE: OnceLock<Il2Cpp> = OnceLock::new();
101
102/// The game's Il2Cpp runtime.
103pub struct Il2Cpp {
104    api: Api,
105    _library: Library,
106}
107
108fn cstring(value: &str) -> Result<CString> {
109    CString::new(value).map_err(|_| Error::Nul(value.to_owned()))
110}
111
112pub(crate) unsafe fn c_str<'a>(value: *const std::ffi::c_char) -> &'a str {
113    if value.is_null() {
114        ""
115    } else {
116        unsafe { CStr::from_ptr(value) }.to_str().unwrap_or("")
117    }
118}
119
120impl Il2Cpp {
121    fn install(library: Library) -> Result<&'static Il2Cpp> {
122        let api = Api::load(&library)?;
123        tracing::debug!("loaded the il2cpp_* API from the game binary");
124        Ok(INSTANCE.get_or_init(|| Il2Cpp {
125            api,
126            _library: library,
127        }))
128    }
129
130    /// The runtime of the game binary already loaded in this process.
131    pub fn loaded() -> Result<&'static Il2Cpp> {
132        if let Some(il2cpp) = INSTANCE.get() {
133            return Ok(il2cpp);
134        }
135        let path = loaded_game_assembly()
136            .ok_or_else(|| Error::NotFound("a loaded GameAssembly".into()))?;
137        check_format(&path)?;
138        tracing::debug!(path = %path.display(), "using the loaded game binary");
139        #[cfg(unix)]
140        let library = unsafe {
141            libloading::os::unix::Library::open(Some(&path), libc::RTLD_NOW | libc::RTLD_NOLOAD)
142                .map(Library::from)
143        };
144        #[cfg(windows)]
145        let library =
146            libloading::os::windows::Library::open_already_loaded(&path).map(Library::from);
147        Self::install(library.map_err(Error::Load)?)
148    }
149
150    /// Loads a game binary into this process, e.g. to run a game's code without Unity.
151    pub fn load(path: impl AsRef<Path>) -> Result<&'static Il2Cpp> {
152        if let Some(il2cpp) = INSTANCE.get() {
153            return Ok(il2cpp);
154        }
155        check_format(path.as_ref())?;
156        tracing::debug!(path = %path.as_ref().display(), "loading the game binary");
157        let library = unsafe { Library::new(path.as_ref()) }.map_err(Error::Load)?;
158        Self::install(library)
159    }
160
161    /// The instance set up by [`Il2Cpp::loaded`] or [`Il2Cpp::load`].
162    pub fn get() -> Option<&'static Il2Cpp> {
163        INSTANCE.get()
164    }
165
166    pub fn api(&self) -> &Api {
167        &self.api
168    }
169
170    /// Starts the runtime without Unity, given the game's `<Game>_Data/il2cpp_data` folder.
171    /// Only the game's pure .NET code can run this way; anything calling into Unity will fail.
172    pub fn init_standalone(&self, data_dir: impl AsRef<Path>) -> Result<()> {
173        tracing::debug!(data_dir = %data_dir.as_ref().display(), "starting Il2Cpp without Unity");
174        let data_dir = cstring(&data_dir.as_ref().to_string_lossy())?;
175        unsafe {
176            (self.api.il2cpp_set_data_dir)(data_dir.as_ptr());
177            if (self.api.il2cpp_init)(c"hao".as_ptr()) == 0 {
178                return Err(Error::Init);
179            }
180        }
181        Ok(())
182    }
183
184    /// Lets the calling thread run managed code. Needed on threads the game didn't start.
185    pub fn attach_thread(&self) {
186        unsafe { (self.api.il2cpp_thread_attach)((self.api.il2cpp_domain_get)()) };
187    }
188
189    /// Finds a class, e.g. `class("Assembly-CSharp", "Game.Player", "Health")`.
190    pub fn class(&'static self, assembly: &str, namespace: &str, name: &str) -> Result<Class> {
191        let (assembly_c, namespace_c, name_c) =
192            (cstring(assembly)?, cstring(namespace)?, cstring(name)?);
193        let class = unsafe {
194            let domain = (self.api.il2cpp_domain_get)();
195            let opened = (self.api.il2cpp_domain_assembly_open)(domain, assembly_c.as_ptr());
196            if opened.is_null() {
197                return Err(Error::NotFound(format!("assembly {}", assembly)));
198            }
199            let image = (self.api.il2cpp_assembly_get_image)(opened);
200            (self.api.il2cpp_class_from_name)(image, namespace_c.as_ptr(), name_c.as_ptr())
201        };
202        if class.is_null() {
203            return Err(Error::NotFound(format!(
204                "class {}.{} in {}",
205                namespace, name, assembly
206            )));
207        }
208        tracing::trace!(assembly, namespace, name, "found class");
209        Ok(Class {
210            il2cpp: self,
211            ptr: class,
212        })
213    }
214
215    /// A new managed string.
216    pub fn string(&self, value: &str) -> Result<Il2CppString> {
217        let value = cstring(value)?;
218        Ok(Il2CppString(Object(unsafe {
219            (self.api.il2cpp_string_new)(value.as_ptr())
220        })))
221    }
222
223    /// A new managed `byte[]` holding a copy of `bytes`, e.g. to pass to
224    /// `Texture2D.LoadRawTextureData`.
225    pub fn byte_array(&'static self, bytes: &[u8]) -> Result<Object> {
226        let class = self.class("mscorlib", "System", "Byte")?;
227        let array = unsafe { (self.api.il2cpp_array_new)(class.as_ptr(), bytes.len()) };
228        if array.is_null() {
229            return Err(Error::NotFound("could not allocate a byte[]".into()));
230        }
231        // Array elements follow the header (object header, bounds, length): 4 pointers.
232        let base = 4 * std::mem::size_of::<usize>();
233        unsafe {
234            std::ptr::copy_nonoverlapping(bytes.as_ptr(), (array as *mut u8).add(base), bytes.len());
235        }
236        Ok(Object(array))
237    }
238
239    /// Reads a managed string, `None` for null.
240    ///
241    /// # Safety
242    /// `string` must be null or a live `System.String`.
243    pub unsafe fn read_string(&self, string: Object) -> Option<String> {
244        if string.is_null() {
245            return None;
246        }
247        unsafe {
248            let length = (self.api.il2cpp_string_length)(string.0).max(0) as usize;
249            let chars =
250                std::slice::from_raw_parts((self.api.il2cpp_string_chars)(string.0), length);
251            Some(String::from_utf16_lossy(chars))
252        }
253    }
254
255    /// The class of a managed object.
256    ///
257    /// # Safety
258    /// `object` must be a live managed object.
259    pub unsafe fn class_of(&'static self, object: Object) -> Class {
260        Class {
261            il2cpp: self,
262            ptr: unsafe { (self.api.il2cpp_object_get_class)(object.0) },
263        }
264    }
265}
266
267/// A managed class (`Il2CppClass*`).
268#[derive(Clone, Copy)]
269pub struct Class {
270    il2cpp: &'static Il2Cpp,
271    ptr: Ptr,
272}
273
274unsafe impl Send for Class {}
275unsafe impl Sync for Class {}
276
277impl Class {
278    pub fn as_ptr(&self) -> Ptr {
279        self.ptr
280    }
281
282    pub fn name(&self) -> &'static str {
283        unsafe { c_str((self.il2cpp.api.il2cpp_class_get_name)(self.ptr)) }
284    }
285
286    pub fn namespace(&self) -> &'static str {
287        unsafe { c_str((self.il2cpp.api.il2cpp_class_get_namespace)(self.ptr)) }
288    }
289
290    /// Finds a method by name and parameter count (`-1` for any).
291    pub fn method(&self, name: &str, parameter_count: i32) -> Result<Method> {
292        let c_name = cstring(name)?;
293        let method = unsafe {
294            (self.il2cpp.api.il2cpp_class_get_method_from_name)(
295                self.ptr,
296                c_name.as_ptr(),
297                parameter_count,
298            )
299        };
300        if method.is_null() {
301            return Err(Error::NotFound(format!(
302                "method {}.{}({} parameters)",
303                self.name(),
304                name,
305                parameter_count
306            )));
307        }
308        tracing::trace!(class = self.name(), name, parameter_count, "found method");
309        Ok(Method {
310            il2cpp: self.il2cpp,
311            ptr: method,
312        })
313    }
314
315    /// Allocates an object of this class without running a constructor; call
316    /// `.ctor` on it with [`Method::call`].
317    pub fn new_object(&self) -> Object {
318        Object(unsafe { (self.il2cpp.api.il2cpp_object_new)(self.ptr) })
319    }
320
321    /// The class's `System.Type`, as `typeof` gives it.
322    pub fn type_object(&self) -> Object {
323        Object(unsafe {
324            (self.il2cpp.api.il2cpp_type_get_object)((self.il2cpp.api.il2cpp_class_get_type)(
325                self.ptr,
326            ))
327        })
328    }
329
330    /// Every method declared by the class, e.g. to pick an overload by [`Method::signature`].
331    pub fn methods(&self) -> impl Iterator<Item = Method> + '_ {
332        let mut iter: Ptr = std::ptr::null_mut();
333        std::iter::from_fn(move || {
334            let method = unsafe { (self.il2cpp.api.il2cpp_class_get_methods)(self.ptr, &mut iter) };
335            (!method.is_null()).then_some(Method {
336                il2cpp: self.il2cpp,
337                ptr: method,
338            })
339        })
340    }
341
342    /// A field by name, with its type, offset and whether it is static.
343    pub fn field(&self, name: &str) -> Result<Field> {
344        let c_name = cstring(name)?;
345        let field = unsafe {
346            (self.il2cpp.api.il2cpp_class_get_field_from_name)(self.ptr, c_name.as_ptr())
347        };
348        if field.is_null() {
349            return Err(Error::NotFound(format!("field {}.{}", self.name(), name)));
350        }
351        Ok(Field {
352            il2cpp: self.il2cpp,
353            ptr: field,
354        })
355    }
356
357    /// Every field declared by the class.
358    pub fn fields(&self) -> impl Iterator<Item = Field> + '_ {
359        let mut iter: Ptr = std::ptr::null_mut();
360        std::iter::from_fn(move || {
361            let field = unsafe { (self.il2cpp.api.il2cpp_class_get_fields)(self.ptr, &mut iter) };
362            (!field.is_null()).then_some(Field {
363                il2cpp: self.il2cpp,
364                ptr: field,
365            })
366        })
367    }
368
369    /// The byte offset of an instance field from the start of an object.
370    pub fn field_offset(&self, name: &str) -> Result<usize> {
371        Ok(self.field(name)?.offset())
372    }
373}
374
375/// A managed field (`FieldInfo*`).
376#[derive(Clone, Copy)]
377pub struct Field {
378    il2cpp: &'static Il2Cpp,
379    ptr: Ptr,
380}
381
382unsafe impl Send for Field {}
383unsafe impl Sync for Field {}
384
385/// `FIELD_ATTRIBUTE_STATIC` in the field's flags.
386const FIELD_STATIC: i32 = 0x0010;
387
388impl Field {
389    pub fn as_ptr(&self) -> Ptr {
390        self.ptr
391    }
392
393    pub fn name(&self) -> &'static str {
394        unsafe { c_str((self.il2cpp.api.il2cpp_field_get_name)(self.ptr)) }
395    }
396
397    /// The managed type name, e.g. `System.Single`.
398    pub fn type_name(&self) -> String {
399        let ty = unsafe { (self.il2cpp.api.il2cpp_field_get_type)(self.ptr) };
400        unsafe { c_str((self.il2cpp.api.il2cpp_type_get_name)(ty)) }.to_owned()
401    }
402
403    /// The byte offset from the start of an object (for instance fields), with
404    /// [`read_field`]/[`write_field`].
405    pub fn offset(&self) -> usize {
406        unsafe { (self.il2cpp.api.il2cpp_field_get_offset)(self.ptr) }
407    }
408
409    pub fn is_static(&self) -> bool {
410        unsafe { (self.il2cpp.api.il2cpp_field_get_flags)(self.ptr) & FIELD_STATIC != 0 }
411    }
412
413    /// Reads this instance field's value from `object`.
414    ///
415    /// # Safety
416    /// `T` must match the field's layout, and `object` must be an instance of
417    /// the field's class.
418    pub unsafe fn read<T: Copy>(&self, object: Object) -> T {
419        unsafe { read_field(object, self.offset()) }
420    }
421
422    /// Writes this instance field's value on `object`.
423    ///
424    /// # Safety
425    /// As for [`Field::read`].
426    pub unsafe fn write<T: Copy>(&self, object: Object, value: T) {
427        unsafe { write_field(object, self.offset(), value) }
428    }
429}
430
431/// Keeps an object alive and findable after the garbage collector moves or
432/// would free it. The collector doesn't scan Rust memory, so objects kept
433/// between calls (in statics or closures) need one. Freed on drop.
434pub struct GcHandle {
435    il2cpp: &'static Il2Cpp,
436    handle: Ptr,
437}
438
439unsafe impl Send for GcHandle {}
440unsafe impl Sync for GcHandle {}
441
442impl GcHandle {
443    pub fn new(il2cpp: &'static Il2Cpp, object: Object) -> Self {
444        Self {
445            il2cpp,
446            handle: unsafe { (il2cpp.api.il2cpp_gchandle_new)(object.0, false) },
447        }
448    }
449
450    pub fn target(&self) -> Object {
451        Object(unsafe { (self.il2cpp.api.il2cpp_gchandle_get_target)(self.handle) })
452    }
453}
454
455impl Drop for GcHandle {
456    fn drop(&mut self) {
457        unsafe { (self.il2cpp.api.il2cpp_gchandle_free)(self.handle) }
458    }
459}
460
461/// A managed method (`MethodInfo*`).
462#[derive(Clone, Copy)]
463pub struct Method {
464    il2cpp: &'static Il2Cpp,
465    ptr: Ptr,
466}
467
468unsafe impl Send for Method {}
469unsafe impl Sync for Method {}
470
471impl Method {
472    /// The `MethodInfo*`, passed as the last argument when calling the method.
473    pub fn as_ptr(&self) -> MethodInfo {
474        self.ptr
475    }
476
477    pub fn name(&self) -> &'static str {
478        unsafe { c_str((self.il2cpp.api.il2cpp_method_get_name)(self.ptr)) }
479    }
480
481    /// The method's compiled code. Call it with the instance first (for instance
482    /// methods), then the arguments, then [`Method::as_ptr`].
483    pub fn code(&self) -> *mut c_void {
484        // `methodPointer` is the first field of `MethodInfo`.
485        unsafe { *(self.ptr as *const *mut c_void) }
486    }
487
488    /// Redirects every call of the method to `detour`, which has the method's
489    /// signature as described on [`Method::code`]. Inside the detour, [`original!`]
490    /// gets a function that calls the original code. [`Method::hook`] is the safe,
491    /// typed version of this.
492    ///
493    /// The hook stays in place when the returned value is dropped.
494    ///
495    /// # Safety
496    /// `detour` must be an `extern "C"` function with exactly the method's signature.
497    pub unsafe fn hook_raw(&self, detour: *mut u8) -> Result<MethodHook> {
498        let mut hook = unsafe { hooking::Hook::create(self.code() as *mut u8, detour) }
499            .map_err(Error::Hook)?;
500        unsafe { hook.apply_hook() }.map_err(Error::Hook)?;
501        tracing::debug!(method = self.name(), code = ?self.code(), "hooked (raw)");
502        Ok(MethodHook(hook))
503    }
504}
505
506/// An applied method hook. Dropping it leaves the hook in place.
507pub struct MethodHook(pub(crate) hooking::Hook<'static>);
508
509impl MethodHook {
510    pub fn remove(mut self) -> Result<()> {
511        unsafe { self.0.remove_hook() }.map_err(Error::Hook)?;
512        tracing::debug!(code = ?self.0.data.symbol_address, "removed hook");
513        Ok(())
514    }
515}
516
517/// Reads a managed object's field at `offset` (from [`Class::field_offset`]).
518///
519/// # Safety
520/// `object` must be a live object with a field of type `T` at `offset`.
521pub unsafe fn read_field<T: Copy>(object: Object, offset: usize) -> T {
522    unsafe { std::ptr::read_unaligned((object.0 as *const u8).add(offset) as *const T) }
523}
524
525/// Writes a managed object's field at `offset`. Only for fields that don't hold references.
526///
527/// # Safety
528/// `object` must be a live object with a field of type `T` at `offset`.
529pub unsafe fn write_field<T: Copy>(object: Object, offset: usize, value: T) {
530    unsafe { std::ptr::write_unaligned((object.0 as *mut u8).add(offset) as *mut T, value) }
531}
532
533/// Inside a detour from [`Method::hook_raw`], gets the function that calls the
534/// original method. Must be the first thing the detour does.
535#[macro_export]
536macro_rules! original {
537    ($fn_type:ty) => {{
538        let original =
539            $crate::__original_function_ptr().expect("original! must be used inside a hook");
540        unsafe { ::core::mem::transmute::<*mut ::core::ffi::c_void, $fn_type>(original.as_ptr()) }
541    }};
542}
543
544#[doc(hidden)]
545pub use hooking::original_function_ptr as __original_function_ptr;
546
547#[cfg(test)]
548mod tests {
549    use super::*;
550
551    #[test]
552    fn game_assembly_names() {
553        assert!(is_game_assembly("/games/Example/GameAssembly.so"));
554        assert!(is_game_assembly("C:\\Games\\Example\\GameAssembly.dll"));
555        assert!(!is_game_assembly("/games/Example/UnityPlayer.so"));
556        assert!(!is_game_assembly("/games/Example/NotGameAssembly.dll"));
557    }
558
559    #[test]
560    fn finds_and_checks_the_game_binary() {
561        let dir = std::env::temp_dir().join(format!("hao-il2cpp-runtime-{}", std::process::id()));
562        std::fs::create_dir_all(&dir).unwrap();
563        std::fs::write(dir.join("UnityPlayer.dll"), b"MZ\x90\x00").unwrap();
564        std::fs::write(dir.join("GameAssembly.dll"), b"MZ\x90\x00").unwrap();
565        let found = find_game_assembly(&dir).unwrap();
566        assert_eq!(found, dir.join("GameAssembly.dll"));
567        if cfg!(unix) {
568            assert!(matches!(
569                check_format(&found),
570                Err(Error::UnsupportedBinary(_))
571            ));
572        }
573        std::fs::remove_dir_all(dir).unwrap();
574    }
575}