1 use crate::ALLOCATOR; 2 use core::{ 3 alloc::{GlobalAlloc, Layout}, 4 sync::atomic::{AtomicUsize, Ordering}, 5 }; 6 7 use super::types::*; 8 9 extern "C" { 10 fn create_mspace(capacity: size_t, locked: c_int) -> usize; 11 fn mspace_malloc(msp: usize, bytes: size_t) -> *mut c_void; 12 fn mspace_memalign(msp: usize, alignment: size_t, bytes: size_t) -> *mut c_void; 13 fn mspace_realloc(msp: usize, oldmem: *mut c_void, bytes: size_t) -> *mut c_void; 14 fn mspace_free(msp: usize, mem: *mut c_void); 15 //fn dlmalloc(bytes: size_t) -> *mut c_void; 16 //fn dlmemalign(alignment: size_t, bytes: size_t) -> *mut c_void; 17 //fn dlrealloc(oldmem: *mut c_void, bytes: size_t) -> *mut c_void; 18 //fn dlfree(mem: *mut c_void); 19 } 20 21 pub struct Allocator { 22 mstate: AtomicUsize, 23 } 24 25 pub const NEWALLOCATOR: Allocator = Allocator { 26 mstate: AtomicUsize::new(0), 27 }; 28 29 impl Allocator { 30 pub fn set_book_keeper(&self, mstate: usize) { 31 self.mstate.store(mstate, Ordering::Relaxed); 32 } 33 pub fn get_book_keeper(&self) -> usize { 34 self.mstate.load(Ordering::Relaxed) 35 } 36 } 37 unsafe impl<'a> GlobalAlloc for Allocator { 38 unsafe fn alloc(&self, layout: Layout) -> *mut u8 { 39 alloc_align(layout.size(), layout.align()) as *mut u8 40 } 41 42 unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) { 43 free(ptr as *mut c_void) 44 } 45 } 46 47 pub unsafe fn alloc(size: usize) -> *mut c_void { 48 mspace_malloc(ALLOCATOR.get_book_keeper(), size) 49 } 50 51 pub unsafe fn alloc_align(size: usize, alignment: usize) -> *mut c_void { 52 mspace_memalign(ALLOCATOR.get_book_keeper(), alignment, size) 53 } 54 55 pub unsafe fn realloc(ptr: *mut c_void, size: size_t) -> *mut c_void { 56 mspace_realloc(ALLOCATOR.get_book_keeper(), ptr, size) 57 } 58 59 pub unsafe fn free(ptr: *mut c_void) { 60 mspace_free(ALLOCATOR.get_book_keeper(), ptr) 61 } 62 63 pub fn new_mspace() -> usize { 64 unsafe { create_mspace(0, 0) } 65 } 66