lib.rs 1.32 KB
Newer Older
Jeremy Soller's avatar
Jeremy Soller committed
1
#![feature(allocator_api)]
Jeremy Soller's avatar
Jeremy Soller committed
2
#![feature(const_fn)]
Jeremy Soller's avatar
Jeremy Soller committed
3
#![feature(try_trait)]
Jeremy Soller's avatar
Jeremy Soller committed
4
5
6
7
#![no_std]

extern crate uefi;

Jeremy Soller's avatar
Jeremy Soller committed
8
use core::alloc::{GlobalAlloc, Layout};
Jeremy Soller's avatar
Jeremy Soller committed
9
use core::ops::Try;
Jeremy Soller's avatar
Jeremy Soller committed
10
use core::ptr;
Jeremy Soller's avatar
Jeremy Soller committed
11
use uefi::memory::MemoryType;
Jeremy Soller's avatar
Jeremy Soller committed
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
use uefi::system::SystemTable;

static mut UEFI: *mut SystemTable = 0 as *mut SystemTable;

pub unsafe fn init(table: &'static mut SystemTable) {
    UEFI = table;
}

fn get_uefi() -> Option<&'static mut SystemTable> {
    unsafe {
        if UEFI as usize == 0 {
            None
        } else {
            Some(&mut *UEFI)
        }
    }
}

Jeremy Soller's avatar
Jeremy Soller committed
30
31
pub struct Allocator;

32
unsafe impl GlobalAlloc for Allocator {
Jeremy Soller's avatar
Jeremy Soller committed
33
    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
Jeremy Soller's avatar
Jeremy Soller committed
34
35
36
        if let Some(ref mut uefi) = get_uefi() {
            let mut ptr = 0;
            if let Err(_) = (uefi.BootServices.AllocatePool)(MemoryType::EfiLoaderData, layout.size(), &mut ptr).into_result() {
Jeremy Soller's avatar
Jeremy Soller committed
37
                ptr::null_mut()
Jeremy Soller's avatar
Jeremy Soller committed
38
            } else {
Jeremy Soller's avatar
Jeremy Soller committed
39
                ptr as *mut u8
Jeremy Soller's avatar
Jeremy Soller committed
40
41
42
            }
        } else {
            panic!("__rust_allocate: uefi not initialized");
Jeremy Soller's avatar
Jeremy Soller committed
43
44
45
        }
    }

Jeremy Soller's avatar
Jeremy Soller committed
46
    unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) {
Jeremy Soller's avatar
Jeremy Soller committed
47
48
49
50
51
        if let Some(ref mut uefi) = get_uefi() {
            let _ = (uefi.BootServices.FreePool)(ptr as usize);
        } else {
            panic!("__rust_deallocate: uefi not initialized");
        }
Jeremy Soller's avatar
Jeremy Soller committed
52
53
    }
}