diversion 0.2.0

Ergonomic function hooks for Windows and Linux
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
use std::{
    fmt,
    mem::{self, ManuallyDrop},
    ops::Deref,
    sync::{
        Arc,
        atomic::{AtomicBool, AtomicUsize, Ordering},
    },
};

use closure_ffi::{
    BareFnAny, UntypedBareFn, thunk_factory,
    traits::{FnMutThunk, FnOnceThunk, FnPtr, FnThunk},
};
use diversion_abi::{
    context::library::{ErasedClosureList, LibraryContext},
    fn_ptr::AtomicFnPtr,
    sync::Mutex,
};

use crate::{
    hook::{Handle, RawHook, Weak},
    installer::HookInstaller,
};

pub struct Hook<T, Ctx>
where
    T: FnPtr + 'static,
{
    inner: RawHook<T, Ctx>,
    list: &'static ErasedClosureList,
    key: AtomicUsize,
}

pub trait TemporaryHook<T, Ctx>: HookInstaller<Target = T, Context = Ctx>
where
    T: FnPtr,
    Ctx: Send + Sync + 'static,
{
    #[must_use = "the hook will be removed when the handle is dropped"]
    unsafe fn hook<H>(self, source: impl FnOnce(Weak<T, Ctx>) -> H) -> Handle<T, Ctx>
    where
        (T::CC, H): FnThunk<T>,
        H: Send + Sync + 'static,
    {
        // SAFETY: `H` is already `'static`.
        unsafe { self.hook_unchecked_lt(move |hook| (T::CC::default(), source(hook))) }
    }

    #[must_use = "the hook will be removed when the handle is dropped"]
    unsafe fn hook_mut<H>(self, source: impl FnOnce(Weak<T, Ctx>) -> H) -> Handle<T, Ctx>
    where
        (T::CC, H): FnMutThunk<T>,
        H: Send + 'static,
    {
        // SAFETY: `H` is already `'static`.
        unsafe {
            self.hook_unchecked_lt(move |hook| {
                let hook_fn = Mutex::new((T::CC::default(), source(hook)));
                thunk_factory::make_send_sync(move |args| hook_fn.lock().call_mut(args))
            })
        }
    }

    #[must_use = "the hook will be removed when the handle is dropped"]
    unsafe fn hook_once<H>(self, source: impl FnOnce(Weak<T, Ctx>) -> H) -> Handle<T, Ctx>
    where
        (T::CC, H): FnOnceThunk<T>,
        H: Send + 'static,
    {
        // SAFETY: `H` is already `'static`.
        unsafe {
            self.hook_unchecked_lt(move |hook| {
                let hook_fn_once = (T::CC::default(), source(hook.clone()));
                let hook_fn = Mutex::new(Some(hook_fn_once));
                let flag = AtomicBool::new(true);
                thunk_factory::make_send_sync(move |args| {
                    if flag.load(Ordering::Acquire)
                        && let Some(hook) = { hook_fn.lock().take() }
                    {
                        flag.store(false, Ordering::Release);
                        hook.call_once(args)
                    } else {
                        hook.upgrade().unwrap().call_original(args)
                    }
                })
            })
        }
    }
}

pub(super) trait TemporaryHookExt<T, Ctx>: HookInstaller<Target = T, Context = Ctx>
where
    T: FnPtr,
    Ctx: Send + Sync + 'static,
{
    /// # Safety
    ///
    /// Same as [`TemporaryHook::hook`], except `H: 'static` is not enforced!
    /// It **must outlive** the returned [`Handle`].
    unsafe fn hook_unchecked_lt<H>(self, source: impl FnOnce(Weak<T, Ctx>) -> H) -> Handle<T, Ctx>
    where
        H: FnThunk<T> + Send + Sync,
    {
        let hook = self.into_unowned_handle();

        // Hold an exclusive lock until `hook.key` is set.
        // Trying to upgrade and call original inside `source` will deadlock.
        let mut closures = hook.list.closures.write();
        let hook_fn = source(Arc::downgrade(&hook));

        let untyped_with_lt = BareFnAny::with_thunk(hook_fn).into_untyped();

        // SAFETY: iff the hook handle does not outlive `untyped_unchecked_lt`.
        // See `closure_ffi::UntypedBareFn::upcast` for other correctness notes.
        let untyped_unchecked_lt = unsafe {
            mem::transmute_copy::<
                UntypedBareFn<dyn Send + Sync>,
                UntypedBareFn<dyn Send + Sync + 'static>,
            >(&ManuallyDrop::new(untyped_with_lt))
        };

        let key = closures.push_front(Arc::new(untyped_unchecked_lt));
        hook.key.store(key, Ordering::Relaxed);

        hook.list.extra_count.fetch_add(1, Ordering::Release);

        hook
    }

    fn into_unowned_handle(self) -> Handle<T, Ctx> {
        let list = LibraryContext::acquire().closures(self.target());

        let original_ptr = list.original_ptr.get_or_init(|| {
            // SAFETY: we make sure to initialize this before `thunk` is ever called.
            let original_ptr: &'static AtomicFnPtr<T> =
                unsafe { Box::leak(Box::new(AtomicFnPtr::new_uninit())) };

            let thunk = BareFnAny::<T, dyn Send + Sync + 'static>::with_thunk(
                thunk_factory::make_send_sync(|args| {
                    // Don't hold the reader lock for long, just clone the inner `Arc`.
                    // It will stay alive for the rest of this scope, which means `original`
                    // also will.
                    let first = match list.closures.read().first() {
                        Some(first) => first.clone(),
                        None => unsafe {
                            return original_ptr.load(Ordering::Acquire).call(args);
                        },
                    };

                    unsafe { T::from_ptr(first.bare()).call(args) }
                }),
            )
            .leak();

            let original = self.update_thunk(|original| {
                // Initialize `original` before `thunk` may be called,
                // fulfilling the `AtomicFnPtr::new_uninit` safety contract.
                original_ptr.store(original, Ordering::Release);
                thunk
            });

            AtomicFnPtr::new(original).erase()
        });

        // SAFETY: we know the exact function type `.closures` promises to return.
        let original = unsafe { original_ptr.downcast::<T>().load(Ordering::Relaxed) };

        Handle::new(Hook {
            inner: RawHook {
                context: self.into_context(),
                original,
            },
            list,
            // Placeholder value, it cannot be sourced until the hook is owned.
            key: AtomicUsize::new(usize::MAX),
        })
    }
}

impl<H, T, Ctx> TemporaryHook<T, Ctx> for H
where
    T: FnPtr,
    Ctx: Send + Sync + 'static,
    H: HookInstaller<Target = T, Context = Ctx>,
{
}

impl<H, T, Ctx> TemporaryHookExt<T, Ctx> for H
where
    T: FnPtr,
    Ctx: Send + Sync + 'static,
    H: HookInstaller<Target = T, Context = Ctx>,
{
}

impl<T, Ctx> Hook<T, Ctx>
where
    T: FnPtr + 'static,
{
    /// Calls the original (hooked) function trampoline.
    ///
    /// # Safety
    ///
    /// The invariants of the hooked function must be preserved when calling this.
    #[inline]
    pub unsafe fn call_original<'a, 'b, 'c>(
        &self,
        args: T::Args<'a, 'b, 'c>,
    ) -> T::Ret<'a, 'b, 'c> {
        // Check for extra (chained) hooks:
        // SAFETY: function invariants upheld by caller.
        if self.list.extra_count.load(Ordering::Acquire) > 0 {
            unsafe { self.call_original_slow(args) }
        } else {
            unsafe { self.inner.original.call(args) }
        }
    }

    /// Calls the original (hooked) function trampoline.
    ///
    /// # Safety
    ///
    /// The invariants of the hooked function must be preserved when calling this.
    #[cold]
    unsafe fn call_original_slow<'a, 'b, 'c>(
        &self,
        args: T::Args<'a, 'b, 'c>,
    ) -> T::Ret<'a, 'b, 'c> {
        // Don't hold the reader lock for long, just clone the inner `Arc`.
        // It will stay alive for the rest of this scope, which means `original` also will.
        let next_hook = {
            let closures = self.list.closures.read();
            let key = self.key.load(Ordering::Relaxed);
            closures.get_next(key).cloned()
        };

        // SAFETY: we know the concrete function type.
        let original = match &next_hook {
            Some(closure) => unsafe { T::from_ptr(closure.bare()) },
            None => self.inner.original,
        };

        // SAFETY: function invariants upheld by caller; if `original` is a hook,
        // it can't be deallocated until `next_hook` is dropped.
        unsafe { original.call(args) }
    }
}

impl<T, Ctx> Drop for Hook<T, Ctx>
where
    T: FnPtr + 'static,
{
    fn drop(&mut self) {
        // Remove the trampoline of this hook, making it inaccessible.
        self.list.extra_count.fetch_sub(1, Ordering::Release);
        let mut closures = self.list.closures.write();
        let key = self.key.load(Ordering::Relaxed);
        closures.remove(key);
    }
}

impl<T, Ctx> Deref for Hook<T, Ctx>
where
    T: FnPtr + 'static,
{
    type Target = Ctx;

    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.inner.context
    }
}

impl<T, Ctx: fmt::Debug> fmt::Debug for Hook<T, Ctx>
where
    T: FnPtr + 'static,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Hook")
            .field("inner", &self.inner)
            .finish_non_exhaustive()
    }
}

#[cfg(test)]
mod tests {
    use rayon::iter::{IntoParallelIterator, ParallelIterator};

    use crate::{
        hook::temp::TemporaryHook,
        installer::{
            HookInstaller,
            tests::{ConcatStrFn, mock_installer},
        },
    };

    #[test]
    fn hook() {
        static STR: &str = "This is not a concatenation of the input strings";

        let installer = mock_installer();
        let concat_str = installer.target();

        let hooked = unsafe {
            let _hook = installer.hook(|_| |_, _| STR.to_owned());
            concat_str("Hello, ".to_owned(), "World!".to_owned())
        };

        assert_eq!(hooked, STR);

        assert_unhooked(concat_str);
    }

    #[test]
    fn hook_captures() {
        let new_a = "Goodbye, ".to_owned();

        let installer = mock_installer();
        let concat_str = installer.target();

        let hooked = unsafe {
            let _hook = installer
                .hook(|hook| move |_, b| hook.upgrade().unwrap().call_original((new_a.clone(), b)));
            concat_str("Hello, ".to_owned(), "World!".to_owned())
        };

        assert_eq!(hooked, "Goodbye, World!");

        assert_unhooked(concat_str);
    }

    #[test]
    fn hook_mut() {
        let installer = mock_installer();
        let concat_str = installer.target();

        let hooked = unsafe {
            let _hook = installer.hook_mut(|_| {
                let mut times_called = 0;
                move |_, _| {
                    times_called += 1;
                    times_called.to_string()
                }
            });

            let mut hooked = (0..1000)
                .into_par_iter()
                .map(|_| concat_str(String::new(), String::new()).parse().unwrap())
                .collect::<Vec<u16>>();

            hooked.sort_unstable();

            hooked
        };

        assert_eq!(hooked, (1..=1000).collect::<Vec<_>>());

        assert_unhooked(concat_str);
    }

    #[test]
    fn hook_once() {
        let new_a = "Goodbye, ".to_owned();

        let installer = mock_installer();
        let concat_str = installer.target();

        let hooked = unsafe {
            let _hook = installer.hook_once(|hook| {
                move |_, b| hook.upgrade().unwrap().call_original((new_a.clone(), b))
            });

            let hooked = concat_str("Hello, ".to_owned(), "World!".to_owned());

            assert_unhooked(concat_str);

            hooked
        };

        assert_eq!(hooked, "Goodbye, World!");

        assert_unhooked(concat_str);
    }

    #[test]
    fn static_hook_chained() {
        let installer = mock_installer();
        let concat_str = installer.target();

        let hooked = unsafe {
            let _handles = (1..=6)
                .rev()
                .map(|i| {
                    installer.clone().hook(|hook| {
                        move |a, b| {
                            hook.upgrade()
                                .unwrap()
                                .call_original((format!("{a}{b}"), i.to_string()))
                        }
                    })
                })
                .collect::<Vec<_>>();

            concat_str(String::new(), String::new())
        };

        assert_eq!(hooked, "123456");

        assert_unhooked(concat_str);
    }

    #[track_caller]
    fn assert_unhooked(concat_str: ConcatStrFn) {
        let unhooked = unsafe { concat_str("Hello, ".to_owned(), "World!".to_owned()) };
        assert_eq!(unhooked, "Hello, World!");
    }
}