diff --git a/src/boot/entry.S b/src/boot/entry.S index 0940865..ea94bf8 100644 --- a/src/boot/entry.S +++ b/src/boot/entry.S @@ -2,11 +2,15 @@ .global _start _start: la sp, stack_top # Set up the stack pointer + la t0, trap_entry # Set up the trap handler + csrw mtvec, t0 # Set the trap vector to our trap handler call kmain # Jump to our C code loop: wfi # Wait for Interrupt (saves CPU) j loop # Infinite loop if C returns - +.align 4 +trap_entry: + j handle_trap .section .bss .align 16 stack_low: diff --git a/src/kernel/kernel.c b/src/kernel/kernel.c index 2807836..838bb06 100644 --- a/src/kernel/kernel.c +++ b/src/kernel/kernel.c @@ -2,8 +2,10 @@ #include #include #include +#include void kmain() { kprint("Hello, OS World!\n"); + kpanic_force(); poweroff(); } diff --git a/src/kernel/panic.c b/src/kernel/panic.c new file mode 100644 index 0000000..a110812 --- /dev/null +++ b/src/kernel/panic.c @@ -0,0 +1,27 @@ +#include +#include +#include +#include + +void kpanic(const char *reason){ + kprint(reason); + poweroff(); +} + +void kpanic_force() { + // 1. Immediate Output + kprint("\n!!! FORCE PANIC !!!\n"); + + // 2. Trigger a hardware breakpoint or illegal instruction + // This allows a debugger (GDB) to stop exactly here. + // 'ebreak' is the standard RISC-V way to trigger a debug trap. + __asm__ volatile("ebreak"); + + // 3. If no debugger is attached or we continue, kill the VM + poweroff(); + + // 4. Final halt + while(1) { + __asm__ volatile("wfi"); + } +} diff --git a/src/kernel/panic.h b/src/kernel/panic.h new file mode 100644 index 0000000..0c087e4 --- /dev/null +++ b/src/kernel/panic.h @@ -0,0 +1,16 @@ +#ifndef PANIC_H +#define PANIC_H + +void kpanic(const char *reason); +void kpanic_force(); + +#define KASSERT(cond, msg) \ + if (!(cond)) { \ + kprint("ASSERTION FAILED: "); \ + kprint(__FILE__); \ + kprint(":"); \ + /* Note: Printing line numbers requires a custom itoa/printf */ \ + kpanic(msg); \ + } + +#endif \ No newline at end of file diff --git a/src/kernel/trap.c b/src/kernel/trap.c new file mode 100644 index 0000000..0952313 --- /dev/null +++ b/src/kernel/trap.c @@ -0,0 +1,20 @@ +#include +#include +#include +#include + +void handle_trap() { + kprint("\n!!! HARDWARE EXCEPTION DETECTED !!!\n"); + + // Read the 'mcause' register to see WHY we trapped + unsigned long cause; + __asm__ volatile("csrr %0, mcause" : "=r"(cause)); + + if (cause == 3) { // 3 is the code for 'breakpoint' (ebreak) + kprint("Reason: ebreak (Breakpoint)\n"); + } else { + kprint("Reason: Other Exception\n"); + } + + poweroff(); +} \ No newline at end of file