From 10614e04929a6d109a5e90524e446b637aaf0c13 Mon Sep 17 00:00:00 2001 From: Richard Qin Date: Sat, 3 Jan 2026 02:13:08 +0800 Subject: Fix: critical malloc size calculation bug Summary: - Fixed an integer arithmetic error in malloc() where 'nunits' was initialized to 0, causing incorrect heap sizing. - This bug caused malloc to return pointers pointing to unmapped memory pages, leading to Store Page Fault (scause 15) at process boundaries. - Switched memory allocator logic to use byte-based size calculation instead of K&R style units to prevent off-by-one errors. Improvements: - Shell now starts successfully without segfaults. --- src/kernel/proc/exec.cc | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) (limited to 'src/kernel/proc/exec.cc') diff --git a/src/kernel/proc/exec.cc b/src/kernel/proc/exec.cc index d0e75ef..22e4842 100644 --- a/src/kernel/proc/exec.cc +++ b/src/kernel/proc/exec.cc @@ -129,15 +129,19 @@ namespace Exec // Prepare user stack uint64 sz = PGROUNDUP(vm_guard.sz); - uint64 sz1 = VM::uvmalloc(vm_guard.pagetable, sz, sz + 2 * PGSIZE, PTE_W | PTE_R | PTE_U); + + const int stack_data_pages = 16; + const int stack_total_pages = stack_data_pages + 1; + + uint64 sz1 = VM::uvmalloc(vm_guard.pagetable, sz, sz + stack_total_pages * PGSIZE, PTE_W | PTE_R | PTE_U); if (sz1 == 0) return -1; vm_guard.sz = sz1; - VM::uvmunmap(vm_guard.pagetable, sz1 - 2 * PGSIZE, 1, 0); // protected pagetable + VM::uvmunmap(vm_guard.pagetable, sz, 1, 0); // protected pagetable uint64 sp = sz1; - uint64 stackbase = sp - PGSIZE; + uint64 stackbase = sp - stack_data_pages * PGSIZE; uint64 ustack[32]; uint64 argc = 0; -- cgit v1.2.3