1mod 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
48pub type MethodInfo = Ptr;
50
51pub 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
60pub 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#[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#[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
86fn 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
104pub 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 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 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 pub fn get() -> Option<&'static Il2Cpp> {
165 INSTANCE.get()
166 }
167
168 pub fn api(&self) -> &Api {
169 &self.api
170 }
171
172 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 pub fn attach_thread(&self) {
188 unsafe { (self.api.il2cpp_thread_attach)((self.api.il2cpp_domain_get)()) };
189 }
190
191 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 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 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 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 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 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#[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 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 pub fn new_object(&self) -> Object {
320 Object(unsafe { (self.il2cpp.api.il2cpp_object_new)(self.ptr) })
321 }
322
323 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 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 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 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 pub fn field_offset(&self, name: &str) -> Result<usize> {
373 Ok(self.field(name)?.offset())
374 }
375}
376
377#[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
387const 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 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 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 pub unsafe fn read<T: Copy>(&self, object: Object) -> T {
421 unsafe { read_field(object, self.offset()) }
422 }
423
424 pub unsafe fn write<T: Copy>(&self, object: Object, value: T) {
429 unsafe { write_field(object, self.offset(), value) }
430 }
431}
432
433pub 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#[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 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 pub fn code(&self) -> *mut c_void {
486 unsafe { *(self.ptr as *const *mut c_void) }
488 }
489
490 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
508pub 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
519pub 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
527pub 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#[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}