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,
};
pub type MethodInfo = Ptr;
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."))
}
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))
}
#[cfg(unix)]
pub fn loaded_game_assembly() -> Option<PathBuf> {
let maps = std::fs::read_to_string("/proc/self/maps").ok()?;
maps.lines()
.filter_map(|line| line.split_whitespace().nth(5))
.map(PathBuf::from)
.find(|p| is_game_assembly(p))
}
#[cfg(windows)]
pub fn loaded_game_assembly() -> Option<PathBuf> {
libloading::os::windows::Library::open_already_loaded("GameAssembly.dll")
.ok()
.map(|_| PathBuf::from("GameAssembly.dll"))
}
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();
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,
}))
}
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)?)
}
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)
}
pub fn get() -> Option<&'static Il2Cpp> {
INSTANCE.get()
}
pub fn api(&self) -> &Api {
&self.api
}
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(())
}
pub fn attach_thread(&self) {
unsafe { (self.api.il2cpp_thread_attach)((self.api.il2cpp_domain_get)()) };
}
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,
})
}
pub fn string(&self, value: &str) -> Result<Il2CppString> {
let value = cstring(value)?;
Ok(Il2CppString(Object(unsafe {
(self.api.il2cpp_string_new)(value.as_ptr())
})))
}
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()));
}
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))
}
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))
}
}
pub unsafe fn class_of(&'static self, object: Object) -> Class {
Class {
il2cpp: self,
ptr: unsafe { (self.api.il2cpp_object_get_class)(object.0) },
}
}
}
#[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)) }
}
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,
})
}
pub fn new_object(&self) -> Object {
Object(unsafe { (self.il2cpp.api.il2cpp_object_new)(self.ptr) })
}
pub fn type_object(&self) -> Object {
Object(unsafe {
(self.il2cpp.api.il2cpp_type_get_object)((self.il2cpp.api.il2cpp_class_get_type)(
self.ptr,
))
})
}
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,
})
})
}
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,
})
}
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,
})
})
}
pub fn field_offset(&self, name: &str) -> Result<usize> {
Ok(self.field(name)?.offset())
}
}
#[derive(Clone, Copy)]
pub struct Field {
il2cpp: &'static Il2Cpp,
ptr: Ptr,
}
unsafe impl Send for Field {}
unsafe impl Sync for Field {}
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)) }
}
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()
}
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 unsafe fn read<T: Copy>(&self, object: Object) -> T {
unsafe { read_field(object, self.offset()) }
}
pub unsafe fn write<T: Copy>(&self, object: Object, value: T) {
unsafe { write_field(object, self.offset(), value) }
}
}
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) }
}
}
#[derive(Clone, Copy)]
pub struct Method {
il2cpp: &'static Il2Cpp,
ptr: Ptr,
}
unsafe impl Send for Method {}
unsafe impl Sync for Method {}
impl 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)) }
}
pub fn code(&self) -> *mut c_void {
unsafe { *(self.ptr as *const *mut c_void) }
}
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))
}
}
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 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) }
}
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) }
}
#[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::*;
#[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();
}
}