A custom memory allocator tailored for the Windows kernel space.
Rust has many useful abstractions and utils that require heap allocations, such as String
, Vec
, and Box
. To be able to use them in the Windows kernel space, we need to allocate memory at runtime, which requires a custom allocator. This crate provides such allocators tailored for the Windows kernel.
For more information on custom allocators in Rust, refer to the alloc::GlobalAllocator and alloc::Allocator documentation. Additionally, the Rust book provides details on globalallocator and allocatorapi.
To use KernelAlloc
or PhysicalAllocator
as your global allocator, add the appropriate code to your kernel module:
For KernelAlloc
:
```rust use kernel_alloc::KernelAlloc;
static GLOBAL: KernelAlloc = KernelAlloc; ```
For PhysicalAllocator
:
```rust use kernel_alloc::PhysicalAllocator;
static GLOBAL: PhysicalAllocator = PhysicalAllocator; ```
Box
Once you've set up KernelAlloc
or PhysicalAllocator
as your global allocator, you can use Box
and other heap-allocated types just like you would in a standard Rust environment.
Here's an example demonstrating how to use both KernelAlloc
and PhysicalAllocator
with Box
to allocate memory for different structs in the Windows kernel:
```rust use kernel_alloc::{KernelAlloc, PhysicalAllocator}; use core::mem;
pub const PAGESIZE: usize = 0x1000; pub const KERNELSTACKSIZE: usize = 0x6000; pub const STACKCONTENTSSIZE: usize = KERNELSTACKSIZE - (mem::sizeof::<*mut u64>() * 2);
pub struct Vmxon { pub revisionid: u32, pub data: [u8; PAGESIZE - 4], }
pub struct HostStackLayout { pub stackcontents: [u8; STACKCONTENTSSIZE], pub padding1: u64, pub reserved_1: u64, }
pub struct Vmx {
pub vmxonregion: Box
impl Vmx {
pub fn new() -> Result
Ok(Self {
vmxon_region: vmxon_region,
host_rsp: host_rsp,
})
}
} ```