kernel panic and trapping :)

This commit is contained in:
Liam Kerr 2026-02-08 22:41:38 +00:00
parent fae2e42f8f
commit da95a4acfa
5 changed files with 70 additions and 1 deletions

View file

@ -2,11 +2,15 @@
.global _start .global _start
_start: _start:
la sp, stack_top # Set up the stack pointer 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 call kmain # Jump to our C code
loop: loop:
wfi # Wait for Interrupt (saves CPU) wfi # Wait for Interrupt (saves CPU)
j loop # Infinite loop if C returns j loop # Infinite loop if C returns
.align 4
trap_entry:
j handle_trap
.section .bss .section .bss
.align 16 .align 16
stack_low: stack_low:

View file

@ -2,8 +2,10 @@
#include <stddef.h> #include <stddef.h>
#include <drivers/uart.h> #include <drivers/uart.h>
#include <syscon/syscon.h> #include <syscon/syscon.h>
#include <kernel/panic.h>
void kmain() { void kmain() {
kprint("Hello, OS World!\n"); kprint("Hello, OS World!\n");
kpanic_force();
poweroff(); poweroff();
} }

27
src/kernel/panic.c Normal file
View file

@ -0,0 +1,27 @@
#include <stddef.h>
#include <stdint.h>
#include <drivers/uart.h>
#include <syscon/syscon.h>
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");
}
}

16
src/kernel/panic.h Normal file
View file

@ -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

20
src/kernel/trap.c Normal file
View file

@ -0,0 +1,20 @@
#include <stdint.h>
#include <stddef.h>
#include <drivers/uart.h>
#include <syscon/syscon.h>
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();
}