good_os_framework/memory/
kernel_heap.rs

1use alloc::alloc::Layout;
2use good_memory_allocator::SpinLockedAllocator;
3use x86_64::structures::paging::PageTableFlags;
4use x86_64::VirtAddr;
5
6use super::KERNEL_PAGE_TABLE;
7use crate::memory::MemoryManager;
8
9pub const HEAP_START: usize = 0x114514000000;
10pub const HEAP_SIZE: usize = 64 * 1024 * 1024;
11
12#[global_allocator]
13static ALLOCATOR: SpinLockedAllocator = SpinLockedAllocator::empty();
14
15#[alloc_error_handler]
16fn alloc_error_handler(layout: Layout) -> ! {
17    panic!("Kernel heap allocation error: {:?}", layout)
18}
19
20pub fn init() {
21    let heap_start = VirtAddr::new(HEAP_START as u64);
22
23    let flags = PageTableFlags::PRESENT | PageTableFlags::WRITABLE;
24    let mut page_table = KERNEL_PAGE_TABLE.lock();
25    <MemoryManager>::alloc_range(heap_start, HEAP_SIZE as u64, flags, &mut page_table).unwrap();
26
27    unsafe {
28        ALLOCATOR.init(HEAP_START, HEAP_SIZE);
29    }
30}