os/mm/
heap_allocator.rs

1use crate::config::KERNEL_HEAP_SIZE;
2use buddy_system_allocator::LockedHeap;
3use core::ptr::addr_of_mut;
4
5#[global_allocator]
6static HEAP_ALLOCATOR: LockedHeap = LockedHeap::empty();
7
8#[alloc_error_handler]
9pub fn handle_alloc_error(layout: core::alloc::Layout) -> ! {
10    panic!("Heap allocation error, layout = {:?}", layout);
11}
12
13static mut HEAP_SPACE: [u8; KERNEL_HEAP_SIZE] = [0; KERNEL_HEAP_SIZE];
14
15pub fn init_heap() {
16    unsafe {
17        HEAP_ALLOCATOR
18            .lock()
19            .init(addr_of_mut!(HEAP_SPACE) as usize, KERNEL_HEAP_SIZE);
20    }
21}
22
23#[allow(unused)]
24pub fn heap_test() {
25    use alloc::boxed::Box;
26    use alloc::vec::Vec;
27    unsafe extern "C" {
28        safe fn sbss();
29        safe fn ebss();
30    }
31    let bss_range = sbss as usize..ebss as usize;
32    let a = Box::new(5);
33    assert_eq!(*a, 5);
34    assert!(bss_range.contains(&(a.as_ref() as *const _ as usize)));
35    drop(a);
36    let mut v: Vec<usize> = Vec::new();
37    for i in 0..500 {
38        v.push(i);
39    }
40    for (i, val) in v.iter().take(500).enumerate() {
41        assert_eq!(*val, i);
42    }
43    assert!(bss_range.contains(&(v.as_ptr() as usize)));
44    drop(v);
45    println!("heap_test passed!");
46}