retour\detours/
generic.rs

1use crate::arch::Detour;
2use crate::error::Result;
3use crate::{Function, HookableWith};
4use std::marker::PhantomData;
5
6/// A type-safe detour.
7///
8/// Due to being generated by a macro, the `GenericDetour::call` method is not
9/// exposed in the documentation.  
10/// It accepts the same arguments as `T`, and shares its result type:
11///
12/// ```c
13/// /// Calls the original function regardless of whether it's hooked or not.
14/// fn call(&self, T::Arguments) -> T::Output
15/// ```
16///
17/// # Example
18///
19/// ```rust
20/// # use retour::Result;
21/// use retour::GenericDetour;
22///
23/// fn add5(val: i32) -> i32 {
24///   val + 5
25/// }
26///
27/// fn add10(val: i32) -> i32 {
28///   val + 10
29/// }
30///
31/// # fn main() -> Result<()> {
32/// let mut hook = unsafe { GenericDetour::<fn(i32) -> i32>::new(add5, add10)? };
33///
34/// assert_eq!(add5(5), 10);
35/// assert_eq!(hook.call(5), 10);
36///
37/// unsafe { hook.enable()? };
38///
39/// assert_eq!(add5(5), 15);
40/// assert_eq!(hook.call(5), 10);
41///
42/// unsafe { hook.disable()? };
43///
44/// assert_eq!(add5(5), 10);
45/// # Ok(())
46/// # }
47/// ```
48#[derive(Debug)]
49pub struct GenericDetour<T: Function> {
50  phantom: PhantomData<T>,
51  detour: Detour,
52}
53
54impl<T: Function> GenericDetour<T> {
55  /// Create a new hook given a target function and a compatible detour
56  /// function.
57  pub unsafe fn new<D>(target: T, detour: D) -> Result<Self>
58  where
59    T: HookableWith<D>,
60    D: Function,
61  {
62    Detour::new(target.to_ptr(), detour.to_ptr()).map(|detour| GenericDetour {
63      phantom: PhantomData,
64      detour,
65    })
66  }
67
68  /// Enables the detour.
69  pub unsafe fn enable(&self) -> Result<()> {
70    self.detour.enable()
71  }
72
73  /// Disables the detour.
74  pub unsafe fn disable(&self) -> Result<()> {
75    self.detour.disable()
76  }
77
78  /// Returns whether the detour is enabled or not.
79  pub fn is_enabled(&self) -> bool {
80    self.detour.is_enabled()
81  }
82
83  /// Returns a reference to the generated trampoline.
84  pub(crate) fn trampoline(&self) -> &() {
85    self.detour.trampoline()
86  }
87}
88
89unsafe impl<T: Function> Send for GenericDetour<T> {}
90unsafe impl<T: Function> Sync for GenericDetour<T> {}