Kernel Services, Testing, and Debugging Workflow
local graph
Chapter 10 — Kernel Services, Testing, and Debugging Workflow
Section titled “Chapter 10 — Kernel Services, Testing, and Debugging Workflow”Chapter 10: Kernel Services, Testing, and Debugging Workflow
Section titled “Chapter 10: Kernel Services, Testing, and Debugging Workflow”A kernel becomes easier to extend when its services are organized around clear responsibilities. Up to this point, the project has gained the ability to boot, print output, handle CPU exceptions, allocate physical frames, map virtual pages, use heap-backed Rust types, receive hardware interrupts, count timer ticks, and collect keyboard scancodes. Those capabilities are valuable, but they can quickly become difficult to maintain if every feature is wired directly into the entry function or scattered across unrelated modules.
Good kernel structure is not about making the source tree look tidy. It is about making risk visible. Architecture-specific code should stay separate from general kernel services. Device drivers should not own memory-management policy. Interrupt handlers should not become command interpreters. The shell should not know how the PIC is acknowledged. Test code should not distort normal runtime behavior. Debug helpers should be available without creating hidden dependencies. These boundaries let the kernel grow while preserving the ability to understand failures.
This stage also changes how the kernel is validated. Manual booting is useful, but it is not enough once the system has many moving parts. A kernel should be able to run focused tests inside QEMU, report success or failure through serial output, and exit the emulator with a status code. That gives you repeatability. It also prevents old bugs from returning quietly. A page mapping change should not break heap allocation without being noticed. A console refactor should not break panic output. An interrupt change should not break breakpoint handling. Testing gives the kernel a way to prove its foundation after each change.
Debugging remains equally important. QEMU logs, GDB, register inspection, stack inspection, and serial checkpoints all serve different purposes. Serial output tells you what the kernel chose to report. QEMU logs can show CPU resets and exception chains before your own handlers
run. GDB lets you stop execution, inspect registers, read memory, and verify whether the entry point was reached. Stack inspection helps diagnose corrupted calls, wrong handlers, and unexpected control flow. A professional workflow uses all of these tools deliberately instead of relying on guesswork.
10.1: Organizing Kernel Modules and Architecture-Specific Code
Section titled “10.1: Organizing Kernel Modules and Architecture-Specific Code”A kernel source tree should reflect the system’s actual layers. Some code belongs to the architecture because it depends directly on x86_64 behavior. This includes GDT setup, TSS setup, IDT setup, interrupt enabling and disabling, port I/O, control-register access, page-table structures, and CPU fault instructions. Some code belongs to drivers because it controls a specific device, such as serial output, VGA text mode, framebuffer output, timer programming, or keyboard input. Some code belongs to kernel services because it provides behavior above the hardware layer, such as logging, allocation, shell commands, test dispatch, and initialization policy.
If architecture details leak everywhere, the kernel becomes harder to change. A command in the shell should not directly execute raw port I/O. A memory allocator should not know how keyboard scancodes arrive. The keyboard driver should not parse shell commands. The timer handler should not own scheduling policy yet. Boundaries keep each piece understandable. They also make testing easier because pure or nearly pure modules can be tested without booting every hardware path.
A practical early structure can use modules that match major responsibilities. The crate root can declare the main groups, and the entry point can call a small number of initialization functions. The entry point should coordinate startup, not contain every device and CPU detail.
#![no_std]#![no_main]extern crate alloc;
mod arch; mod boot; mod console; mod drivers; mod interrupts; mod keyboard; mod memory; mod shell; mod testing;
use core::panic::PanicInfo;
#[unsafe(no_mangle)] pub extern “C” fn kernel_main(boot_info: &‘static boot::BootInfo) -> ! { boot::early_init();
arch::init_cpu();interrupts::init();memory::init(boot_info);drivers::init();shell::init();
kprintln!("kernel services initialized");
shell::run()}
#[panic_handler] fn panic(info: &PanicInfo) -> ! { console::panic_print(info); arch::halt_loop(); }
This layout keeps the entry point readable. It shows the startup order without exposing the internal details of every subsystem. Early boot output is initialized first so failures can be reported. CPU tables and interrupts are prepared before hardware interrupts are enabled. Memory is initialized before services that may allocate. Drivers are initialized before the shell starts using input and output. The panic handler delegates printing to the console layer and halting to the architecture layer.
The architecture module can expose a narrow interface. The rest of the kernel does not need to know every x86_64 instruction or structure. It
needs operations such as halt, enable interrupts, disable interrupts, initialize CPU tables, read processor state, and access architecture-specific memory helpers.
pub mod gdt;pub mod idt;pub mod port;pub mod registers;
pub fn init_cpu() { gdt::init(); crate::kprintln!("gdt and tss loaded");
idt::init(); crate::kprintln!("idt loaded");}
pub fn halt_loop() -> ! { loop { x86_64::instructions::hlt(); }}
pub fn enable_interrupts() { x86_64::instructions::interrupts::enable();}
pub fn disable_interrupts() { x86_64::instructions::interrupts::disable();}
pub fn without_interrupts<R>(function: impl FnOnce() -> R) -> R { x86_64::instructions::interrupts::without_interrupts(function)}This module gives the rest of the kernel a stable architecture-facing surface. The implementation uses x86_64 instructions, but callers do not need to import those details directly. If the kernel later reorganizes GDT or IDT setup, the public initialization function can remain the same. If another architecture is ever studied separately, this boundary shows where the architecture-specific work lives.
The drivers module can group hardware devices. Each driver should expose operations that match the device’s purpose rather than raw hardware access. The serial driver should expose initialization and byte output. The keyboard driver should expose scancode buffering and input processing. The timer driver should expose tick count and configuration. The framebuffer or VGA driver should expose drawing or text output. This keeps direct port I/O and volatile memory access close to the device code.
Rust
pub mod framebuffer;pub mod serial;pub mod timer;pub mod vga;
pub fn init() { serial::init(); crate::kprintln!("serial initialized");
timer::init(); crate::kprintln!("timer initialized");
framebuffer::init_if_available(); crate::kprintln!("display initialized");}This function initializes device drivers that can be started after CPU and memory setup. In a real project, some output drivers may be initialized earlier than this because serial output is needed before memory setup. That is fine. The structure can support an early_init path for serial and a later init path for the rest of the driver layer. The important point is that driver startup is explicit and grouped by responsibility.
A boot module can translate bootloader-provided information into kernel-owned startup data. This prevents external boot protocol structures from spreading through memory, console, and driver code. The kernel should receive boot information once, validate what it needs, and pass internal forms to subsystems.
<!-- page: 284 -->
use x86_64::VirtAddr;
pub struct BootInfo { pub physical_memory_offset: VirtAddr, pub memory_regions: &'static [crate::memory::MemoryRegion], pub framebuffer: Option<FramebufferInfo>,}
#[derive(Clone, Copy)]pub struct FramebufferInfo { pub address: *mut u8, pub width: usize, pub height: usize, pub stride: usize, pub bytes_per_pixel: usize,}
pub fn early_init() { crate::drivers::serial::init(); crate::kprintln!("early serial output ready");}
This structure is intentionally kernel-owned. It contains only the startup data the kernel has chosen to preserve. If the bootloader changes later, the translation layer can change without forcing every subsystem to understand a new external format. This is especially important for memory maps and framebuffer metadata, which are used by several later systems.
The memory module can own the frame allocator, page mapping setup, heap setup, and memory-region types. It should avoid importing keyboard, shell, or driver policy. The memory system may need serial output for diagnostics, but the direction should be carefully controlled. Memory code can report errors through a small logging interface. It should not depend on the shell or command system.
Rust
pub mod frame;pub mod heap;pub mod paging;pub mod regions;
pub use regions::{MemoryRegion, MemoryRegionKind};
pub fn init(boot_info: &'static crate::boot::BootInfo) {
<!-- page: 285 -->
rustregions::print_memory_map(boot_info.memory_regions);
let mut frame_allocator = frame::init(boot_info.memory_regions);let mut mapper = unsafe { paging::init_mapper(boot_info.physical_memory_offset)};
unsafe { heap::init(&mut mapper, &mut frame_allocator) .expect("heap initialization failed");}
crate::kprintln!("memory initialized");This function shows the memory initialization flow. It prints the memory map, creates or initializes the frame allocator, creates a mapper for the active page tables, maps and initializes the heap, and reports success. A production-quality design may store the frame allocator and mapper in global kernel state after initialization, but the staged flow remains the same. Memory setup should be readable because many later bugs lead back to it.
The console layer should sit above output drivers. It can write to serial, screen, or both. The rest of the kernel should use kprint! and kprintln! rather than calling serial or VGA directly. This makes logging behavior consistent. If screen output breaks, serial can remain available. If panic output needs a special emergency path, the console module can provide it.
use core::fmt::{self, Write};use core::panic::PanicInfo;
pub struct KernelConsole;
impl Write for KernelConsole { fn write_str(&mut self, text: &str) -> fmt::Result { crate::drivers::serial::write_str(text); crate::drivers::vga::write_str(text); Ok(()) }}
pub fn print(args: fmt::Arguments) {crate::arch::without_interrupts(|| { let mut console = KernelConsole; let _ = console.write_fmt(args);});
pub fn panic_print(info: &PanicInfo) { crate::drivers::serial::write_str("\nkernel panic\n"); crate::drivers::serial::write_str("panic details follow\n");
print(format_args!("{}", info));}
#[macro_export]acro_rules! kprint { ($($arg:tt)*) => { $crate::console::print(format_args!($($arg)*)) };}
#[macro_export]acro_rules! kprintln { () => { $crate::kprint!("\n") }; ($fmt:expr) => { $crate::kprint!(concat!($fmt, "\n")) }; ($fmt:expr, $($arg:tt)*) => { $crate::kprint!(concat!($fmt, "\n"), $($arg)*) };}This console module centralizes formatted output. It disables interrupts around printing to reduce reentrant lock problems on a single CPU. That does not make printing safe in every future context, but it is a practical early design. The panic path writes directly to serial first, then uses the formatted console path. If the formatted path becomes risky later, panic output can be changed without modifying every panic site.
Good organization also requires careful dependency direction. Higher-level services may depend on lower-level services. The shell can depend on keyboard, console, timer, and memory diagnostics. Drivers can depend on architecture port I/O and locks. Architecture code should not depend on the shell. Memory management should not depend on keyboard input. Tests
may depend on many modules, but test-specific behavior should remain clearly separated.
A kernel can keep these boundaries with ordinary Rust modules, private items, and narrow public functions. Do not expose raw internal fields unless another module truly needs them. Do not make every function pub. Public APIs should represent stable kernel services. Private functions can hold implementation details. This matters more in a kernel than in many applications because exposing a raw pointer or mutable global can break system-wide invariants.
10.2: Building a Minimal Interactive Kernel Shell
Section titled “10.2: Building a Minimal Interactive Kernel Shell”A minimal kernel shell is not a full user interface, and it is not a userspace program. It is a small command loop running inside the kernel, useful for inspecting state and exercising services. It can show timer ticks, print memory information, trigger controlled tests, clear the screen, display help, and verify that keyboard input, buffering, output, and command parsing work together. It gives you a practical way to interact with the kernel without rebuilding for every small diagnostic.
The shell should remain modest. It should not allocate heavily in interrupt context. It should not perform unbounded parsing. It should not assume a filesystem or process model. It should read characters from the keyboard input path, store them in a fixed-size command buffer, process complete lines, and execute built-in commands. This keeps it useful without turning it into a large subsystem too early.
The shell depends on the keyboard path from the previous stage. The keyboard interrupt handler reads scancodes and pushes them into a buffer. Normal code drains the buffer, decodes scancodes into characters, and passes characters to the shell. The shell should not read port 0x60 directly. That belongs to the keyboard driver. The shell works with characters.
A command buffer can be fixed-size. This avoids heap allocation and keeps shell input predictable. If the buffer fills, the shell can ignore additional
characters or print a warning. For early kernel work, fixed-size input is the right tradeoff.
Rust
pub struct CommandBuffer { bytes: [u8; 128], len: usize,}
impl CommandBuffer { pub const fn new() -> Self { Self { bytes: [0; 128], len: 0, } }
pub fn push(&mut self, byte: u8) -> Result<(), ()> { if self.len >= self.bytes.len() { return Err(()); } self.bytes[self.len] = byte; self.len += 1; Ok(()) }
pub fn backspace(&mut self) { if self.len > 0 { self.len -= 1; } }
pub fn clear(&mut self) { self.len = 0; }
pub fn as_str(&self) -> &str { core::str::from_utf8(&self.bytes[..self.len]).unwrap_or("") }}This buffer stores one command line. It accepts bytes and exposes a string slice when the input is valid UTF-8. Since the early keyboard decoder only produces simple ASCII bytes, UTF-8 conversion should succeed. If invalid
data appears, the buffer returns an empty string through unwrap_or. A stricter shell could report invalid input, but early input should remain simple.
The shell state can contain the command buffer and prompt behavior. It receives characters one at a time. When it receives a newline, it executes the command and clears the buffer. When it receives backspace, it removes the previous character. Otherwise, it appends the character and echoes it to the console.
Rust
pub struct Shell { buffer: CommandBuffer,}
impl Shell { pub const fn new() -> Self { Self { buffer: CommandBuffer::new(), } }
pub fn prompt(&self) { crate::kprint!("kernel> "); }
pub fn handle_byte(&mut self, byte: u8) { match byte { b'\n' => { crate::kprintln!(); self.execute_current_command(); self.buffer.clear(); self.prompt(); } 8 | 127 => { self.buffer.backspace(); crate::kprint!("\x08 \x08"); } byte => { if self.buffer.push(byte).is_ok() { crate::kprint!("{}", byte as char); } else { crate::kprintln!(); crate::kprintln!("command buffer is full"); self.buffer.clear(); } } } }}self.prompt(); }
fn execute_current_command(&self) { execute_command(self.buffer.as_str()); }
The backspace output uses a common terminal-style sequence: move back, print a space, move back again. Whether this displays correctly depends on the output backend. On serial terminals, it often works. On a custom VGA console, you may need explicit cursor support for proper backspace behavior. The shell logic can stay the same while the console layer improves.
Command execution can start with a small set of built-ins. Avoid using heap allocation for parsing. Trim the input and match directly on known commands. This is enough for early diagnostics.
pub fn execute_command(command: &str) { let command = command.trim();
match command { "" => {}, "help" => help(), "ticks" => ticks(), "mem" => memory(), "clear" => clear(), "panic" => panic!("manual panic from kernel shell"), "fault" => trigger_page_fault(), _ => crate::kprintln!("unknown command: {}", command), }}
fn help() { crate::kprintln!("commands: help, ticks, mem, clear, panic, fault");}
fn ticks() { crate::kprintln!("timer ticks: {}", crate::drivers::timer::ticks());}
<!-- page: 291 -->
fn memory() { crate::memory::print_summary();}
fn clear() { crate::drivers::vga::clear_screen();}
fn trigger_page_fault() { let pointer = 0xdead_beef as *const u64;
unsafe { let _ = core::ptr::read_volatile(pointer); }}
These commands are intentionally focused. `help` displays the available commands. `ticks` proves timer interrupts are working. `mem` gives a memory summary. `clear` tests screen output. `panic` tests panic handling. `fault` deliberately triggers a page fault so the exception handler can be inspected. The dangerous commands should stay obvious and should not be included in a kernel that is intended to run unattended.
The shell should be stored behind a lock because the main loop may access it repeatedly, and future code could interact with it from other contexts. It should not be manipulated from the keyboard interrupt handler. The handler only stores scancodes. The main loop drains input and calls the shell.
## Rust
rustuse spin::Mutex;
static SHELL: Mutex<Shell> = Mutex::new(Shell::new());
pub fn init() { SHELL.lock().prompt();}
pub fn handle_input_byte(byte: u8) { SHELL.lock().handle_byte(byte);}This is a basic global shell state. Since the shell runs in normal kernel context, not interrupt context, it can use the ordinary lock path. If you ever call handle_input_byte from interrupt context, review the locking rules. For now, keep the shell out of interrupt handlers.
The main loop can process keyboard input and pass decoded bytes to the shell. The keyboard module can expose a function that returns decoded bytes rather than raw scancodes. The shell does not need to know scancode set details.
Rust
pub fn run() -> ! { loop { while let Some(byte) = ate::keyboard::pop_decoded_byte() { handle_input_byte(byte); } x86_64::instructions::hlt(); }}This loop drains available input, then halts until the next interrupt. Timer interrupts and keyboard interrupts can wake the CPU. The shell remains responsive without busy-waiting continuously. This is still a single-threaded kernel loop, but it has the structure of an event-driven kernel service.
A slightly more useful keyboard decoding path can separate scancode collection from byte output. The decoder can track Shift state and convert simple letter scancodes into uppercase when Shift is held. This is still not a complete keyboard implementation, but it makes the shell more comfortable.
Rust
pub struct KeyboardDecoder { shift: bool,}impl KeyboardDecoder { pub const fn new() -> Self { Self { shift: false } }
pub fn decode(&mut self, scancode: u8) -> Option<u8> { match scancode { 0x2a | 0x36 => { self.shift = true; None } 0xaa | 0xb6 => { self.shift = false; None } 0x1c => Some(b'\n'), 0x0e => Some(8), code => self.decode_letter(code), }}
fn decode_letter(&self, scancode: u8) -> Option<u8> { let byte = match scancode { 0x10 => b'q', 0x11 => b'w', 0x12 => b'e', 0x13 => b'r', 0x14 => b't', 0x15 => b'y', 0x16 => b'u', 0x17 => b'i', 0x18 => b'o', 0x19 => b'p', 0x1e => b'a', 0x1f => b's', 0x20 => b'd', 0x21 => b'f', 0x22 => b'g', 0x23 => b'h', 0x24 => b'j', 0x25 => b'k', 0x26 => b'l', 0x2c => b'z', 0x2d => b'x', 0x2e => b'c', 0x2f => b'v', 0x30 => b'b', 0x31 => b'n', 0x32 => b'm', 0x39 => b' ', _ => None, }; if self.shift { match byte { b'q' => Some(b'Q'), b'w' => Some(b'W'), b'e' => Some(b'E'), b'r' => Some(b'R'), b't' => Some(b'T'), b'y' => Some(b'Y'), b'u' => Some(b'U'), b'i' => Some(b'I'), b'o' => Some(b'O'), b'p' => Some(b'P'), b'a' => Some(b'A'), b's' => Some(b'S'), b'd' => Some(b'D'), b'f' => Some(b'F'), b'g' => Some(b'G'), b'h' => Some(b'H'), b'j' => Some(b'J'), b'k' => Some(b'K'), b'l' => Some(b'L'), b'z' => Some(b'Z'), b'x' => Some(b'X'), b'c' => Some(b'C'), b'v' => Some(b'V'), b'b' => Some(b'B'), b'n' => Some(b'N'), b'm' => Some(b'M'), b' ' => Some(b' '), _ => None, } } else { Some(byte) }}}
_ => return None,};
if self.shift && byte.is_ascii_lowercase() { Some(byte.to_ascii_uppercase())} else { Some(byte)}This decoder tracks only a small subset of keyboard behavior. It ignores many keys, does not handle Caps Lock, does not fully handle numbers and punctuation, and does not handle extended scancodes. That is fine for an early shell. The important design point is that decoding has its own state and its own module. The shell receives bytes. The keyboard driver receives scancodes. The interrupt handler remains short.
A memory summary command can report allocator and paging information without exposing internals. This gives the shell a practical diagnostic role.
pub fn print_summary() { crate::kprintln!("memory summary"); crate::kprintln!("heap start: {:#x}", crate::memory::heap::HEAP_START.as_u64()); crate::kprintln!("heap size: {} bytes", crate::memory::heap::HEAP_SIZE); crate::kprintln!("allocated frames: {}", crate::memory::frame::allocated_count());}The shell should not directly inspect private allocator fields. The memory module can expose a summary function. This keeps ownership where it belongs. The shell is a consumer of kernel services, not the owner of them.
A minimal shell gives the kernel a useful control surface. It is also a practical test of the system so far. If the shell responds to keyboard input, then the IDT, PIC, keyboard handler, scancode buffer, decoder, console output, and main loop are working together. If the ticks command changes over time, timer interrupts are active. If the fault command prints a page-fault report,
exception handling remains alive. The shell is small, but it gives you a direct way to exercise the kernel’s core services.
10.3: Writing Kernel Tests with Serial Output and QEMU Exit Codes
Section titled “10.3: Writing Kernel Tests with Serial Output and QEMU Exit Codes”Kernel tests need a different approach from ordinary Rust tests. In a normal Rust project, the test harness runs on top of an operating system. It can print to standard output, allocate freely, create threads, open files, and return process exit codes. A kernel test runs inside the kernel environment. It must boot under QEMU, report through a device such as serial output, and signal success or failure through a mechanism the host can observe.
Serial output is the first test reporting channel. It is simple, reliable in QEMU, and already available from early kernel startup. A test can print its name, run assertions, and report success. The missing piece is the final result. If the test succeeds, QEMU should exit with a success code. If it fails, QEMU should exit with a failure code or panic in a way that the test runner treats as failure. Without an exit mechanism, automated tests hang until a timeout.
A common QEMU test setup uses a special debug-exit device. The guest writes a value to a configured I/O port, and QEMU exits. The host process receives an exit status derived from that value. The kernel can wrap this as a small function.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]#[repr(u32)]pub enum QemuExitCode { Success = 0x10, Failed = 0x11,}
pub fn exit_qemu(code: QemuExitCode) -> ! { unsafe { core::arch::asm!( "out dx, eax", in("dx") 0xf4u16,in(“eax”) code as u32, options(nomem, nostack, preserves_flags) );
loop { x86_64::instructions::hlt(); }
This function is unsafe internally because it performs port I/O. The public function can be safe if the kernel’s test environment guarantees that QEMU is configured with the matching debug-exit device. If the device is not configured, the port write may not exit QEMU. The function still never returns because it falls into a halt loop after the port write.
The matching QEMU command includes the debug-exit device and serial output. The command should be part of a script so tests run consistently.
qemu-system-x86_64 \-drive format=raw,file=target/kernel-test.img \-serial stdio \-no-reboot \-no-shutdown \-device isa-debug-exit,iobase=0xf4,iosize=0x04
The iobase value must match the port used by the kernel. The serial output lets you see test progress. The no-reboot and no-shutdown flags make failures easier to inspect during manual runs.
A test runner inside the kernel can be simple. It can receive an array of test functions, print each name if names are available, call them, and exit with success when all finish. In a no_std kernel, the exact custom test framework may depend on the compiler features and project setup, but the core idea is straightforward.
Rust
pub trait Testable { fn run(&self);}
<!-- page: 297 -->
rustimpl<T> Testable for Twhere T: Fn(),{ fn run(&self) { serial_print!("{}...\t", core::any::type_name::<T>()); self(); serial_println!("ok"); }}
pub fn test_runner(tests: &[&dyn Testable]) { serial_println!("running {} tests", tests.len());
for test in tests { test.run(); }
crate::qemu::exit_qemu(crate::qemu::QemuExitCode::Success);}This runner uses type names as test names. It prints a line before and after each test. If a test panics, the panic handler should report failure and exit QEMU with a failure code. If all tests finish, the runner exits with success.
The test panic handler should differ from the normal panic handler. During normal boot, a panic prints and halts. During tests, a panic should print and exit with failure so the host test process can report the failure.
use core::panic::PanicInfo;
#[cfg(test)]#[panic_handler]fn panic(info: &PanicInfo) -> ! { serial_println!("test failed"); serial_println!("{}", info);
crate::qemu::exit_qemu(crate::qemu::QemuExitCode::Failed);}
#[cfg(not(test))]#[panic_handler]fn panic(info: &PanicInfo) -> ! {crate::console::panic_print(info);crate::arch::halt_loop();}This separates test behavior from runtime behavior. It avoids forcing the normal kernel to exit QEMU on panic, while still making automated tests usable. Keeping test-specific code behind conditional compilation prevents test support from distorting the normal kernel path.
Tests should cover small kernel services first. Pure functions and bounded data structures are good candidates. The command buffer can be tested without hardware. The scancode buffer can be tested without triggering interrupts. Address alignment helpers can be tested without paging. Allocator behavior can be tested after heap initialization. Page mapping tests can be run under QEMU because they need real page tables.
.ust
#[test_case]command_buffer_accepts_bytes() { let mut buffer = crate::shell::CommandBuffer::new();
assert!(buffer.push(b'h').is_ok()); assert!(buffer.push(b'e').is_ok()); assert!(buffer.push(b'l').is_ok()); assert!(buffer.push(b'p').is_ok());
assert_eq!(buffer.as_str(), "help");}
#[test_case]fn command_buffer_backspace_removes_last_byte() { let mut buffer = crate::shell::CommandBuffer::new();
assert!(buffer.push(b'a').is_ok()); assert!(buffer.push(b'b').is_ok()); buffer.backspace();
assert_eq!(buffer.as_str(), "a");}These tests do not require hardware interrupts. They prove small behavior in isolation. This is valuable because not every kernel test needs to be a
dramatic QEMU fault test. The more code you can test without triggering hardware behavior, the easier it is to maintain.
Heap allocation can be tested after heap setup. The test kernel must initialize memory before running heap tests. A test entry function can initialize the minimum required services, then call the test runner.
Rust
#[cfg(test)]#[unsafe(no_mangle)]pub extern "C" fn kernel_main(boot_info: &'static crate::boot::BootInfo) -> ! { crate::boot::early_init(); crate::arch::init_cpu(); crate::memory::init(boot_info);
serial_println!("test kernel initialized");
test_main();
crate::qemu::exit_qemu(crate::qemu::QemuExitCode::Failed);}This function assumes the custom test framework generates test_main. If test execution returns unexpectedly, the kernel exits with failure. That makes the control flow strict. A successful run exits from the test runner. A panic exits through the test panic handler. Falling through is not treated as success.
A heap test can check that Box and Vec work.
Rust
#[test_case]fn heap_allocates_box() { let value = alloc::boxed::Box::new(1234_u64); assert_eq!(*value, 1234);}
#[test_case]fn heap_allocates_vector() { let mut values = alloc::vec::Vec::new();for value in 0..64 { values.push(value);}
assert_eq!(values.len(), 64);assert_eq!(values[10], 10);These tests exercise the global allocator. If the heap is not mapped or the allocator is not initialized, they will fail quickly. If the allocator returns overlapping memory, values may be corrupted. Heap tests should remain part of the test suite because allocator changes can break many later services.
Exception tests need special handling. Some exceptions are expected to be fatal in normal runtime but successful in a test if the handler is reached. A breakpoint test can be non-fatal because the handler returns. Page fault and double fault tests usually need test-specific handlers that exit QEMU with success when reached.
#[test_case]fn breakpoint_exception_returns() { serial_println!("triggering breakpoint test"); x86_64::instructions::interrupts::int3(); serial_println!("breakpoint returned");}This test confirms that the breakpoint handler runs and returns. The handler itself should print diagnostic output. If the test continues after int3, the path worked.
A page-fault test can use a separate test binary or feature flag because it intentionally does not return through normal execution. The page-fault handler exits QEMU with success if it sees the expected fault.
pub extern "x86-interrupt" fn test_page_fault_handler( _stack_frame: x86_64::structures::idt::InterruptStackFrame, _error_code: x86_64::structures::idt::PageFaultErrorCode,) { let address = x86_64::registers::control::Cr2::read(); serial_println!("expected page fault at {:?}", address); crate::qemu::exit_qemu(crate::qemu::QemuExitCode::Success);}This handler should be installed only for the specific page-fault test environment. In normal runtime, a page fault should print diagnostics and halt. In the test, reaching the handler means the expected exception path worked.
A shell test can test command parsing without running the interactive loop. Command execution can be split so it returns a result for testable commands rather than only printing. For early code, you can test the parsing function directly.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum Command { Empty, Help, Ticks, Mem, Clear, Panic, Fault, Unknown,}
pub fn parse_command(input: &str) -> Command { match input.trim() { "" => Command::Empty, "help" => Command::Help, "ticks" => Command::Ticks, "mem" => Command::Mem, "clear" => Command::Clear, "panic" => Command::Panic, "fault" => Command::Fault, _ => Command::Unknown, }}
#[test_case]fn parses_help_command() { assert_eq!(parse_command("help"), Command::Help);}
#[test_case]fn trims_command_whitespace() { assert_eq!(parse_command(" ticks "), Command::Ticks);}This is better than testing command execution only through serial output. The parser is pure and easy to test. The executor can still print and trigger actions, but the parser has its own verifiable behavior.
Testing does not remove the need for manual debugging. It gives you a baseline. When a change breaks the kernel, tests can show which layer failed. If command buffer tests pass but shell input fails, the problem may be in keyboard decoding or the main loop. If heap tests fail after a paging change, the heap mapping or frame allocator may be involved. If breakpoint tests fail after IDT changes, CPU exception setup needs attention. Good tests turn broad failure into narrower investigation.
10.4: Debugging with QEMU Logs, GDB, Registers, and Stack Inspection
Section titled “10.4: Debugging with QEMU Logs, GDB, Registers, and Stack Inspection”A kernel debugger workflow should not depend on one tool. Serial output, QEMU logs, GDB, register inspection, and stack inspection each answer different questions. Serial output tells you what the kernel reached and what it chose to print. QEMU logs tell you about CPU events even when the kernel cannot report them. GDB lets you stop and inspect execution. Register inspection tells you what the CPU is actually doing. Stack inspection helps explain how execution reached a point or why returning from a handler failed.
The first debugging tool remains serial checkpoints. Print before and after major initialization steps. This is simple and effective because early kernel failures often happen during startup. If the kernel prints idt loaded but not heap initialized, you know where to look. If it prints hardware interrupts enabled and then hangs, the first interrupt path is suspicious. Serial
checkpoints should be short, stable, and placed around dangerous transitions.
Rust
pub fn init_kernel(boot_info: &'static crate::boot::BootInfo) { crate::kprintln!("init: cpu"); crate::arch::init_cpu(); crate::kprintln!("init: cpu complete");
crate::kprintln!("init: memory"); crate::memory::init(boot_info); crate::kprintln!("init: memory complete");
crate::kprintln!("init: drivers"); crate::drivers::init(); crate::kprintln!("init: drivers complete");
crate::kprintln!("init: interrupts"); crate::interrupts::enable(); crate::kprintln!("init: interrupts enabled");}This function is intentionally verbose during initialization. The output creates a trace of startup progress. Once the kernel becomes stable, you can reduce normal boot output or put it behind a debug flag. During development, it is worth keeping.
QEMU logs help when the kernel cannot print. If an exception occurs before the IDT is loaded, or if a double fault becomes a triple fault, your own handlers may never run. QEMU can log interrupts, exceptions, and CPU resets.
Shell
qemu-system-x86_64 \-drive format=raw,file=target/kernel.img \-serial stdio \-no-reboot \-no-shutdown \-d int,cpu_reset \-D target/qemu.logThis command writes diagnostic events to target/qemu.log. The log can be noisy, but it is useful when the machine resets with little output. If the log shows a page fault followed by a double fault and then a reset, the double-fault path is not working or the double-fault handler could not be reached. If the log shows repeated CPU resets, the kernel may be triple-faulting or the boot path may be looping.
GDB gives more direct control. Start QEMU paused with a GDB stub enabled. Then connect a debugger, set breakpoints, and continue execution.
qemu-system-x86_64 \-drive format=raw,file=target/kernel.img \-serial stdio \no-reboot \no-shutdown \-s \sThe -s option starts the CPU paused. The -s option opens a GDB server on the default port. This lets you connect before the kernel begins running. That is useful when the kernel fails before printing anything.
Start GDB with the kernel symbol file, then connect to QEMU.
gdb target/x86_64-kernel/debug/rust_kernelInside GDB, connect and set a breakpoint at the kernel entry point.
target remote :1234break kernel_maincontinueIf the breakpoint is hit, the bootloader reached the kernel’s Rust entry path. If it is not hit, the problem is earlier: the boot image, bootloader configuration, entry symbol, or linker layout may be wrong. If the
breakpoint name does not resolve, inspect the symbol table and check the actual entry function name.
When stopped in GDB, inspect registers.
GDB
info registers
The instruction pointer shows the current execution address. The stack pointer shows the active stack. The flags register can show interrupt state. General-purpose registers may contain boot parameters depending on the calling convention and how early you stop. If the instruction pointer is not in the expected kernel range, the boot path may have jumped somewhere unexpected. If the stack pointer is unmapped or suspicious, the kernel may fault on the next function call or interrupt.
Disassembly helps confirm what code is actually executing.
GDB
x/16i $rip
This command displays instructions at the current instruction pointer. It is useful when source-level debugging does not line up or when the kernel stops in low-level entry code. If GDB shows instructions that do not match the function you expected, check whether symbols match the running image. Booting an old image while debugging a new symbol file can lead to misleading results.
Stack inspection is essential when diagnosing corrupted control flow. The stack contains return addresses, saved registers, interrupt frames, and local data depending on context. If a handler returns to a bad address, the stack may show why. If a function panics unexpectedly, the stack can help identify the call path.
GDB
x/32gx $rsp
This prints 32 eight-byte values from the current stack pointer. The raw values may not be meaningful at first, but patterns emerge. Addresses in the kernel code range may be return addresses. Values that match known markers or pointers can reveal context. During an interrupt handler, the stack contains a CPU-created frame. During a page fault, it may contain the interrupted instruction pointer and flags.
Page-fault debugging should combine GDB with the kernel’s own diagnostics. The page-fault handler should print cr2, the error code, instruction pointer, and stack pointer. If the handler runs, start with that output. If the handler does not run, use QEMU logs and GDB to find out whether the IDT was loaded and whether the page-fault entry is valid.
A helper function can print key registers from inside the kernel. This is useful when GDB is not attached.
use x86_64::registers::control::{Cr0, Cr2, Cr3, Cr4};use x86_64::registers::rflags::RFlags;
pub fn print_register_summary() { let cr0 = Cr0::read(); let cr2 = Cr2::read(); let (cr3_frame, cr3_flags) = Cr3::read(); let cr4 = Cr4::read(); let flags = RFlags::read();
crate::kprintln!("register summary"); crate::kprintln!("cr0: {:?}", cr0); crate::kprintln!("cr2: {:?}", cr2); crate::kprintln!("cr3 frame: {:?}", cr3_frame); crate::kprintln!("cr3 flags: {:?}", cr3_flags); crate::kprintln!("cr4: {:?}", cr4); crate::kprintln!("rflags: {:?}", flags);}This function gives useful CPU state through serial or screen output. cr2 is especially useful after a page fault because it contains the faulting virtual address. cr3 identifies the active page table. rflags shows whether
interrupts are enabled. This information can be exposed through a shell command.
Rust
pub fn execute_command(command: &str) { match crate::shell::parse_command(command) { crate::shell::Command::Help => crate::shell::help(), crate::shell::Command::Ticks => crate::drivers::timer::print_status(), crate::shell::Command::Mem => crate::memory::print_summary(), crate::shell::Command::Clear => crate::drivers::vga::clear_screen(), crate::shell::Command::Panic => panic!("manual panic from shell"), crate::shell::Command::Fault => crate::debug::trigger_page_fault(), crate::shell::Command::Unknown => crate::kprintln!("unknown command"), crate::shell::Command::Empty => {} }}A debug command can trigger a controlled page fault. This should be used only when testing the handler.
Rust
pub fn trigger_page_fault() { crate::kprintln!("triggering controlled page fault");
let pointer = 0xdead_beef as *const u64;
unsafe { let _ = core::ptr::read_volatile(pointer); }}The page-fault handler should then report the faulting address and stop. If it does not, the handler path is broken. If it reports a different address, check the generated code and the access. If the kernel resets, inspect QEMU logs for a fault chain.
When debugging stack problems, add guard pages when paging support is strong enough. A guard page is an unmapped page placed next to a stack. If the stack overflows into the guard page, the CPU raises a page fault instead of silently corrupting nearby memory. This is one of the most useful ways paging improves debugging.
use x86_64::{ VirtAddr, structures::paging::{ FrameAllocator, Mapper, Page, PageTableFlags, Size4KiB, },};
impl unsafe fn map_stack_with_guard<M, A>( mapper: &mut M, frame_allocator: &mut A, stack_bottom: VirtAddr, stack_size: u64,) -> Result<VirtAddr, &'static str>where M: Mapper<Size4KiB>, A: FrameAllocator<Size4KiB>,{ let guard_page = Page::containing_address(stack_bottom); let usable_start = stack_bottom + 4096u64; let usable_size = stack_size - 4096;
crate::kprintln!("guard page left unmapped at {:?}", guard_page.start_address());
let flags = PageTableFlags::PRESENT | PageTableFlags::WRITABLE | PageTableFlags::NO_EXECUTE;
unsafe { crate::memory::paging::try_map_allocated_range( mapper, frame_allocator, usable_start, usable_size, flags, )?; }}Ok(stack_bottom + stack_size)
This function leaves the first page unmapped as a guard and maps the rest as stack memory. It returns the top of the stack because x86_64 stacks grow downward. It assumes stack_size is larger than one page and properly aligned. A more defensive version should validate those conditions. The important idea is that unmapped guard pages turn memory corruption into page-fault diagnostics.
GDB can also inspect memory at specific addresses. If the page-fault handler reports an instruction pointer, you can disassemble near that address. If it reports a stack pointer, you can inspect stack values. If it reports a faulting address, you can ask whether that address is mapped through your page-table diagnostics or inspect page-table structures manually.
GDB
x/16gx 0xffff900000000000 x/16i 0xfffffffff80001000
These commands inspect memory and instructions at specific addresses. The addresses shown are examples. Use addresses from your kernel’s output, linker layout, and fault reports. If GDB cannot read a virtual address, the address may not be mapped in the current execution context or the debugger may not have enough information about the guest address space. Combine this with kernel-side translation diagnostics.
When debugging interrupts, the most common failures involve missing IDT entries, wrong vector numbers, not sending EOI, enabling interrupts too early, and deadlocking inside handlers. If the timer fires once and never again, suspect missing EOI. If enabling interrupts immediately resets the machine, suspect an interrupt arrived before a valid handler path existed. If keyboard input produces no response, check whether IRQ1 is unmasked, whether the keyboard handler is installed at vector 33, whether the handler reads port 0x60, and whether it acknowledges the PIC.
<!-- page: 310 -->
A debug function can print interrupt state.
## Rust
rustuse x86_64::registers::rflags::RFlags;
pub fn print_interrupt_state() { let flags = RFlags::read();
if flags.contains(RFlags::INTERRUPT_FLAG) { crate::kprintln!("interrupt flag: enabled"); } else { crate::kprintln!("interrupt flag: disabled"); }
crate::kprintln!("timer ticks: {}", crate::drivers::timer::ticks());}This can be exposed through the shell or called during startup. If interrupts are enabled but timer ticks never increase, the problem may be PIC configuration, timer configuration, or the IDT vector. If interrupts are disabled when you expected them to be enabled, check initialization order.
The best debugging workflow is layered. Start with serial checkpoints because they are fast. Use QEMU logs when the kernel resets or fails before output. Use GDB when you need exact control, breakpoints, registers, or stack contents. Use kernel-side register printouts when you need diagnostics without a debugger. Use shell commands to trigger controlled tests after boot. Use automated tests to catch regressions. These tools reinforce each other.
By this stage, the kernel has enough structure to be worked on seriously. It has modules with clear responsibilities, an interactive shell for controlled inspection, a test path that can report through serial and exit QEMU, and a debugging workflow that reaches below ordinary print statements when needed. That combination matters. Building operating-system code is not only about adding features. It is about keeping the system observable and understandable as those features interact.