← Architecture | Documentation Index | Next: System Library →
Kernel/ holds the core services: error handling, logging, power control, paging, and runtime self-checks. This document covers each module, its public functions, and what you must do before calling them.
void kernel_panic(const char *msg, const char *error_code);Halts the system after printing an error banner.
What it does, in order:
- Clears the screen with
vga_clear_screen("F"). - Hides the text cursor with
vga_cursor_mode("D", 0, 0). - Sets red text on a white background.
- Prints
== OpenKernel PANIC ==, then yourmsg, thenError Details:andError code:witherror_code. - Enters an infinite
hltloop.
if (something_failed) {
kernel_panic("Page table allocation failed", "E_MEM_01");
}Requirements and limitations:
vga_init()must have been called, otherwise the message is never displayed.- There is no register dump, no stack trace, and no caller address. You get exactly two strings.
- It never returns. Do not put cleanup code after it.
void log_message(klog_level_t level, const char *message);Prints a prefixed, colour-coded message to the VGA console.
| Level | Prefix | Colour |
|---|---|---|
LOG_SUCCESS |
[SUCCESS]: |
Green |
LOG_ERROR |
[ERROR]: |
Red |
LOG_WARNING |
[WARNING]: |
Light brown |
LOG_INFO |
[INFO]: |
Light blue |
LOG_UNKNOWN |
[UNKNOWN]: |
Light grey |
log_message(LOG_INFO, "Keyboard driver initialised");
log_message(LOG_ERROR, "Disk read failed");Requirements and limitations:
vga_init()must have been called.- Compiles cleanly. The old bug -
log.hending the enum with} klog_level_t;, which declared a global variable instead of a type alias - is fixed:log.hnow ownstypedef enum kernel_log_level klog_level_t;,structs.handsyscall_extern.hincludelog.hinstead of redeclaring the enum, andlog.c,syscall.c, andsecurity.call compile again. See 09 - Project Status. SystemLib/SystemIO/qemu_io.hresolves the type through the samelog.hinclude.
void sys_next_status(const char *mode, uint32_t seconds);
void exit_program(const char *mode, const char *message);Power and reset control. The mode is matched on the whole string, not just the first character.
| Mode | Behaviour |
|---|---|
"shutdown" |
Sleeps seconds, then writes 0x00 to I/O port 0x604 (QEMU/ICH9 ACPI power button), waits via port 0x80, then writes 0x20 to port 0x605. |
"reboot" |
Disables interrupts, waits for the 8042 keyboard controller input buffer to clear (port 0x64 bit 1), then writes 0xFE to port 0x64 to trigger a CPU reset. |
sys_next_status("shutdown", 3); /* power off after 3 seconds */
sys_next_status("reboot", 0); /* restart immediately */Notes:
- The shutdown path targets QEMU and similar PC firmware. On real hardware the ACPI ports differ and this may do nothing.
secondsis passed tosleep(), which delegates topit_sleep_ms()(see 05 - System Library). It waits on the IRQ0 millisecond counter, so it is accurate to one tick, but it busy-waits rather than suspending anything - and it returns immediately if the PIT has not been initialised or interrupts are off.
void exit_program(const char *mode, const char *message);Two modes:
"D"- prints nothing extra, then halts."C"- printsmessage, then halts.
Both end in an infinite hlt loop and never return.
void paging_init(void);
void load_page_dir(uint32_t *pd);
void enable_paging(void);Flags defined in vmem.h:
#define PAGE_PRESENT 0x1
#define PAGE_RW 0x2
#define PAGE_USER 0x4paging_init() builds a single page directory and one page table, both declared __attribute__((aligned(4096))) as static arrays. It identity-maps the first 4 MiB - virtual address N maps to physical address N - then:
- Points page directory entry 0 at the first page table.
- Loads the directory into CR3 via
load_page_dir(). - Sets CR0 bit 31 (paging enable) via
enable_paging().
- It maps only 1 of the 1024 possible page directory entries, so only 4 MiB of the address space is valid. Access beyond that faults.
PAGE_USERis never applied to any entry; there is no user/supervisor distinction.- There is no page fault handler yet. An IDT now exists (section 6), so one could be attached with
interrupt_register_handler(14, ...); until that happens a fault panics the kernel through the default dispatch path. - There is no map/unmap function for dynamic allocation, no higher-half layout, and no TLB management.
- Nothing in the repository calls
paging_init(). Enabling paging is entirely up to your entry point, and you should only do so once you have a fault handler or you are certain all your accesses fall in the mapped range.
A self-test framework referred to internally as PSC (OpenKernel Security Checker). 602 lines, the largest file in the project.
typedef enum { SEC_OK, SEC_WARN, SEC_CRITICAL, SEC_PANIC } securchk_severity_t;
typedef struct {
int total_checks, passed, warnings, critical;
int tasks_validated, stack_overflows, heap_corruptions;
int syscall_violations, memory_leaks;
} securchk_result_t;
typedef struct {
securchk_severity_t severity;
const char* module;
const char* message;
uint32_t detail;
} securchk_issue_t; /* up to SECURCHK_MAX_ISSUES = 32 entries */| Function | Purpose |
|---|---|
securchk_init(void) |
Initialises the issue log. |
securchk_run(securchk_result_t*) |
Auto-initialises, resets counters and the issue log, prints a banner, runs all seven checks, prints a report. |
securchk_check_task_integrity(...) |
Walks the task list (bounded, breaks when it returns to the head) and validates entry, stack, state range, id, and that a non-zero esp/ebp falls inside the task stack. |
securchk_check_stack_overflow(...) |
Same range validation for stacks, also bounded. |
securchk_check_heap_integrity(...) |
Verifies the guard magic of the next heap block, checks a kmalloc'd block for a 1 GiB address-range sanity, tests that a freed block can be re-claimed, then frees. |
securchk_check_syscall_bounds(...) |
Asserts syscall(-1, NULL) and syscall(SYSCALL_PRINT_TIME + 1, NULL) both return -1 (the upper bound is kept in sync with the real syscall table, currently 43). |
securchk_check_memory_safety(...) |
Self-tests memset, memcpy, memcmp (including zero-length cases) and warns about stack alignment. |
securchk_check_driver_state(...) |
Probes the VGA text buffer with a cell write/readback (saving and restoring the original cell), then reports OK. |
securchk_check_kernel_structures(...) |
Static asserts plus linker-symbol sanity: PAGE_SIZE == 4096, pointer/integer widths, __ro_start <= __bss_start <= __stack_start <= __heap_start <= __kernel_end. |
securchk_print_result(...) |
Formats the counters into a report. |
securchk_log_issue(...) |
Records a single issue with severity, module, message, and detail in a bounded ring (drops the oldest when full). |
securchk_get_issue(i) / securchk_get_issue_count(void) |
Read access to the recorded issues. |
securchk_get_overall_status(...) |
Returns an overall verdict derived from the counters. |
securchk_stack_canary_set/check(...) |
Places or verifies the canary value 0xDEADBEEF at the first and last word of a stack region. |
- It is a diagnostic report generator, not a protection mechanism. It observes state; it does not enforce anything.
- The stack canary helpers are never called anywhere in the repository.
- It now compiles cleanly (
-Wall -Wextra) and no longer depends on the statictask_list/currentsymbols: the task walk goes through thetask_list_head()accessor added toSystemLib/TaskMng/task.c. - The syscall upper bound is derived from
SYSCALL_PRINT_TIME, so it cannot silently drift from the real table again. - The heap check verifies guard magic, block ranges, and free/re-claim behaviour instead of only "did
kmallocreturn non-NULL". - The driver-state check no longer wipes the screen; it touches one VGA cell and restores it.
- Nothing ever calls
securchk_init()orsecurchk_run(), and the module is untested at runtime (the project has no boot code).
The first interrupt-handling code in the project: two C modules plus the NASM entry stubs, all listed in the Makefile (ASM_SRC / C_SRC).
| File | Purpose |
|---|---|
interrupt.c / interrupt.h |
IDT construction, handler registry and the C dispatch path |
pic.c / pic.h |
8259A initialisation (remap to vectors 32-47), masking and EOI |
isr.asm |
Entry stubs for the 32 exception vectors and 16 IRQ vectors (generated with %rep) plus the shared isr_common tail |
| Function | Purpose |
|---|---|
interrupt_init(void) |
Installs gates 0-47, runs pic_init(), resets the handler registry and loads the IDTR with lidt. IRQ lines stay masked afterwards. Must run before any driver registers a handler. |
interrupt_register_handler(vector, handler) |
Appends a C handler to an exception (0-31) or IRQ vector (32-47). Vectors keep a list of handlers (from a fixed 32-node pool, no allocation in interrupt context), so devices sharing a PCI IRQ line can all listen; registering the same function twice is a no-op. |
interrupt_dispatch(registers_t*) |
Called from isr.asm. Exceptions run their handler(s) or kernel_panic(); for IRQs every registered handler runs in registration order, then the EOI is sent either way. |
pic_init(void) |
ICW1-ICW4 sequence: IRQ0-15 map to vectors 32-47, then every line is masked. |
pic_set_mask(irq) / pic_clear_mask(irq) |
Mask or unmask one line (0-15). |
pic_send_eoi(irq) |
Acknowledge the interrupt, including the cascade line for IRQ8-15. |
registers_t in interrupt.h must match the pushes in isr.asm exactly; two static asserts pin sizeof(registers_t) == 64 and eip at offset 44. The stubs normalise the frame so exceptions that carry a CPU error code (8, 10-14, 17) have the same shape as the ones that do not.
- No GDT of its own. Gates use selector
0x08, which is whatever the multiboot loader left in CS; there is no GDT code in the repository. - Nothing registers a handler by default. An unhandled exception panics with the vector mnemonic; an IRQ without a handler is only acknowledged (the EOI is still sent so the controller keeps running). Drivers that do register: PIT (IRQ0), Keyboard (IRQ1), Serial (IRQ4), ATA (IRQ14), Mouse (IRQ12), e1000 / RTL8139 (their PCI line).
- All IRQ lines start masked - a driver must call
pic_clear_mask()for the line it wants. - No handler unregistration: once appended to a vector's list a handler stays there (masking the line is how a driver stops it, which is what
pit_stop(),kbd_close()andmouse_close()do). - No APIC support, no per-vector priority, no DPL3 (user) gates and no
int 0x80syscall gate. - Nothing in the repository calls
interrupt_init()yet - the project still has no boot code.
Exercised under QEMU (-kernel, multiboot): IDT limit/base via sidt, software int $0x2F and int3, a real #GP with its error code, a real timer IRQ0 on vector 32 after pic_clear_mask(0) + sti(), and an unhandled exception reaching kernel_panic(). The harness lives outside the repository; there is no in-repo test suite.
#define KRNL_NAME "OpenKernel"
#define KRNL_VER "5.0"
#define KRNL_ARCH "x86 (32-bit)"
#define KRNL_LAST_COMMIT "06c18fe"Informational only. No file in the repository includes it, and KRNL_LAST_COMMIT is stale compared with the current HEAD.
These services have interdependencies. A safe order from your kernel_main():
void kernel_main(void)
{
vga_init(); /* 1. screen - everything below may print */
heap_init(_heap_start, 0x100000); /* 2. heap - needed by kmalloc users */
interrupt_init(); /* 3. IDT + PIC, IRQs start masked */
kbd_init(); /* 4. input */
/* 5. optional: paging only once you have a fault handler */
/* paging_init(); */
/* 6. optional: diagnostics */
/* securchk_result_t r; securchk_run(&r); */
}Rules of thumb:
- Anything that prints requires
vga_init()first. - Anything that allocates requires
heap_init()first. - Anything that registers a handler or unmasks an IRQ requires
interrupt_init()first; a driver then callspic_clear_mask()for its own line. log_message()is usable:log.hnow owns theklog_level_ttypedef (the duplicate enum instructs.hwas removed in favour of includinglog.h).
← Architecture | Documentation Index | Next: System Library →