Skip to main content

hao_il2cpp_runtime/
loader.rs

1//! Runs mod code once the game's Il2Cpp runtime has started.
2//!
3//! Unity loads the game binary with `dlopen` and then calls `il2cpp_init`. A
4//! mod loaded earlier (with `LD_PRELOAD`) hooks `dlopen` to see the binary
5//! arrive, then hooks its `il2cpp_init`.
6
7use std::{
8    ffi::{c_char, c_int, c_void, CStr},
9    sync::{
10        atomic::{AtomicBool, Ordering},
11        Mutex,
12    },
13};
14
15use crate::{is_game_assembly, loaded_game_assembly, original, Error, Il2Cpp, Result};
16
17type Callback = Box<dyn FnOnce(&'static Il2Cpp) -> Result<()> + Send>;
18
19static CALLBACKS: Mutex<Vec<Callback>> = Mutex::new(Vec::new());
20static DLOPEN_HOOKED: AtomicBool = AtomicBool::new(false);
21static INIT_HOOKED: AtomicBool = AtomicBool::new(false);
22static INITIALIZED: AtomicBool = AtomicBool::new(false);
23
24/// Runs `callback` once `il2cpp_init` has finished, or straight away if it already has.
25///
26/// The mod has to be loaded before the game binary initialises Il2Cpp, which
27/// `LD_PRELOAD` guarantees. Errors are printed to stderr.
28pub fn on_init(callback: impl FnOnce(&'static Il2Cpp) -> Result<()> + Send + 'static) {
29    if INITIALIZED.load(Ordering::SeqCst) {
30        run(Box::new(callback));
31        return;
32    }
33    CALLBACKS
34        .lock()
35        .unwrap_or_else(|e| e.into_inner())
36        .push(Box::new(callback));
37    if let Err(e) = install() {
38        tracing::error!("could not watch for the game binary: {}", e);
39    }
40}
41
42fn run(callback: Callback) {
43    match Il2Cpp::loaded() {
44        Ok(il2cpp) => {
45            if let Err(e) = callback(il2cpp) {
46                tracing::error!("mod failed: {}", e);
47            }
48        }
49        Err(e) => tracing::error!("{}", e),
50    }
51}
52
53/// Runs every queued callback, once. Used when `il2cpp_init` finishes, or
54/// straight away when the mod is injected into an already-running game.
55fn run_callbacks() {
56    if INITIALIZED.swap(true, Ordering::SeqCst) {
57        return;
58    }
59    let callbacks = std::mem::take(&mut *CALLBACKS.lock().unwrap_or_else(|e| e.into_inner()));
60    for callback in callbacks {
61        run(callback);
62    }
63}
64
65/// Whether the game's Il2Cpp runtime has already started, for a mod injected late.
66fn already_running() -> bool {
67    matches!(Il2Cpp::loaded(), Ok(il2cpp) if !unsafe { (il2cpp.api().il2cpp_domain_get)() }.is_null())
68}
69
70fn install() -> Result<()> {
71    // The binary may already be loaded, and may already be initialised.
72    if let Some(path) = loaded_game_assembly() {
73        crate::check_format(&path)?;
74        let name = std::ffi::CString::new(path.to_string_lossy().into_owned())
75            .map_err(|_| Error::Nul(path.display().to_string()))?;
76        let handle = unsafe { libc::dlopen(name.as_ptr(), libc::RTLD_NOW | libc::RTLD_NOLOAD) };
77        if !handle.is_null() {
78            tracing::debug!(path = %path.display(), "game binary already loaded");
79            if already_running() {
80                // Injected after il2cpp_init: attach this thread and run now.
81                tracing::debug!("il2cpp already initialised; running callbacks immediately");
82                if let Ok(il2cpp) = Il2Cpp::loaded() {
83                    il2cpp.attach_thread();
84                }
85                run_callbacks();
86                return Ok(());
87            }
88            return hook_init(handle);
89        }
90    }
91    if DLOPEN_HOOKED.swap(true, Ordering::SeqCst) {
92        return Ok(());
93    }
94    tracing::debug!("hooking dlopen to wait for the game binary");
95    let mut hook = unsafe { hooking::Hook::by_name(None, c"dlopen", dlopen_detour as *mut u8) }
96        .map_err(Error::Hook)?;
97    unsafe { hook.apply_hook() }.map_err(Error::Hook)
98}
99
100fn hook_init(handle: *mut c_void) -> Result<()> {
101    if INIT_HOOKED.swap(true, Ordering::SeqCst) {
102        return Ok(());
103    }
104    let init = unsafe { libc::dlsym(handle, c"il2cpp_init".as_ptr()) };
105    if init.is_null() {
106        return Err(Error::NotFound("il2cpp_init in the game binary".into()));
107    }
108    tracing::debug!("hooking il2cpp_init");
109    let mut hook = unsafe { hooking::Hook::create(init as *mut u8, init_detour as *mut u8) }
110        .map_err(Error::Hook)?;
111    unsafe { hook.apply_hook() }.map_err(Error::Hook)
112}
113
114extern "C" fn dlopen_detour(filename: *const c_char, flags: c_int) -> *mut c_void {
115    let dlopen = original!(extern "C" fn(*const c_char, c_int) -> *mut c_void);
116    let handle = dlopen(filename, flags);
117    if !handle.is_null() && !filename.is_null() && !INIT_HOOKED.load(Ordering::SeqCst) {
118        let name = unsafe { CStr::from_ptr(filename) }.to_string_lossy();
119        if is_game_assembly(name.as_ref()) {
120            tracing::debug!(%name, "the game binary was loaded");
121            if let Err(e) = hook_init(handle) {
122                tracing::error!("could not hook il2cpp_init: {}", e);
123            }
124        }
125    }
126    handle
127}
128
129extern "C" fn init_detour(domain_name: *const c_char) -> i32 {
130    let init = original!(extern "C" fn(*const c_char) -> i32);
131    tracing::debug!("il2cpp_init called");
132    let result = init(domain_name);
133    tracing::debug!(result, "il2cpp_init returned");
134    if result != 0 {
135        run_callbacks();
136    }
137    result
138}