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
714
715
716
717
718
719
720
721
722
723
724
725
use std::{
    cmp::Ordering,
    collections::BTreeMap,
    ffi::c_void,
    fmt,
    hash::BuildHasherDefault,
    mem,
    ptr::{self, NonNull},
    slice,
    sync::{
        Arc,
        atomic::{AtomicPtr, Ordering as AtomicOrdering},
    },
};

use fxhash::{FxBuildHasher, FxHashMap};
use parking_lot::Mutex;
use windows_sys::Win32::{
    Foundation::STATUS_SUCCESS,
    System::Memory::{
        MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_EXECUTE_READWRITE, PAGE_READWRITE, VirtualAlloc,
        VirtualFree,
    },
};

use crate::{
    address::AsAddress,
    hook::{HookGroup, asm},
    system::{
        self,
        alloc::{AllocBounds, try_alloc_in_bounds_unchecked},
        module::Module,
        nt::{
            LDR_DLL_NOTIFICATION_DATA, LDR_DLL_NOTIFICATION_REASON_LOADED,
            LDR_DLL_NOTIFICATION_REASON_UNLOADED, LdrRegisterDllNotification,
            LdrUnregisterDllNotification,
        },
    },
};

// CALL (e8 + `i32`) + DATA (`usize` aligned to 256, without low 0 byte).
const CALL_REL32_DATA_LEN: usize = 1 + size_of::<i32>() + size_of::<usize>() - 1;

// Full landing pad length, it's a multiple of 2.
const LANDING_PAD_LEN: usize = LANDING_PAD_TEMPLATE.len();

// The length of the area that cannot be jumped to (targeted) on the landing pad,
// [0, 239) are indices that can be jumped to.
const LANDING_PAD_EXCLUDE_LEN: usize = 18;

// The upper bound above.
const LANDING_PAD_INCLUDE_LEN: usize = LANDING_PAD_LEN - LANDING_PAD_EXCLUDE_LEN + 1;

// What is the landing pad data pointer offset?
const LANDING_PAD_OFFSET_START: usize = LANDING_PAD_INCLUDE_LEN + 2;

/// A shared hook allocator used by [`HookInstaller`](super::installer::HookInstaller).
///
/// Hooks allocated by the same [`HookAllocator`] benefit from faster installation,
/// grouping and ordering by [`HookInstaller::push_back`](super::installer::HookInstaller::push_back).
#[derive(Clone)]
pub struct HookAllocator {
    inner: Arc<(RawHookAllocator, Module)>,
}

struct RawHookAllocator {
    module_mapping: Mutex<FxHashMap<Module, HookModuleGroup>>,
    memory_mapping: Mutex<BTreeMap<usize, Box<[Option<Module>]>>>,
    loader_cookie: AtomicPtr<c_void>,
    alloc_granularity: usize,
    pages_per_alloc: usize,
    page_size: usize,
}

struct HookModuleGroup {
    base_address: *mut u8,
    address_ranges: Vec<(u32, u32)>,
    group_allocator: HookGroupBumpAllocator,
    groups_by_ptr: FxHashMap<*const (), NonNull<HookGroup>>,
}

struct HookGroupBumpAllocator(Vec<(NonNull<HookGroup>, NonNull<HookGroup>)>);

impl HookAllocator {
    /// Construct a new [`HookAllocator`].
    ///
    /// Hooks allocated by the same [`HookAllocator`] benefit from faster installation,
    /// grouping and ordering by [`HookInstaller::push_back`](super::installer::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.
    /// It's wasteful to create and use multiple instances of this allocator without a good reason.
    /// Resources allocated by each instance will only be cleaned up when a corresponding to the
    /// hooked function module is unloaded.
    /// </p>
    pub fn new() -> Self {
        let system_info = system::get_info();

        let alloc_granularity = system_info.dwAllocationGranularity as usize;
        let page_size = system_info.dwPageSize as usize;

        // Sanity checks:
        assert!(page_size.is_power_of_two(), "page size is not a power of 2");

        assert!(
            alloc_granularity.is_power_of_two(),
            "allocation granularity is not a power of 2"
        );

        assert!(
            page_size <= alloc_granularity,
            "page size is greater than the allocation granularity"
        );

        assert!(
            page_size >= LANDING_PAD_LEN,
            "page size is smaller than `LANDING_PAD_LEN` bytes"
        );

        let pages_per_alloc = alloc_granularity / page_size;

        let owning_module =
            Module::try_from_address(Self::new as *const ()).expect("failed to get owning module");

        let inner = Arc::new((
            RawHookAllocator {
                alloc_granularity,
                pages_per_alloc,
                page_size,
                ..const { RawHookAllocator::new() }
            },
            owning_module,
        ));

        let mut loader_cookie = ptr::null_mut();

        // WinHook registers a module unloading listener.
        // It's safe to reason about deallocating the hook memory when a module is freed.
        if unsafe {
            LdrRegisterDllNotification(
                0,
                Some(Self::loader_notification),
                Arc::into_raw(inner.clone()) as *mut _,
                &mut loader_cookie,
            ) != STATUS_SUCCESS
        } {
            panic!("LdrRegisterDllNotification failed");
        }

        inner
            .0
            .loader_cookie
            .store(loader_cookie, AtomicOrdering::Relaxed);

        Self { inner }
    }

    pub(super) fn get_existing(
        &self,
        module: Module,
        fn_ptr: *const (),
    ) -> Option<NonNull<HookGroup>> {
        self.inner.0.get_existing(module, fn_ptr)
    }

    pub(super) unsafe fn try_alloc_in_bounds<B: AllocBounds<A>, A: AsAddress>(
        &self,
        bounds: B,
        module: Module,
        fn_ptr: *const (),
        code_offset: u32,
        code: &[u8],
        f: &dyn Fn(NonNull<HookGroup>),
    ) -> Option<(*const (), NonNull<HookGroup>)> {
        unsafe {
            self.inner
                .0
                .try_alloc_in_bounds(bounds, module, fn_ptr, code_offset, code, f)
        }
    }

    pub(super) unsafe fn dealloc_failed_hook(&self, module: Module, fn_ptr: *const ()) {
        unsafe {
            self.inner.0.dealloc_failed_hook(module, fn_ptr);
        }
    }

    unsafe extern "system" fn loader_notification(
        reason: u32,
        data: *const LDR_DLL_NOTIFICATION_DATA,
        context: *mut c_void,
    ) {
        match reason {
            LDR_DLL_NOTIFICATION_REASON_LOADED => {
                // let data = unsafe { &(*data).Loaded };
            }
            LDR_DLL_NOTIFICATION_REASON_UNLOADED => {
                let data = unsafe { &(*data).Unloaded };

                // Retrieve the context passed by `HookAllocator::new`.
                let context = unsafe { &(*context.cast::<(RawHookAllocator, Module)>()) };

                let Some(unloaded_module_base) = NonNull::new(data.DllBase as *mut u8) else {
                    return;
                };

                let unloaded_module =
                    unsafe { Module::from_raw_parts(unloaded_module_base, data.SizeOfImage) };

                // Drop the unloaded module mapping.
                drop(context.0.module_mapping.lock().remove(&unloaded_module));

                // Check the range this module might have had hook landing pads in.
                const PLUS_MINUS_2GB: usize = 0x80000000;

                let module_address_space = unloaded_module.address_space();

                let low_address_bound = module_address_space
                    .start
                    .addr()
                    .saturating_sub(PLUS_MINUS_2GB);

                let high_address_bound = module_address_space
                    .end
                    .addr()
                    .saturating_add(PLUS_MINUS_2GB);

                // Look for landing pads to orphan and free whole pages if they are fully cleared.
                {
                    let mut memory_mapping = context.0.memory_mapping.lock();
                    let mut cleared_pages = vec![];

                    for (&page_addr, owners) in
                        memory_mapping.range_mut(low_address_bound..high_address_bound)
                    {
                        if owners.iter_mut().fold(true, |mut all_cleared, owner| {
                            all_cleared &=
                                owner.take_if(|module| *module == unloaded_module).is_some();
                            all_cleared
                        }) {
                            cleared_pages.push(page_addr);
                        }
                    }

                    // Remove and clear pages.
                    for page in cleared_pages {
                        memory_mapping.remove(&page);
                        unsafe {
                            VirtualFree(page as _, 0, MEM_RELEASE);
                        }
                    }
                }

                // Check if the owner is unloading (and this callback must be unregistered).
                if unloaded_module == context.1 {
                    let cookie = context.0.loader_cookie.load(AtomicOrdering::Relaxed);

                    unsafe {
                        LdrUnregisterDllNotification(cookie);
                        drop(Arc::from_raw(context));
                    }
                }
            }
            _ => {}
        }
    }
}

impl RawHookAllocator {
    fn get_existing(&self, module: Module, fn_ptr: *const ()) -> Option<NonNull<HookGroup>> {
        self.module_mapping
            .lock()
            .get(&module)
            .and_then(|group| group.groups_by_ptr.get(&fn_ptr).cloned())
    }

    /// # Panics
    ///
    /// - If it is not possible to duplicate the module address space (OOM).
    /// - If a hook has previously been allocated for the given `fn_ptr`.
    unsafe fn try_alloc_in_bounds<B: AllocBounds<A>, A: AsAddress>(
        &self,
        bounds: B,
        module: Module,
        fn_ptr: *const (),
        code_offset: u32,
        code: &[u8],
        f: &dyn Fn(NonNull<HookGroup>),
    ) -> Option<(*const (), NonNull<HookGroup>)> {
        let (mut low_addr, mut high_addr) = bounds.as_alloc_bounds();

        if high_addr - low_addr <= LANDING_PAD_EXCLUDE_LEN {
            let high_rem = high_addr % LANDING_PAD_LEN;
            high_addr = high_addr - high_rem + high_rem.min(LANDING_PAD_INCLUDE_LEN);

            let low_rem = low_addr % LANDING_PAD_LEN;
            if low_rem >= LANDING_PAD_INCLUDE_LEN {
                low_addr = low_addr - low_rem + LANDING_PAD_LEN;
            }

            if low_addr >= high_addr {
                // Targeting a landing pad is not possible in this address range.
                return None;
            }
        }

        let mut module_mapping = self.module_mapping.lock();

        let hook_module_group = module_mapping.entry(module).or_insert_with(|| {
            // Unlikely to run into OOM, the entire address space
            // except 4 GB around the module's address space is available.
            let new_address_space = module
                .dupe_module_address_space()
                .expect("could not duplicate module address space; out of memory");

            let entry_thunk = asm::hook_entry_thunk();
            let entry_thunk_len = entry_thunk.len();

            unsafe {
                let page = VirtualAlloc(
                    new_address_space.start as _,
                    entry_thunk_len,
                    MEM_COMMIT,
                    PAGE_EXECUTE_READWRITE,
                ) as *mut u8;

                assert!(
                    !page.is_null(),
                    "failed to commit page at {:?}",
                    new_address_space.start
                );

                ptr::copy_nonoverlapping(entry_thunk.as_ptr(), page, entry_thunk_len);
            }

            HookModuleGroup {
                base_address: new_address_space.start,
                address_ranges: vec![(0, entry_thunk_len as u32)],
                group_allocator: HookGroupBumpAllocator(vec![]),
                groups_by_ptr: FxHashMap::with_hasher(BuildHasherDefault::new()),
            }
        });

        if hook_module_group.groups_by_ptr.contains_key(&fn_ptr) {
            panic!("tried to allocate new hook for a hooked function");
        }

        let next_address_range_index = hook_module_group
            .address_ranges
            .binary_search_by(|(start, _)| start.cmp(&code_offset).then(Ordering::Less))
            .unwrap_err();

        let address_range_upper = hook_module_group
            .address_ranges
            .get(next_address_range_index)
            .map_or(u32::MAX, |(start, _)| *start);

        let address_range_lower = next_address_range_index
            .checked_sub(1)
            .map(|prev_index| hook_module_group.address_ranges[prev_index].1)
            .unwrap_or(0);

        if code_offset < address_range_lower
            || code
                .len()
                .saturating_add(code_offset as usize + CALL_REL32_DATA_LEN)
                > address_range_upper as usize
        {
            return None;
        }

        let alloc_granularity = self.alloc_granularity;
        let page_size = self.page_size;

        let mut low_alloc_bound = low_addr
            .saturating_sub(alloc_granularity - 1)
            .next_multiple_of(alloc_granularity);

        // Prevent the tail end from hanging off at the end of an allocation.
        if low_alloc_bound + alloc_granularity - low_addr <= LANDING_PAD_EXCLUDE_LEN {
            low_alloc_bound += alloc_granularity;
        }

        let high_alloc_bound = high_addr.next_multiple_of(alloc_granularity);

        if low_alloc_bound == high_alloc_bound {
            return None;
        }

        let mut memory_mapping = self.memory_mapping.lock();

        // Find a page to reuse (preferred) or an empty one to allocate.
        let maybe_available_page = memory_mapping
            .range_mut(low_alloc_bound..high_alloc_bound)
            .find_map(|(addr, pages)| {
                let mut page_addr = *addr;

                let mut reused_page = None;
                let mut empty_page = None;

                // FIXME: optimize to only check page range [low_addr, high_addr)
                for page in pages {
                    if high_addr > page_addr && low_addr < page_addr + page_size {
                        let mut low_addr = Ord::max(low_addr, page_addr);
                        let high_addr = Ord::min(high_addr, page_addr + page_size);

                        if high_addr - low_addr <= LANDING_PAD_EXCLUDE_LEN
                            && low_addr % LANDING_PAD_LEN >= LANDING_PAD_INCLUDE_LEN
                        {
                            low_addr = low_addr.next_multiple_of(256);

                            if low_addr >= high_addr {
                                // Targeting a landing pad is not possible in this address range.
                                continue;
                            }
                        }

                        if page.is_some_and(|owner| owner == module) {
                            // Use the first reusable (owned by current module) page if one exists.
                            reused_page = Some((page_addr, page));
                            break;
                        }

                        if page.is_none() && empty_page.is_none() {
                            // Remember the first empty page, but continue to look for reusable ones.
                            empty_page = Some((page_addr, page));
                        }
                    }

                    page_addr += page_size;
                }

                reused_page.or(empty_page)
            });

        // Allocate a range of pages if one was not already found.
        let (page_addr, page_owner) = match maybe_available_page {
            Some(available_page) => available_page,
            None => {
                let alloc = unsafe {
                    try_alloc_in_bounds_unchecked(
                        low_alloc_bound..high_alloc_bound,
                        alloc_granularity,
                        MEM_RESERVE,
                        PAGE_EXECUTE_READWRITE,
                        alloc_granularity,
                        page_size,
                    )?
                    .start
                };

                let mut occupied_pages = Vec::with_capacity(self.pages_per_alloc);
                occupied_pages.resize(self.pages_per_alloc, None);

                let pages = memory_mapping
                    .entry(alloc.addr())
                    .or_insert(occupied_pages.into_boxed_slice());

                let mut page_addr = low_addr
                    .max(alloc.addr())
                    .saturating_sub(page_size - 1)
                    .next_multiple_of(page_size);

                // Don't choose a page for its trailing `LANDING_PAD_EXCLUDE_LEN` bytes, which cannot
                // be addressed. There should always be a next page to advance to, because allocations
                // where this page would be the last are skipped.
                if page_addr + page_size - low_addr <= LANDING_PAD_EXCLUDE_LEN {
                    page_addr += page_size;
                }

                let page = pages.get_mut((page_addr - alloc.addr()) / page_size)?;

                (high_addr > page_addr).then_some((page_addr, page))?
            }
        };

        // Commit and fill the landing pad page if needed.
        let _ = page_owner.get_or_insert_with(|| unsafe {
            let page = VirtualAlloc(
                page_addr as _,
                page_size,
                MEM_COMMIT,
                PAGE_EXECUTE_READWRITE,
            ) as *mut u8;

            assert!(!page.is_null(), "failed to commit page at {page_addr:x}");

            let module_delta = hook_module_group
                .base_address
                .addr()
                .wrapping_sub(module.image_base().addr());

            Self::fill_landing_pad_page(page, page_size, module_delta);

            module
        });

        // Intersect the page's address range and the requested address range.
        let mut addr = Ord::max(low_addr, page_addr);
        let high_addr = Ord::min(high_addr, page_addr + page_size);

        let low_rem = addr % LANDING_PAD_LEN;
        if low_rem >= LANDING_PAD_INCLUDE_LEN {
            addr = addr - low_rem + LANDING_PAD_LEN;
        }

        assert!(addr < high_addr, "allocated an invalid address range");

        let hook_group = unsafe {
            // Allocate and initialize the hook group.
            let hook_group = hook_module_group.group_allocator.alloc(alloc_granularity);
            f(hook_group);

            // Associate the hook group with this function pointer.
            hook_module_group.groups_by_ptr.insert(fn_ptr, hook_group);

            hook_group
        };

        // Commit and fill the code region.
        unsafe {
            Self::write_code_region(hook_module_group, hook_group, code, code_offset);
        }

        Some((addr as *const (), hook_group))
    }

    unsafe fn dealloc_failed_hook(&self, module: Module, fn_ptr: *const ()) {
        let mut module_mapping = self.module_mapping.lock();

        if let Some(hook_module_group) = module_mapping.get_mut(&module)
            && let Some(hook_group) = hook_module_group.groups_by_ptr.remove(&fn_ptr)
        {
            unsafe {
                ptr::drop_in_place(hook_group.as_ptr());
                hook_module_group
                    .group_allocator
                    .try_dealloc(self.alloc_granularity, hook_group);
            }
        }
    }

    /// # Safety
    ///
    /// `page_addr` must be a valid page address of size `page_size`.
    /// [page, page + page_size) must be safe to represent as a mutable slice.
    unsafe fn fill_landing_pad_page(page: *mut u8, page_size: usize, module_delta: usize) {
        let module_offset = (module_delta as u64).to_le_bytes();

        let mut landing_pad = LANDING_PAD_TEMPLATE;
        landing_pad[LANDING_PAD_OFFSET_START..LANDING_PAD_OFFSET_START + 8]
            .copy_from_slice(&module_offset[..]);

        let page = unsafe { slice::from_raw_parts_mut(page, page_size) };
        for page_chunk in page.chunks_exact_mut(LANDING_PAD_LEN) {
            page_chunk.copy_from_slice(&landing_pad);
        }
    }

    unsafe fn write_code_region(
        hook_module_group: &mut HookModuleGroup,
        hook_group: NonNull<HookGroup>,
        code: &[u8],
        code_offset: u32,
    ) {
        assert!(
            hook_group.addr().get().is_multiple_of(256),
            "bump allocator alignment failure"
        );

        let code_start = unsafe { hook_module_group.base_address.add(code_offset as usize) };
        let code_len = code.len() + CALL_REL32_DATA_LEN;

        let page = unsafe {
            VirtualAlloc(
                code_start as _,
                code_len,
                MEM_COMMIT,
                PAGE_EXECUTE_READWRITE,
            )
        };

        assert!(!page.is_null(), "failed to commit page at {code_start:?}");

        let hook_group_addr = hook_group.addr().get().to_le_bytes();
        let disp32 = unsafe {
            hook_module_group
                .base_address
                .offset_from(code_start.add(code.len() + 5)) as i32
        }
        .to_le_bytes();

        let mut buf = Vec::with_capacity(code_len);

        buf.extend_from_slice(code);
        buf.push(0xe8);
        buf.extend_from_slice(&disp32);
        buf.extend_from_slice(&hook_group_addr[1..]);

        unsafe {
            ptr::copy_nonoverlapping(buf.as_ptr(), code_start, buf.len());
        }

        let index = hook_module_group
            .address_ranges
            .binary_search_by_key(&code_offset, |(start, _)| *start)
            .expect_err("BUG: range already occupied");

        hook_module_group
            .address_ranges
            .insert(index, (code_offset, code_offset + code_len as u32));
    }
}

impl RawHookAllocator {
    const fn new() -> Self {
        Self {
            module_mapping: Mutex::new(FxHashMap::with_hasher(FxBuildHasher::new())),
            memory_mapping: Mutex::new(BTreeMap::new()),
            loader_cookie: AtomicPtr::new(ptr::null_mut()),
            alloc_granularity: 4096 * 16,
            pages_per_alloc: 16,
            page_size: 4096,
        }
    }
}

impl HookGroupBumpAllocator {
    unsafe fn alloc(&mut self, alloc_granularity: usize) -> NonNull<HookGroup> {
        const _HOOK_GROUP_SIZE: () = assert!(size_of::<HookGroup>() == 256);

        let next = match self
            .0
            .last_mut()
            .filter(|(start, end)| unsafe { start.byte_add(alloc_granularity) != *end })
        {
            Some((_, next)) => next,
            None => {
                let alloc = unsafe {
                    VirtualAlloc(
                        ptr::null(),
                        alloc_granularity,
                        MEM_COMMIT | MEM_RESERVE,
                        PAGE_READWRITE,
                    ) as *mut HookGroup
                };

                let ptr = NonNull::new(alloc).expect("VirtualAlloc failed");
                self.0.push((ptr, ptr));

                let (_, next) = self.0.last_mut().unwrap();
                next
            }
        };

        let result = next.cast::<HookGroup>();
        *next = unsafe { next.add(1) };

        result
    }

    unsafe fn try_dealloc(&mut self, alloc_granularity: usize, ptr: NonNull<HookGroup>) {
        if let Some((_, end)) = self
            .0
            .last_mut()
            .filter(|(start, end)| unsafe { start.byte_add(alloc_granularity) != *end })
        {
            let prev = unsafe { end.sub(1) };
            if prev == ptr {
                *end = prev;
            }
        }
    }
}

impl Drop for HookModuleGroup {
    fn drop(&mut self) {
        unsafe {
            for hook_group in self.groups_by_ptr.values() {
                ptr::drop_in_place(hook_group.as_ptr());
            }

            VirtualFree(self.base_address as _, 0, MEM_RELEASE);
        }
    }
}

impl Drop for HookGroupBumpAllocator {
    fn drop(&mut self) {
        for (shard, _) in mem::take(&mut self.0) {
            unsafe {
                VirtualFree(shard.as_ptr() as _, 0, MEM_RELEASE);
            }
        }
    }
}

unsafe impl Send for RawHookAllocator {}

unsafe impl Sync for RawHookAllocator {}

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

static LANDING_PAD_TEMPLATE: [u8; 256] = [
    0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e,
    0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e,
    0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e,
    0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e,
    0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e,
    0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e,
    0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e,
    0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e,
    0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e,
    0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e,
    0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e, 0xeb, 0x3e,
    0x66, 0x90, 0xeb, 0x2e, 0xeb, 0x2e, 0xeb, 0x2e, 0xeb, 0x2e, 0xeb, 0x2e, 0xeb, 0x2e, 0xeb, 0x2e,
    0x66, 0x90, 0xeb, 0x26, 0xeb, 0x26, 0xeb, 0x26, 0x66, 0x90, 0x66, 0x90, 0x66, 0x90, 0x66, 0x90,
    0x66, 0x90, 0x66, 0x90, 0x66, 0x90, 0x66, 0x90, 0x66, 0x90, 0x66, 0x90, 0x66, 0x90, 0x66, 0x90,
    0x66, 0x90, 0x66, 0x90, 0x66, 0x90, 0x66, 0x90, 0x66, 0x90, 0x66, 0x90, 0x66, 0x90, 0x50, 0x48,
    0xb8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x48, 0x01, 0x44, 0x24, 0x08, 0x58, 0xc3,
];