hao-il2cpp-runtime 0.0.7

Hook and call into Unity Il2Cpp games from inside the game process
Documentation
//! Runs mod code once the game's Il2Cpp runtime has started.
//!
//! Unity loads the game binary with `dlopen` and then calls `il2cpp_init`. A
//! mod loaded earlier (with `LD_PRELOAD`) hooks `dlopen` to see the binary
//! arrive, then hooks its `il2cpp_init`.

use std::{
    ffi::{c_char, c_int, c_void, CStr},
    sync::{
        atomic::{AtomicBool, Ordering},
        Mutex,
    },
};

use crate::{is_game_assembly, loaded_game_assembly, original, Error, Il2Cpp, Result};

type Callback = Box<dyn FnOnce(&'static Il2Cpp) -> Result<()> + Send>;

static CALLBACKS: Mutex<Vec<Callback>> = Mutex::new(Vec::new());
static DLOPEN_HOOKED: AtomicBool = AtomicBool::new(false);
static INIT_HOOKED: AtomicBool = AtomicBool::new(false);
static INITIALIZED: AtomicBool = AtomicBool::new(false);

/// Runs `callback` once `il2cpp_init` has finished, or straight away if it already has.
///
/// The mod has to be loaded before the game binary initialises Il2Cpp, which
/// `LD_PRELOAD` guarantees. Errors are printed to stderr.
pub fn on_init(callback: impl FnOnce(&'static Il2Cpp) -> Result<()> + Send + 'static) {
    if INITIALIZED.load(Ordering::SeqCst) {
        run(Box::new(callback));
        return;
    }
    CALLBACKS
        .lock()
        .unwrap_or_else(|e| e.into_inner())
        .push(Box::new(callback));
    if let Err(e) = install() {
        tracing::error!("could not watch for the game binary: {}", e);
    }
}

fn run(callback: Callback) {
    match Il2Cpp::loaded() {
        Ok(il2cpp) => {
            if let Err(e) = callback(il2cpp) {
                tracing::error!("mod failed: {}", e);
            }
        }
        Err(e) => tracing::error!("{}", e),
    }
}

/// Runs every queued callback, once. Used when `il2cpp_init` finishes, or
/// straight away when the mod is injected into an already-running game.
fn run_callbacks() {
    if INITIALIZED.swap(true, Ordering::SeqCst) {
        return;
    }
    let callbacks = std::mem::take(&mut *CALLBACKS.lock().unwrap_or_else(|e| e.into_inner()));
    for callback in callbacks {
        run(callback);
    }
}

/// Whether the game's Il2Cpp runtime has already started, for a mod injected late.
fn already_running() -> bool {
    matches!(Il2Cpp::loaded(), Ok(il2cpp) if !unsafe { (il2cpp.api().il2cpp_domain_get)() }.is_null())
}

fn install() -> Result<()> {
    // The binary may already be loaded, and may already be initialised.
    if let Some(path) = loaded_game_assembly() {
        crate::check_format(&path)?;
        let name = std::ffi::CString::new(path.to_string_lossy().into_owned())
            .map_err(|_| Error::Nul(path.display().to_string()))?;
        let handle = unsafe { libc::dlopen(name.as_ptr(), libc::RTLD_NOW | libc::RTLD_NOLOAD) };
        if !handle.is_null() {
            tracing::debug!(path = %path.display(), "game binary already loaded");
            if already_running() {
                // Injected after il2cpp_init: attach this thread and run now.
                tracing::debug!("il2cpp already initialised; running callbacks immediately");
                if let Ok(il2cpp) = Il2Cpp::loaded() {
                    il2cpp.attach_thread();
                }
                run_callbacks();
                return Ok(());
            }
            return hook_init(handle);
        }
    }
    if DLOPEN_HOOKED.swap(true, Ordering::SeqCst) {
        return Ok(());
    }
    tracing::debug!("hooking dlopen to wait for the game binary");
    let mut hook = unsafe { hooking::Hook::by_name(None, c"dlopen", dlopen_detour as *mut u8) }
        .map_err(Error::Hook)?;
    unsafe { hook.apply_hook() }.map_err(Error::Hook)
}

fn hook_init(handle: *mut c_void) -> Result<()> {
    if INIT_HOOKED.swap(true, Ordering::SeqCst) {
        return Ok(());
    }
    let init = unsafe { libc::dlsym(handle, c"il2cpp_init".as_ptr()) };
    if init.is_null() {
        return Err(Error::NotFound("il2cpp_init in the game binary".into()));
    }
    tracing::debug!("hooking il2cpp_init");
    let mut hook = unsafe { hooking::Hook::create(init as *mut u8, init_detour as *mut u8) }
        .map_err(Error::Hook)?;
    unsafe { hook.apply_hook() }.map_err(Error::Hook)
}

extern "C" fn dlopen_detour(filename: *const c_char, flags: c_int) -> *mut c_void {
    let dlopen = original!(extern "C" fn(*const c_char, c_int) -> *mut c_void);
    let handle = dlopen(filename, flags);
    if !handle.is_null() && !filename.is_null() && !INIT_HOOKED.load(Ordering::SeqCst) {
        let name = unsafe { CStr::from_ptr(filename) }.to_string_lossy();
        if is_game_assembly(name.as_ref()) {
            tracing::debug!(%name, "the game binary was loaded");
            if let Err(e) = hook_init(handle) {
                tracing::error!("could not hook il2cpp_init: {}", e);
            }
        }
    }
    handle
}

extern "C" fn init_detour(domain_name: *const c_char) -> i32 {
    let init = original!(extern "C" fn(*const c_char) -> i32);
    tracing::debug!("il2cpp_init called");
    let result = init(domain_name);
    tracing::debug!(result, "il2cpp_init returned");
    if result != 0 {
        run_callbacks();
    }
    result
}