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 fn assemblies(&'static self) -> Vec<Image> {
259 let mut count: usize = 0;
260 let domain = unsafe { (self.api.il2cpp_domain_get)() };
261 let array = unsafe { (self.api.il2cpp_domain_get_assemblies)(domain, &mut count) };
262 if array.is_null() || count == 0 {
263 return Vec::new();
264 }
265 let ptrs = unsafe { std::slice::from_raw_parts(array, count) };
266 ptrs.iter()
267 .map(|&asm| {
268 let image = unsafe { (self.api.il2cpp_assembly_get_image)(asm) };
269 Image {
270 il2cpp: self,
271 ptr: image,
272 }
273 })
274 .collect()
275 }
276
277 pub unsafe fn class_of(&'static self, object: Object) -> Class {
282 Class {
283 il2cpp: self,
284 ptr: unsafe { (self.api.il2cpp_object_get_class)(object.0) },
285 }
286 }
287
288 pub unsafe fn exception_message(&self, exception: Ptr) -> String {
295 let cls = (self.api.il2cpp_object_get_class)(exception);
296 let class_name = if cls.is_null() {
297 "UnknownException"
298 } else {
299 c_str((self.api.il2cpp_class_get_name)(cls))
300 };
301
302 if !cls.is_null() {
303 if let Ok(to_string) = cstring("ToString") {
304 let method = (self.api.il2cpp_class_get_method_from_name)(
305 cls,
306 to_string.as_ptr(),
307 0,
308 );
309 if !method.is_null() {
310 let mut nested: Ptr = std::ptr::null_mut();
311 let str_obj = (self.api.il2cpp_runtime_invoke)(
312 method,
313 exception,
314 std::ptr::null_mut(),
315 &mut nested,
316 );
317 if nested.is_null() && !str_obj.is_null() {
318 if let Some(s) = self.read_string(Object(str_obj)) {
319 return s;
320 }
321 }
322 }
323 }
324 }
325
326 format!("{class_name} (could not read exception message)")
327 }
328}
329
330#[derive(Clone, Copy)]
332pub struct Class {
333 il2cpp: &'static Il2Cpp,
334 ptr: Ptr,
335}
336
337unsafe impl Send for Class {}
338unsafe impl Sync for Class {}
339
340impl Class {
341 pub fn as_ptr(&self) -> Ptr {
342 self.ptr
343 }
344
345 pub fn name(&self) -> &'static str {
346 unsafe { c_str((self.il2cpp.api.il2cpp_class_get_name)(self.ptr)) }
347 }
348
349 pub fn namespace(&self) -> &'static str {
350 unsafe { c_str((self.il2cpp.api.il2cpp_class_get_namespace)(self.ptr)) }
351 }
352
353 pub fn method(&self, name: &str, parameter_count: i32) -> Result<Method> {
355 let c_name = cstring(name)?;
356 let method = unsafe {
357 (self.il2cpp.api.il2cpp_class_get_method_from_name)(
358 self.ptr,
359 c_name.as_ptr(),
360 parameter_count,
361 )
362 };
363 if method.is_null() {
364 return Err(Error::NotFound(format!(
365 "method {}.{}({} parameters)",
366 self.name(),
367 name,
368 parameter_count
369 )));
370 }
371 tracing::trace!(class = self.name(), name, parameter_count, "found method");
372 Ok(Method {
373 il2cpp: self.il2cpp,
374 ptr: method,
375 })
376 }
377
378 pub fn new_object(&self) -> Object {
381 Object(unsafe { (self.il2cpp.api.il2cpp_object_new)(self.ptr) })
382 }
383
384 pub fn type_object(&self) -> Object {
386 Object(unsafe {
387 (self.il2cpp.api.il2cpp_type_get_object)((self.il2cpp.api.il2cpp_class_get_type)(
388 self.ptr,
389 ))
390 })
391 }
392
393 pub fn methods(&self) -> impl Iterator<Item = Method> + '_ {
395 let mut iter: Ptr = std::ptr::null_mut();
396 std::iter::from_fn(move || {
397 let method = unsafe { (self.il2cpp.api.il2cpp_class_get_methods)(self.ptr, &mut iter) };
398 (!method.is_null()).then_some(Method {
399 il2cpp: self.il2cpp,
400 ptr: method,
401 })
402 })
403 }
404
405 pub fn field(&self, name: &str) -> Result<Field> {
407 let c_name = cstring(name)?;
408 let field = unsafe {
409 (self.il2cpp.api.il2cpp_class_get_field_from_name)(self.ptr, c_name.as_ptr())
410 };
411 if field.is_null() {
412 return Err(Error::NotFound(format!("field {}.{}", self.name(), name)));
413 }
414 Ok(Field {
415 il2cpp: self.il2cpp,
416 ptr: field,
417 })
418 }
419
420 pub fn fields(&self) -> impl Iterator<Item = Field> + '_ {
422 let mut iter: Ptr = std::ptr::null_mut();
423 std::iter::from_fn(move || {
424 let field = unsafe { (self.il2cpp.api.il2cpp_class_get_fields)(self.ptr, &mut iter) };
425 (!field.is_null()).then_some(Field {
426 il2cpp: self.il2cpp,
427 ptr: field,
428 })
429 })
430 }
431
432 pub fn field_offset(&self, name: &str) -> Result<usize> {
434 Ok(self.field(name)?.offset())
435 }
436}
437
438#[derive(Clone, Copy)]
440pub struct Image {
441 il2cpp: &'static Il2Cpp,
442 ptr: Ptr,
443}
444
445unsafe impl Send for Image {}
446unsafe impl Sync for Image {}
447
448impl Image {
449 pub fn name(&self) -> &'static str {
450 unsafe { c_str((self.il2cpp.api.il2cpp_image_get_name)(self.ptr)) }
451 }
452
453 pub fn class_count(&self) -> usize {
454 unsafe { (self.il2cpp.api.il2cpp_image_get_class_count)(self.ptr) }
455 }
456
457 pub fn classes(&self) -> impl Iterator<Item = Class> + '_ {
458 let count = self.class_count();
459 (0..count).map(move |i| {
460 let ptr = unsafe { (self.il2cpp.api.il2cpp_image_get_class)(self.ptr, i) };
461 Class {
462 il2cpp: self.il2cpp,
463 ptr,
464 }
465 })
466 }
467}
468
469#[derive(Clone, Copy)]
471pub struct Field {
472 il2cpp: &'static Il2Cpp,
473 ptr: Ptr,
474}
475
476unsafe impl Send for Field {}
477unsafe impl Sync for Field {}
478
479const FIELD_STATIC: i32 = 0x0010;
481
482impl Field {
483 pub fn as_ptr(&self) -> Ptr {
484 self.ptr
485 }
486
487 pub fn name(&self) -> &'static str {
488 unsafe { c_str((self.il2cpp.api.il2cpp_field_get_name)(self.ptr)) }
489 }
490
491 pub fn type_name(&self) -> String {
493 let ty = unsafe { (self.il2cpp.api.il2cpp_field_get_type)(self.ptr) };
494 unsafe { c_str((self.il2cpp.api.il2cpp_type_get_name)(ty)) }.to_owned()
495 }
496
497 pub fn offset(&self) -> usize {
500 unsafe { (self.il2cpp.api.il2cpp_field_get_offset)(self.ptr) }
501 }
502
503 pub fn is_static(&self) -> bool {
504 unsafe { (self.il2cpp.api.il2cpp_field_get_flags)(self.ptr) & FIELD_STATIC != 0 }
505 }
506
507 pub fn element_type(&self) -> typed::ElementType {
508 let ty = unsafe { (self.il2cpp.api.il2cpp_field_get_type)(self.ptr) };
509 let raw = unsafe { (self.il2cpp.api.il2cpp_type_get_type)(ty) };
510 typed::ElementType::from(raw)
511 }
512
513 pub unsafe fn read<T: Copy>(&self, object: Object) -> T {
519 unsafe { read_field(object, self.offset()) }
520 }
521
522 pub unsafe fn write<T: Copy>(&self, object: Object, value: T) {
527 unsafe { write_field(object, self.offset(), value) }
528 }
529}
530
531pub struct GcHandle {
535 il2cpp: &'static Il2Cpp,
536 handle: Ptr,
537}
538
539unsafe impl Send for GcHandle {}
540unsafe impl Sync for GcHandle {}
541
542impl GcHandle {
543 pub fn new(il2cpp: &'static Il2Cpp, object: Object) -> Self {
544 Self {
545 il2cpp,
546 handle: unsafe { (il2cpp.api.il2cpp_gchandle_new)(object.0, false) },
547 }
548 }
549
550 pub fn target(&self) -> Object {
551 Object(unsafe { (self.il2cpp.api.il2cpp_gchandle_get_target)(self.handle) })
552 }
553}
554
555impl Drop for GcHandle {
556 fn drop(&mut self) {
557 unsafe { (self.il2cpp.api.il2cpp_gchandle_free)(self.handle) }
558 }
559}
560
561#[derive(Clone, Copy)]
563pub struct Method {
564 il2cpp: &'static Il2Cpp,
565 ptr: Ptr,
566}
567
568unsafe impl Send for Method {}
569unsafe impl Sync for Method {}
570
571impl Method {
572 pub fn as_ptr(&self) -> MethodInfo {
574 self.ptr
575 }
576
577 pub fn name(&self) -> &'static str {
578 unsafe { c_str((self.il2cpp.api.il2cpp_method_get_name)(self.ptr)) }
579 }
580
581 pub fn code(&self) -> *mut c_void {
584 unsafe { *(self.ptr as *const *mut c_void) }
586 }
587
588 pub fn runtime_invoke(&self, this: Object, args: &mut [Ptr]) -> Result<Object> {
592 let args_ptr = if args.is_empty() {
593 std::ptr::null_mut()
594 } else {
595 args.as_mut_ptr()
596 };
597 let mut exception: Ptr = std::ptr::null_mut();
598 let result = unsafe {
599 (self.il2cpp.api.il2cpp_runtime_invoke)(
600 self.ptr,
601 this.0,
602 args_ptr as *mut Ptr,
603 &mut exception,
604 )
605 };
606 if !exception.is_null() {
607 let msg = unsafe { self.il2cpp.exception_message(exception) };
608 return Err(Error::Exception(msg));
609 }
610 Ok(Object(result))
611 }
612
613 pub unsafe fn hook_raw(&self, detour: *mut u8) -> Result<MethodHook> {
623 let mut hook = unsafe { hooking::Hook::create(self.code() as *mut u8, detour) }
624 .map_err(Error::Hook)?;
625 unsafe { hook.apply_hook() }.map_err(Error::Hook)?;
626 tracing::debug!(method = self.name(), code = ?self.code(), "hooked (raw)");
627 Ok(MethodHook(hook))
628 }
629}
630
631pub struct MethodHook(pub(crate) hooking::Hook<'static>);
633
634impl MethodHook {
635 pub fn remove(mut self) -> Result<()> {
636 unsafe { self.0.remove_hook() }.map_err(Error::Hook)?;
637 tracing::debug!(code = ?self.0.data.symbol_address, "removed hook");
638 Ok(())
639 }
640}
641
642pub use typed::{ElementType, VoidBlockHook};
643#[cfg(target_arch = "x86_64")]
644pub use typed::{GenericHookMeta, GenericParam, ParamSlot};
645
646pub unsafe fn read_field<T: Copy>(object: Object, offset: usize) -> T {
651 unsafe { std::ptr::read_unaligned((object.0 as *const u8).add(offset) as *const T) }
652}
653
654pub unsafe fn write_field<T: Copy>(object: Object, offset: usize, value: T) {
659 unsafe { std::ptr::write_unaligned((object.0 as *mut u8).add(offset) as *mut T, value) }
660}
661
662#[macro_export]
665macro_rules! original {
666 ($fn_type:ty) => {{
667 let original =
668 $crate::__original_function_ptr().expect("original! must be used inside a hook");
669 unsafe { ::core::mem::transmute::<*mut ::core::ffi::c_void, $fn_type>(original.as_ptr()) }
670 }};
671}
672
673#[doc(hidden)]
674pub use hooking::original_function_ptr as __original_function_ptr;
675
676#[cfg(test)]
677mod tests {
678 use super::*;
679
680 #[test]
681 fn game_assembly_names() {
682 assert!(is_game_assembly("/games/Example/GameAssembly.so"));
683 assert!(is_game_assembly("C:\\Games\\Example\\GameAssembly.dll"));
684 assert!(!is_game_assembly("/games/Example/UnityPlayer.so"));
685 assert!(!is_game_assembly("/games/Example/NotGameAssembly.dll"));
686 }
687
688 #[test]
689 fn finds_and_checks_the_game_binary() {
690 let dir = std::env::temp_dir().join(format!("hao-il2cpp-runtime-{}", std::process::id()));
691 std::fs::create_dir_all(&dir).unwrap();
692 std::fs::write(dir.join("UnityPlayer.dll"), b"MZ\x90\x00").unwrap();
693 std::fs::write(dir.join("GameAssembly.dll"), b"MZ\x90\x00").unwrap();
694 let found = find_game_assembly(&dir).unwrap();
695 assert_eq!(found, dir.join("GameAssembly.dll"));
696 if cfg!(unix) {
697 assert!(matches!(
698 check_format(&found),
699 Err(Error::UnsupportedBinary(_))
700 ));
701 }
702 std::fs::remove_dir_all(dir).unwrap();
703 }
704}