Compare commits

...

15 Commits

Author SHA1 Message Date
Philipp Oppermann
93aff8cfa8 Test our exception handler by invoking a breakpoint exception 2017-11-19 14:22:24 +01:00
Philipp Oppermann
fab320271a Create and load an IDT 2017-11-19 14:21:51 +01:00
Philipp Oppermann
7becaf5f30 Add a dependency on lazy_static 2017-11-19 14:21:51 +01:00
Philipp Oppermann
3bbc2a0bdc Add a simple handler function for the breakpoint exception 2017-11-19 14:21:36 +01:00
Philipp Oppermann
c2d22af1c7 Create a new interrupts module 2017-11-19 14:21:12 +01:00
Philipp Oppermann
0ddd214a1b Update Readme for “Handling Exceptions” post 2017-11-19 14:21:00 +01:00
Philipp Oppermann
ad211de615 Use linked list allocator instead of bump allocator 2017-11-19 14:20:46 +01:00
Philipp Oppermann
01f8c43ffb Map the heap pages to physical frames 2017-11-19 14:20:46 +01:00
Philipp Oppermann
f2bbe43099 Use once crate to ensure that memory::init is only called once 2017-11-19 14:20:45 +01:00
Philipp Oppermann
76550dcd95 Refactor: Move memory initialization to memory::init function 2017-11-19 14:20:45 +01:00
Philipp Oppermann
c0d403abbe Set a global allocator 2017-11-19 14:20:45 +01:00
Philipp Oppermann
9dc998222a Make the bump allocator lock free and impl Alloc for shared reference 2017-11-19 14:20:45 +01:00
Philipp Oppermann
1f6633fe44 Add a heap_allocator module with a basic bump allocator 2017-11-19 14:20:45 +01:00
Philipp Oppermann
5f017124dd Add a dependency on the alloc crate 2017-11-19 14:20:45 +01:00
Philipp Oppermann
36369cfbe2 Update Readme for “Kernel Heap” post 2017-11-19 14:20:45 +01:00
8 changed files with 211 additions and 33 deletions

View File

@@ -13,3 +13,9 @@ spin = "0.4.5"
multiboot2 = "0.1.0"
bitflags = "0.7.0"
x86_64 = "0.1.2"
once = "0.3.3"
linked_list_allocator = "0.4.2"
[dependencies.lazy_static]
version = "0.2.4"
features = ["spin_no_std"]

View File

@@ -1,7 +1,7 @@
# Blog OS (Remap the Kernel)
[![Build Status](https://travis-ci.org/phil-opp/blog_os.svg?branch=post_7)](https://travis-ci.org/phil-opp/blog_os/branches)
# Blog OS (Handling Exceptions)
[![Build Status](https://travis-ci.org/phil-opp/blog_os.svg?branch=post_9)](https://travis-ci.org/phil-opp/blog_os/branches)
This repository contains the source code for the [Remap the Kernel](http://os.phil-opp.com/remap-the-kernel.html) post of the [Writing an OS in Rust](http://os.phil-opp.com) series.
This repository contains the source code for the [Handling Exceptions](http://os.phil-opp.com/handling-exceptions.html) post of the [Writing an OS in Rust](http://os.phil-opp.com) series.
**Check out the [master branch](https://github.com/phil-opp/blog_os) for more information.**

2
Xargo.toml Normal file
View File

@@ -0,0 +1,2 @@
[target.x86_64-blog_os.dependencies]
alloc = {}

19
src/interrupts.rs Normal file
View File

@@ -0,0 +1,19 @@
use x86_64::structures::idt::{Idt, ExceptionStackFrame};
lazy_static! {
static ref IDT: Idt = {
let mut idt = Idt::new();
idt.breakpoint.set_handler_fn(breakpoint_handler);
idt
};
}
pub fn init() {
IDT.load();
}
extern "x86-interrupt" fn breakpoint_handler(
stack_frame: &mut ExceptionStackFrame)
{
println!("EXCEPTION: BREAKPOINT\n{:#?}", stack_frame);
}

View File

@@ -1,9 +1,17 @@
#![feature(lang_items)]
#![feature(const_fn)]
#![feature(const_unique_new)]
#![feature(alloc)]
#![feature(const_unique_new, const_atomic_usize_new)]
#![feature(unique)]
#![feature(allocator_api)]
#![feature(global_allocator)]
#![feature(abi_x86_interrupt)]
#![no_std]
#[macro_use]
extern crate alloc;
extern crate rlibc;
extern crate volatile;
extern crate spin;
@@ -11,45 +19,46 @@ extern crate multiboot2;
#[macro_use]
extern crate bitflags;
extern crate x86_64;
#[macro_use]
extern crate once;
extern crate linked_list_allocator;
#[macro_use]
extern crate lazy_static;
#[macro_use]
mod vga_buffer;
mod memory;
mod interrupts;
#[no_mangle]
pub extern fn rust_main(multiboot_information_address: usize) {
use memory::FrameAllocator;
pub extern "C" fn rust_main(multiboot_information_address: usize) {
// ATTENTION: we have a very small stack and no guard page
vga_buffer::clear_screen();
println!("Hello World{}", "!");
let boot_info = unsafe{ multiboot2::load(multiboot_information_address) };
let memory_map_tag = boot_info.memory_map_tag()
.expect("Memory map tag required");
let elf_sections_tag = boot_info.elf_sections_tag()
.expect("Elf sections tag required");
let kernel_start = elf_sections_tag.sections().map(|s| s.addr)
.min().unwrap();
let kernel_end = elf_sections_tag.sections().map(|s| s.addr + s.size)
.max().unwrap();
let multiboot_start = multiboot_information_address;
let multiboot_end = multiboot_start + (boot_info.total_size as usize);
println!("kernel start: 0x{:x}, kernel end: 0x{:x}",
kernel_start, kernel_end);
println!("multiboot start: 0x{:x}, multiboot end: 0x{:x}",
multiboot_start, multiboot_end);
let mut frame_allocator = memory::AreaFrameAllocator::new(
kernel_start as usize, kernel_end as usize, multiboot_start,
multiboot_end, memory_map_tag.memory_areas());
let boot_info = unsafe {
multiboot2::load(multiboot_information_address)
};
enable_nxe_bit();
enable_write_protect_bit();
memory::remap_the_kernel(&mut frame_allocator, boot_info);
println!("It did not crash!");
// set up guard page and map the heap pages
memory::init(boot_info);
unsafe {
HEAP_ALLOCATOR.lock().init(HEAP_START, HEAP_START + HEAP_SIZE);
}
// initialize our IDT
interrupts::init();
for i in 0..10000 {
format!("Some String");
}
// invoke a breakpoint exception
x86_64::instructions::interrupts::int3();
println!("It did not crash!");
loop {}
}
@@ -78,3 +87,11 @@ pub extern fn panic_fmt(fmt: core::fmt::Arguments, file: &'static str, line: u32
println!(" {}", fmt);
loop{}
}
use linked_list_allocator::LockedHeap;
pub const HEAP_START: usize = 0o_000_001_000_000_0000;
pub const HEAP_SIZE: usize = 100 * 1024; // 100 KiB
#[global_allocator]
static HEAP_ALLOCATOR: LockedHeap = LockedHeap::empty();

View File

@@ -0,0 +1,62 @@
use alloc::heap::{Alloc, AllocErr, Layout};
use core::sync::atomic::{AtomicUsize, Ordering};
/// A simple allocator that allocates memory linearly and ignores freed memory.
#[derive(Debug)]
pub struct BumpAllocator {
heap_start: usize,
heap_end: usize,
next: AtomicUsize,
}
impl BumpAllocator {
pub const fn new(heap_start: usize, heap_end: usize) -> Self {
Self { heap_start, heap_end, next: AtomicUsize::new(heap_start) }
}
}
unsafe impl<'a> Alloc for &'a BumpAllocator {
unsafe fn alloc(&mut self, layout: Layout) -> Result<*mut u8, AllocErr> {
loop {
// load current state of the `next` field
let current_next = self.next.load(Ordering::Relaxed);
let alloc_start = align_up(current_next, layout.align());
let alloc_end = alloc_start.saturating_add(layout.size());
if alloc_end <= self.heap_end {
// update the `next` pointer if it still has the value `current_next`
let next_now = self.next.compare_and_swap(current_next, alloc_end,
Ordering::Relaxed);
if next_now == current_next {
// next address was successfully updated, allocation succeeded
return Ok(alloc_start as *mut u8);
}
} else {
return Err(AllocErr::Exhausted{ request: layout })
}
}
}
unsafe fn dealloc(&mut self, ptr: *mut u8, layout: Layout) {
// do nothing, leak memory
}
}
/// Align downwards. Returns the greatest x with alignment `align`
/// so that x <= addr. The alignment must be a power of 2.
pub fn align_down(addr: usize, align: usize) -> usize {
if align.is_power_of_two() {
addr & !(align - 1)
} else if align == 0 {
addr
} else {
panic!("`align` must be a power of 2");
}
}
/// Align upwards. Returns the smallest x with alignment `align`
/// so that x >= addr. The alignment must be a power of 2.
pub fn align_up(addr: usize, align: usize) -> usize {
align_down(addr + align - 1, align)
}

View File

@@ -1,12 +1,55 @@
pub use self::area_frame_allocator::AreaFrameAllocator;
pub use self::paging::remap_the_kernel;
use self::paging::PhysicalAddress;
use multiboot2::BootInformation;
mod area_frame_allocator;
pub mod heap_allocator;
mod paging;
pub const PAGE_SIZE: usize = 4096;
pub fn init(boot_info: &BootInformation) {
assert_has_not_been_called!("memory::init must be called only once");
let memory_map_tag = boot_info.memory_map_tag().expect(
"Memory map tag required");
let elf_sections_tag = boot_info.elf_sections_tag().expect(
"Elf sections tag required");
let kernel_start = elf_sections_tag.sections()
.filter(|s| s.is_allocated()).map(|s| s.addr).min().unwrap();
let kernel_end = elf_sections_tag.sections()
.filter(|s| s.is_allocated()).map(|s| s.addr + s.size).max()
.unwrap();
println!("kernel start: {:#x}, kernel end: {:#x}",
kernel_start,
kernel_end);
println!("multiboot start: {:#x}, multiboot end: {:#x}",
boot_info.start_address(),
boot_info.end_address());
let mut frame_allocator = AreaFrameAllocator::new(
kernel_start as usize, kernel_end as usize,
boot_info.start_address(), boot_info.end_address(),
memory_map_tag.memory_areas());
let mut active_table = paging::remap_the_kernel(&mut frame_allocator,
boot_info);
use self::paging::Page;
use {HEAP_START, HEAP_SIZE};
let heap_start_page = Page::containing_address(HEAP_START);
let heap_end_page = Page::containing_address(HEAP_START + HEAP_SIZE-1);
for page in Page::range_inclusive(heap_start_page, heap_end_page) {
active_table.map(page, paging::WRITABLE, &mut frame_allocator);
}
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct Frame {
number: usize,

View File

@@ -17,7 +17,7 @@ const ENTRY_COUNT: usize = 512;
pub type PhysicalAddress = usize;
pub type VirtualAddress = usize;
#[derive(Debug, Clone, Copy)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Page {
number: usize,
}
@@ -46,6 +46,32 @@ impl Page {
fn p1_index(&self) -> usize {
(self.number >> 0) & 0o777
}
pub fn range_inclusive(start: Page, end: Page) -> PageIter {
PageIter {
start: start,
end: end,
}
}
}
pub struct PageIter {
start: Page,
end: Page,
}
impl Iterator for PageIter {
type Item = Page;
fn next(&mut self) -> Option<Page> {
if self.start <= self.end {
let page = self.start;
self.start.number += 1;
Some(page)
} else {
None
}
}
}
pub struct ActivePageTable {
@@ -145,6 +171,7 @@ impl InactivePageTable {
}
pub fn remap_the_kernel<A>(allocator: &mut A, boot_info: &BootInformation)
-> ActivePageTable
where A: FrameAllocator
{
let mut temporary_page = TemporaryPage::new(Page { number: 0xcafebabe },
@@ -203,4 +230,6 @@ pub fn remap_the_kernel<A>(allocator: &mut A, boot_info: &BootInformation)
);
active_table.unmap(old_p4_page, allocator);
println!("guard page at {:#x}", old_p4_page.start_address());
active_table
}