1use std::{any::Any, ffi::c_void, marker::PhantomData, sync::RwLock};
4
5use crate::{Error, Il2Cpp, Method, MethodInfo, Ptr, Result};
6
7pub mod element {
9 pub const VOID: i32 = 0x01;
11 pub const BOOLEAN: i32 = 0x02;
13 pub const CHAR: i32 = 0x03;
15 pub const I1: i32 = 0x04;
17 pub const U1: i32 = 0x05;
19 pub const I2: i32 = 0x06;
21 pub const U2: i32 = 0x07;
23 pub const I4: i32 = 0x08;
25 pub const U4: i32 = 0x09;
27 pub const I8: i32 = 0x0A;
29 pub const U8: i32 = 0x0B;
31 pub const R4: i32 = 0x0C;
33 pub const R8: i32 = 0x0D;
35 pub const STRING: i32 = 0x0E;
37 pub const PTR: i32 = 0x0F;
39 pub const VALUETYPE: i32 = 0x11;
41 pub const CLASS: i32 = 0x12;
43 pub const VAR: i32 = 0x13;
45 pub const ARRAY: i32 = 0x14;
47 pub const GENERICINST: i32 = 0x15;
49 pub const I: i32 = 0x18;
51 pub const U: i32 = 0x19;
53 pub const OBJECT: i32 = 0x1C;
55 pub const SZARRAY: i32 = 0x1D;
57 pub const MVAR: i32 = 0x1E;
59}
60
61#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
63pub enum ElementType {
64 Void,
66 Boolean,
68 Char,
70 I1,
72 U1,
74 I2,
76 U2,
78 I4,
80 U4,
82 I8,
84 U8,
86 R4,
88 R8,
90 String,
92 Ptr,
94 ValueType,
96 Class,
98 Var,
100 Array,
102 GenericInst,
104 I,
106 U,
108 Object,
110 SzArray,
112 MVar,
114 Unknown(i32),
116}
117
118impl ElementType {
119 pub fn is_float(self) -> bool {
121 matches!(self, Self::R4 | Self::R8)
122 }
123
124 pub fn is_integer(self) -> bool {
127 matches!(
128 self,
129 Self::Boolean
130 | Self::Char
131 | Self::I1
132 | Self::U1
133 | Self::I2
134 | Self::U2
135 | Self::I4
136 | Self::U4
137 | Self::I8
138 | Self::U8
139 | Self::I
140 | Self::U
141 )
142 }
143
144 pub fn is_reference(self) -> bool {
148 matches!(
149 self,
150 Self::String
151 | Self::Class
152 | Self::Object
153 | Self::GenericInst
154 | Self::Array
155 | Self::SzArray
156 )
157 }
158
159 pub fn raw(self) -> i32 {
161 match self {
162 Self::Void => element::VOID,
163 Self::Boolean => element::BOOLEAN,
164 Self::Char => element::CHAR,
165 Self::I1 => element::I1,
166 Self::U1 => element::U1,
167 Self::I2 => element::I2,
168 Self::U2 => element::U2,
169 Self::I4 => element::I4,
170 Self::U4 => element::U4,
171 Self::I8 => element::I8,
172 Self::U8 => element::U8,
173 Self::R4 => element::R4,
174 Self::R8 => element::R8,
175 Self::String => element::STRING,
176 Self::Ptr => element::PTR,
177 Self::ValueType => element::VALUETYPE,
178 Self::Class => element::CLASS,
179 Self::Var => element::VAR,
180 Self::Array => element::ARRAY,
181 Self::GenericInst => element::GENERICINST,
182 Self::I => element::I,
183 Self::U => element::U,
184 Self::Object => element::OBJECT,
185 Self::SzArray => element::SZARRAY,
186 Self::MVar => element::MVAR,
187 Self::Unknown(v) => v,
188 }
189 }
190}
191
192impl From<i32> for ElementType {
193 fn from(v: i32) -> Self {
194 match v {
195 element::VOID => Self::Void,
196 element::BOOLEAN => Self::Boolean,
197 element::CHAR => Self::Char,
198 element::I1 => Self::I1,
199 element::U1 => Self::U1,
200 element::I2 => Self::I2,
201 element::U2 => Self::U2,
202 element::I4 => Self::I4,
203 element::U4 => Self::U4,
204 element::I8 => Self::I8,
205 element::U8 => Self::U8,
206 element::R4 => Self::R4,
207 element::R8 => Self::R8,
208 element::STRING => Self::String,
209 element::PTR => Self::Ptr,
210 element::VALUETYPE => Self::ValueType,
211 element::CLASS => Self::Class,
212 element::VAR => Self::Var,
213 element::ARRAY => Self::Array,
214 element::GENERICINST => Self::GenericInst,
215 element::I => Self::I,
216 element::U => Self::U,
217 element::OBJECT => Self::Object,
218 element::SZARRAY => Self::SzArray,
219 element::MVAR => Self::MVar,
220 other => Self::Unknown(other),
221 }
222 }
223}
224
225impl std::fmt::Display for ElementType {
226 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
227 match self {
228 Self::Void => f.write_str("void"),
229 Self::Boolean => f.write_str("bool"),
230 Self::Char => f.write_str("char"),
231 Self::I1 => f.write_str("i8"),
232 Self::U1 => f.write_str("u8"),
233 Self::I2 => f.write_str("i16"),
234 Self::U2 => f.write_str("u16"),
235 Self::I4 => f.write_str("i32"),
236 Self::U4 => f.write_str("u32"),
237 Self::I8 => f.write_str("i64"),
238 Self::U8 => f.write_str("u64"),
239 Self::R4 => f.write_str("f32"),
240 Self::R8 => f.write_str("f64"),
241 Self::String => f.write_str("string"),
242 Self::Ptr => f.write_str("ptr"),
243 Self::ValueType => f.write_str("valuetype"),
244 Self::Class => f.write_str("class"),
245 Self::Var => f.write_str("var"),
246 Self::Array => f.write_str("array"),
247 Self::GenericInst => f.write_str("generic"),
248 Self::I => f.write_str("nint"),
249 Self::U => f.write_str("nuint"),
250 Self::Object => f.write_str("object"),
251 Self::SzArray => f.write_str("szarray"),
252 Self::MVar => f.write_str("mvar"),
253 Self::Unknown(v) => write!(f, "unknown(0x{v:02X})"),
254 }
255 }
256}
257
258#[derive(Debug, Clone, Copy, PartialEq, Eq)]
260#[cfg_attr(feature = "reflect", derive(facet::Facet))]
261pub struct TypeInfo {
262 pub element: i32,
264 pub value_type: bool,
267 pub is_enum: bool,
269 pub byref: bool,
271 pub namespace: &'static str,
273 pub name: &'static str,
275}
276
277impl TypeInfo {
278 pub fn is_value_type(&self, namespace: &str, name: &str) -> bool {
281 !self.byref
282 && self.value_type
283 && !self.is_enum
284 && self.namespace == namespace
285 && self.name == name
286 }
287}
288
289#[derive(Debug, Clone, PartialEq, Eq)]
291#[cfg_attr(feature = "reflect", derive(facet::Facet))]
292pub struct Parameter {
293 pub name: String,
295 pub type_name: String,
297}
298
299#[repr(transparent)]
301#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
302pub struct Object(pub Ptr);
303
304unsafe impl Send for Object {}
305unsafe impl Sync for Object {}
306
307impl Object {
308 pub const NULL: Object = Object(std::ptr::null_mut());
310
311 pub fn is_null(&self) -> bool {
313 self.0.is_null()
314 }
315
316 pub fn as_ptr(&self) -> Ptr {
318 self.0
319 }
320}
321
322#[repr(transparent)]
324#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
325pub struct Il2CppString(pub Object);
326
327impl Il2CppString {
328 pub fn new(il2cpp: &Il2Cpp, value: &str) -> Result<Self> {
330 il2cpp.string(value)
331 }
332
333 pub fn is_null(&self) -> bool {
335 self.0.is_null()
336 }
337
338 pub fn to_rust(&self) -> Option<String> {
340 let il2cpp = Il2Cpp::get()?;
341 unsafe { il2cpp.read_string(self.0) }
343 }
344}
345
346pub unsafe trait Il2CppValue: Copy + 'static {
352 fn matches(ty: TypeInfo) -> bool;
354
355 fn describe() -> &'static str {
357 std::any::type_name::<Self>()
358 }
359
360 fn is_reference() -> bool {
362 false
363 }
364}
365
366macro_rules! primitive {
367 ($($t:ty => [$($e:ident),+];)*) => {$(
368 unsafe impl Il2CppValue for $t {
369 fn matches(ty: TypeInfo) -> bool {
370 !ty.byref && [$(element::$e),+].contains(&ty.element)
371 }
372 }
373 )*};
374}
375
376primitive! {
377 () => [VOID];
378 bool => [BOOLEAN];
379 u16 => [CHAR, U2];
380 i8 => [I1];
381 u8 => [U1];
382 i16 => [I2];
383 i32 => [I4];
384 u32 => [U4];
385 i64 => [I8];
386 u64 => [U8];
387 f32 => [R4];
388 f64 => [R8];
389 isize => [I];
390 usize => [U];
391}
392
393unsafe impl Il2CppValue for Object {
394 fn is_reference() -> bool {
395 true
396 }
397
398 fn matches(ty: TypeInfo) -> bool {
399 !ty.byref
400 && !ty.value_type
401 && [
402 element::STRING,
403 element::CLASS,
404 element::OBJECT,
405 element::SZARRAY,
406 element::ARRAY,
407 element::GENERICINST,
408 element::VAR,
409 element::MVAR,
410 ]
411 .contains(&ty.element)
412 }
413}
414
415unsafe impl Il2CppValue for Il2CppString {
416 fn is_reference() -> bool {
417 true
418 }
419
420 fn matches(ty: TypeInfo) -> bool {
421 !ty.byref && ty.element == element::STRING
422 }
423}
424
425unsafe impl Il2CppValue for *mut c_void {
427 fn is_reference() -> bool {
428 true
429 }
430
431 fn matches(ty: TypeInfo) -> bool {
432 ty.byref || ty.element == element::PTR
433 }
434}
435
436pub struct Original<Args, R> {
438 code: *const c_void,
439 method: MethodInfo,
440 _marker: PhantomData<fn(Args) -> R>,
441}
442
443#[derive(Clone, Copy)]
445pub struct ValueCheck {
446 pub matches: fn(TypeInfo) -> bool,
448 pub name: &'static str,
450 pub reference: bool,
452}
453
454impl ValueCheck {
455 pub fn of<T: Il2CppValue>() -> Self {
457 Self {
458 matches: T::matches,
459 name: T::describe(),
460 reference: T::is_reference(),
461 }
462 }
463}
464
465pub struct Signature {
467 pub parameters: Vec<ValueCheck>,
469 pub ret: ValueCheck,
471}
472
473impl<Args: MethodArgs, R: Il2CppValue> Original<Args, R> {
474 pub fn call(&self, args: Args) -> R {
476 unsafe { args.invoke(self.code, self.method) }
477 }
478}
479
480pub trait HookCallback<Args, R>: Send + Sync + 'static {
483 #[doc(hidden)]
484 fn trampoline() -> *mut u8;
485 #[doc(hidden)]
486 fn signature() -> Signature;
487}
488
489pub trait MethodArgs {
491 #[doc(hidden)]
492 fn parameters() -> Vec<ValueCheck>;
493 #[doc(hidden)]
494 unsafe fn invoke<R: Il2CppValue>(self, code: *const c_void, method: MethodInfo) -> R;
495}
496
497type Callbacks = RwLock<Vec<(usize, &'static (dyn Any + Send + Sync))>>;
498
499static CALLBACKS: Callbacks = RwLock::new(Vec::new());
501
502pub(crate) fn register<F: Any + Send + Sync>(stub: usize, callback: F) {
503 let callback: &'static (dyn Any + Send + Sync) = Box::leak(Box::new(callback));
504 CALLBACKS
505 .write()
506 .unwrap_or_else(|e| e.into_inner())
507 .push((stub, callback));
508}
509
510fn callback<F: Any>(stub: usize) -> &'static F {
511 let callbacks = CALLBACKS.read().unwrap_or_else(|e| e.into_inner());
512 callbacks
513 .iter()
514 .rev()
515 .find(|(s, _)| *s == stub)
516 .and_then(|(_, c)| c.downcast_ref::<F>())
517 .unwrap_or_else(|| {
518 tracing::error!("no callback registered for hook {:#x}, aborting", stub);
519 eprintln!("[hao] no callback registered for hook {:#x}", stub);
520 std::process::abort()
521 })
522}
523
524macro_rules! arity {
525 ($trampoline:ident; $($t:ident $v:ident),*) => {
526 impl<F, $($t: Il2CppValue,)* R: Il2CppValue> HookCallback<($($t,)*), R> for F
527 where
528 F: Fn($($t,)* Original<($($t,)*), R>) -> R + Send + Sync + 'static,
529 {
530 fn trampoline() -> *mut u8 {
531 $trampoline::<F, $($t,)* R> as *mut u8
532 }
533
534 fn signature() -> Signature {
535 Signature {
536 parameters: vec![$(ValueCheck::of::<$t>(),)*],
537 ret: ValueCheck::of::<R>(),
538 }
539 }
540 }
541
542 #[allow(clippy::too_many_arguments)]
543 extern "C-unwind" fn $trampoline<F, $($t,)* R>($($v: $t,)* method: MethodInfo) -> R
544 where
545 F: Fn($($t,)* Original<($($t,)*), R>) -> R + Send + Sync + 'static,
546 {
547 let code = hooking::original_function_ptr().map_or(std::ptr::null_mut(), |p| p.as_ptr());
549 let callback = callback::<F>(code as usize);
550 callback($($v,)* Original { code, method, _marker: PhantomData })
551 }
552
553 impl<$($t: Il2CppValue,)*> MethodArgs for ($($t,)*) {
554 fn parameters() -> Vec<ValueCheck> {
555 vec![$(ValueCheck::of::<$t>(),)*]
556 }
557
558 #[allow(clippy::unused_unit)]
559 unsafe fn invoke<R: Il2CppValue>(self, code: *const c_void, method: MethodInfo) -> R {
560 let ($($v,)*) = self;
561 let f: extern "C-unwind" fn($($t,)* MethodInfo) -> R = unsafe { std::mem::transmute(code) };
562 f($($v,)* method)
563 }
564 }
565 };
566}
567
568arity!(trampoline0;);
569arity!(trampoline1; A a);
570arity!(trampoline2; A a, B b);
571arity!(trampoline3; A a, B b, C c);
572arity!(trampoline4; A a, B b, C c, D d);
573arity!(trampoline5; A a, B b, C c, D d, E e);
574arity!(trampoline6; A a, B b, C c, D d, E e, G g);
575arity!(trampoline7; A a, B b, C c, D d, E e, G g, H h);
576arity!(trampoline8; A a, B b, C c, D d, E e, G g, H h, I i);
577
578impl Method {
579 fn type_info(&self, ty: Ptr) -> TypeInfo {
580 let api = &self.il2cpp.api;
581 unsafe {
582 let mut element = (api.il2cpp_type_get_type)(ty);
583 let byref = (api.il2cpp_type_is_byref)(ty);
584 let class = (api.il2cpp_type_get_class_or_element_class)(ty);
585 let value_type = match element {
586 element::VALUETYPE => true,
587 element::GENERICINST => !class.is_null() && (api.il2cpp_class_is_valuetype)(class),
588 _ => false,
589 };
590 let is_enum = element == element::VALUETYPE
591 && !class.is_null()
592 && (api.il2cpp_class_is_enum)(class);
593 if is_enum {
594 element = (api.il2cpp_type_get_type)((api.il2cpp_class_enum_basetype)(class));
595 }
596 let (namespace, name) = if class.is_null() {
597 ("", "")
598 } else {
599 (
600 crate::c_str((api.il2cpp_class_get_namespace)(class)),
601 crate::c_str((api.il2cpp_class_get_name)(class)),
602 )
603 };
604 TypeInfo {
605 element,
606 value_type,
607 is_enum,
608 byref,
609 namespace,
610 name,
611 }
612 }
613 }
614
615 fn type_name(&self, ty: Ptr) -> String {
616 unsafe {
617 let name = (self.il2cpp.api.il2cpp_type_get_name)(ty);
618 if name.is_null() {
619 return "?".into();
620 }
621 std::ffi::CStr::from_ptr(name)
622 .to_string_lossy()
623 .into_owned()
624 }
625 }
626
627 pub fn is_instance(&self) -> bool {
630 unsafe { (self.il2cpp.api.il2cpp_method_is_instance)(self.ptr) }
631 }
632
633 pub fn parameter_count(&self) -> u32 {
635 unsafe { (self.il2cpp.api.il2cpp_method_get_param_count)(self.ptr) }
636 }
637
638 pub fn return_type_name(&self) -> String {
640 self.type_name(unsafe { (self.il2cpp.api.il2cpp_method_get_return_type)(self.ptr) })
641 }
642
643 pub fn parameter_type_name(&self, index: u32) -> String {
645 self.type_name(unsafe { (self.il2cpp.api.il2cpp_method_get_param)(self.ptr, index) })
646 }
647
648 pub fn parameter_name(&self, index: u32) -> String {
651 let name = unsafe { (self.il2cpp.api.il2cpp_method_get_param_name)(self.ptr, index) };
652 unsafe { crate::c_str(name) }.to_owned()
653 }
654
655 pub fn parameters(&self) -> impl Iterator<Item = Parameter> + '_ {
657 (0..self.parameter_count()).map(move |i| Parameter {
658 name: self.parameter_name(i),
659 type_name: self.parameter_type_name(i),
660 })
661 }
662
663 pub fn signature(&self) -> String {
666 let params: Vec<String> = self.parameters().map(|p| p.type_name).collect();
667 format!(
668 "{}{} {}({})",
669 if self.is_instance() { "" } else { "static " },
670 self.return_type_name(),
671 self.name(),
672 params.join(", ")
673 )
674 }
675
676 fn check(&self, params: &[ValueCheck], ret: ValueCheck) -> Result<()> {
678 let api = &self.il2cpp.api;
679 let instance = self.is_instance() as usize;
680 let count = self.parameter_count() as usize;
681 let mismatch =
682 |detail: String| Error::Signature(format!("{}: {}", self.signature(), detail));
683 if params.len() != count + instance {
684 return Err(mismatch(format!(
685 "expected {} arguments{}, got {}",
686 count + instance,
687 if instance == 1 {
688 " including the instance"
689 } else {
690 ""
691 },
692 params.len()
693 )));
694 }
695 if instance == 1 && !params[0].reference {
696 return Err(mismatch(format!(
697 "the instance can't be passed as {}",
698 params[0].name
699 )));
700 }
701 for (i, check) in params[instance..].iter().enumerate() {
702 let ty = unsafe { (api.il2cpp_method_get_param)(self.ptr, i as u32) };
703 if !(check.matches)(self.type_info(ty)) {
704 return Err(mismatch(format!(
705 "parameter {} is {}, not {}",
706 i,
707 self.type_name(ty),
708 check.name
709 )));
710 }
711 }
712 let ty = unsafe { (api.il2cpp_method_get_return_type)(self.ptr) };
713 if !(ret.matches)(self.type_info(ty)) {
714 return Err(mismatch(format!(
715 "returns {}, not {}",
716 self.type_name(ty),
717 ret.name
718 )));
719 }
720 Ok(())
721 }
722
723 pub fn check_types<Args: MethodArgs, R: Il2CppValue>(&self) -> Result<()> {
727 self.check(&Args::parameters(), ValueCheck::of::<R>())
728 }
729
730 pub fn hook<Args, R, F: HookCallback<Args, R>>(
745 &self,
746 callback: F,
747 ) -> Result<crate::MethodHook> {
748 let signature = F::signature();
749 self.check(&signature.parameters, signature.ret)?;
750 let mut hook = unsafe { hooking::Hook::create(self.code() as *mut u8, F::trampoline()) }
751 .map_err(Error::Hook)?;
752 register(
753 hook.data.original_fn_call_stub_data.as_ptr() as usize,
754 callback,
755 );
756 unsafe { hook.apply_hook() }.map_err(Error::Hook)?;
757 tracing::debug!(method = %self.signature(), code = ?self.code(), "hooked");
758 Ok(crate::MethodHook(hook))
759 }
760
761 pub fn call<Args: MethodArgs, R: Il2CppValue>(&self, args: Args) -> Result<R> {
766 self.check(&Args::parameters(), ValueCheck::of::<R>())?;
767 Ok(unsafe { args.invoke(self.code(), self.ptr) })
768 }
769
770 pub unsafe fn call_unchecked<Args: MethodArgs, R: Il2CppValue>(&self, args: Args) -> R {
776 unsafe { args.invoke(self.code(), self.ptr) }
777 }
778
779 #[cfg(target_arch = "x86_64")]
798 pub fn hook_void_block(&self) -> Result<VoidBlockHook> {
799 let ret = self.return_type_name();
800 if ret != "System.Void" {
801 return Err(Error::Signature(format!(
802 "hook_void_block requires a void method, but `{}` returns {}",
803 self.name(),
804 ret,
805 )));
806 }
807
808 let state = Box::leak(Box::new(std::sync::atomic::AtomicBool::new(false)));
809 let state_ptr = state as *const std::sync::atomic::AtomicBool;
810
811 let mut hook = unsafe {
812 hooking::Hook::create(self.code() as *mut u8, void_block_trampoline as *mut u8)
813 }
814 .map_err(Error::Hook)?;
815 let original = hook.data.original_fn_call_stub_data.as_ptr() as usize;
816 register(original, state_ptr as usize);
817 unsafe { hook.apply_hook() }.map_err(Error::Hook)?;
818
819 tracing::debug!(method = %self.signature(), code = ?self.code(), "hooked (void block)");
820
821 Ok(VoidBlockHook {
822 state,
823 _hook: crate::MethodHook(hook),
824 })
825 }
826}
827
828pub struct VoidBlockHook {
831 pub state: &'static std::sync::atomic::AtomicBool,
833 _hook: crate::MethodHook,
834}
835
836impl VoidBlockHook {
837 pub fn set_blocked(&self, blocked: bool) {
839 self.state
840 .store(blocked, std::sync::atomic::Ordering::Relaxed);
841 }
842
843 pub fn is_blocked(&self) -> bool {
845 self.state.load(std::sync::atomic::Ordering::Relaxed)
846 }
847}
848
849#[cfg(target_arch = "x86_64")]
853#[derive(Debug, Clone, Copy)]
854pub enum ParamSlot {
855 IntReg(u8),
857 FloatReg(u8),
859}
860
861#[cfg(target_arch = "x86_64")]
863#[derive(Debug, Clone)]
864pub struct GenericParam {
865 pub slot: ParamSlot,
867 pub type_info: TypeInfo,
869 pub name: String,
872}
873
874#[cfg(target_arch = "x86_64")]
880#[derive(Debug, Clone)]
881pub struct GenericHookMeta {
882 pub params: Vec<GenericParam>,
885 pub return_type: TypeInfo,
887 pub is_instance: bool,
889 pub signature: String,
891}
892
893#[cfg(target_arch = "x86_64")]
894type GenericHookCallback = Box<
895 dyn Fn(usize, &GenericHookMeta, &hooking::SavedRegs) -> hooking::DispatchResult + Send + Sync,
896>;
897
898struct GenericHookEntry {
899 meta: GenericHookMeta,
900 callback: GenericHookCallback,
901}
902
903#[cfg(target_arch = "x86_64")]
904impl Method {
905 pub fn hook_generic(
932 &self,
933 callback: impl Fn(usize, &GenericHookMeta, &hooking::SavedRegs) -> hooking::DispatchResult
934 + Send
935 + Sync
936 + 'static,
937 ) -> Result<crate::MethodHook> {
938 let meta = self.build_generic_meta();
939 let entry = GenericHookEntry {
940 meta,
941 callback: Box::new(callback),
942 };
943
944 let mut hook = unsafe {
945 hooking::Hook::create_save_registers(self.code() as *mut u8, generic_hook_dispatch)
946 }
947 .map_err(Error::Hook)?;
948
949 let stub_addr = hook.data.original_fn_call_stub_data.as_ptr() as usize;
950 register(stub_addr, entry);
951
952 unsafe { hook.apply_hook() }.map_err(Error::Hook)?;
953 tracing::debug!(method = %self.signature(), code = ?self.code(), "hooked (generic)");
954 Ok(crate::MethodHook(hook))
955 }
956
957 fn build_generic_meta(&self) -> GenericHookMeta {
958 let is_instance = self.is_instance();
959 let param_count = self.parameter_count();
960
961 let mut params = Vec::new();
962 let mut int_idx: u8 = 0;
963 let mut float_idx: u8 = 0;
964
965 if is_instance {
966 params.push(GenericParam {
967 slot: ParamSlot::IntReg(int_idx),
968 type_info: TypeInfo {
969 element: element::OBJECT,
970 value_type: false,
971 is_enum: false,
972 byref: false,
973 namespace: "",
974 name: "",
975 },
976 name: "this".to_owned(),
977 });
978 int_idx += 1;
979 }
980
981 for i in 0..param_count {
982 let ty = unsafe { (self.il2cpp.api.il2cpp_method_get_param)(self.ptr, i) };
983 let info = self.type_info(ty);
984 let name = self.parameter_name(i);
985
986 let is_float = matches!(info.element, element::R4 | element::R8) && !info.byref;
987 let slot = if is_float {
988 if float_idx < 8 {
989 let s = ParamSlot::FloatReg(float_idx);
990 float_idx += 1;
991 s
992 } else {
993 continue;
994 }
995 } else if int_idx < 6 {
996 let s = ParamSlot::IntReg(int_idx);
997 int_idx += 1;
998 s
999 } else {
1000 continue;
1001 };
1002
1003 params.push(GenericParam {
1004 slot,
1005 type_info: info,
1006 name,
1007 });
1008 }
1009
1010 let ret_ty = unsafe { (self.il2cpp.api.il2cpp_method_get_return_type)(self.ptr) };
1011
1012 GenericHookMeta {
1013 params,
1014 return_type: self.type_info(ret_ty),
1015 is_instance,
1016 signature: self.signature(),
1017 }
1018 }
1019}
1020
1021#[cfg(target_arch = "x86_64")]
1023extern "C" fn generic_hook_dispatch(
1024 original: usize,
1025 int_regs: *mut u64,
1026 sse_regs: *mut [u8; 16],
1027) -> hooking::DispatchResult {
1028 let entry = callback::<GenericHookEntry>(original);
1029 let regs = hooking::SavedRegs { int_regs, sse_regs };
1030
1031 let action = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1032 (entry.callback)(original, &entry.meta, ®s)
1033 }));
1034
1035 match action {
1036 Ok(a) => a,
1037 Err(_) => {
1038 tracing::error!("generic hook callback panicked, calling original");
1039 hooking::DispatchResult::Passthrough
1040 }
1041 }
1042}
1043
1044extern "C" fn void_block_check(original: usize) -> bool {
1047 let state_ptr = callback::<usize>(original);
1048 let state = unsafe { &*(*state_ptr as *const std::sync::atomic::AtomicBool) };
1049 state.load(std::sync::atomic::Ordering::Relaxed)
1050}
1051
1052#[unsafe(naked)]
1056#[cfg(target_arch = "x86_64")]
1057unsafe extern "C" fn void_block_trampoline() {
1058 core::arch::naked_asm!(
1061 "push rbx",
1063
1064 "mov rbx, r10",
1066 "movabs rax, 0xDEADBEEFCAFEBABE",
1067 "xor rax, r10",
1068 "cmp rax, r11",
1069 "jne 9f",
1070
1071 "push rdi",
1073 "push rsi",
1074 "push rdx",
1075 "push rcx",
1076 "push r8",
1077 "push r9",
1078
1079 "sub rsp, 0x80",
1081 "movdqu [rsp+0x00], xmm0",
1082 "movdqu [rsp+0x10], xmm1",
1083 "movdqu [rsp+0x20], xmm2",
1084 "movdqu [rsp+0x30], xmm3",
1085 "movdqu [rsp+0x40], xmm4",
1086 "movdqu [rsp+0x50], xmm5",
1087 "movdqu [rsp+0x60], xmm6",
1088 "movdqu [rsp+0x70], xmm7",
1089
1090 "mov rdi, rbx",
1093 "call {check}",
1094 "test al, al",
1095 "jnz 2f",
1096
1097 "movdqu xmm0, [rsp+0x00]",
1099 "movdqu xmm1, [rsp+0x10]",
1100 "movdqu xmm2, [rsp+0x20]",
1101 "movdqu xmm3, [rsp+0x30]",
1102 "movdqu xmm4, [rsp+0x40]",
1103 "movdqu xmm5, [rsp+0x50]",
1104 "movdqu xmm6, [rsp+0x60]",
1105 "movdqu xmm7, [rsp+0x70]",
1106 "add rsp, 0x80",
1107 "pop r9",
1108 "pop r8",
1109 "pop rcx",
1110 "pop rdx",
1111 "pop rsi",
1112 "pop rdi",
1113 "mov rax, rbx",
1114 "pop rbx",
1115 "jmp rax",
1116
1117 "2:",
1118 "add rsp, 0x80",
1120 "pop r9",
1121 "pop r8",
1122 "pop rcx",
1123 "pop rdx",
1124 "pop rsi",
1125 "pop rdi",
1126 "pop rbx",
1127 "ret",
1128
1129 "9:",
1130 "pop rbx",
1132 "ret",
1133
1134 check = sym void_block_check,
1135 );
1136}