Skip to content
ImagineWorld

Interrupts, Exceptions, and Fault Handling

node_idnode-book_writing-operating-systems-in-rust_chapter-05-interrupts-exceptions-and-fault-handling
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num5
chapter_titleInterrupts, Exceptions, and Fault Handling
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 5 — Interrupts, Exceptions, and Fault Handling

Section titled “Chapter 5 — Interrupts, Exceptions, and Fault Handling”

Chapter 5: Interrupts, Exceptions, and Fault Handling

Section titled “Chapter 5: Interrupts, Exceptions, and Fault Handling”

Interrupts and exceptions are where the kernel stops being a program that only runs straight-line startup code and begins responding to the processor. Until now, the kernel has controlled execution mostly by calling functions in a known order. That is useful, but it is not enough for an operating system. The processor can report faults. Hardware can request attention. Debug instructions can intentionally interrupt execution. Invalid memory accesses can redirect control into a page-fault handler. Timer and keyboard devices will later depend on the same foundation.

This part of kernel development must be handled with care because interrupts and exceptions are not ordinary function calls. The CPU enters a handler according to tables and descriptors that the kernel prepares. The handler must use the correct calling convention. Some exceptions include error codes and some do not. Some failures can occur while the kernel is already trying to handle another failure. If the handler entry path is wrong, the machine may reset before anything can be printed. That is why the Interrupt Descriptor Table, the Task State Segment, and dedicated fault stacks are closely connected.

A Rust kernel can make this stage much more manageable by expressing interrupt setup through clear functions, typed handler signatures, and narrow unsafe blocks. The unsafe parts do not disappear, because the CPU is still using architecture-specific tables and stack behavior. The improvement is that the danger can be isolated. Instead of spreading raw descriptor manipulation through the kernel, you can build one interrupt module that owns the IDT, installs handlers, connects selected handlers to known-good stacks, and provides controlled testing paths.

Good exception handling does not only prevent crashes. It gives you evidence. A page fault should print the accessed address, the error code, and the instruction pointer. A general protection fault should show that the CPU rejected an invalid protected operation. A breakpoint should prove that the

IDT is installed and the handler ABI is correct. A double-fault handler should use a dedicated stack so the kernel can report a serious failure rather than silently resetting. These diagnostics are not optional polish. They are what allow you to keep building safely after the kernel becomes more complex.

5.1: Building the Interrupt Descriptor Table

Section titled “5.1: Building the Interrupt Descriptor Table”

The Interrupt Descriptor Table is the structure the x86_64 processor consults when an interrupt or exception occurs. Each entry in the table points to a handler for a specific vector. Some vectors are reserved for CPU-defined exceptions, such as breakpoint, page fault, general protection fault, and double fault. Later, hardware interrupts such as timer and keyboard events will also be routed through IDT entries after the interrupt controller is configured. Before any of that can work, the kernel must create an IDT, fill the entries it cares about, and load the table into the CPU.

An interrupt or exception handler is not called like an ordinary Rust function. When the CPU enters a handler, it saves processor state onto the stack, switches stacks in certain cases, may push an error code, and transfers control according to the descriptor entry. The function signature must match what the processor pushes. In Rust, the extern "x86-interrupt" calling convention is used for these handlers because it tells the compiler to generate function entry and exit code appropriate for x86 interrupt handling. This is very different from extern "C", which is used for ordinary C-compatible function boundaries.

The first IDT should handle a breakpoint exception because it is easy to trigger intentionally and does not represent a broken system. The breakpoint exception is raised by the int3 instruction. It is useful for proving that the IDT is loaded and that a handler can run and return. If the breakpoint handler prints a message and execution continues, you have strong evidence that the IDT path works.

Rust

use lazy_static::lazy_static;
use x86_64::structures::idt::{InterruptDescriptorTable,
InterruptStackFrame};
lazy_static! {
static ref IDT: InterruptDescriptorTable = {
let mut idt = InterruptDescriptorTable::new();
idt.breakpoint.set_handler_fn(breakpoint_handler);
idt
};
}
pub fn init() {
IDT.load();
}
extern "x86-interrupt" fn breakpoint_handler(stack_frame:
InterruptStackFrame) {
serial_println!("breakpoint exception");
serial_println!("{:#?}", stack_frame);
}

This code creates a static IDT and installs a breakpoint handler. The lazy_static pattern ensures that the table is initialized before it is loaded, while still allowing construction code that is more complex than a plain constant. The init function loads the IDT into the CPU through the lidt instruction hidden behind the table abstraction. After this call, the processor uses this table for exceptions and interrupts.

The breakpoint_handler receives an InterruptStackFrame. This frame contains saved state from the interrupted context, including the instruction pointer, code segment, flags, stack pointer, and stack segment when applicable. Printing it is useful because it shows where the exception occurred. For breakpoint tests, the instruction pointer should point to the location after the int3 instruction, which is expected behavior.

The IDT must live in stable memory. Loading the IDT does not copy the whole table into the processor. The CPU stores a pointer to it. If the table were allocated on a function stack and then the function returned, the CPU would later read invalid memory when an exception occurred. This is why the IDT is static. Kernel descriptor tables should be placed in memory that remains valid and mapped for as long as the CPU may use them.

Once the IDT is initialized, the kernel can trigger a breakpoint to confirm the path.

#[unsafe(no_mangle)]
pub extern "C" fn _start() -> ! {
serial::init();
serial_println!("kernel entered");
gdt::init();
serial_println!("gdt loaded");
interrupts::init_idt();
serial_println!("idt loaded");
x86_64::instructions::interrupts::int3();
serial_println!("continued after breakpoint");
loop {
x86_64::instructions::hlt();
}
}

This startup sequence deliberately triggers the breakpoint after loading the GDT and IDT. If the kernel prints the breakpoint message and then prints continued after breakpoint, the handler returned successfully. That confirms more than the existence of the table. It confirms that the CPU found the IDT entry, entered the handler using the correct calling convention, and resumed execution after the handler returned.

A stronger IDT setup includes handlers for several CPU exceptions from the start. Some handlers can return, while others should halt because the kernel cannot safely continue. Breakpoints can return. Page faults usually should not return in an early kernel because the memory manager is not yet able to resolve missing pages dynamically. General protection faults usually indicate a serious invalid operation. Double faults should never return in this stage.

use lazy_static::lazy_static;

use x86_64::structures::idt::{ InterruptDescriptorTable, InterruptStackFrame, PageFaultErrorCode, };

lazy_static! { static ref IDT: InterruptDescriptorTable = { let mut idt = InterruptDescriptorTable::new();

idt.breakpoint.set_handler_fn(breakpoint_handler);
idt.page_fault.set_handler_fn(page_fault_handler);
idt.general_protection_fault.set_handler_fn(general_protection_fault_handler);
idt
};

}

pub fn init_idt() { IDT.load(); }

extern “x86-interrupt” fn breakpoint_handler(stack_frame: InterruptStackFrame) { serial_println!(“breakpoint exception”); serial_println!(”{}”, stack_frame); }

extern “x86-interrupt” fn page_fault_handler( stack_frame: InterruptStackFrame, error_code: PageFaultErrorCode, ) { let address = x86_64::registers::control::Cr2::read();

serial_println!("page fault");
serial_println!("accessed address: {:?}", address);
serial_println!("error code: {:?}", error_code);
serial_println!("stack frame: {:?}", stack_frame);
crate::arch::halt_loop();

}

extern “x86-interrupt” fn general_protection_fault_handler( stack_frame: InterruptStackFrame, error_code: u64, ) { serial_println!(“general protection fault”); serial_println!(“error code: {}”, error_code); }

serial_println!("stack frame: {:?}", stack_frame);
crate::arch::halt_loop();
}

This version introduces handlers with different signatures. The breakpoint handler receives only the interrupt stack frame. The page-fault handler receives a stack frame and a page-fault error code. The general protection fault handler receives a stack frame and an error code. The signatures matter. If a handler expects an error code when the CPU did not push one, or fails to expect one when the CPU did push one, the stack layout will be wrong and returning from the handler can corrupt execution.

This is one of the reasons using typed architecture support is valuable. It helps match common exception signatures and reduces the chance of manually creating invalid descriptors. Even so, the meaning remains your responsibility. The CPU does not know that your Rust function is conceptually a page-fault handler. It follows the IDT entry and calling convention. If the table entry and function signature do not match the hardware event, the failure can be immediate and confusing.

The IDT should be loaded before intentionally causing any exception. It should also be loaded before enabling hardware interrupts later. Loading the IDT does not enable external interrupts by itself. It only tells the processor where to go if an event needs handling. Enabling interrupts with an empty or incomplete IDT is dangerous because the CPU may receive a hardware interrupt and have no valid path to handle it. At this stage, keep external interrupts disabled until the IDT and interrupt controller setup are both ready.

It is also useful to separate exception initialization from hardware interrupt initialization. CPU exceptions can be configured first. Hardware interrupts require more work because the interrupt controller must route device signals to selected vectors and handlers must acknowledge the controller. Keeping those stages separate makes debugging easier. If a breakpoint works but a timer interrupt fails later, the IDT mechanism itself is probably working, and the problem may be in the interrupt controller, vector mapping, handler logic, or acknowledgement path.

The IDT is not just a table to satisfy the processor. It is the beginning of serious kernel diagnostics. A good IDT lets the kernel report faults instead of disappearing. Once page faults, general protection faults, and double faults produce readable serial output, later memory and hardware work becomes far less blind. The machine may still stop, but it stops with information.

5.2: Handling Breakpoints, Page Faults, and General Protection Faults

Section titled “5.2: Handling Breakpoints, Page Faults, and General Protection Faults”

Different exceptions mean different things, and a useful kernel treats them differently. A breakpoint exception is usually intentional. A page fault reports a memory-access problem. A general protection fault reports a violation of protected execution rules. Grouping all exceptions under a vague “fault happened” message loses the information that the CPU is trying to give you. Good exception handlers turn CPU events into clear diagnostics.

The breakpoint exception is the safest place to begin because it can be triggered deliberately and returned from. The int3 instruction raises a breakpoint exception. Debuggers use this mechanism, but the kernel can also call it directly during early setup to prove that the IDT is active. If the breakpoint handler runs, prints the stack frame, and returns, you know that the CPU can enter and leave at least one exception handler correctly.

extern "x86-interrupt" fn breakpoint_handler(stack_frame: InterruptStackFrame) {
serial_println!("breakpoint exception");
serial_println!("instruction pointer: {:?}", stack_frame.instruction_pointer);
serial_println!("stack pointer: {:?}", stack_frame.stack_pointer);
}

This handler prints only the most immediately useful fields instead of dumping the whole frame. The instruction pointer tells you where execution will continue after the breakpoint handler returns. The stack pointer tells

you what stack was active. During early testing, this confirms that the handler is running in the expected context.

A breakpoint test should be placed after the IDT is loaded. If it is placed before IDT initialization, the CPU may not have a valid handler path. The test should also print after the breakpoint so you can confirm that execution resumed.

Rust

pub fn test_breakpoint_handler() {
serial_println!("triggering breakpoint");
x86_64::instructions::interrupts::int3();
serial_println!("returned from breakpoint handler");
}

If you see the first message but not the second, the handler did not return successfully. If you do not see the handler’s message, the IDT entry may not be installed or the IDT may not be loaded. If the virtual machine resets, the exception path may be invalid enough to cause a fault chain. A working breakpoint handler is a valuable first proof before testing more dangerous faults.

The page-fault handler is more important for future memory management. A page fault occurs when the processor cannot complete a memory access according to the current page tables and permissions. The cause may be that the page is not present, that the access violated permissions, that a write targeted a read-only page, that instruction fetch was blocked, or that user-mode code attempted something it was not allowed to do. The handler receives an error code that describes the access, and the processor stores the faulting virtual address in cr2.

Rust

use x86_64::registers::control::Cr2;
use x86_64::structures::idt::{InterruptStackFrame, PageFaultErrorCode};
extern "x86-interrupt" fn page_fault_handler(
stack_frame: InterruptStackFrame,
error_code: PageFaultErrorCode,
) {
let accessed_address = Cr2::read();
serial_println!("page fault");
serial_println!("accessed address: {:?}", accessed_address);
serial_println!("error code: {:?}", error_code);
serial_println!("instruction pointer: {:?}", stack_frame.instruction_pointer);
serial_println!("stack pointer: {:?}", stack_frame.stack_pointer);
crate::arch::halt_loop();
}

This handler stops the kernel after printing the fault information. That is the right behavior for an early kernel. Later, when virtual memory is more advanced, some page faults can be handled deliberately. For example, a mature system may lazily allocate pages, grow stacks, map files, or enforce copy-on-write behavior. This kernel is not there yet. At this stage, a page fault means the kernel accessed memory that its current mappings do not permit, and continuing would likely hide or worsen the bug.

The accessed address from cr2 is one of the most useful values in low-level debugging. If it is 0x0 or a small address, suspect a null pointer or uninitialized pointer. If it is near the heap range you planned to use, suspect that heap pages were not mapped. If it is near a framebuffer address, suspect that the framebuffer physical memory was not mapped into virtual memory. If it is near the instruction pointer, suspect that code execution moved into an unmapped area. The address alone does not prove the cause, but it gives you a strong starting point.

The page-fault error code must not be ignored. It separates a missing page from a protection violation. That distinction changes the diagnosis. A missing page suggests that the mapping does not exist. A protection violation suggests that the mapping exists but does not allow the requested operation. For example, writing to a read-only page and reading an unmapped page are different bugs. The handler can print these distinctions directly.

<!-- page: 131 -->
rust
use x86_64::structures::idt::PageFaultErrorCode;
fn print_page_fault_reason(error_code: PageFaultErrorCode) {
if error_code.contains(PageFaultErrorCode::PROTECTION_VIOLATION) {
serial_println!("reason: protection violation");
} else {
serial_println!("reason: page not present");
}
if error_code.contains(PageFaultErrorCode::CAUSED_BY_WRITE) {
serial_println!("access type: write");
} else {
serial_println!("access type: read or fetch");
}
if error_code.contains(PageFaultErrorCode::USER_MODE) {
serial_println!("origin: user mode");
} else {
serial_println!("origin: kernel mode");
}
if error_code.contains(PageFaultErrorCode::INSTRUCTION_FETCH) {
serial_println!("instruction fetch was blocked");
}
}

This helper keeps the handler readable. It also makes the output easier to scan when you are debugging a failing boot. In a kernel, diagnostic quality matters. A page fault message that includes the address, reason, access type, origin, instruction pointer, and stack pointer is far more useful than a message that simply says page fault.

The page-fault handler can then call the helper.

extern "x86-interrupt" fn page_fault_handler(
stack_frame: InterruptStackFrame,
error_code: PageFaultErrorCode,
) {
let accessed_address = Cr2::read();
serial_println!("page fault");
serial_println!("accessed address: {:?}", accessed_address);
print_page_fault_reason(error_code);
}
serial_println!("instruction pointer: {:?}", stack_frame.instruction_pointer);
serial_println!("stack pointer: {:?}", stack_frame.stack_pointer);
crate::arch::halt_loop();
}

This version is still small, but it gives the kind of output that helps you fix real bugs. When memory management is introduced, this handler will quickly become one of the most valuable parts of the kernel.

The general protection fault is different. It is raised when the processor detects a protection-rule violation that is not better represented by another exception. Common causes include invalid segment selectors, invalid descriptor use, certain privileged instruction issues, bad control-register operations, canonical address violations in some cases, and other protected-mode or long-mode rule violations. In early kernel work, a general protection fault often indicates that CPU structure setup or a privileged operation is wrong.

extern "x86-interrupt" fn general_protection_fault_handler(
stack_frame: InterruptStackFrame,
error_code: u64,
) {
serial_println!("general protection fault");
serial_println!("error code: {}", error_code);
serial_println!("instruction pointer: {:?}", stack_frame.instruction_pointer);
serial_println!("stack pointer: {:?}", stack_frame.stack_pointer);
serial_println!("stack frame: {:?}", stack_frame);
crate::arch::halt_loop();
}

The general protection fault handler should halt in an early kernel. Unlike a breakpoint, this is not normally a friendly event. It usually means the CPU rejected something fundamental. The error code may identify a selector-related cause in some cases, but it is often not enough on its own. The instruction pointer is crucial because it tells you which instruction caused

the fault. If the fault occurs while loading the TSS, setting a segment register, enabling a feature, or performing an invalid memory access pattern, the instruction pointer points directly at the failing operation.

A useful improvement is to keep all fatal exception exits consistent. Instead of writing a halt loop inside every handler, create a function that prints a final message and halts. This keeps the behavior uniform.

Rust

pub fn fatal_exception_stop() -> ! {
serial_println!("kernel stopped after fatal exception");
loop {
x86_64::instructions::hlt();
}
}

Handlers can then call this function.

Rust

extern "x86-interrupt" fn general_protection_fault_handler(
stack_frame: InterruptStackFrame,
error_code: u64,
) {
serial_println!("general protection fault");
serial_println!("error code: {}", error_code);
serial_println!("instruction pointer: {:?}", stack_frame.instruction_pointer);
serial_println!("stack pointer: {:?}", stack_frame.stack_pointer);
crate::exceptions::fatal_exception_stop();
}

This does not change the CPU behavior, but it improves code consistency. As more fatal handlers are added, a shared stop path prevents each handler from drifting into slightly different behavior.

Exception handlers should avoid unnecessary complexity. They run at moments when the kernel may already be in a damaged state. The page-fault handler may run because memory mappings are wrong. The general

protection fault handler may run because descriptor or CPU state is wrong. The double-fault handler may run because the first exception path failed. These handlers should not allocate, should not take locks carelessly, and should not call large subsystems that may depend on the state that just failed. Serial output is useful because it can be kept small and direct. Complex formatting is convenient, but keep fatal paths practical.

This does not mean all diagnostic output must be crude. It means the handler should use a logging path that is known to work this early. If the normal console writer locks both VGA and serial output, and the fault occurred while one of those locks was held, the handler may deadlock. In early versions, that risk may be acceptable. As the kernel matures, fatal exception handlers may need emergency serial output that avoids normal locks. The design can evolve, but the principle stays the same: a fault handler must be more reliable than the code that failed.

Once breakpoint, page-fault, and general protection fault handlers are installed, the kernel is much better prepared for later work. A wrong memory access can produce a readable report. A descriptor mistake can identify the failing instruction. A deliberate breakpoint can prove the IDT still works after changes. This is how exception handling becomes part of the development workflow, not just an architecture requirement.

5.3: Preventing and Debugging Double Faults

Section titled “5.3: Preventing and Debugging Double Faults”

A double fault is one of the most important early exceptions to understand because it often marks the difference between a readable failure and a silent reset. A double fault happens when the processor encounters an exception while trying to call the handler for a previous exception, and the pair of exceptions cannot be handled separately. It is not simply “two bugs happened.” It is a specific CPU-level failure during exception delivery or handling.

In early kernel development, double faults often come from stack problems, invalid handler addresses, missing page mappings, or broken descriptor setup. A page fault may occur, then the CPU tries to call the page-fault handler. If the handler address is unmapped, the stack is invalid, or the IDT

entry is wrong, the CPU cannot complete the handler call. That can escalate to a double fault. If the double-fault handler is also not callable, or if it uses the same broken stack, the processor can triple-fault and reset. At that point, QEMU may simply restart or freeze, and you may see no useful message.

The key to making double faults debuggable is to give the double-fault handler a separate known-good stack. This is done through the Task State Segment and the Interrupt Stack Table. The GDT must include a TSS descriptor, the TSS must contain a valid stack pointer in the chosen IST slot, and the IDT double-fault entry must be configured to use that IST slot. These pieces must agree.

First, the kernel reserves a dedicated stack and stores its top address in the TSS. The stack must live in static memory or another region guaranteed to remain valid. It must not be a local variable. It must remain mapped. It should be large enough for the handler and its diagnostic output.

use lazy_static::lazy_static;
use x86_64::VirtAddr;
use x86_64::structures::tss::TaskStateSegment;
pub const DOUBLE_FAULT_IST_INDEX: u16 = 0;
#[repr(align(16))]
struct FaultStack {
bytes: [u8; FaultStack::SIZE],
}
impl FaultStack {
const SIZE: usize = 4096 * 5;
const fn new() -> Self {
Self {
bytes: [0; Self::SIZE],
}
}
fn top(&self) -> VirtAddr {
VirtAddr::from_ptr(self.bytes.as_ptr()) + Self::SIZE
}
}

}

static DOUBLE_FAULT_STACK: FaultStack = FaultStack::new();

lazy_static! { pub static ref TSS: TaskStateSegment = { let mut tss = TaskStateSegment::new();

tss.interrupt_stack_table[DOUBLE_FAULT_IST_INDEX as usize] =
DOUBLE_FAULT_STACK.top();
tss
};

}

This code reserves a fault stack and connects it to the first IST slot. The stack grows downward, so the top address is the start address plus the stack size. The type wrapper gives the stack a clear alignment and keeps the raw bytes from being casually accessed as ordinary mutable state.

Next, the GDT must contain a TSS descriptor and the CPU must load the TSS selector.

use lazy_static::lazy_static;
use x86_64::instructions::segmentation::{CS, Segment};
use x86_64::instructions::tables::load_tss;
use x86_64::structures::gdt::{Descriptor, GlobalDescriptorTable, SegmentSelector};
use crate::tss::TSS;
lazy_static! {
static ref GDT: (GlobalDescriptorTable, Selectors) = {
let mut gdt = GlobalDescriptorTable::new();
let code_selector =
gdt.append(Descriptor::kernel_code_segment());
let tss_selector =
gdt.append(Descriptor::tss_segment(&TSS));
(
gdt,
Selectors {
code_selector,

tss_selector, }, );

};

struct Selectors { code_selector: SegmentSelector, tss_selector: SegmentSelector, }

pub fn init() { GDT.0.load();

unsafe {
CS::set_reg(GDT.1.code_selector);
load_tss(GDT.1.tss_selector);
}

}

The unsafe block is justified because loading segment and TSS state changes the processor execution environment. The descriptors must be valid, and the TSS must remain available. If the TSS descriptor is wrong, load_tss can fault. If that fault occurs before a working IDT is installed, the machine may reset. This is why serial checkpoints around GDT and TSS initialization are useful.

Finally, the IDT double-fault entry must use the same IST index.

use lazy_static::lazy_static;
use x86_64::structures::idt::{InterruptDescriptorTable, InterruptStackFrame};
use crate::tss::DOUBLE_FAULT_IST_INDEX;
lazy_static! {
static ref IDT: InterruptDescriptorTable = {
let mut idt = InterruptDescriptorTable::new();
unsafe {
idt.double_fault
.set_handler_fn(double_fault_handler)
.set_stack_index(DOUBLE_FAULT_IST_INDEX);
}
}
}
<!-- page: 138 -->
rust
idt
};
pub fn init_idt() {
IDT.load();
}
extern "x86-interrupt" fn double_fault_handler(
stack_frame: InterruptStackFrame,
error_code: u64,
) -> ! {
serial_println!("double fault");
serial_println!("error code: {}", error_code);
serial_println!("stack frame: {:?}", stack_frame);
crate::arch::halt_loop();
}

The set_stack_index call is unsafe because Rust cannot verify that the index refers to a configured TSS entry. The programmer must ensure that the TSS exists, that it has a valid stack pointer at that index, that the GDT has been loaded, and that the TSS has been loaded before the double-fault handler can run. This is a clear example of architecture-specific safety. The code is valid only because the CPU setup sequence establishes the required state.

The double-fault handler should return !. In an early kernel, a double fault is fatal. It means exception handling itself failed. Continuing would be unreliable. The best behavior is to print the diagnostic data and halt. The error code for a double fault is typically zero, but the handler signature includes it because the CPU pushes one for this exception.

The initialization order matters. The kernel should initialize serial output first, then load the GDT and TSS, then load the IDT. After those steps, a double-fault handler can use the dedicated stack.

pub fn init_cpu_exception_state() {
crate::serial::init();
serial_println!("serial online");
}

crate::gdt::init(); serial_println!(“gdt and tss loaded”);

crate::interrupts::init_idt(); serial_println!(“idt loaded”);

This sequence gives you clear evidence of progress. If the kernel fails before gdt and tss loaded, inspect GDT and TSS setup. If it fails after that but before idt loaded, inspect IDT construction. If it fails only when testing a double fault, inspect the IST index, stack address, and handler signature.

To test the double-fault stack, a common technique is to cause a stack overflow after the double-fault handler is configured. The recursive function must prevent the compiler from optimizing away the recursion. Using a volatile read is one way to force stack use in the recursive path.

#[allow(unconditional_recursion)]
fn stack_overflow() {
stack_overflow();
unsafe {
core::ptr::read_volatile(40);
}
}
pub fn test_double_fault() {
serial_println!("triggering stack overflow");
stack_overflow();
}

This function intentionally recurses until the stack overflows. When guard pages and paging are configured appropriately, the overflow can cause a page fault while using a bad stack, which may escalate to a double fault. In very early setups without guard pages, recursion may corrupt adjacent memory instead, so the behavior depends on stack layout and mappings. This test should be used with care and should not remain in normal startup code.

<!-- page: 140 -->
A cleaner approach is to keep such tests behind a conditional compilation flag or a dedicated test entry. You do not want the normal kernel boot path to intentionally crash every time.
## Rust
```rust
#[cfg(feature = "test-double-fault")]
pub fn maybe_test_double_fault() {
test_double_fault();
}
#[cfg(not(feature = "test-double-fault"))]
pub fn maybe_test_double_fault() {}

This lets you enable the test only when needed. A fatal exception test should be deliberate. It should not be mixed into ordinary initialization after you have already proved the handler works.

Debugging double faults requires patience because the original cause may not be the double-fault handler itself. The double fault may be the second visible stage of an earlier failure. If a page-fault handler is missing or broken, a memory bug may become a double fault. If the IDT entry points to an unmapped handler address, the CPU may double-fault while trying to enter the first handler. If the current stack is invalid, even a correctly installed page-fault handler may not be callable without an IST entry. The double-fault message tells you that exception delivery failed badly, but you still need to look backward to find the first cause.

QEMU logs help when double faults become triple faults. Running with interrupt and reset logging can show exception sequences that occur before serial output appears.

Terminal window
qemu-system-x86_64 \
-drive format=raw,file=target/kernel.img \
-serial stdio \
-no-reboot \
-no-shutdown \
-d int,cpu_reset \
-D target/qemu.log

If the log shows a page fault followed by a double fault followed by a reset, you likely do not have a working double-fault path. If the log shows the double-fault handler running and the serial output prints the stack frame, the dedicated stack is doing its job. The kernel still has a fatal bug, but now it is a bug with evidence.

Preventing double faults is not about pretending serious faults will not happen. It is about giving the processor a reliable emergency path. Dedicated stacks, correct TSS setup, correct IDT entries, and conservative handler behavior make that path possible. Once the kernel can report a double fault instead of resetting, you have removed one of the most frustrating early blind spots.

Exception handlers should be tested deliberately. It is not enough to install an IDT and assume the handlers work. A handler can have the wrong signature, the IDT may not be loaded, the TSS stack index may be wrong, or a panic inside the handler may hide the original problem. Testing each handler in QEMU gives you controlled evidence that the CPU can enter the handler, the handler can print useful diagnostics, and the kernel stops or resumes in the expected way.

QEMU is especially useful here because exception testing often involves intentionally breaking execution. You do not want to do early fatal fault tests on physical hardware. In QEMU, the machine can be restarted quickly, serial output can be captured, CPU reset behavior can be logged, and the debugger can attach before execution begins. This makes QEMU the right place to prove exception paths before adding more kernel complexity.

Start with a runner that attaches serial output and prevents immediate reboot. These options should be part of the ordinary development workflow, not special emergency tools.

Shell

qemu-system-x86_64 \

-drive format=raw,file=target/kernel.img
-serial stdio
-no-reboot
-no-shutdown

With this command, serial output appears in the terminal. If the kernel halts after a fatal exception, QEMU stays open. If the CPU would normally reset after a triple fault, -no-reboot helps prevent the reset from hiding the failure. For deeper diagnosis, enable QEMU logging.

bash qemu-system-x86_64
-drive format=raw,file=target/kernel.img
-serial stdio
-no-reboot
-no-shutdown
-d int,cpu_reset
-D target/qemu.log

The log file is useful when serial output stops before the handler prints. It can show whether an exception occurred, whether another exception followed, and whether the virtual CPU reset. When exception handling is broken, serial output alone may not be enough because the kernel may fail before it can write anything.
The breakpoint handler is the first test because it is expected to return. The kernel can trigger it and then print a message after it returns.
## Rust
```rust
pub fn test_breakpoint() {
serial_println!("test: breakpoint before");
x86_64::instructions::interrupts::int3();
serial_println!("test: breakpoint after");
}

The expected output should include the message before the breakpoint, the breakpoint handler’s message, and the message after the breakpoint. If the final message is missing, the handler did not return properly. If the handler message is missing, the IDT entry may not be installed or the IDT may not be loaded. If QEMU resets, the exception path is seriously broken. This test

is safe enough to keep as an early diagnostic function, although it should not necessarily run on every normal boot after the IDT is known to work.

A page-fault test should be more careful because it intentionally causes a fatal condition in the early kernel. One direct way is to read from an address that is not mapped. The exact address should be chosen according to the current memory map. Using a clearly invalid address can trigger a page fault, but some addresses may be canonical or non-canonical in ways that produce different exceptions. For a simple early test, reading from a high invalid pointer can be effective if it is not mapped.

Rust

pub fn test_page_fault() {
serial_println!("test: page fault before");
let pointer = 0xdead_beef as *const u64;
unsafe {
core::ptr::read_volatile(pointer);
}
serial_println!("test: page fault after");
}

The final message should not print. If it does, then the address was unexpectedly readable or the compiler behavior did not produce the access you intended. The volatile read is used to force the memory access to happen. Without it, the compiler might remove an unused read. The page-fault handler should print the accessed address from cr2, the error code, and the saved instruction pointer.

This test is intentionally fatal. It should be run only when you are testing the page-fault handler. Do not leave it in normal startup. A good pattern is to place fatal tests behind feature flags.

Rust

pub fn run_exception_tests() {
test_breakpoint();
}
#[cfg(feature = "test-page-fault")]
test_page_fault();
#[cfg(feature = "test-double-fault")]
crate::double_fault_tests::test_double_fault();

This lets the normal kernel boot run the breakpoint test or no tests at all, while fatal tests are enabled only when needed. Feature-gated tests keep the project controlled. They also prevent confusion when returning to normal development after a deliberate crash test.

A general protection fault can be harder to test cleanly because many ways of causing it involve privileged state and may vary depending on the current CPU setup. One controlled approach is to load an invalid or inappropriate segment selector, but this should be done carefully because it can destabilize the CPU state. Another approach is to test the handler indirectly when developing GDT, TSS, or descriptor code. For early educational testing, it is usually enough to install the handler and rely on QEMU logs and controlled CPU setup changes to validate it when a real GPF occurs. If you do create a deliberate GPF test, isolate it behind a feature flag and expect the kernel to halt.

#[cfg(feature = "test-general-protection-fault")]
pub fn test_general_protection_fault() {
serial_println!("test: general protection fault before");
unsafe {
core::arch::asm!(
"mov ax, 0x28",
"mov ds, ax",
options(nostack, preserves_flags)
);
}
serial_println!("test: general protection fault after");
}

This test attempts to load a data segment selector that may be invalid for the current GDT. Whether it faults depends on the actual descriptor table

setup. This is why GPF tests should be treated with care. The purpose is not to create a universal magic fault instruction. The purpose is to understand that some CPU-state violations can be tested deliberately, but only when you know the descriptor state you have installed.

Fatal tests benefit from a QEMU exit mechanism once the project has a test harness. Instead of halting forever, a test kernel can exit QEMU with success or failure codes. That makes automated testing possible. Before that mechanism exists, manual serial output is enough. After it exists, exception tests can become part of a controlled test suite.

#[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 code writes an exit code to a special I/O port commonly used in QEMU test setups when the emulator is configured to treat that port as an exit device. It is unsafe because it performs port I/O. The exact QEMU configuration must match the port and value behavior expected by the test. Without the matching QEMU device configuration, the write may do nothing useful.

A matching QEMU command can configure the debug-exit device.

Terminal window
qemu-system-x86_64 \
-drive format=raw,file=target/kernel.img \
-serial stdio \
-no-reboot \
-no-shutdown \
-device isa-debug-exit,iobase=0xf4,iosize=0x04

With this setup, the kernel can signal test success or failure to the host environment. This becomes especially useful for breakpoint tests and other non-fatal handler tests. Fatal exception tests need special handling because the expected result may be that a handler runs and exits QEMU with success rather than halting.

A test-specific breakpoint handler can exit QEMU after proving it was called.

extern "x86-interrupt" fn test_breakpoint_handler(
_stack_frame: InterruptStackFrame,
) {
serial_println!("breakpoint handler reached");
crate::qemu::exit_qemu(crate::qemu::QemuExitCode::Success);
}

This handler would be used only in a test IDT, not necessarily in the normal kernel IDT. The normal handler should return so the kernel can continue. The test handler exits because its purpose is to prove handler entry. This distinction is useful. A kernel can have normal runtime behavior and separate test behavior without confusing the two.

A page-fault test can also exit successfully from the page-fault handler if the test intentionally triggered the fault. In normal operation, a page fault halts. In a test kernel, reaching the page-fault handler with the expected address can mean the test passed.

extern "x86-interrupt" fn test_page_fault_handler(
_stack_frame: InterruptStackFrame,
_error_code: PageFaultErrorCode,
) {
let address = x86_64::registers::control::Cr2::read();
serial_println!("page fault handler reached");
serial_println!("fault address: {:?}", address);
crate::qemu::exit_qemu(crate::qemu::QemuExitCode::Success);
}

This pattern prevents fatal tests from hanging forever during automated runs. It also proves that the handler was reached, not merely that the machine crashed. That distinction matters. A crash after a deliberate invalid access does not prove the page-fault handler works. Successful handler output or a test exit code does.

The double-fault test needs even more care because it may reset the machine if the TSS or IST setup is wrong. A test double-fault handler can exit QEMU with success once reached.

extern "x86-interrupt" fn test_double_fault_handler(
_stack_frame: InterruptStackFrame,
_error_code: u64,
) -> ! {
serial_println!("double fault handler reached");
crate::qemu::exit_qemu(crate::qemu::QemuExitCode::Success);
}

This handler still returns !, because double-fault handlers should not return. In the test case, exiting QEMU replaces halting as the non-returning action. If QEMU exits with success, the double-fault path reached the handler. If QEMU resets or hangs, the test failed. QEMU logs can then show whether the CPU reached the double fault and whether a triple fault followed.

When tests require different handlers from normal operation, use separate initialization paths or conditional compilation. Do not make the normal kernel handler behave strangely just to satisfy tests. A clean design has a

normal IDT for runtime and test-specific IDTs or handler choices for controlled exception tests.

#[cfg(test)]
pub fn init_idt() {
TEST_IDT.load();
}
#[cfg(not(test))]
pub fn init_idt() {
IDT.load();
}

This pattern keeps the public initialization name the same while allowing different tables depending on the build. The normal kernel gets normal behavior. The test kernel gets handlers that report test results. This is cleaner than filling runtime handlers with test-only branches.

Exception testing should become part of the development rhythm. After changing GDT setup, test breakpoints again. After changing TSS or double-fault stack code, test the double-fault path. After changing paging code, keep the page-fault handler informative. After modifying logging locks, make sure fatal handlers can still print. These tests protect the foundation that later kernel features rely on.

QEMU does not make exception handling safe by itself. It gives you a place to observe it. The safety comes from correct IDT entries, correct handler signatures, valid stacks, careful initialization order, and disciplined test design. When those pieces are in place, exceptions stop being silent disasters. They become structured signals that the kernel can report, test, and use to guide the next stage of development.