uefi_async/
global_allocator.rs

1use core::alloc::{GlobalAlloc, Layout};
2use talc::{ClaimOnOom, Span, Talc, Talck};
3use uefi::boot::{allocate_pages, AllocateType, MemoryType};
4
5pub struct UefiTalc(Talck<spin::Mutex<()>, ClaimOnOom>);
6
7#[global_allocator]
8pub static ALLOCATOR: UefiTalc = unsafe {
9    UefiTalc(Talc::new(ClaimOnOom::new(Span::empty())).lock::<spin::Mutex<()>>())
10};
11
12unsafe impl GlobalAlloc for UefiTalc {
13    unsafe fn alloc(&self, layout: Layout) -> *mut u8 { unsafe { self.0.alloc(layout) } }
14
15    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { unsafe { self.0.dealloc(ptr, layout) } }
16}
17
18impl UefiTalc {
19    pub unsafe fn init(&self, start: *mut u8, size: usize) {
20        let span = Span::from_base_size(start, size);
21
22        let mut talc = self.0.lock();
23        let _ = unsafe { talc.claim(span) };
24    }
25}
26
27pub fn alloc_init_wrapper() {
28    let pages = 131072; // 512MB
29    let pool_ptr = allocate_pages(AllocateType::AnyPages, MemoryType::LOADER_DATA, pages)
30        .expect("Failed to allocate heap pages");
31
32    unsafe {
33        // 初始化全局分配器
34        ALLOCATOR.init(pool_ptr.as_ptr(), pages * 4096);
35    }
36}