winhook 0.1.0

x86_64 function hooking library for Windows and Wine
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
use std::{
    fmt,
    io::{self, Seek, Write},
    marker::PhantomData,
    ptr::{self, NonNull},
    sync::atomic::{AtomicBool, Ordering},
};

use closure_ffi::{
    JitAlloc,
    jit_alloc::GlobalJitAlloc,
    thunk_factory,
    traits::{FnMutThunk, FnOnceThunk, FnPtr, FnThunk},
};
use closure_ffi_iced_x86::Register;
use parking_lot::Mutex;
use windows_sys::Win32::System::Memory::{
    PAGE_EXECUTE, PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE, PAGE_EXECUTE_WRITECOPY,
};

use crate::{
    analysis::PrologueProbe,
    cconv::CConv,
    hook::{
        HookGroup, HookHandle, MIN_HOOKABLE_REGION_LEN, STATIC_ALLOCATOR,
        alloc::HookAllocator,
        cas::{CMPXCHG64_LEN, CasBuffer},
    },
    system::{self, module::Module},
};

/// A builder for installing function hooks.
///
/// See [`HookInstaller::for_function`], [`HookInstaller::install`],
/// [`HookInstaller::install_mut`], [`HookInstaller::install_once`].
#[derive(Clone)]
pub struct HookInstaller<F: FnPtr + CConv + 'static> {
    inner: HookInstallerInner,
    _marker: PhantomData<F>,
}

#[doc(hidden)]
#[repr(transparent)]
pub struct HookRetryInstaller {
    inner: Box<dyn FnOnce() -> Result<HookHandle, Error>>,
}

#[derive(Clone)]
struct HookInstallerInner {
    ptr: *const (),
    enable: bool,
    push_back: bool,
    prefer_early: bool,
    allocator: Option<HookAllocator>,
}

/// Error returned by [`HookInstaller`].
///
/// Also see [`InstallerResultExt`].
#[derive(Debug, thiserror::Error)]
pub enum Error {
    /// A function hookable by WinHook must be inside a module, like an executable or a DLL.
    #[error("cannot determine which module address (is {0:x}) belongs to")]
    NotInModule(usize),

    /// The function pointer does not point to executable memory.
    #[error("nowhere to install hook (inacessible or non-executable memory)")]
    InvalidMemoryRegion,

    /// Could not find any instructions to host the hook.
    ///
    /// This is more likely to happen when a function is not 16-byte aligned.
    /// In that case, the unsafe [`InstallerResultExt::retry_unchecked`] could be used.
    #[error("nowhere to install hook (at least {0} bytes are available)")]
    NoHookableArea(usize, Option<HookRetryInstaller>),
}

mod private {
    pub trait Sealed {}
}

/// Extension trait for [`Result<HookHandle, Error>`].
///
/// [`InstallerResultExt::retry_unchecked`] may be used when a function is not 16-byte aligned,
/// which normally limits WinHook to only hooking the first 8 bytes of the prologue instead of 16.
///
/// [`InstallerResultExt::retry_unchecked`] is unsafe because it is *NOT* atomic.
/// You must guarantee there is no possible data race (which would be Undefined Behavior).
pub trait InstallerResultExt: private::Sealed {
    /// Opt-in to retry hooking unaligned functions in a *non-atomic* way.
    ///
    /// # Examples
    ///
    /// ```
    /// extern "C" fn meow() {
    ///     println!("meow");
    /// }
    ///
    /// use winhook::{HookInstaller, InstallerResultExt};
    ///
    /// let _handle = unsafe {
    ///     HookInstaller::<unsafe extern "C" fn()>::for_function(meow)
    ///         .enable(true)
    ///         .install(|_| || println!("woof"))
    ///         .retry_unchecked()
    ///         .unwrap()
    /// };
    /// ```
    ///
    /// # Safety
    ///
    /// Race conditions are UB. You must guarantee no concurrent modifications to
    /// the hooked function happen at the same time as this method runs.
    unsafe fn retry_unchecked(self) -> Result<HookHandle, Error>;
}

impl<F: FnPtr + CConv + 'static> HookInstaller<F> {
    /// Prepare a new [`HookInstaller`] for the provided `unsafe extern "C"`,
    /// `unsafe extern "system"` or `unsafe extern "win64"` function.
    ///
    /// By default, [`HookInstaller::enable`] is `false`, [`HookInstaller::push_back`] is `false`,
    /// [`HookInstaller::prefer_early`] is `true`.
    ///
    /// # Examples
    ///
    /// Function *items* should be coerced to function *pointers*. There are two ways
    /// to achieve this:
    ///
    /// ```
    /// extern "system" fn add(a: i32, b: i32) -> i32 {
    ///     a + b
    /// }
    ///
    /// use winhook::HookInstaller;
    ///
    /// // Via an explicit generic type:
    /// let _installer =
    ///     HookInstaller::<unsafe extern "system" fn(_, _) -> _>::for_function(add);
    ///
    /// // Via an `as` cast:
    /// let _installer =
    ///     HookInstaller::for_function(add as unsafe extern "system" fn(_, _) -> _);
    /// ```
    ///
    /// # Safety
    ///
    /// Installing a hook is safe, as it is done fully atomically (and threadsafe),
    /// but enabling it with [`HookInstaller::enable`] is not.
    #[inline]
    pub fn for_function(fn_ptr: F) -> Self {
        Self {
            inner: HookInstallerInner {
                ptr: fn_ptr.to_ptr(),
                enable: false,
                push_back: false,
                prefer_early: true,
                allocator: None,
            },
            _marker: PhantomData,
        }
    }

    /// Enable the hook right after installing it.
    ///
    /// This is more efficient than calling [`HookHandle::enable`] on the returned handle,
    /// if you mean to enable the hook as soon as you install it.
    ///
    /// # Safety
    ///
    /// Just like with [`HookHandle::enable`], the installed hookmust maintain
    /// the hooked function's invariants.
    #[inline]
    pub unsafe fn enable(self, enable: bool) -> Self {
        Self {
            inner: HookInstallerInner {
                enable,
                ..self.inner
            },
            _marker: PhantomData,
        }
    }

    /// Should this hook be ordered last w.r.t. other WinHook hooks using the same
    /// [`HookInstaller::with_allocator`]?
    ///
    /// This influences the order of invocation of multiple hooks to the same function.
    /// Hooks installed with `push_back == false` are installed before all other hooks,
    /// while `push_back == true` are installed after all other hooks.
    ///
    /// The default is `false`.
    #[inline]
    pub fn push_back(self, push_back: bool) -> Self {
        Self {
            inner: HookInstallerInner {
                push_back,
                ..self.inner
            },
            _marker: PhantomData,
        }
    }

    /// Should WinHook prioritize earlier in the function prologue instructions
    /// or longer ones when choosing where to insert the jump to the hook?
    ///
    /// Prioritizing longer instructions (`prefer_early == false`) results in slightly better
    /// memory usage and installation speed, but may install the hook past a branch back
    /// to the start of the instruction.
    ///
    /// Prioritizing early instructions is slightly slower and more inefficient, but is less likely
    /// to cause issues with backwards branches invoking the hook multiple times.
    #[inline]
    pub fn prefer_early(self, prefer_early: bool) -> Self {
        Self {
            inner: HookInstallerInner {
                prefer_early,
                ..self.inner
            },
            _marker: PhantomData,
        }
    }

    /// Provide a [`HookAllocator`] to allocate and group hooks by instead of the
    /// static allocator provided by this crate.
    ///
    /// Hooks allocated by the same [`HookAllocator`] benefit from faster installation,
    /// grouping and ordering by [`HookInstaller::push_back`].
    ///
    /// <p style="background:rgba(163, 137, 20, 0.5)">
    /// <strong>WARNING:</strong> Prefer to reuse the same allocator everywhere in your code.
    /// Do not call this method if you do not have a good reason to.
    /// </p>
    #[inline]
    pub fn with_allocator(self, allocator: HookAllocator) -> Self {
        Self {
            inner: HookInstallerInner {
                allocator: Some(allocator),
                ..self.inner
            },
            _marker: PhantomData,
        }
    }

    /// Install the function hook provided by a closure.
    ///
    /// They may capture any variables, as long as they have a `'static` lifetime.
    ///
    /// # Examples
    ///
    /// ```
    /// extern "C" fn add(a: i32, b: i32) -> i32 {
    ///     a + b
    /// }
    ///
    /// use winhook::HookInstaller;
    ///
    /// let hook_handle = HookInstaller::<unsafe extern "C" fn(_, _) -> _>::for_function(add)
    ///     .install(move |original| move |a, b| {
    ///         // SAFETY: it's definitely safe to call the original function once
    ///         // with the original arguments.
    ///         let sum = unsafe { original(a, b) };
    ///
    ///         // Will print on every invocation of `add` only after enabling the hook.
    ///         println!("{sum}");
    ///
    ///         // Return the original result.
    ///         sum
    ///     })
    ///     .unwrap();
    /// ```
    ///
    /// # Safety
    ///
    /// Installing *any* hook is safe, *enabling* it is not.
    #[must_use = "the hook will be uninstalled when the handle is dropped"]
    pub fn install<C, H>(&self, c: C) -> Result<HookHandle, Error>
    where
        C: FnOnce(F) -> H + 'static,
        H: Send + Sync + 'static,
        (F::CC, H): FnThunk<F> + Send + Sync + 'static,
    {
        self.install_new_or_existing(true, move |f: F| (F::CC::default(), c(f)))
    }

    /// Install the function hook with mutable state to run provided by a closure.
    ///
    /// This method accepts `FnMut` closures, which may mutate their state on invocation.
    /// They may capture any variables, as long as they have a `'static` lifetime.
    ///
    /// The closure is protected by a `Mutex`.
    /// Calling the original function *must not lead to a recursive call to itself*.
    ///
    /// # Examples
    ///
    /// ```
    /// extern "C" fn add(a: i32, b: i32) -> i32 {
    ///     a + b
    /// }
    ///
    /// use winhook::HookInstaller;
    ///
    /// let mut total = 0i32;
    ///
    /// let hook_handle = HookInstaller::<unsafe extern "C" fn(_, _) -> _>::for_function(add)
    ///     .install_mut(move |original| move |a, b| {
    ///         // SAFETY: it's definitely safe to call the original function once
    ///         // with the original arguments.
    ///         let sum = unsafe { original(a, b) };
    ///
    ///         // Will print on every invocation of `add` only after enabling the hook.
    ///         total += sum;
    ///         println!("{sum} {total}");
    ///
    ///         // Return the original result.
    ///         sum
    ///     })
    ///     .unwrap();
    /// ```
    ///
    /// # Safety
    ///
    /// Installing *any* hook is safe, *enabling* it is not.
    #[must_use = "the hook will be uninstalled when the handle is dropped"]
    pub fn install_mut<C, H>(&self, c: C) -> Result<HookHandle, Error>
    where
        C: FnOnce(F) -> H + 'static,
        H: Send + Sync + 'static,
        (F::CC, H): FnMutThunk<F> + Send + Sync + 'static,
    {
        self.install_new_or_existing(true, move |f: F| {
            let hook = Mutex::new((F::CC::default(), c(f)));
            thunk_factory::make_send_sync(move |args| unsafe { hook.lock().call_mut(args) })
        })
    }

    /// Install the function hook to run once provided by a closure.
    ///
    /// This method accepts `FnOnce` closures, which will only execute once.
    ///
    /// # Examples
    ///
    /// ```
    /// extern "C" fn add(a: i32, b: i32) -> i32 {
    ///     a + b
    /// }
    ///
    /// use winhook::HookInstaller;
    ///
    /// let hook_handle = HookInstaller::<unsafe extern "C" fn(_, _) -> _>::for_function(add)
    ///     .install_once(move |original| move |a, b| {
    ///         // SAFETY: it's definitely safe to call the original function once
    ///         // with the original arguments.
    ///         let sum = unsafe { original(a, b) };
    ///
    ///         // Will print on the first invocation of `add` only after enabling the hook.
    ///         println!("{sum}");
    ///
    ///         // Return the original result.
    ///         sum
    ///     })
    ///     .unwrap();
    /// ```
    ///
    /// # Safety
    ///
    /// Installing *any* hook is safe, *enabling* it is not.
    #[must_use = "the hook will be uninstalled when the handle is dropped"]
    pub fn install_once<C, H>(&self, c: C) -> Result<HookHandle, Error>
    where
        C: FnOnce(F) -> H + 'static,
        H: Send + Sync + 'static,
        (F::CC, H): FnOnceThunk<F> + Send + Sync + 'static,
    {
        self.install_new_or_existing(true, move |f: F| {
            let hook = Mutex::new(Some((F::CC::default(), c(f))));
            let once = AtomicBool::new(true);
            thunk_factory::make_send_sync(move |args| unsafe {
                if !once.load(Ordering::Relaxed) {
                    return f.call(args);
                }

                match once
                    .swap(false, Ordering::Relaxed)
                    .then(|| hook.lock().take())
                {
                    Some(Some(hook)) => hook.call_once(args),
                    _ => f.call(args),
                }
            })
        })
    }

    fn install_new_or_existing<C, H>(&self, use_atomics: bool, c: C) -> Result<HookHandle, Error>
    where
        C: FnOnce(F) -> H + 'static,
        H: FnThunk<F> + Send + Sync + 'static,
    {
        let (module, region_len) = self.inner.verify_module_and_region()?;

        let hook_allocator = self
            .inner
            .allocator
            .as_ref()
            .unwrap_or_else(|| &STATIC_ALLOCATOR);

        // Use dyn dispatch to improve code deduplication; a closure was previously passed
        // by value to `HookAllocator::try_alloc_in_bounds`.
        let init_hook_group =
            |ptr, trampoline| unsafe { HookGroup::write(ptr, F::from_ptr(trampoline)) };

        let hook_group = match hook_allocator.get_existing(module, self.inner.ptr) {
            Some(existing) => existing,
            None => match self.inner.install_new(
                module,
                region_len,
                hook_allocator,
                use_atomics,
                F::called_with(),
                &init_hook_group,
            ) {
                Err(Error::NoHookableArea(CMPXCHG64_LEN, _)) => {
                    let retry = HookRetryInstaller::new({
                        let installer = self.clone();
                        move || installer.install_new_or_existing(false, c)
                    });

                    return Err(Error::NoHookableArea(CMPXCHG64_LEN, Some(retry)));
                }
                result => result?,
            },
        };

        unsafe {
            Ok(HookGroup::push_hook(
                hook_group,
                self.inner.enable,
                !self.inner.push_back,
                c,
            ))
        }
    }
}

impl HookInstallerInner {
    fn install_new(
        &self,
        module: Module,
        region_len: usize,
        hook_allocator: &HookAllocator,
        use_atomics: bool,
        called_with: &'static [Register],
        init_hook_group: &dyn Fn(NonNull<HookGroup>, *const ()),
    ) -> Result<NonNull<HookGroup>, Error> {
        let module_address_space = module.address_space();

        let mut cas_buf = unsafe { CasBuffer::new(self.ptr as *const u8, region_len, use_atomics) };

        'cas: loop {
            // Analyze the function prologue at the injection area.
            let prologue = PrologueProbe::new(&cas_buf, self.ptr, called_with);

            // Prioritize instructions that can fit a 5 byte `CALL disp32`.
            let instructions = if !self.prefer_early {
                prologue.enumerate_instructions_by_len(1 + size_of::<i32>())
            } else {
                prologue.enumerate_instructions()
            };

            for &(index, instruction) in &instructions {
                let instruction_start = instruction.ip() - self.ptr as u64;

                let instruction_len = if !instruction.is_invalid() {
                    instruction.len()
                } else {
                    // Use all bytes including ones that failed to decode in the trailing
                    // possibly invalid instruction.
                    cas_buf.remaining_len()
                };

                let Some(undo_seq) = prologue.encode_undo_sequence(index) else {
                    continue;
                };

                let Some(trampoline) = prologue.encode_trampoline(index) else {
                    continue;
                };

                // Below unwraps should not fail due to being inside instruction bounds.
                for i in 0..instruction_len {
                    cas_buf.refresh();

                    cas_buf
                        .seek(io::SeekFrom::Start(instruction_start))
                        .unwrap();

                    // NOP ...
                    const NOPS: [u8; 15] = [0x90; 15];
                    cas_buf.write_all(&NOPS[..i]).unwrap();

                    // CALL [disp32]
                    cas_buf.write_all(&[0xe8]).unwrap();

                    // ... NOP
                    if let Some(trailing_len) =
                        instruction_len.checked_sub(i + 1 + size_of::<i32>())
                    {
                        cas_buf
                            .seek(io::SeekFrom::Current(size_of::<i32>() as i64))
                            .unwrap();

                        let _ = cas_buf.write(&NOPS[..trailing_len]).unwrap();

                        cas_buf
                            .seek(io::SeekFrom::Start(instruction_start + i as u64 + 1))
                            .unwrap();
                    }

                    let disp32_arbitrary_len = size_of::<i32>().min(instruction_len - 1 - i);

                    let (disp32_min, disp32_max) = Self::calculate_disp32_bounds(
                        cas_buf.remaining_as_slice(),
                        disp32_arbitrary_len,
                    );

                    let next_ip = instruction_start as usize + 1 + size_of::<i32>();
                    let next_instruction_ptr = self.ptr.cast::<u8>().wrapping_add(next_ip);

                    let call_target_min = next_instruction_ptr.wrapping_offset(disp32_min);
                    let call_target_max = next_instruction_ptr.wrapping_offset(disp32_max);

                    let code_offset = unsafe {
                        next_instruction_ptr.offset_from_unsigned(module.image_base()) as u32
                    };

                    let alloc_trampoline = |hook_group| unsafe {
                        let (rx, rw) = GlobalJitAlloc
                            .alloc(trampoline.len())
                            .expect("failed to allocate JIT memory");

                        ptr::copy_nonoverlapping(trampoline.as_ptr(), rw, trampoline.len());

                        init_hook_group(hook_group, rx as *const ());
                    };

                    let result = (call_target_min.addr() < module_address_space.start.addr())
                        .then(|| unsafe {
                            hook_allocator.try_alloc_in_bounds(
                                call_target_min..=call_target_max.min(module_address_space.start),
                                module,
                                self.ptr,
                                code_offset,
                                &undo_seq,
                                &alloc_trampoline,
                            )
                        })
                        .or_else(|| {
                            (call_target_max.addr() > module_address_space.end.addr()).then(
                                || unsafe {
                                    hook_allocator.try_alloc_in_bounds(
                                        call_target_min.max(module_address_space.end)
                                            ..=call_target_max,
                                        module,
                                        self.ptr,
                                        code_offset,
                                        &undo_seq,
                                        &alloc_trampoline,
                                    )
                                },
                            )
                        })
                        .flatten();

                    if let Some((ptr, hook_group)) = result {
                        let displacement = ptr as isize - next_instruction_ptr as isize;

                        cas_buf
                            .write_all(&i32::to_le_bytes(displacement as i32))
                            .unwrap();

                        if let Err(e) = cas_buf.flush() {
                            unsafe {
                                hook_allocator.dealloc_failed_hook(module, self.ptr);
                            }

                            match e.kind() {
                                io::ErrorKind::Interrupted => continue 'cas,
                                _ => return Err(Error::InvalidMemoryRegion),
                            }
                        }

                        return Ok(hook_group);
                    }
                }
            }

            // Inner loop finished without finding a patchable region.
            return Err(Error::NoHookableArea(cas_buf.len(), None));
        }
    }

    fn verify_module_and_region(&self) -> Result<(Module, usize), Error> {
        let ptr = self.ptr as *const u8;

        let module = Module::try_from_address(ptr).ok_or(Error::NotInModule(ptr.addr()))?;
        let module_address_space = module.address_space();

        // Sanity checks to ensure unsafe preconditions for later.
        if !module_address_space.contains(&ptr) {
            return Err(Error::NotInModule(ptr.addr()));
        }

        // SAFETY: `ptr` was determined to be inside a module's address space.
        let available_bytes = unsafe { module_address_space.end.offset_from_unsigned(ptr) };

        let memory_info = system::query_memory(ptr).ok_or(Error::InvalidMemoryRegion)?;

        if !matches!(
            memory_info.Protect,
            PAGE_EXECUTE | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY
        ) {
            return Err(Error::InvalidMemoryRegion);
        }

        if available_bytes < MIN_HOOKABLE_REGION_LEN {
            return Err(Error::NoHookableArea(available_bytes, None));
        }

        Ok((module, available_bytes))
    }

    fn calculate_disp32_bounds(disp32: &[u8], disp32_arbitrary_len: usize) -> (isize, isize) {
        if disp32_arbitrary_len == size_of::<i32>() {
            return (i32::MIN as isize, i32::MAX as isize);
        }

        let mut disp32_bytes = [0u8; size_of::<i32>()];

        disp32_bytes[disp32_arbitrary_len..]
            .clone_from_slice(&disp32[disp32_arbitrary_len..size_of::<i32>()]);

        let disp32_min = i32::from_le_bytes(disp32_bytes);

        disp32_bytes[..disp32_arbitrary_len]
            .clone_from_slice(&[u8::MAX; 4][..disp32_arbitrary_len]);

        let disp32_max = i32::from_le_bytes(disp32_bytes);

        (disp32_min as isize, disp32_max as isize)
    }
}

impl HookRetryInstaller {
    #[cold]
    pub unsafe fn retry_unchecked(self) -> Result<HookHandle, Error> {
        (self.inner)()
    }

    fn new<F>(f: F) -> Self
    where
        F: FnOnce() -> Result<HookHandle, Error> + 'static,
    {
        Self { inner: Box::new(f) }
    }
}

impl private::Sealed for Result<HookHandle, Error> {}
impl InstallerResultExt for Result<HookHandle, Error> {
    unsafe fn retry_unchecked(self) -> Result<HookHandle, Error> {
        match self {
            Err(Error::NoHookableArea(CMPXCHG64_LEN, Some(installer))) => unsafe {
                installer.retry_unchecked()
            },
            result => result,
        }
    }
}

impl<F: FnPtr + CConv + 'static> fmt::Debug for HookInstaller<F> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("HookInstaller")
            .field("enable", &self.inner.enable)
            .field("push_back", &self.inner.push_back)
            .field("allocator", &self.inner.allocator)
            .finish()
    }
}

impl fmt::Debug for HookRetryInstaller {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("HookRetryInstaller").finish()
    }
}

#[cfg(test)]
mod tests {
    use super::HookInstaller;

    unsafe extern "C" fn hello_world() {
        println!("Hello, World!");
    }

    #[test]
    fn try_patch() {
        unsafe {
            let _handle = HookInstaller::<unsafe extern "C" fn()>::for_function(hello_world)
                .enable(true)
                .push_back(false)
                .install(|trampoline| move || trampoline())
                .unwrap();

            hello_world();
        }
    }
}