ros666/mm/
heap_allocator.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
//! 堆内存分配器
use slab_allocator::LockedHeap;

use crate::{extern_global, printkln, trace};

/// 内核堆大小
#[cfg(debug_assertions)]
pub const KERNEL_HEAP_SIZE: usize = 0x90_0000;
#[cfg(not(debug_assertions))]
pub const KERNEL_HEAP_SIZE: usize = 0x40_0000;

/// 全局分配器
#[global_allocator]
static HEAP_ALLOCATOR: LockedHeap = LockedHeap::empty();

// NOTE: 如果不使用 `static mut`,`HEAP` 会被放到 `.rodata` 段
// 使用 `static mut` 可以将 `HEAP` 放到 `.bss` 段
// .bss: uninitialized global variables
// .rodata: const global variables
static mut HEAP: [u8; KERNEL_HEAP_SIZE] = [0; KERNEL_HEAP_SIZE];

#[allow(static_mut_refs)]
/// 初始化内核堆内存分配器
pub fn init_heap() {
    unsafe {
        trace!(
            "HEAP BASE: {:#x}, SIZE: {:#x}",
            HEAP.as_ptr() as usize,
            KERNEL_HEAP_SIZE
        );
        HEAP_ALLOCATOR
            .lock()
            .init(HEAP.as_ptr() as usize, KERNEL_HEAP_SIZE);
    }
}

/// Rust 语言项 - 分配错误处理函数
///
/// 当分配失败,例如 Out Of Memory 时会调用该函数
#[alloc_error_handler]
fn alloc_error_handler(layout: core::alloc::Layout) -> ! {
    panic!("Heap allocation error: {:?}", layout)
}

#[allow(unused)]
/// 堆内存分配测试函数
pub fn heap_test() {
    use alloc::boxed::Box;
    use alloc::vec::Vec;

    // 获取 .bss 段的范围
    let bss_range = extern_global!(__bss_start) as usize..extern_global!(__bss_end) as usize;

    // 测试 Box 分配
    let a = Box::new(5);
    assert_eq!(*a, 5);
    assert!(bss_range.contains(&(a.as_ref() as *const _ as usize)));
    drop(a);

    // 测试 Vec 分配
    let mut v: Vec<usize> = Vec::new();
    for i in 0..500 {
        v.push(i);
    }
    for i in 0..500 {
        assert_eq!(v[i], i);
    }
    assert!(bss_range.contains(&(v.as_ptr() as usize)));
    drop(v);

    // 打印测试通过信息
    printkln!("heap_test passed!");
}