Skip to main content

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/// heap space ([u8; KERNEL_HEAP_SIZE])
9static mut HEAP_SPACE: [u8; KERNEL_HEAP_SIZE] = [0; KERNEL_HEAP_SIZE];
10
11pub fn init_heap() {
12    unsafe {
13        HEAP_ALLOCATOR
14            .lock()
15            .init(addr_of_mut!(HEAP_SPACE) as usize, KERNEL_HEAP_SIZE);
16    }
17}
18
19#[allow(unused)]
20pub fn heap_test() {
21    use alloc::boxed::Box;
22    use alloc::vec::Vec;
23    unsafe extern "C" {
24        safe fn sbss();
25        safe fn ebss();
26    }
27    let bss_range = linker_symbol_addr!(sbss)..linker_symbol_addr!(ebss);
28    let a = Box::new(5);
29    assert_eq!(*a, 5);
30    assert!(bss_range.contains(&(a.as_ref() as *const _ as usize)));
31    drop(a);
32    let mut v: Vec<usize> = Vec::new();
33    for i in 0..500 {
34        v.push(i);
35    }
36    for (i, val) in v.iter().take(500).enumerate() {
37        assert_eq!(*val, i);
38    }
39    assert!(bss_range.contains(&(v.as_ptr() as usize)));
40    drop(v);
41    println!("heap_test passed!");
42}