1#![no_std]
2
3use core::alloc::{GlobalAlloc, Layout};
4use core::ptr::{self, NonNull};
5use uefi::prelude::*;
6use uefi::memory::MemoryType;
7
8#[global_allocator]
9static ALLOCATOR: Allocator = Allocator;
10
11static mut UEFI: Option<NonNull<SystemTable>> = None;
12
13pub unsafe fn init(table: &'static mut SystemTable) {
14 UEFI = NonNull::new(table);
15}
16
17pub struct Allocator;
18
19unsafe impl GlobalAlloc for Allocator {
20 unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
21 let uefi = UEFI.expect("__rust_allocate: uefi not initialized");
22 let mut ptr = 0;
23 let res = (uefi.as_ref().BootServices.AllocatePool)(
24 MemoryType::EfiLoaderData,
25 layout.size(),
26 &mut ptr,
27 );
28
29 match res {
30 Status::SUCCESS => ptr as *mut u8,
31 _ => ptr::null_mut(),
32 }
33 }
34
35 unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) {
36 let uefi = UEFI.expect("__rust_deallocate: uefi not initialized");
37 let _ = (uefi.as_ref().BootServices.FreePool)(ptr as usize);
38 }
39}