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 game_assembly_in_maps(&maps)
73}
74
75#[cfg(unix)]
76fn game_assembly_in_maps(maps: &str) -> Option<PathBuf> {
77 maps.lines()
78 .filter_map(|line| line.find('/').map(|start| &line[start..]))
80 .map(PathBuf::from)
81 .find(|p| is_game_assembly(p))
82}
83
84#[cfg(windows)]
86pub fn loaded_game_assembly() -> Option<PathBuf> {
87 libloading::os::windows::Library::open_already_loaded("GameAssembly.dll")
88 .ok()
89 .map(|_| PathBuf::from("GameAssembly.dll"))
90}
91
92fn check_format(path: &Path) -> Result<()> {
94 use std::io::Read;
95 let mut magic = [0u8; 4];
96 let read = std::fs::File::open(path).and_then(|mut f| f.read_exact(&mut magic));
97 let (elf, pe) = (magic == *b"\x7fELF", magic.starts_with(b"MZ"));
98 match read {
99 Ok(()) if cfg!(unix) && pe => Err(Error::UnsupportedBinary(format!(
100 "{} is a Windows binary (a Windows build running under Wine/Proton), which a Linux mod can't load yet",
101 path.display()
102 ))),
103 Ok(()) if cfg!(windows) && elf => Err(Error::UnsupportedBinary(format!("{} is not a Windows binary", path.display()))),
104 _ => Ok(()),
105 }
106}
107
108static INSTANCE: OnceLock<Il2Cpp> = OnceLock::new();
109
110pub struct Il2Cpp {
112 api: Api,
113 _library: Library,
114}
115
116fn cstring(value: &str) -> Result<CString> {
117 CString::new(value).map_err(|_| Error::Nul(value.to_owned()))
118}
119
120pub(crate) unsafe fn c_str<'a>(value: *const std::ffi::c_char) -> &'a str {
121 if value.is_null() {
122 ""
123 } else {
124 unsafe { CStr::from_ptr(value) }.to_str().unwrap_or("")
125 }
126}
127
128impl Il2Cpp {
129 fn install(library: Library) -> Result<&'static Il2Cpp> {
130 let api = Api::load(&library)?;
131 tracing::debug!("loaded the il2cpp_* API from the game binary");
132 Ok(INSTANCE.get_or_init(|| Il2Cpp {
133 api,
134 _library: library,
135 }))
136 }
137
138 pub fn loaded() -> Result<&'static Il2Cpp> {
140 if let Some(il2cpp) = INSTANCE.get() {
141 return Ok(il2cpp);
142 }
143 let path = loaded_game_assembly()
144 .ok_or_else(|| Error::NotFound("a loaded GameAssembly".into()))?;
145 check_format(&path)?;
146 tracing::debug!(path = %path.display(), "using the loaded game binary");
147 #[cfg(unix)]
148 let library = unsafe {
149 libloading::os::unix::Library::open(Some(&path), libc::RTLD_NOW | libc::RTLD_NOLOAD)
150 .map(Library::from)
151 };
152 #[cfg(windows)]
153 let library =
154 libloading::os::windows::Library::open_already_loaded(&path).map(Library::from);
155 Self::install(library.map_err(Error::Load)?)
156 }
157
158 pub fn load(path: impl AsRef<Path>) -> Result<&'static Il2Cpp> {
160 if let Some(il2cpp) = INSTANCE.get() {
161 return Ok(il2cpp);
162 }
163 check_format(path.as_ref())?;
164 tracing::debug!(path = %path.as_ref().display(), "loading the game binary");
165 let library = unsafe { Library::new(path.as_ref()) }.map_err(Error::Load)?;
166 Self::install(library)
167 }
168
169 pub fn get() -> Option<&'static Il2Cpp> {
171 INSTANCE.get()
172 }
173
174 pub fn api(&self) -> &Api {
175 &self.api
176 }
177
178 pub fn init_standalone(&self, data_dir: impl AsRef<Path>) -> Result<()> {
181 tracing::debug!(data_dir = %data_dir.as_ref().display(), "starting Il2Cpp without Unity");
182 let data_dir = cstring(&data_dir.as_ref().to_string_lossy())?;
183 unsafe {
184 (self.api.il2cpp_set_data_dir)(data_dir.as_ptr());
185 if (self.api.il2cpp_init)(c"hao".as_ptr()) == 0 {
186 return Err(Error::Init);
187 }
188 }
189 Ok(())
190 }
191
192 pub fn attach_thread(&self) {
194 unsafe { (self.api.il2cpp_thread_attach)((self.api.il2cpp_domain_get)()) };
195 }
196
197 pub fn class(&'static self, assembly: &str, namespace: &str, name: &str) -> Result<Class> {
199 let (assembly_c, namespace_c, name_c) =
200 (cstring(assembly)?, cstring(namespace)?, cstring(name)?);
201 let class = unsafe {
202 let domain = (self.api.il2cpp_domain_get)();
203 let opened = (self.api.il2cpp_domain_assembly_open)(domain, assembly_c.as_ptr());
204 if opened.is_null() {
205 return Err(Error::NotFound(format!("assembly {}", assembly)));
206 }
207 let image = (self.api.il2cpp_assembly_get_image)(opened);
208 (self.api.il2cpp_class_from_name)(image, namespace_c.as_ptr(), name_c.as_ptr())
209 };
210 if class.is_null() {
211 return Err(Error::NotFound(format!(
212 "class {}.{} in {}",
213 namespace, name, assembly
214 )));
215 }
216 tracing::trace!(assembly, namespace, name, "found class");
217 Ok(Class {
218 il2cpp: self,
219 ptr: class,
220 })
221 }
222
223 pub fn method(&'static self, image_name: &str, token: u32) -> Result<Method> {
233 let assembly = cstring(image_name.strip_suffix(".dll").unwrap_or(image_name))?;
234 let image = unsafe {
235 let domain = (self.api.il2cpp_domain_get)();
236 let opened = (self.api.il2cpp_domain_assembly_open)(domain, assembly.as_ptr());
237 if opened.is_null() {
238 return Err(Error::NotFound(format!("assembly {image_name}")));
239 }
240 Image {
241 il2cpp: self,
242 ptr: (self.api.il2cpp_assembly_get_image)(opened),
243 }
244 };
245 for class in image.classes() {
246 if let Some(method) = class.methods().find(|m| m.token() == token) {
247 tracing::trace!(image = image_name, token, class = class.name(), "found method by token");
248 return Ok(method);
249 }
250 }
251 Err(Error::NotFound(format!(
252 "method with token {token:#x} in {image_name}"
253 )))
254 }
255
256 pub fn string(&self, value: &str) -> Result<Il2CppString> {
258 let value = cstring(value)?;
259 Ok(Il2CppString(Object(unsafe {
260 (self.api.il2cpp_string_new)(value.as_ptr())
261 })))
262 }
263
264 pub fn byte_array(&'static self, bytes: &[u8]) -> Result<Object> {
267 let class = self.class("mscorlib", "System", "Byte")?;
268 let array = unsafe { (self.api.il2cpp_array_new)(class.as_ptr(), bytes.len()) };
269 if array.is_null() {
270 return Err(Error::NotFound("could not allocate a byte[]".into()));
271 }
272 let base = 4 * std::mem::size_of::<usize>();
274 unsafe {
275 std::ptr::copy_nonoverlapping(bytes.as_ptr(), (array as *mut u8).add(base), bytes.len());
276 }
277 Ok(Object(array))
278 }
279
280 pub unsafe fn read_string(&self, string: Object) -> Option<String> {
285 if string.is_null() {
286 return None;
287 }
288 unsafe {
289 let length = (self.api.il2cpp_string_length)(string.0).max(0) as usize;
290 let chars =
291 std::slice::from_raw_parts((self.api.il2cpp_string_chars)(string.0), length);
292 Some(String::from_utf16_lossy(chars))
293 }
294 }
295
296 pub fn assemblies(&'static self) -> Vec<Image> {
298 let mut count: usize = 0;
299 let domain = unsafe { (self.api.il2cpp_domain_get)() };
300 let array = unsafe { (self.api.il2cpp_domain_get_assemblies)(domain, &mut count) };
301 if array.is_null() || count == 0 {
302 return Vec::new();
303 }
304 let ptrs = unsafe { std::slice::from_raw_parts(array, count) };
305 ptrs.iter()
306 .map(|&asm| {
307 let image = unsafe { (self.api.il2cpp_assembly_get_image)(asm) };
308 Image {
309 il2cpp: self,
310 ptr: image,
311 }
312 })
313 .collect()
314 }
315
316 pub unsafe fn class_of(&'static self, object: Object) -> Class {
321 Class {
322 il2cpp: self,
323 ptr: unsafe { (self.api.il2cpp_object_get_class)(object.0) },
324 }
325 }
326
327 pub unsafe fn exception_message(&self, exception: Ptr) -> String {
334 let cls = (self.api.il2cpp_object_get_class)(exception);
335 let class_name = if cls.is_null() {
336 "UnknownException"
337 } else {
338 c_str((self.api.il2cpp_class_get_name)(cls))
339 };
340
341 if !cls.is_null() {
342 if let Ok(to_string) = cstring("ToString") {
343 let method = (self.api.il2cpp_class_get_method_from_name)(
344 cls,
345 to_string.as_ptr(),
346 0,
347 );
348 if !method.is_null() {
349 let mut nested: Ptr = std::ptr::null_mut();
350 let str_obj = (self.api.il2cpp_runtime_invoke)(
351 method,
352 exception,
353 std::ptr::null_mut(),
354 &mut nested,
355 );
356 if nested.is_null() && !str_obj.is_null() {
357 if let Some(s) = self.read_string(Object(str_obj)) {
358 return s;
359 }
360 }
361 }
362 }
363 }
364
365 format!("{class_name} (could not read exception message)")
366 }
367}
368
369#[derive(Clone, Copy)]
371pub struct Class {
372 il2cpp: &'static Il2Cpp,
373 ptr: Ptr,
374}
375
376unsafe impl Send for Class {}
377unsafe impl Sync for Class {}
378
379impl Class {
380 pub fn as_ptr(&self) -> Ptr {
381 self.ptr
382 }
383
384 pub fn name(&self) -> &'static str {
385 unsafe { c_str((self.il2cpp.api.il2cpp_class_get_name)(self.ptr)) }
386 }
387
388 pub fn namespace(&self) -> &'static str {
389 unsafe { c_str((self.il2cpp.api.il2cpp_class_get_namespace)(self.ptr)) }
390 }
391
392 pub fn method(&self, name: &str, parameter_count: i32) -> Result<Method> {
394 let c_name = cstring(name)?;
395 let method = unsafe {
396 (self.il2cpp.api.il2cpp_class_get_method_from_name)(
397 self.ptr,
398 c_name.as_ptr(),
399 parameter_count,
400 )
401 };
402 if method.is_null() {
403 return Err(Error::NotFound(format!(
404 "method {}.{}({} parameters)",
405 self.name(),
406 name,
407 parameter_count
408 )));
409 }
410 tracing::trace!(class = self.name(), name, parameter_count, "found method");
411 Ok(Method {
412 il2cpp: self.il2cpp,
413 ptr: method,
414 })
415 }
416
417 pub fn new_object(&self) -> Object {
420 Object(unsafe { (self.il2cpp.api.il2cpp_object_new)(self.ptr) })
421 }
422
423 pub fn type_object(&self) -> Object {
425 Object(unsafe {
426 (self.il2cpp.api.il2cpp_type_get_object)((self.il2cpp.api.il2cpp_class_get_type)(
427 self.ptr,
428 ))
429 })
430 }
431
432 pub fn methods(&self) -> impl Iterator<Item = Method> + '_ {
434 let mut iter: Ptr = std::ptr::null_mut();
435 std::iter::from_fn(move || {
436 let method = unsafe { (self.il2cpp.api.il2cpp_class_get_methods)(self.ptr, &mut iter) };
437 (!method.is_null()).then_some(Method {
438 il2cpp: self.il2cpp,
439 ptr: method,
440 })
441 })
442 }
443
444 pub fn field(&self, name: &str) -> Result<Field> {
446 let c_name = cstring(name)?;
447 let field = unsafe {
448 (self.il2cpp.api.il2cpp_class_get_field_from_name)(self.ptr, c_name.as_ptr())
449 };
450 if field.is_null() {
451 return Err(Error::NotFound(format!("field {}.{}", self.name(), name)));
452 }
453 Ok(Field {
454 il2cpp: self.il2cpp,
455 ptr: field,
456 })
457 }
458
459 pub fn fields(&self) -> impl Iterator<Item = Field> + '_ {
461 let mut iter: Ptr = std::ptr::null_mut();
462 std::iter::from_fn(move || {
463 let field = unsafe { (self.il2cpp.api.il2cpp_class_get_fields)(self.ptr, &mut iter) };
464 (!field.is_null()).then_some(Field {
465 il2cpp: self.il2cpp,
466 ptr: field,
467 })
468 })
469 }
470
471 pub fn field_offset(&self, name: &str) -> Result<usize> {
473 Ok(self.field(name)?.offset())
474 }
475}
476
477#[derive(Clone, Copy)]
479pub struct Image {
480 il2cpp: &'static Il2Cpp,
481 ptr: Ptr,
482}
483
484unsafe impl Send for Image {}
485unsafe impl Sync for Image {}
486
487impl Image {
488 pub fn name(&self) -> &'static str {
489 unsafe { c_str((self.il2cpp.api.il2cpp_image_get_name)(self.ptr)) }
490 }
491
492 pub fn class_count(&self) -> usize {
493 unsafe { (self.il2cpp.api.il2cpp_image_get_class_count)(self.ptr) }
494 }
495
496 pub fn classes(&self) -> impl Iterator<Item = Class> + '_ {
497 let count = self.class_count();
498 (0..count).map(move |i| {
499 let ptr = unsafe { (self.il2cpp.api.il2cpp_image_get_class)(self.ptr, i) };
500 Class {
501 il2cpp: self.il2cpp,
502 ptr,
503 }
504 })
505 }
506}
507
508#[derive(Clone, Copy)]
510pub struct Field {
511 il2cpp: &'static Il2Cpp,
512 ptr: Ptr,
513}
514
515unsafe impl Send for Field {}
516unsafe impl Sync for Field {}
517
518const FIELD_STATIC: i32 = 0x0010;
520
521impl Field {
522 pub fn as_ptr(&self) -> Ptr {
523 self.ptr
524 }
525
526 pub fn name(&self) -> &'static str {
527 unsafe { c_str((self.il2cpp.api.il2cpp_field_get_name)(self.ptr)) }
528 }
529
530 pub fn type_name(&self) -> String {
532 let ty = unsafe { (self.il2cpp.api.il2cpp_field_get_type)(self.ptr) };
533 unsafe { c_str((self.il2cpp.api.il2cpp_type_get_name)(ty)) }.to_owned()
534 }
535
536 pub fn offset(&self) -> usize {
539 unsafe { (self.il2cpp.api.il2cpp_field_get_offset)(self.ptr) }
540 }
541
542 pub fn is_static(&self) -> bool {
543 unsafe { (self.il2cpp.api.il2cpp_field_get_flags)(self.ptr) & FIELD_STATIC != 0 }
544 }
545
546 pub fn element_type(&self) -> typed::ElementType {
547 let ty = unsafe { (self.il2cpp.api.il2cpp_field_get_type)(self.ptr) };
548 let raw = unsafe { (self.il2cpp.api.il2cpp_type_get_type)(ty) };
549 typed::ElementType::from(raw)
550 }
551
552 pub unsafe fn read<T: Copy>(&self, object: Object) -> T {
558 unsafe { read_field(object, self.offset()) }
559 }
560
561 pub unsafe fn write<T: Copy>(&self, object: Object, value: T) {
566 unsafe { write_field(object, self.offset(), value) }
567 }
568}
569
570pub struct GcHandle {
574 il2cpp: &'static Il2Cpp,
575 handle: Ptr,
576}
577
578unsafe impl Send for GcHandle {}
579unsafe impl Sync for GcHandle {}
580
581impl GcHandle {
582 pub fn new(il2cpp: &'static Il2Cpp, object: Object) -> Self {
583 Self {
584 il2cpp,
585 handle: unsafe { (il2cpp.api.il2cpp_gchandle_new)(object.0, false) },
586 }
587 }
588
589 pub fn target(&self) -> Object {
590 Object(unsafe { (self.il2cpp.api.il2cpp_gchandle_get_target)(self.handle) })
591 }
592}
593
594impl Drop for GcHandle {
595 fn drop(&mut self) {
596 unsafe { (self.il2cpp.api.il2cpp_gchandle_free)(self.handle) }
597 }
598}
599
600#[derive(Clone, Copy)]
602pub struct Method {
603 il2cpp: &'static Il2Cpp,
604 ptr: Ptr,
605}
606
607unsafe impl Send for Method {}
608unsafe impl Sync for Method {}
609
610impl Method {
611 pub fn as_ptr(&self) -> MethodInfo {
613 self.ptr
614 }
615
616 pub fn name(&self) -> &'static str {
617 unsafe { c_str((self.il2cpp.api.il2cpp_method_get_name)(self.ptr)) }
618 }
619
620 pub fn token(&self) -> u32 {
625 unsafe { (self.il2cpp.api.il2cpp_method_get_token)(self.ptr) }
626 }
627
628 pub fn code(&self) -> *mut c_void {
631 unsafe { *(self.ptr as *const *mut c_void) }
633 }
634
635 pub fn runtime_invoke(&self, this: Object, args: &mut [Ptr]) -> Result<Object> {
639 let args_ptr = if args.is_empty() {
640 std::ptr::null_mut()
641 } else {
642 args.as_mut_ptr()
643 };
644 let mut exception: Ptr = std::ptr::null_mut();
645 let result = unsafe {
646 (self.il2cpp.api.il2cpp_runtime_invoke)(
647 self.ptr,
648 this.0,
649 args_ptr as *mut Ptr,
650 &mut exception,
651 )
652 };
653 if !exception.is_null() {
654 let msg = unsafe { self.il2cpp.exception_message(exception) };
655 return Err(Error::Exception(msg));
656 }
657 Ok(Object(result))
658 }
659
660 pub unsafe fn hook_raw(&self, detour: *mut u8) -> Result<MethodHook> {
670 let mut hook = unsafe { hooking::Hook::create(self.code() as *mut u8, detour) }
671 .map_err(Error::Hook)?;
672 unsafe { hook.apply_hook() }.map_err(Error::Hook)?;
673 tracing::debug!(method = self.name(), code = ?self.code(), "hooked (raw)");
674 Ok(MethodHook(hook))
675 }
676}
677
678pub struct MethodHook(pub(crate) hooking::Hook<'static>);
680
681impl MethodHook {
682 pub fn remove(mut self) -> Result<()> {
683 unsafe { self.0.remove_hook() }.map_err(Error::Hook)?;
684 tracing::debug!(code = ?self.0.data.symbol_address, "removed hook");
685 Ok(())
686 }
687}
688
689pub use typed::{ElementType, VoidBlockHook};
690#[cfg(target_arch = "x86_64")]
691pub use typed::{GenericHookMeta, GenericParam, ParamSlot};
692
693pub unsafe fn read_field<T: Copy>(object: Object, offset: usize) -> T {
698 unsafe { std::ptr::read_unaligned((object.0 as *const u8).add(offset) as *const T) }
699}
700
701pub unsafe fn write_field<T: Copy>(object: Object, offset: usize, value: T) {
706 unsafe { std::ptr::write_unaligned((object.0 as *mut u8).add(offset) as *mut T, value) }
707}
708
709#[macro_export]
712macro_rules! original {
713 ($fn_type:ty) => {{
714 let original =
715 $crate::__original_function_ptr().expect("original! must be used inside a hook");
716 unsafe { ::core::mem::transmute::<*mut ::core::ffi::c_void, $fn_type>(original.as_ptr()) }
717 }};
718}
719
720#[doc(hidden)]
721pub use hooking::original_function_ptr as __original_function_ptr;
722
723#[cfg(test)]
724mod tests {
725 use super::*;
726
727 #[cfg(unix)]
728 #[test]
729 fn mapped_game_assembly_paths() {
730 for path in [
731 "/games/Example/GameAssembly.so",
732 "/games/Idle Slayer/GameAssembly.so",
733 ] {
734 let maps = format!(
735 "1000-2000 r-xp 00000000 08:01 1 /games/Idle Slayer/UnityPlayer.so\n\
736 2000-3000 r-xp 00000000 08:01 2 {path}\n"
737 );
738 assert_eq!(game_assembly_in_maps(&maps), Some(PathBuf::from(path)));
739 }
740 }
741
742 #[cfg(unix)]
743 #[test]
744 fn maps_without_game_assembly() {
745 let maps = "1000-2000 r-xp 00000000 08:01 1 /games/Example/UnityPlayer.so\n\
746 2000-3000 rw-p 00000000 00:00 0 [heap]\n\
747 3000-4000 rw-p 00000000 00:00 0\n";
748 assert_eq!(game_assembly_in_maps(maps), None);
749 assert_eq!(game_assembly_in_maps(""), None);
750 }
751
752 #[test]
753 fn game_assembly_names() {
754 assert!(is_game_assembly("/games/Example/GameAssembly.so"));
755 assert!(is_game_assembly("C:\\Games\\Example\\GameAssembly.dll"));
756 assert!(!is_game_assembly("/games/Example/UnityPlayer.so"));
757 assert!(!is_game_assembly("/games/Example/NotGameAssembly.dll"));
758 }
759
760 #[test]
761 fn finds_and_checks_the_game_binary() {
762 let dir = std::env::temp_dir().join(format!("hao-il2cpp-runtime-{}", std::process::id()));
763 std::fs::create_dir_all(&dir).unwrap();
764 std::fs::write(dir.join("UnityPlayer.dll"), b"MZ\x90\x00").unwrap();
765 std::fs::write(dir.join("GameAssembly.dll"), b"MZ\x90\x00").unwrap();
766 let found = find_game_assembly(&dir).unwrap();
767 assert_eq!(found, dir.join("GameAssembly.dll"));
768 if cfg!(unix) {
769 assert!(matches!(
770 check_format(&found),
771 Err(Error::UnsupportedBinary(_))
772 ));
773 }
774 std::fs::remove_dir_all(dir).unwrap();
775 }
776}