Created
September 4, 2020 18:02
-
-
Save bobmcwhirter/33b305c5fca54958e98e45e867a92fa3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static mut ALLOCATOR: Option<CortexMHeap> = Option::None; | |
pub fn setup_platform(start: usize, size: usize) { | |
let mut heap = CortexMHeap::empty(); | |
unsafe { | |
heap.init(start, size); | |
ALLOCATOR.replace(heap); | |
} | |
unsafe { platform_set_calloc_free(Some(platform_calloc_f), Some(platform_free_f)) }; | |
} | |
extern "C" fn platform_calloc_f(count: usize, size: usize) -> *mut c_void { | |
unsafe { | |
if let Some(ref alloc) = ALLOCATOR { | |
let requested_size = count * size; | |
let header_size = 2 * 4; | |
let total_size = header_size + requested_size; | |
let layout = Layout::from_size_align(total_size, 4).unwrap().pad_to_align(); | |
log::info!("calloc {} ({}+({}*{})) from free: {} used: {} -- {}", | |
total_size, | |
header_size, | |
count, | |
size, | |
alloc.free(), | |
alloc.used(), | |
layout.size()); | |
let mut ptr = alloc.alloc(layout) as *mut usize; | |
*ptr = layout.size(); | |
ptr = ptr.offset(1); | |
*ptr = layout.align(); | |
ptr = ptr.offset(1); | |
ptr as *mut c_void | |
//0 as *mut c_void | |
} else { | |
0 as *mut c_void | |
} | |
} | |
} | |
extern "C" fn platform_free_f(ptr: *mut c_void) { | |
unsafe { | |
if let Some(ref alloc) = ALLOCATOR { | |
let mut ptr = ptr as *mut usize; | |
ptr = ptr.offset(-1); | |
let align = *ptr; | |
ptr = ptr.offset( -1 ); | |
let size = *ptr; | |
alloc.dealloc( ptr as *mut u8, Layout::from_size_align(size, align).unwrap()); | |
} | |
} | |
log::info!("free {}", ptr as u32); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment