From 06fc63028ab3b4e111303b957356e937f625d437 Mon Sep 17 00:00:00 2001 From: Philipp Oppermann Date: Wed, 26 Jun 2019 13:14:56 +0200 Subject: [PATCH] Create a heap memory area --- src/allocator.rs | 34 +++++++++++++++++++++++++++++++++- src/main.rs | 5 ++++- 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/src/allocator.rs b/src/allocator.rs index ac452c10..cf85bd6d 100644 --- a/src/allocator.rs +++ b/src/allocator.rs @@ -1,5 +1,37 @@ use alloc::alloc::{GlobalAlloc, Layout}; use core::ptr::null_mut; +use x86_64::{ + structures::paging::{ + mapper::MapToError, FrameAllocator, Mapper, Page, PageTableFlags, Size4KiB, + }, + VirtAddr, +}; + +pub const HEAP_START: usize = 0x_4444_4444_0000; +pub const HEAP_SIZE: usize = 100 * 1024; // 100 KiB + +pub fn init_heap( + mapper: &mut impl Mapper, + frame_allocator: &mut impl FrameAllocator, +) -> Result<(), MapToError> { + let page_range = { + let heap_start = VirtAddr::new(HEAP_START as u64); + let heap_end = heap_start + HEAP_SIZE - 1u64; + let heap_start_page = Page::containing_address(heap_start); + let heap_end_page = Page::containing_address(heap_end); + Page::range_inclusive(heap_start_page, heap_end_page) + }; + + for page in page_range { + let frame = frame_allocator + .allocate_frame() + .ok_or(MapToError::FrameAllocationFailed)?; + let flags = PageTableFlags::PRESENT | PageTableFlags::WRITABLE; + unsafe { mapper.map_to(page, frame, flags, frame_allocator)?.flush() }; + } + + Ok(()) +} pub struct Dummy; @@ -11,4 +43,4 @@ unsafe impl GlobalAlloc for Dummy { unsafe fn dealloc(&self, _ptr: *mut u8, _layout: Layout) { panic!("dealloc should be never called") } -} \ No newline at end of file +} diff --git a/src/main.rs b/src/main.rs index 0d3e0df6..69e73633 100644 --- a/src/main.rs +++ b/src/main.rs @@ -14,8 +14,8 @@ use alloc::boxed::Box; entry_point!(kernel_main); fn kernel_main(boot_info: &'static BootInfo) -> ! { + use blog_os::allocator; use blog_os::memory::{self, BootInfoFrameAllocator}; - use x86_64::{structures::paging::Page, VirtAddr}; println!("Hello World{}", "!"); blog_os::init(); @@ -23,6 +23,9 @@ fn kernel_main(boot_info: &'static BootInfo) -> ! { let mut mapper = unsafe { memory::init(boot_info.physical_memory_offset) }; let mut frame_allocator = unsafe { BootInfoFrameAllocator::init(&boot_info.memory_map) }; + allocator::init_heap(&mut mapper, &mut frame_allocator) + .expect("heap initialization failed"); + let x = Box::new(41); #[cfg(test)]