From 640872d1543592502af627bc75d7a592f5cf652e Mon Sep 17 00:00:00 2001 From: WangRunji Date: Mon, 6 Aug 2018 19:04:18 +0800 Subject: [PATCH] Use alloc API to fix stack overflow in release mode. --- kernel/src/fs.rs | 8 +++++++- kernel/src/memory.rs | 9 ++------- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/kernel/src/fs.rs b/kernel/src/fs.rs index c573623..8262467 100644 --- a/kernel/src/fs.rs +++ b/kernel/src/fs.rs @@ -30,7 +30,12 @@ pub fn shell() { let files = root.borrow().list().unwrap(); println!("Available programs: {:?}", files); - let mut buf = Box::new([0; 64 << 12]); + // Avoid stack overflow in release mode + // Equal to: `buf = Box::new([0; 64 << 12])` + use alloc::alloc::{alloc, dealloc, Layout}; + const BUF_SIZE: usize = 0x40000; + let layout = Layout::from_size_align(BUF_SIZE, 0x1000).unwrap(); + let buf = unsafe{ slice::from_raw_parts_mut(alloc(layout), BUF_SIZE) }; loop { print!(">> "); use console::get_line; @@ -47,6 +52,7 @@ pub fn shell() { println!("Program not exist"); } } + unsafe { dealloc(buf.as_mut_ptr(), layout) }; } struct MemBuf(&'static [u8]); diff --git a/kernel/src/memory.rs b/kernel/src/memory.rs index cd4d17c..0da3fb3 100644 --- a/kernel/src/memory.rs +++ b/kernel/src/memory.rs @@ -26,14 +26,9 @@ pub fn dealloc_frame(target: usize) { // alloc from heap pub fn alloc_stack() -> Stack { - use alloc::boxed::Box; + use alloc::alloc::{alloc, Layout}; const STACK_SIZE: usize = 0x8000; - // FIXME: This alignment will cause rsp align with 0x8000 in x86_64 release mode. - // Because kernel stack is not large enough, it will trigger double fault. - #[repr(align(0x8000))] - struct StackData([u8; STACK_SIZE]); - let data = Box::new(StackData([0; STACK_SIZE])); - let bottom = Box::into_raw(data) as usize; + let bottom = unsafe{ alloc(Layout::from_size_align(STACK_SIZE, 0x8000).unwrap()) } as usize; let top = bottom + STACK_SIZE; Stack { top, bottom } }