1#![cfg_attr(docsrs, feature(doc_cfg))]
47#![warn(missing_docs)]
48
49mod api;
50mod error;
51#[cfg(unix)]
52mod loader;
53#[cfg(feature = "reflect")]
54pub mod reflect;
55mod typed;
56
57use std::{
58 ffi::{c_void, CStr, CString},
59 path::{Path, PathBuf},
60 sync::OnceLock,
61};
62
63use libloading::Library;
64
65pub use api::{Api, Ptr};
66pub use error::{Error, Result};
67#[cfg(unix)]
68pub use loader::on_init;
69pub use typed::{
70 element, HookCallback, Il2CppString, Il2CppValue, MethodArgs, Object, Original, Parameter,
71 Signature, TypeInfo, ValueCheck,
72};
73
74pub type MethodInfo = Ptr;
76
77pub fn is_game_assembly(path: impl AsRef<Path>) -> bool {
80 let path = path.as_ref().to_string_lossy();
81 path.rsplit(['/', '\\'])
82 .next()
83 .is_some_and(|name| name.starts_with("GameAssembly."))
84}
85
86pub fn find_game_assembly(dir: impl AsRef<Path>) -> Option<PathBuf> {
88 std::fs::read_dir(dir)
89 .ok()?
90 .filter_map(|e| e.ok().map(|e| e.path()))
91 .find(|p| p.is_file() && is_game_assembly(p))
92}
93
94#[cfg(unix)]
96pub fn loaded_game_assembly() -> Option<PathBuf> {
97 let maps = std::fs::read_to_string("/proc/self/maps").ok()?;
98 game_assembly_in_maps(&maps)
99}
100
101#[cfg(unix)]
102fn game_assembly_in_maps(maps: &str) -> Option<PathBuf> {
103 maps.lines()
104 .filter_map(|line| line.find('/').map(|start| &line[start..]))
106 .map(PathBuf::from)
107 .find(|p| is_game_assembly(p))
108}
109
110#[cfg(windows)]
112pub fn loaded_game_assembly() -> Option<PathBuf> {
113 libloading::os::windows::Library::open_already_loaded("GameAssembly.dll")
114 .ok()
115 .map(|_| PathBuf::from("GameAssembly.dll"))
116}
117
118fn check_format(path: &Path) -> Result<()> {
120 use std::io::Read;
121 let mut magic = [0u8; 4];
122 let read = std::fs::File::open(path).and_then(|mut f| f.read_exact(&mut magic));
123 let (elf, pe) = (magic == *b"\x7fELF", magic.starts_with(b"MZ"));
124 match read {
125 Ok(()) if cfg!(unix) && pe => Err(Error::UnsupportedBinary(format!(
126 "{} is a Windows binary (a Windows build running under Wine/Proton), which a Linux mod can't load yet",
127 path.display()
128 ))),
129 Ok(()) if cfg!(windows) && elf => Err(Error::UnsupportedBinary(format!("{} is not a Windows binary", path.display()))),
130 _ => Ok(()),
131 }
132}
133
134static INSTANCE: OnceLock<Il2Cpp> = OnceLock::new();
135
136pub struct Il2Cpp {
138 api: Api,
139 _library: Library,
140}
141
142fn cstring(value: &str) -> Result<CString> {
143 CString::new(value).map_err(|_| Error::Nul(value.to_owned()))
144}
145
146pub(crate) unsafe fn c_str<'a>(value: *const std::ffi::c_char) -> &'a str {
147 if value.is_null() {
148 ""
149 } else {
150 unsafe { CStr::from_ptr(value) }.to_str().unwrap_or("")
151 }
152}
153
154impl Il2Cpp {
155 fn install(library: Library) -> Result<&'static Il2Cpp> {
156 let api = Api::load(&library)?;
157 tracing::debug!("loaded the il2cpp_* API from the game binary");
158 Ok(INSTANCE.get_or_init(|| Il2Cpp {
159 api,
160 _library: library,
161 }))
162 }
163
164 pub fn loaded() -> Result<&'static Il2Cpp> {
166 if let Some(il2cpp) = INSTANCE.get() {
167 return Ok(il2cpp);
168 }
169 let path = loaded_game_assembly()
170 .ok_or_else(|| Error::NotFound("a loaded GameAssembly".into()))?;
171 check_format(&path)?;
172 tracing::debug!(path = %path.display(), "using the loaded game binary");
173 #[cfg(unix)]
174 let library = unsafe {
175 libloading::os::unix::Library::open(Some(&path), libc::RTLD_NOW | libc::RTLD_NOLOAD)
176 .map(Library::from)
177 };
178 #[cfg(windows)]
179 let library =
180 libloading::os::windows::Library::open_already_loaded(&path).map(Library::from);
181 Self::install(library.map_err(Error::Load)?)
182 }
183
184 pub fn load(path: impl AsRef<Path>) -> Result<&'static Il2Cpp> {
186 if let Some(il2cpp) = INSTANCE.get() {
187 return Ok(il2cpp);
188 }
189 check_format(path.as_ref())?;
190 tracing::debug!(path = %path.as_ref().display(), "loading the game binary");
191 let library = unsafe { Library::new(path.as_ref()) }.map_err(Error::Load)?;
192 Self::install(library)
193 }
194
195 pub fn get() -> Option<&'static Il2Cpp> {
197 INSTANCE.get()
198 }
199
200 pub fn api(&self) -> &Api {
202 &self.api
203 }
204
205 pub fn init_standalone(&self, data_dir: impl AsRef<Path>) -> Result<()> {
208 tracing::debug!(data_dir = %data_dir.as_ref().display(), "starting Il2Cpp without Unity");
209 let data_dir = cstring(&data_dir.as_ref().to_string_lossy())?;
210 unsafe {
211 (self.api.il2cpp_set_data_dir)(data_dir.as_ptr());
212 if (self.api.il2cpp_init)(c"hao".as_ptr()) == 0 {
213 return Err(Error::Init);
214 }
215 }
216 Ok(())
217 }
218
219 pub fn attach_thread(&self) {
221 unsafe { (self.api.il2cpp_thread_attach)((self.api.il2cpp_domain_get)()) };
222 }
223
224 pub fn class(&'static self, assembly: &str, namespace: &str, name: &str) -> Result<Class> {
226 let (assembly_c, namespace_c, name_c) =
227 (cstring(assembly)?, cstring(namespace)?, cstring(name)?);
228 let class = unsafe {
229 let domain = (self.api.il2cpp_domain_get)();
230 let opened = (self.api.il2cpp_domain_assembly_open)(domain, assembly_c.as_ptr());
231 if opened.is_null() {
232 return Err(Error::NotFound(format!("assembly {}", assembly)));
233 }
234 let image = (self.api.il2cpp_assembly_get_image)(opened);
235 (self.api.il2cpp_class_from_name)(image, namespace_c.as_ptr(), name_c.as_ptr())
236 };
237 if class.is_null() {
238 return Err(Error::NotFound(format!(
239 "class {}.{} in {}",
240 namespace, name, assembly
241 )));
242 }
243 tracing::trace!(assembly, namespace, name, "found class");
244 Ok(Class {
245 il2cpp: self,
246 ptr: class,
247 })
248 }
249
250 pub fn method(&'static self, image_name: &str, token: u32) -> Result<Method> {
260 let assembly = cstring(image_name.strip_suffix(".dll").unwrap_or(image_name))?;
261 let image = unsafe {
262 let domain = (self.api.il2cpp_domain_get)();
263 let opened = (self.api.il2cpp_domain_assembly_open)(domain, assembly.as_ptr());
264 if opened.is_null() {
265 return Err(Error::NotFound(format!("assembly {image_name}")));
266 }
267 Image {
268 il2cpp: self,
269 ptr: (self.api.il2cpp_assembly_get_image)(opened),
270 }
271 };
272 for class in image.classes() {
273 if let Some(method) = class.methods().find(|m| m.token() == token) {
274 tracing::trace!(
275 image = image_name,
276 token,
277 class = class.name(),
278 "found method by token"
279 );
280 return Ok(method);
281 }
282 }
283 Err(Error::NotFound(format!(
284 "method with token {token:#x} in {image_name}"
285 )))
286 }
287
288 pub fn string(&self, value: &str) -> Result<Il2CppString> {
290 let value = cstring(value)?;
291 Ok(Il2CppString(Object(unsafe {
292 (self.api.il2cpp_string_new)(value.as_ptr())
293 })))
294 }
295
296 pub fn byte_array(&'static self, bytes: &[u8]) -> Result<Object> {
299 let class = self.class("mscorlib", "System", "Byte")?;
300 let array = unsafe { (self.api.il2cpp_array_new)(class.as_ptr(), bytes.len()) };
301 if array.is_null() {
302 return Err(Error::NotFound("could not allocate a byte[]".into()));
303 }
304 let base = 4 * std::mem::size_of::<usize>();
306 unsafe {
307 std::ptr::copy_nonoverlapping(
308 bytes.as_ptr(),
309 (array as *mut u8).add(base),
310 bytes.len(),
311 );
312 }
313 Ok(Object(array))
314 }
315
316 pub unsafe fn read_string(&self, string: Object) -> Option<String> {
321 if string.is_null() {
322 return None;
323 }
324 unsafe {
325 let length = (self.api.il2cpp_string_length)(string.0).max(0) as usize;
326 let chars =
327 std::slice::from_raw_parts((self.api.il2cpp_string_chars)(string.0), length);
328 Some(String::from_utf16_lossy(chars))
329 }
330 }
331
332 pub fn assemblies(&'static self) -> Vec<Image> {
334 let mut count: usize = 0;
335 let domain = unsafe { (self.api.il2cpp_domain_get)() };
336 let array = unsafe { (self.api.il2cpp_domain_get_assemblies)(domain, &mut count) };
337 if array.is_null() || count == 0 {
338 return Vec::new();
339 }
340 let ptrs = unsafe { std::slice::from_raw_parts(array, count) };
341 ptrs.iter()
342 .map(|&asm| {
343 let image = unsafe { (self.api.il2cpp_assembly_get_image)(asm) };
344 Image {
345 il2cpp: self,
346 ptr: image,
347 }
348 })
349 .collect()
350 }
351
352 pub unsafe fn class_of(&'static self, object: Object) -> Class {
357 Class {
358 il2cpp: self,
359 ptr: unsafe { (self.api.il2cpp_object_get_class)(object.0) },
360 }
361 }
362
363 pub unsafe fn exception_message(&self, exception: Ptr) -> String {
370 let cls = (self.api.il2cpp_object_get_class)(exception);
371 let class_name = if cls.is_null() {
372 "UnknownException"
373 } else {
374 c_str((self.api.il2cpp_class_get_name)(cls))
375 };
376
377 if !cls.is_null() {
378 if let Ok(to_string) = cstring("ToString") {
379 let method =
380 (self.api.il2cpp_class_get_method_from_name)(cls, to_string.as_ptr(), 0);
381 if !method.is_null() {
382 let mut nested: Ptr = std::ptr::null_mut();
383 let str_obj = (self.api.il2cpp_runtime_invoke)(
384 method,
385 exception,
386 std::ptr::null_mut(),
387 &mut nested,
388 );
389 if nested.is_null() && !str_obj.is_null() {
390 if let Some(s) = self.read_string(Object(str_obj)) {
391 return s;
392 }
393 }
394 }
395 }
396 }
397
398 format!("{class_name} (could not read exception message)")
399 }
400}
401
402#[derive(Clone, Copy)]
404pub struct Class {
405 il2cpp: &'static Il2Cpp,
406 ptr: Ptr,
407}
408
409unsafe impl Send for Class {}
410unsafe impl Sync for Class {}
411
412impl Class {
413 pub fn as_ptr(&self) -> Ptr {
415 self.ptr
416 }
417
418 pub fn name(&self) -> &'static str {
420 unsafe { c_str((self.il2cpp.api.il2cpp_class_get_name)(self.ptr)) }
421 }
422
423 pub fn namespace(&self) -> &'static str {
425 unsafe { c_str((self.il2cpp.api.il2cpp_class_get_namespace)(self.ptr)) }
426 }
427
428 pub fn method(&self, name: &str, parameter_count: i32) -> Result<Method> {
430 let c_name = cstring(name)?;
431 let method = unsafe {
432 (self.il2cpp.api.il2cpp_class_get_method_from_name)(
433 self.ptr,
434 c_name.as_ptr(),
435 parameter_count,
436 )
437 };
438 if method.is_null() {
439 return Err(Error::NotFound(format!(
440 "method {}.{}({} parameters)",
441 self.name(),
442 name,
443 parameter_count
444 )));
445 }
446 tracing::trace!(class = self.name(), name, parameter_count, "found method");
447 Ok(Method {
448 il2cpp: self.il2cpp,
449 ptr: method,
450 })
451 }
452
453 pub fn new_object(&self) -> Object {
456 Object(unsafe { (self.il2cpp.api.il2cpp_object_new)(self.ptr) })
457 }
458
459 pub fn type_object(&self) -> Object {
461 Object(unsafe {
462 (self.il2cpp.api.il2cpp_type_get_object)((self.il2cpp.api.il2cpp_class_get_type)(
463 self.ptr,
464 ))
465 })
466 }
467
468 pub fn methods(&self) -> impl Iterator<Item = Method> + '_ {
470 let mut iter: Ptr = std::ptr::null_mut();
471 std::iter::from_fn(move || {
472 let method = unsafe { (self.il2cpp.api.il2cpp_class_get_methods)(self.ptr, &mut iter) };
473 (!method.is_null()).then_some(Method {
474 il2cpp: self.il2cpp,
475 ptr: method,
476 })
477 })
478 }
479
480 pub fn field(&self, name: &str) -> Result<Field> {
482 let c_name = cstring(name)?;
483 let field = unsafe {
484 (self.il2cpp.api.il2cpp_class_get_field_from_name)(self.ptr, c_name.as_ptr())
485 };
486 if field.is_null() {
487 return Err(Error::NotFound(format!("field {}.{}", self.name(), name)));
488 }
489 Ok(Field {
490 il2cpp: self.il2cpp,
491 ptr: field,
492 })
493 }
494
495 pub fn fields(&self) -> impl Iterator<Item = Field> + '_ {
497 let mut iter: Ptr = std::ptr::null_mut();
498 std::iter::from_fn(move || {
499 let field = unsafe { (self.il2cpp.api.il2cpp_class_get_fields)(self.ptr, &mut iter) };
500 (!field.is_null()).then_some(Field {
501 il2cpp: self.il2cpp,
502 ptr: field,
503 })
504 })
505 }
506
507 pub fn field_offset(&self, name: &str) -> Result<usize> {
509 Ok(self.field(name)?.offset())
510 }
511}
512
513#[derive(Clone, Copy)]
515pub struct Image {
516 il2cpp: &'static Il2Cpp,
517 ptr: Ptr,
518}
519
520unsafe impl Send for Image {}
521unsafe impl Sync for Image {}
522
523impl Image {
524 pub fn name(&self) -> &'static str {
526 unsafe { c_str((self.il2cpp.api.il2cpp_image_get_name)(self.ptr)) }
527 }
528
529 pub fn class_count(&self) -> usize {
531 unsafe { (self.il2cpp.api.il2cpp_image_get_class_count)(self.ptr) }
532 }
533
534 pub fn classes(&self) -> impl Iterator<Item = Class> + '_ {
536 let count = self.class_count();
537 (0..count).map(move |i| {
538 let ptr = unsafe { (self.il2cpp.api.il2cpp_image_get_class)(self.ptr, i) };
539 Class {
540 il2cpp: self.il2cpp,
541 ptr,
542 }
543 })
544 }
545}
546
547#[derive(Clone, Copy)]
549pub struct Field {
550 il2cpp: &'static Il2Cpp,
551 ptr: Ptr,
552}
553
554unsafe impl Send for Field {}
555unsafe impl Sync for Field {}
556
557const FIELD_STATIC: i32 = 0x0010;
559
560impl Field {
561 pub fn as_ptr(&self) -> Ptr {
563 self.ptr
564 }
565
566 pub fn name(&self) -> &'static str {
568 unsafe { c_str((self.il2cpp.api.il2cpp_field_get_name)(self.ptr)) }
569 }
570
571 pub fn type_name(&self) -> String {
573 let ty = unsafe { (self.il2cpp.api.il2cpp_field_get_type)(self.ptr) };
574 unsafe { c_str((self.il2cpp.api.il2cpp_type_get_name)(ty)) }.to_owned()
575 }
576
577 pub fn offset(&self) -> usize {
580 unsafe { (self.il2cpp.api.il2cpp_field_get_offset)(self.ptr) }
581 }
582
583 pub fn is_static(&self) -> bool {
586 unsafe { (self.il2cpp.api.il2cpp_field_get_flags)(self.ptr) & FIELD_STATIC != 0 }
587 }
588
589 pub fn element_type(&self) -> typed::ElementType {
592 let ty = unsafe { (self.il2cpp.api.il2cpp_field_get_type)(self.ptr) };
593 let raw = unsafe { (self.il2cpp.api.il2cpp_type_get_type)(ty) };
594 typed::ElementType::from(raw)
595 }
596
597 pub unsafe fn read<T: Copy>(&self, object: Object) -> T {
603 unsafe { read_field(object, self.offset()) }
604 }
605
606 pub unsafe fn write<T: Copy>(&self, object: Object, value: T) {
611 unsafe { write_field(object, self.offset(), value) }
612 }
613}
614
615pub struct GcHandle {
619 il2cpp: &'static Il2Cpp,
620 handle: Ptr,
621}
622
623unsafe impl Send for GcHandle {}
624unsafe impl Sync for GcHandle {}
625
626impl GcHandle {
627 pub fn new(il2cpp: &'static Il2Cpp, object: Object) -> Self {
629 Self {
630 il2cpp,
631 handle: unsafe { (il2cpp.api.il2cpp_gchandle_new)(object.0, false) },
632 }
633 }
634
635 pub fn target(&self) -> Object {
637 Object(unsafe { (self.il2cpp.api.il2cpp_gchandle_get_target)(self.handle) })
638 }
639}
640
641impl Drop for GcHandle {
642 fn drop(&mut self) {
643 unsafe { (self.il2cpp.api.il2cpp_gchandle_free)(self.handle) }
644 }
645}
646
647#[derive(Clone, Copy)]
649pub struct Method {
650 il2cpp: &'static Il2Cpp,
651 ptr: Ptr,
652}
653
654unsafe impl Send for Method {}
655unsafe impl Sync for Method {}
656
657impl Method {
658 pub fn as_ptr(&self) -> MethodInfo {
660 self.ptr
661 }
662
663 pub fn name(&self) -> &'static str {
665 unsafe { c_str((self.il2cpp.api.il2cpp_method_get_name)(self.ptr)) }
666 }
667
668 pub fn token(&self) -> u32 {
673 unsafe { (self.il2cpp.api.il2cpp_method_get_token)(self.ptr) }
674 }
675
676 pub fn code(&self) -> *mut c_void {
679 unsafe { *(self.ptr as *const *mut c_void) }
681 }
682
683 pub fn runtime_invoke(&self, this: Object, args: &mut [Ptr]) -> Result<Object> {
687 let args_ptr = if args.is_empty() {
688 std::ptr::null_mut()
689 } else {
690 args.as_mut_ptr()
691 };
692 let mut exception: Ptr = std::ptr::null_mut();
693 let result = unsafe {
694 (self.il2cpp.api.il2cpp_runtime_invoke)(
695 self.ptr,
696 this.0,
697 args_ptr as *mut Ptr,
698 &mut exception,
699 )
700 };
701 if !exception.is_null() {
702 let msg = unsafe { self.il2cpp.exception_message(exception) };
703 return Err(Error::Exception(msg));
704 }
705 Ok(Object(result))
706 }
707
708 pub unsafe fn hook_raw(&self, detour: *mut u8) -> Result<MethodHook> {
718 let mut hook = unsafe { hooking::Hook::create(self.code() as *mut u8, detour) }
719 .map_err(Error::Hook)?;
720 unsafe { hook.apply_hook() }.map_err(Error::Hook)?;
721 tracing::debug!(method = self.name(), code = ?self.code(), "hooked (raw)");
722 Ok(MethodHook(hook))
723 }
724}
725
726pub struct MethodHook(pub(crate) hooking::Hook<'static>);
728
729impl MethodHook {
730 pub fn remove(mut self) -> Result<()> {
732 unsafe { self.0.remove_hook() }.map_err(Error::Hook)?;
733 tracing::debug!(code = ?self.0.data.symbol_address, "removed hook");
734 Ok(())
735 }
736}
737
738pub use typed::{ElementType, VoidBlockHook};
739#[cfg(target_arch = "x86_64")]
740pub use typed::{GenericHookMeta, GenericParam, ParamSlot};
741
742pub unsafe fn read_field<T: Copy>(object: Object, offset: usize) -> T {
747 unsafe { std::ptr::read_unaligned((object.0 as *const u8).add(offset) as *const T) }
748}
749
750pub unsafe fn write_field<T: Copy>(object: Object, offset: usize, value: T) {
755 unsafe { std::ptr::write_unaligned((object.0 as *mut u8).add(offset) as *mut T, value) }
756}
757
758#[macro_export]
761macro_rules! original {
762 ($fn_type:ty) => {{
763 let original =
764 $crate::__original_function_ptr().expect("original! must be used inside a hook");
765 unsafe { ::core::mem::transmute::<*mut ::core::ffi::c_void, $fn_type>(original.as_ptr()) }
766 }};
767}
768
769#[doc(hidden)]
770pub use hooking::original_function_ptr as __original_function_ptr;
771
772#[cfg(test)]
773mod tests {
774 use super::*;
775
776 #[cfg(unix)]
777 #[test]
778 fn mapped_game_assembly_paths() {
779 for path in [
780 "/games/Example/GameAssembly.so",
781 "/games/Idle Slayer/GameAssembly.so",
782 ] {
783 let maps = format!(
784 "1000-2000 r-xp 00000000 08:01 1 /games/Idle Slayer/UnityPlayer.so\n\
785 2000-3000 r-xp 00000000 08:01 2 {path}\n"
786 );
787 assert_eq!(game_assembly_in_maps(&maps), Some(PathBuf::from(path)));
788 }
789 }
790
791 #[cfg(unix)]
792 #[test]
793 fn maps_without_game_assembly() {
794 let maps = "1000-2000 r-xp 00000000 08:01 1 /games/Example/UnityPlayer.so\n\
795 2000-3000 rw-p 00000000 00:00 0 [heap]\n\
796 3000-4000 rw-p 00000000 00:00 0\n";
797 assert_eq!(game_assembly_in_maps(maps), None);
798 assert_eq!(game_assembly_in_maps(""), None);
799 }
800
801 #[test]
802 fn game_assembly_names() {
803 assert!(is_game_assembly("/games/Example/GameAssembly.so"));
804 assert!(is_game_assembly("C:\\Games\\Example\\GameAssembly.dll"));
805 assert!(!is_game_assembly("/games/Example/UnityPlayer.so"));
806 assert!(!is_game_assembly("/games/Example/NotGameAssembly.dll"));
807 }
808
809 #[test]
810 fn finds_and_checks_the_game_binary() {
811 let dir = std::env::temp_dir().join(format!("hao-il2cpp-runtime-{}", std::process::id()));
812 std::fs::create_dir_all(&dir).unwrap();
813 std::fs::write(dir.join("UnityPlayer.dll"), b"MZ\x90\x00").unwrap();
814 std::fs::write(dir.join("GameAssembly.dll"), b"MZ\x90\x00").unwrap();
815 let found = find_game_assembly(&dir).unwrap();
816 assert_eq!(found, dir.join("GameAssembly.dll"));
817 if cfg!(unix) {
818 assert!(matches!(
819 check_format(&found),
820 Err(Error::UnsupportedBinary(_))
821 ));
822 }
823 std::fs::remove_dir_all(dir).unwrap();
824 }
825}