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/trap/handler.cc | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) (limited to 'src/kernel/trap/handler.cc') diff --git a/src/kernel/trap/handler.cc b/src/kernel/trap/handler.cc index 3e73213..3fb772e 100644 --- a/src/kernel/trap/handler.cc +++ b/src/kernel/trap/handler.cc @@ -157,15 +157,19 @@ extern "C" void usertrap() } else if (scause == 15) // Store Page Fault { - uint64 pte = VM::walkaddr(p->pagetable, stval); - - // Drivers::uart_puts("[Debug] Faulting PTE:"); - // Drivers::print_hex(pte); - // Drivers::uart_puts("\n"); - if (VM::handle_cow_fault(p->pagetable, PGROUNDDOWN(stval)) != 0) { - Drivers::uart_puts("usertrap: cow failed at "); + uint64 pa = VM::walkaddr(p->pagetable, stval); + + if (pa == 0) + { + Drivers::uart_puts("usertrap: Segmentation Fault (unmapped) at "); + } + else + { + Drivers::uart_puts("usertrap: Protection Fault (or OOM) at "); + } + Drivers::print_hex(stval); Drivers::uart_puts("\n"); p->state = ZOMBIE; -- cgit v1.2.3