1mod api;
24mod error;
25#[cfg(unix)]
26mod loader;
27mod typed;
28
29use std::{
30 ffi::{c_void, CStr, CString},
31 path::{Path, PathBuf},
32 sync::OnceLock,
33};
34
35use libloading::Library;
36
37pub use api::{Api, Ptr};
38pub use error::{Error, Result};
39#[cfg(unix)]
40pub use loader::on_init;
41pub use typed::{
42 element, HookCallback, Il2CppString, Il2CppValue, MethodArgs, Object, Original, Parameter,
43 Signature, TypeInfo, ValueCheck,
44};
45
46pub type MethodInfo = Ptr;
48
49pub fn is_game_assembly(path: impl AsRef<Path>) -> bool {
52 let path = path.as_ref().to_string_lossy();
53 path.rsplit(['/', '\\'])
54 .next()
55 .is_some_and(|name| name.starts_with("GameAssembly."))
56}
57
58pub fn find_game_assembly(dir: impl AsRef<Path>) -> Option<PathBuf> {
60 std::fs::read_dir(dir)
61 .ok()?
62 .filter_map(|e| e.ok().map(|e| e.path()))
63 .find(|p| p.is_file() && is_game_assembly(p))
64}
65
66#[cfg(unix)]
68pub fn loaded_game_assembly() -> Option<PathBuf> {
69 let maps = std::fs::read_to_string("/proc/self/maps").ok()?;
70 maps.lines()
71 .filter_map(|line| line.split_whitespace().nth(5))
72 .map(PathBuf::from)
73 .find(|p| is_game_assembly(p))
74}
75
76#[cfg(windows)]
78pub fn loaded_game_assembly() -> Option<PathBuf> {
79 libloading::os::windows::Library::open_already_loaded("GameAssembly.dll")
80 .ok()
81 .map(|_| PathBuf::from("GameAssembly.dll"))
82}
83
84fn check_format(path: &Path) -> Result<()> {
86 use std::io::Read;
87 let mut magic = [0u8; 4];
88 let read = std::fs::File::open(path).and_then(|mut f| f.read_exact(&mut magic));
89 let (elf, pe) = (magic == *b"\x7fELF", magic.starts_with(b"MZ"));
90 match read {
91 Ok(()) if cfg!(unix) && pe => Err(Error::UnsupportedBinary(format!(
92 "{} is a Windows binary (a Windows build running under Wine/Proton), which a Linux mod can't load yet",
93 path.display()
94 ))),
95 Ok(()) if cfg!(windows) && elf => Err(Error::UnsupportedBinary(format!("{} is not a Windows binary", path.display()))),
96 _ => Ok(()),
97 }
98}
99
100static INSTANCE: OnceLock<Il2Cpp> = OnceLock::new();
101
102pub struct Il2Cpp {
104 api: Api,
105 _library: Library,
106}
107
108fn cstring(value: &str) -> Result<CString> {
109 CString::new(value).map_err(|_| Error::Nul(value.to_owned()))
110}
111
112pub(crate) unsafe fn c_str<'a>(value: *const std::ffi::c_char) -> &'a str {
113 if value.is_null() {
114 ""
115 } else {
116 unsafe { CStr::from_ptr(value) }.to_str().unwrap_or("")
117 }
118}
119
120impl Il2Cpp {
121 fn install(library: Library) -> Result<&'static Il2Cpp> {
122 let api = Api::load(&library)?;
123 tracing::debug!("loaded the il2cpp_* API from the game binary");
124 Ok(INSTANCE.get_or_init(|| Il2Cpp {
125 api,
126 _library: library,
127 }))
128 }
129
130 pub fn loaded() -> Result<&'static Il2Cpp> {
132 if let Some(il2cpp) = INSTANCE.get() {
133 return Ok(il2cpp);
134 }
135 let path = loaded_game_assembly()
136 .ok_or_else(|| Error::NotFound("a loaded GameAssembly".into()))?;
137 check_format(&path)?;
138 tracing::debug!(path = %path.display(), "using the loaded game binary");
139 #[cfg(unix)]
140 let library = unsafe {
141 libloading::os::unix::Library::open(Some(&path), libc::RTLD_NOW | libc::RTLD_NOLOAD)
142 .map(Library::from)
143 };
144 #[cfg(windows)]
145 let library =
146 libloading::os::windows::Library::open_already_loaded(&path).map(Library::from);
147 Self::install(library.map_err(Error::Load)?)
148 }
149
150 pub fn load(path: impl AsRef<Path>) -> Result<&'static Il2Cpp> {
152 if let Some(il2cpp) = INSTANCE.get() {
153 return Ok(il2cpp);
154 }
155 check_format(path.as_ref())?;
156 tracing::debug!(path = %path.as_ref().display(), "loading the game binary");
157 let library = unsafe { Library::new(path.as_ref()) }.map_err(Error::Load)?;
158 Self::install(library)
159 }
160
161 pub fn get() -> Option<&'static Il2Cpp> {
163 INSTANCE.get()
164 }
165
166 pub fn api(&self) -> &Api {
167 &self.api
168 }
169
170 pub fn init_standalone(&self, data_dir: impl AsRef<Path>) -> Result<()> {
173 tracing::debug!(data_dir = %data_dir.as_ref().display(), "starting Il2Cpp without Unity");
174 let data_dir = cstring(&data_dir.as_ref().to_string_lossy())?;
175 unsafe {
176 (self.api.il2cpp_set_data_dir)(data_dir.as_ptr());
177 if (self.api.il2cpp_init)(c"hao".as_ptr()) == 0 {
178 return Err(Error::Init);
179 }
180 }
181 Ok(())
182 }
183
184 pub fn attach_thread(&self) {
186 unsafe { (self.api.il2cpp_thread_attach)((self.api.il2cpp_domain_get)()) };
187 }
188
189 pub fn class(&'static self, assembly: &str, namespace: &str, name: &str) -> Result<Class> {
191 let (assembly_c, namespace_c, name_c) =
192 (cstring(assembly)?, cstring(namespace)?, cstring(name)?);
193 let class = unsafe {
194 let domain = (self.api.il2cpp_domain_get)();
195 let opened = (self.api.il2cpp_domain_assembly_open)(domain, assembly_c.as_ptr());
196 if opened.is_null() {
197 return Err(Error::NotFound(format!("assembly {}", assembly)));
198 }
199 let image = (self.api.il2cpp_assembly_get_image)(opened);
200 (self.api.il2cpp_class_from_name)(image, namespace_c.as_ptr(), name_c.as_ptr())
201 };
202 if class.is_null() {
203 return Err(Error::NotFound(format!(
204 "class {}.{} in {}",
205 namespace, name, assembly
206 )));
207 }
208 tracing::trace!(assembly, namespace, name, "found class");
209 Ok(Class {
210 il2cpp: self,
211 ptr: class,
212 })
213 }
214
215 pub fn string(&self, value: &str) -> Result<Il2CppString> {
217 let value = cstring(value)?;
218 Ok(Il2CppString(Object(unsafe {
219 (self.api.il2cpp_string_new)(value.as_ptr())
220 })))
221 }
222
223 pub fn byte_array(&'static self, bytes: &[u8]) -> Result<Object> {
226 let class = self.class("mscorlib", "System", "Byte")?;
227 let array = unsafe { (self.api.il2cpp_array_new)(class.as_ptr(), bytes.len()) };
228 if array.is_null() {
229 return Err(Error::NotFound("could not allocate a byte[]".into()));
230 }
231 let base = 4 * std::mem::size_of::<usize>();
233 unsafe {
234 std::ptr::copy_nonoverlapping(bytes.as_ptr(), (array as *mut u8).add(base), bytes.len());
235 }
236 Ok(Object(array))
237 }
238
239 pub unsafe fn read_string(&self, string: Object) -> Option<String> {
244 if string.is_null() {
245 return None;
246 }
247 unsafe {
248 let length = (self.api.il2cpp_string_length)(string.0).max(0) as usize;
249 let chars =
250 std::slice::from_raw_parts((self.api.il2cpp_string_chars)(string.0), length);
251 Some(String::from_utf16_lossy(chars))
252 }
253 }
254
255 pub unsafe fn class_of(&'static self, object: Object) -> Class {
260 Class {
261 il2cpp: self,
262 ptr: unsafe { (self.api.il2cpp_object_get_class)(object.0) },
263 }
264 }
265}
266
267#[derive(Clone, Copy)]
269pub struct Class {
270 il2cpp: &'static Il2Cpp,
271 ptr: Ptr,
272}
273
274unsafe impl Send for Class {}
275unsafe impl Sync for Class {}
276
277impl Class {
278 pub fn as_ptr(&self) -> Ptr {
279 self.ptr
280 }
281
282 pub fn name(&self) -> &'static str {
283 unsafe { c_str((self.il2cpp.api.il2cpp_class_get_name)(self.ptr)) }
284 }
285
286 pub fn namespace(&self) -> &'static str {
287 unsafe { c_str((self.il2cpp.api.il2cpp_class_get_namespace)(self.ptr)) }
288 }
289
290 pub fn method(&self, name: &str, parameter_count: i32) -> Result<Method> {
292 let c_name = cstring(name)?;
293 let method = unsafe {
294 (self.il2cpp.api.il2cpp_class_get_method_from_name)(
295 self.ptr,
296 c_name.as_ptr(),
297 parameter_count,
298 )
299 };
300 if method.is_null() {
301 return Err(Error::NotFound(format!(
302 "method {}.{}({} parameters)",
303 self.name(),
304 name,
305 parameter_count
306 )));
307 }
308 tracing::trace!(class = self.name(), name, parameter_count, "found method");
309 Ok(Method {
310 il2cpp: self.il2cpp,
311 ptr: method,
312 })
313 }
314
315 pub fn new_object(&self) -> Object {
318 Object(unsafe { (self.il2cpp.api.il2cpp_object_new)(self.ptr) })
319 }
320
321 pub fn type_object(&self) -> Object {
323 Object(unsafe {
324 (self.il2cpp.api.il2cpp_type_get_object)((self.il2cpp.api.il2cpp_class_get_type)(
325 self.ptr,
326 ))
327 })
328 }
329
330 pub fn methods(&self) -> impl Iterator<Item = Method> + '_ {
332 let mut iter: Ptr = std::ptr::null_mut();
333 std::iter::from_fn(move || {
334 let method = unsafe { (self.il2cpp.api.il2cpp_class_get_methods)(self.ptr, &mut iter) };
335 (!method.is_null()).then_some(Method {
336 il2cpp: self.il2cpp,
337 ptr: method,
338 })
339 })
340 }
341
342 pub fn field(&self, name: &str) -> Result<Field> {
344 let c_name = cstring(name)?;
345 let field = unsafe {
346 (self.il2cpp.api.il2cpp_class_get_field_from_name)(self.ptr, c_name.as_ptr())
347 };
348 if field.is_null() {
349 return Err(Error::NotFound(format!("field {}.{}", self.name(), name)));
350 }
351 Ok(Field {
352 il2cpp: self.il2cpp,
353 ptr: field,
354 })
355 }
356
357 pub fn fields(&self) -> impl Iterator<Item = Field> + '_ {
359 let mut iter: Ptr = std::ptr::null_mut();
360 std::iter::from_fn(move || {
361 let field = unsafe { (self.il2cpp.api.il2cpp_class_get_fields)(self.ptr, &mut iter) };
362 (!field.is_null()).then_some(Field {
363 il2cpp: self.il2cpp,
364 ptr: field,
365 })
366 })
367 }
368
369 pub fn field_offset(&self, name: &str) -> Result<usize> {
371 Ok(self.field(name)?.offset())
372 }
373}
374
375#[derive(Clone, Copy)]
377pub struct Field {
378 il2cpp: &'static Il2Cpp,
379 ptr: Ptr,
380}
381
382unsafe impl Send for Field {}
383unsafe impl Sync for Field {}
384
385const FIELD_STATIC: i32 = 0x0010;
387
388impl Field {
389 pub fn as_ptr(&self) -> Ptr {
390 self.ptr
391 }
392
393 pub fn name(&self) -> &'static str {
394 unsafe { c_str((self.il2cpp.api.il2cpp_field_get_name)(self.ptr)) }
395 }
396
397 pub fn type_name(&self) -> String {
399 let ty = unsafe { (self.il2cpp.api.il2cpp_field_get_type)(self.ptr) };
400 unsafe { c_str((self.il2cpp.api.il2cpp_type_get_name)(ty)) }.to_owned()
401 }
402
403 pub fn offset(&self) -> usize {
406 unsafe { (self.il2cpp.api.il2cpp_field_get_offset)(self.ptr) }
407 }
408
409 pub fn is_static(&self) -> bool {
410 unsafe { (self.il2cpp.api.il2cpp_field_get_flags)(self.ptr) & FIELD_STATIC != 0 }
411 }
412
413 pub unsafe fn read<T: Copy>(&self, object: Object) -> T {
419 unsafe { read_field(object, self.offset()) }
420 }
421
422 pub unsafe fn write<T: Copy>(&self, object: Object, value: T) {
427 unsafe { write_field(object, self.offset(), value) }
428 }
429}
430
431pub struct GcHandle {
435 il2cpp: &'static Il2Cpp,
436 handle: Ptr,
437}
438
439unsafe impl Send for GcHandle {}
440unsafe impl Sync for GcHandle {}
441
442impl GcHandle {
443 pub fn new(il2cpp: &'static Il2Cpp, object: Object) -> Self {
444 Self {
445 il2cpp,
446 handle: unsafe { (il2cpp.api.il2cpp_gchandle_new)(object.0, false) },
447 }
448 }
449
450 pub fn target(&self) -> Object {
451 Object(unsafe { (self.il2cpp.api.il2cpp_gchandle_get_target)(self.handle) })
452 }
453}
454
455impl Drop for GcHandle {
456 fn drop(&mut self) {
457 unsafe { (self.il2cpp.api.il2cpp_gchandle_free)(self.handle) }
458 }
459}
460
461#[derive(Clone, Copy)]
463pub struct Method {
464 il2cpp: &'static Il2Cpp,
465 ptr: Ptr,
466}
467
468unsafe impl Send for Method {}
469unsafe impl Sync for Method {}
470
471impl Method {
472 pub fn as_ptr(&self) -> MethodInfo {
474 self.ptr
475 }
476
477 pub fn name(&self) -> &'static str {
478 unsafe { c_str((self.il2cpp.api.il2cpp_method_get_name)(self.ptr)) }
479 }
480
481 pub fn code(&self) -> *mut c_void {
484 unsafe { *(self.ptr as *const *mut c_void) }
486 }
487
488 pub unsafe fn hook_raw(&self, detour: *mut u8) -> Result<MethodHook> {
498 let mut hook = unsafe { hooking::Hook::create(self.code() as *mut u8, detour) }
499 .map_err(Error::Hook)?;
500 unsafe { hook.apply_hook() }.map_err(Error::Hook)?;
501 tracing::debug!(method = self.name(), code = ?self.code(), "hooked (raw)");
502 Ok(MethodHook(hook))
503 }
504}
505
506pub struct MethodHook(pub(crate) hooking::Hook<'static>);
508
509impl MethodHook {
510 pub fn remove(mut self) -> Result<()> {
511 unsafe { self.0.remove_hook() }.map_err(Error::Hook)?;
512 tracing::debug!(code = ?self.0.data.symbol_address, "removed hook");
513 Ok(())
514 }
515}
516
517pub unsafe fn read_field<T: Copy>(object: Object, offset: usize) -> T {
522 unsafe { std::ptr::read_unaligned((object.0 as *const u8).add(offset) as *const T) }
523}
524
525pub unsafe fn write_field<T: Copy>(object: Object, offset: usize, value: T) {
530 unsafe { std::ptr::write_unaligned((object.0 as *mut u8).add(offset) as *mut T, value) }
531}
532
533#[macro_export]
536macro_rules! original {
537 ($fn_type:ty) => {{
538 let original =
539 $crate::__original_function_ptr().expect("original! must be used inside a hook");
540 unsafe { ::core::mem::transmute::<*mut ::core::ffi::c_void, $fn_type>(original.as_ptr()) }
541 }};
542}
543
544#[doc(hidden)]
545pub use hooking::original_function_ptr as __original_function_ptr;
546
547#[cfg(test)]
548mod tests {
549 use super::*;
550
551 #[test]
552 fn game_assembly_names() {
553 assert!(is_game_assembly("/games/Example/GameAssembly.so"));
554 assert!(is_game_assembly("C:\\Games\\Example\\GameAssembly.dll"));
555 assert!(!is_game_assembly("/games/Example/UnityPlayer.so"));
556 assert!(!is_game_assembly("/games/Example/NotGameAssembly.dll"));
557 }
558
559 #[test]
560 fn finds_and_checks_the_game_binary() {
561 let dir = std::env::temp_dir().join(format!("hao-il2cpp-runtime-{}", std::process::id()));
562 std::fs::create_dir_all(&dir).unwrap();
563 std::fs::write(dir.join("UnityPlayer.dll"), b"MZ\x90\x00").unwrap();
564 std::fs::write(dir.join("GameAssembly.dll"), b"MZ\x90\x00").unwrap();
565 let found = find_game_assembly(&dir).unwrap();
566 assert_eq!(found, dir.join("GameAssembly.dll"));
567 if cfg!(unix) {
568 assert!(matches!(
569 check_format(&found),
570 Err(Error::UnsupportedBinary(_))
571 ));
572 }
573 std::fs::remove_dir_all(dir).unwrap();
574 }
575}