|
| 1 | +use alloc::alloc::{alloc, alloc_zeroed, dealloc, realloc}; |
| 2 | +use core::alloc::Layout; |
| 3 | +use core::mem::MaybeUninit; |
| 4 | + |
| 5 | +use spinning_top::RawSpinlock; |
| 6 | +use talc::TalcLock; |
| 7 | +use talc::source::Claim; |
| 8 | + |
| 9 | +#[global_allocator] |
| 10 | +static TALC: TalcLock<RawSpinlock, Claim> = TalcLock::new(unsafe { |
| 11 | + #[repr(C, align(0x1000))] |
| 12 | + struct Heap([MaybeUninit<u8>; 0x1_0000]); |
| 13 | + |
| 14 | + static mut HEAP: Heap = Heap([MaybeUninit::uninit(); _]); |
| 15 | + |
| 16 | + let base = (&raw mut HEAP).cast::<u8>(); |
| 17 | + let size = size_of::<Heap>(); |
| 18 | + Claim::new(base, size) |
| 19 | +}); |
| 20 | + |
| 21 | +#[unsafe(no_mangle)] |
| 22 | +unsafe extern "C" fn sys_alloc(size: usize, align: usize) -> *mut u8 { |
| 23 | + unsafe { alloc(layout_from_size_align(size, align)) } |
| 24 | +} |
| 25 | + |
| 26 | +#[unsafe(no_mangle)] |
| 27 | +unsafe extern "C" fn sys_dealloc(ptr: *mut u8, size: usize, align: usize) { |
| 28 | + unsafe { dealloc(ptr, layout_from_size_align(size, align)) } |
| 29 | +} |
| 30 | + |
| 31 | +#[unsafe(no_mangle)] |
| 32 | +unsafe extern "C" fn sys_alloc_zeroed(size: usize, align: usize) -> *mut u8 { |
| 33 | + unsafe { alloc_zeroed(layout_from_size_align(size, align)) } |
| 34 | +} |
| 35 | + |
| 36 | +#[unsafe(no_mangle)] |
| 37 | +unsafe extern "C" fn sys_realloc( |
| 38 | + ptr: *mut u8, |
| 39 | + size: usize, |
| 40 | + align: usize, |
| 41 | + new_size: usize, |
| 42 | +) -> *mut u8 { |
| 43 | + unsafe { realloc(ptr, layout_from_size_align(size, align), new_size) } |
| 44 | +} |
| 45 | + |
| 46 | +/// Deprecated |
| 47 | +#[unsafe(no_mangle)] |
| 48 | +unsafe extern "C" fn sys_malloc(size: usize, align: usize) -> *mut u8 { |
| 49 | + unsafe { sys_alloc(size, align) } |
| 50 | +} |
| 51 | + |
| 52 | +/// Deprecated |
| 53 | +#[unsafe(no_mangle)] |
| 54 | +unsafe extern "C" fn sys_free(ptr: *mut u8, size: usize, align: usize) { |
| 55 | + unsafe { sys_dealloc(ptr, size, align) } |
| 56 | +} |
| 57 | + |
| 58 | +unsafe fn layout_from_size_align(size: usize, align: usize) -> Layout { |
| 59 | + if cfg!(debug_assertions) { |
| 60 | + Layout::from_size_align(size, align).unwrap() |
| 61 | + } else { |
| 62 | + unsafe { Layout::from_size_align_unchecked(size, align) } |
| 63 | + } |
| 64 | +} |
0 commit comments