Skip to main content

os/mm/
heap_allocator.rs

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