wdk_mutex/
alloc.rs

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
//! Internal allocator to allow wdk-mutex to use the allocator as required.

use core::{alloc::GlobalAlloc, ptr::null_mut};

use wdk_sys::{
    ntddk::{ExAllocatePool2, ExFreePool},
    POOL_FLAG_NON_PAGED,
};

/// Memory allocator used by the crate.
///
/// SAFETY: This is safe IRQL <= DISPATCH_LEVEL
pub struct KMAlloc;

// The value memory tags are stored as.
const MEM_TAG_WDK_MUTEX: u32 = u32::from_le_bytes(*b"kmtx");

unsafe impl GlobalAlloc for KMAlloc {
    unsafe fn alloc(&self, layout: core::alloc::Layout) -> *mut u8 {
        let ptr = unsafe {
            ExAllocatePool2(POOL_FLAG_NON_PAGED, layout.size() as u64, MEM_TAG_WDK_MUTEX)
        };
        if ptr.is_null() {
            return null_mut();
        }

        ptr.cast()
    }

    unsafe fn dealloc(&self, ptr: *mut u8, _layout: core::alloc::Layout) {
        unsafe {
            ExFreePool(ptr.cast());
        }
    }
}