wdk_mutex/
alloc.rs

1//! Internal allocator to allow wdk-mutex to use the allocator as required.
2
3use core::{alloc::GlobalAlloc, ptr::null_mut};
4
5use wdk_sys::{
6    ntddk::{ExAllocatePool2, ExFreePool},
7    POOL_FLAG_NON_PAGED,
8};
9
10/// Memory allocator used by the crate.
11///
12/// SAFETY: This is safe IRQL <= DISPATCH_LEVEL
13pub struct KMAlloc;
14
15// The value memory tags are stored as.
16const MEM_TAG_WDK_MUTEX: u32 = u32::from_le_bytes(*b"kmtx");
17
18unsafe impl GlobalAlloc for KMAlloc {
19    unsafe fn alloc(&self, layout: core::alloc::Layout) -> *mut u8 {
20        let ptr = unsafe {
21            ExAllocatePool2(POOL_FLAG_NON_PAGED, layout.size() as u64, MEM_TAG_WDK_MUTEX)
22        };
23        if ptr.is_null() {
24            return null_mut();
25        }
26
27        ptr.cast()
28    }
29
30    unsafe fn dealloc(&self, ptr: *mut u8, _layout: core::alloc::Layout) {
31        unsafe {
32            ExFreePool(ptr.cast());
33        }
34    }
35}