Skip to content
ImagineWorld

Bare-Metal Output, Panic Handling, and Early Debugging

node_idnode-book_writing-operating-systems-in-rust_chapter-03-bare-metal-output-panic-handling-and-early-debugging
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num3
chapter_titleBare-Metal Output, Panic Handling, and Early Debugging
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 3 — Bare-Metal Output, Panic Handling, and Early Debugging

Section titled “Chapter 3 — Bare-Metal Output, Panic Handling, and Early Debugging”

Chapter 3: Bare-Metal Output, Panic Handling, and Early Debugging

Section titled “Chapter 3: Bare-Metal Output, Panic Handling, and Early Debugging”

A kernel without output is difficult to trust. It may be running correctly, failing immediately, sitting in a halt loop, resetting the virtual machine, or faulting before your first visible operation. Early output is therefore not a cosmetic feature. It is one of the first survival tools in kernel development. Before the kernel has a display driver, filesystem, shell, allocator, keyboard input, or exception reporting, it needs a way to say where execution has reached.

Bare-metal output also teaches an important difference between application programming and kernel programming. In an ordinary Rust application, printing is easy because the operating system provides standard output. The application writes to a stream, the runtime and standard library handle formatting and buffering, and the operating system delivers the bytes to a terminal or file. In a kernel, none of that exists unless the kernel builds it or receives help from the boot environment. There is no println! from std, no file descriptor, no terminal device, and no process to terminate cleanly when something goes wrong.

The early debugging path should be built in layers. Serial output comes first because it is simple, reliable in an emulator, and visible even when graphical output is not ready. Panic handling comes next because Rust requires a panic handler in a freestanding environment, and a silent panic is not useful. Screen output follows, either through VGA text mode or a framebuffer handed off by the bootloader. After those pieces are in place, failures become much easier to diagnose. You can place checkpoints in initialization code, print panic messages, confirm whether the kernel reached the entry point, and distinguish a boot failure from an output failure.

This stage also begins a habit that will matter throughout kernel development: make failure observable before adding complexity. It is tempting to rush into page tables, interrupts, heap allocation, and keyboard

input. That creates a fragile project. Each of those features can fail in ways that produce little or no visible feedback. A better foundation gives the kernel a small but dependable voice before more dangerous operations begin.

3.1: Writing to Serial Output Before Screen Output Works

Section titled “3.1: Writing to Serial Output Before Screen Output Works”

Serial output is one of the most useful early debugging tools for a kernel. It does not require a windowing system, a graphics mode, font rendering, a framebuffer abstraction, or keyboard input. In an emulator, serial bytes can be redirected to the terminal where you launched the virtual machine. This makes serial output ideal for the first visible proof that your kernel entry point was reached.

The serial port used in many early x86_64 kernel projects is the first PC-compatible serial port, often referred to as COM1. Its common base I/O port is 0x3f8. Writing to it is not the same as writing to normal memory. It uses port I/O, where the CPU communicates with hardware through a separate I/O address space. Rust does not provide safe high-level access to hardware ports because the compiler cannot know whether a port exists, whether it is ready, whether the access width is correct, or whether the operation is valid in the current execution environment. Port I/O is therefore unsafe and must be wrapped carefully.

The first version of serial output can be intentionally small. It can write one byte at a time to the serial data port. This is enough to prove that the kernel has entered Rust code and that QEMU is forwarding serial output correctly.

#![no_std]
#![no_main]
use core::panic::PanicInfo;
const COM1: u16 = 0x3f8;

Chapter 3: Bare-Metal Output, Panic Handling, and Early Debugging

Section titled “Chapter 3: Bare-Metal Output, Panic Handling, and Early Debugging”

A kernel without output is difficult to trust. It may be running correctly, failing immediately, sitting in a halt loop, resetting the virtual machine, or faulting before your first visible operation. Early output is therefore not a cosmetic feature. It is one of the first survival tools in kernel development. Before the kernel has a display driver, filesystem, shell, allocator, keyboard input, or exception reporting, it needs a way to say where execution has reached.

Bare-metal output also teaches an important difference between application programming and kernel programming. In an ordinary Rust application, printing is easy because the operating system provides standard output. The application writes to a stream, the runtime and standard library handle formatting and buffering, and the operating system delivers the bytes to a terminal or file. In a kernel, none of that exists unless the kernel builds it or receives help from the boot environment. There is no println! from std, no file descriptor, no terminal device, and no process to terminate cleanly when something goes wrong.

The early debugging path should be built in layers. Serial output comes first because it is simple, reliable in an emulator, and visible even when graphical output is not ready. Panic handling comes next because Rust requires a panic handler in a freestanding environment, and a silent panic is not useful. Screen output follows, either through VGA text mode or a framebuffer handed off by the bootloader. After those pieces are in place, failures become much easier to diagnose. You can place checkpoints in initialization code, print panic messages, confirm whether the kernel reached the entry point, and distinguish a boot failure from an output failure.

This stage also begins a habit that will matter throughout kernel development: make failure observable before adding complexity. It is tempting to rush into page tables, interrupts, heap allocation, and keyboard

input. That crea that produce kernel a sma begin.

Serial output does not require framebuffer abstr be redirected to th makes serial output point was reached

The serial port used in many early x86 compatible serial port, often referred to as is 0x3f8. Writing to it is not the same as writing to normal memory port I/O, where the CPU communicates with hardware through a I/O address space. Rust does not provide safe high-level access to hard ports because the compiler cannot know whether a port exists, whether it is ready, whether the access width is correct, or whether the operation is valid in the current execution environment. Port I/O is therefore unsafe and must be wrapped carefully.

The first version of serial output can be intentionally small. It can write one byte at a time to the serial data port. This is enough to prove that the kernel has entered Rust code and that QEMU is forwarding serial output correctly.

#![no_std]
#![no_main]
use core::panic::PanicInfo;
const COM1: u16 = 0x3f8;
#[unsafe(no_mangle)]
pub extern "C" fn _start() -> ! {
unsafe {
outb(COM1, b'K');
outb(COM1, b'E');
outb(COM1, b'R');
outb(COM1, b'N');
outb(COM1, b'E');
outb(COM1, b'L');
outb(COM1, b'\n');
}
loop {
core::hint::spin_loop();
}
}
unsafe fn outb(port: u16, value: u8) {
unsafe {
core::arch::asm!(
"out dx, al",
in("dx") port,
in("al") value,
options(nomem, nostack, preserves_flags)
);
}
}
#[panic_handler]
fn panic(_info: &PanicInfo) -> ! {
loop {
core::hint::spin_loop();
}
}

This code is useful because it is direct. The kernel exports _start, writes several bytes to COM1, then loops forever. The outb function uses inline assembly to execute the x86 out instruction. The dx register receives the port number, and the al register receives the byte value. The assembly options say that this snippet does not access normal memory, does not use the stack, and preserves flags. Those options help the compiler reason about the assembly block, but they do not make the operation safe. The operation is safe only if the caller uses a valid I/O port in an environment where port I/O is permitted.

This first version has a serious limitation. It writes to the data port without configuring the UART. In many emulator setups, it may still appear to work well enough for early experiments, but a proper serial driver should initialize the port. Serial initialization usually disables interrupts for the UART, enables access to the baud-rate divisor, configures the divisor, sets the data format, enables FIFO behavior, and marks the line control state. Those details matter because a serial port is a device, not a magical text stream.

A more controlled version places serial access behind a small module. The entry point should not contain raw port I/O. The entry point should say that the serial device is initialized and that a message is being written. The unsafe instructions belong in the hardware boundary.

Rust

#![no_std]
#![no_main]
use core::panic::PanicInfo;
mod serial {
const COM1: u16 = 0x3f8;
pub fn init() {
unsafe {
outb(COM1 + 1, 0x00);
outb(COM1 + 3, 0x80);
outb(COM1, 0x03);
outb(COM1 + 1, 0x00);
outb(COM1 + 3, 0x03);
outb(COM1 + 2, 0xc7);
outb(COM1 + 4, 0x0b);
}
}
pub fn write_byte(byte: u8) {
unsafe {
outb(COM1, byte);
}
}
pub fn write_str(text: &str) {
for byte in text.bytes() {
match byte {

b’\n’ => { write_byte(b’\r’); write_byte(b’\n’); } byte => write_byte(byte), }

unsafe fn outb(port: u16, value: u8) { unsafe { core::arch::asm!( “out dx, al”, in(“dx”) port, in(“al”) value, options(nomem, nostack, preserves_flags) ); } }

#[unsafe(no_mangle)] pub extern “C” fn _start() -> ! { serial::init(); serial::write_str(“serial output is online\n”);

loop {
core::hint::spin_loop();
}

}

#[panic_handler] fn panic(_info: &PanicInfo) -> ! { serial::write_str(“kernel panic\n”);

loop {
core::hint::spin_loop();
}

}

This version is still compact, but it is much closer to the shape you want in a kernel project. The initialization sequence is kept inside the serial module. The entry function does not know the UART register layout. The public interface exposes init, write_byte, and write_str. That gives the rest of the kernel a small, understandable surface. If serial behavior changes later, the caller does not need to change.

There is another important detail in write_str. It translates \n into \r\n. Many serial terminals expect carriage return plus newline to move to the beginning of the next line. Without that translation, output may move down without returning to the left margin, which makes logs harder to read. This is a small detail, but early kernel logs should be clear. When debugging startup faults, messy output wastes time.

At this point, the serial module can write strings, but formatted output is still awkward. Rust’s formatting system is available through core::fmt, even without the standard library. To use it, you provide a type that implements core::fmt::Write. That type receives formatted string slices and sends them to the serial device. This allows the kernel to create serial_print! and serial_println! macros without depending on std.

use core::fmt::{self, Write};
pub struct SerialWriter;
impl Write for SerialWriter {
fn write_str(&mut self, text: &str) -> fmt::Result {
crate::serial::write_str(text);
Ok(())
}
}
pub fn print(args: fmt::Arguments) {
let mut writer = SerialWriter;
let _ = writer.write_fmt(args);
}
#[macro_export]
macro_rules! serial_print {
($($arg:tt)*) => {
$crate::serial_writer::print(format_args!($($arg)*))
};
}
#[macro_export]
macro_rules! serial_println {
() => {
$crate::serial_print!("\n")
};
($fmt:expr) => {
$crate::serial_print!(concat!($fmt, "\n"))
);
($fmt:expr, $($arg:tt)*) => {
$crate::serial_print!(concat!($fmt, "\n"), $($arg)*)
};

This code is a useful turning point. It gives the kernel formatted output while still staying in a no_std environment. The format_args! macro does not allocate. It builds formatting arguments that are passed to the writer. This is exactly what early kernel code needs. You can print numbers, addresses, and messages without a heap.

There is a catch. This version creates a new SerialWriter value each time and assumes serial access is not contested. That is acceptable before interrupts and multiple execution contexts are introduced. Later, when interrupts can print diagnostics or multiple code paths can write at once, the output device should be protected with synchronization. A spin-based lock is often used in early kernels because there is no blocking scheduler yet. However, locks and interrupts require care. If an interrupt fires while the kernel already holds the serial lock, and the interrupt handler tries to print, the system can deadlock. The lock strategy must evolve as the interrupt model becomes more complete.

A stronger version can use a global writer protected by a lock, while keeping the unsafe hardware details inside the serial implementation. This version assumes a spin-based mutex is available as a dependency and that the serial module exposes a writer type.

use core::fmt::{self, Write};
use spin::Mutex;
pub static SERIAL_WRITER: Mutex<SerialWriter> =
Mutex::new(SerialWriter);
pub struct SerialWriter;
impl Write for SerialWriter {
fn write_str(&mut self, text: &str) -> fmt::Result {
crate::serial::write_str(text);
Ok(())
}
pub fn print(args: fmt::Arguments) {
use x86_64::instructions::interrupts;
interrupts::without_interrupts(|| {
let mut writer = SERIAL_WRITER.lock();
let _ = writer.write_fmt(args);
});
}

This version disables interrupts while holding the serial lock. That reduces the risk of an interrupt handler trying to acquire the same lock on the same CPU. This approach is common in early kernels, but it should still be used thoughtfully. Disabling interrupts for long periods harms responsiveness once the kernel becomes more advanced. The serial writer should do the smallest reasonable amount of work while interrupts are disabled. Early in the project, correctness and visibility matter more than performance. Later, logging can become buffered and more carefully scheduled.

The QEMU command must connect serial output to the host terminal. Without that, the kernel may write serial bytes successfully while you see nothing. A useful early command is short and repeatable.

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

The -serial stdio option attaches the emulated serial port to the terminal. The -no-reboot and -no-shutdown options help preserve the failure state. These flags are worth using from the beginning. If the kernel resets immediately after a fault, losing the terminal context makes diagnosis harder.

Serial output should become the first checkpoint system. After every major initialization step, print one line. When the kernel later initializes the GDT, IDT, memory map, frame allocator, heap, and interrupts, each step should report success. This is not noisy during early work. It is controlled visibility. A kernel that says “entered kernel,” “serial online,” and then stops before “gdt loaded” has already narrowed the failure to a much smaller area.

Rust requires a panic handler in a no_std kernel. In a normal Rust program, panic behavior is supported by the runtime and standard library. Depending on the configuration, the program may unwind the stack or abort. In a kernel, unwinding is usually not available and should not be assumed. There is no host process to terminate. There is no operating system to receive an exit code. The kernel must decide what a panic means and what happens next.

A panic in early kernel code should be treated as a controlled stop with diagnostics. It means the kernel reached a condition it cannot safely continue from. The panic handler should report as much useful information as the current output system allows, then prevent execution from continuing into unknown state. Returning from a panic handler is not allowed. The handler returns !, which means it never returns.

The smallest panic handler simply loops forever. It satisfies the compiler, but it gives no information.

use core::panic::PanicInfo;
#[panic_handler]
fn panic(_info: &PanicInfo) -> ! {
loop {
core::hint::spin_loop();
}
}

This version is acceptable only before output exists. Once serial output is available, a silent panic is no longer good enough. The PanicInfo value can contain the panic message and location. Printing it to serial can turn a confusing halt into a clear failure report. This is one of the first places where early serial work pays off.

Rust

use core::panic::PanicInfo;
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
serial_println!("kernel panic: {}", info);
loop {
core::hint::spin_loop();
}
}

This handler reports the panic through the serial logging path. If the panic includes a file and line location, that information can appear in the output. That matters because early kernel panics often come from explicit checks that protect unsafe assumptions. For example, the kernel may panic if the bootloader does not provide expected memory information, if a framebuffer format is unsupported, or if heap initialization is attempted twice. A good panic message tells you which invariant failed.

Once architecture support is available, the halt loop can use the CPU hlt instruction instead of continuously spinning. A spin loop keeps the CPU busy. A halt instruction stops execution until the next interrupt. In a panic state, this is often more appropriate. If interrupts are disabled, the CPU may stay halted. If interrupts are enabled, the CPU may wake for interrupts and then halt again. Either way, the handler should not return.

Rust

use core::panic::PanicInfo;
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
serial_println!("kernel panic: {}", info);
}
loop {
x86_64::instructions::hlt();
}

This version assumes the project is using architecture helper functions from an x86_64 support layer. If you want to keep architecture instructions out of the panic module, wrap the halt behavior in your own arch::halt_loop function.

pub mod arch {
pub fn halt_loop() -> ! {
loop {
x86_64::instructions::hlt();
}
}
}
use core::panic::PanicInfo;
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
serial_println!("kernel panic: {}", info);
crate::arch::halt_loop();
}

This shape is easier to maintain. The panic handler does not need to know the exact instruction used to stop the CPU. The architecture layer owns that detail. As the kernel grows, you might want the halt loop to disable interrupts first, run a final logging flush, or behave differently during tests. Keeping the stop behavior behind a function gives you that flexibility.

A better panic handler should also consider interrupts. If a panic occurs while interrupts are enabled, hardware interrupts can still arrive while the panic handler is printing. If an interrupt handler tries to print using the same lock as the panic handler, the system may deadlock. If the interrupt handler touches damaged state, the panic can become a second fault or a reset. A practical early choice is to disable interrupts at the start of the panic handler before printing.

use core::panic::PanicInfo;
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
x86_64::instructions::interrupts::disable();
serial_println!();
serial_println!("kernel panic");
serial_println!("{}", info);
loop {
x86_64::instructions::hlt();
}
}

This version makes the panic path more stable once interrupts are introduced. It prints a blank line first so the panic message does not run into previous output. It then prints a clear marker and the panic details. Disabling interrupts is not a cure for every panic-related problem, but it reduces the number of moving parts during failure reporting.

The panic handler must avoid features that may not be available or may be broken. It should not allocate memory unless the allocator is known to be stable and panic-safe. It should not acquire locks carelessly if the panic could have occurred while the same lock was already held. It should not rely on complex formatting paths that might panic again. It should not attempt broad cleanup work. In an early kernel, the safest panic behavior is usually to print through the most reliable output path and halt.

Double panics are another concern. If the panic handler itself panics, the kernel can collapse into a more confusing failure. Rust’s behavior in such cases depends on the panic strategy and environment, but in a kernel the practical outcome is usually bad. Keep panic handler code small. Avoid indexing that can panic. Avoid unwrap and expect inside the panic handler. Avoid code paths that assume the heap, interrupts, or locks are healthy. The panic handler runs when something is already wrong.

You can build a tiny emergency serial path for panic output that avoids the normal logging lock. This is useful if the normal output path might be locked

at the time of panic. The emergency path should be small and direct. It may produce rougher output, but rough output is better than silence.

mod emergency_serial {
const COM1: u16 = 0x3f8;
pub fn write_str(text: &str) {
for byte in text.bytes() {
unsafe {
outb(COM1, byte);
}
}
}
unsafe fn outb(port: u16, value: u8) {
unsafe {
core::arch::asm!(
"out dx, al",
in("dx") port,
in("al") value,
options(nomem, nostack, preserves_flags)
);
}
}
}
use core::panic::PanicInfo;
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
x86_64::instructions::interrupts::disable();
emergency_serial::write_str("\nkernel panic\n");
if let Some(location) = info.location() {
emergency_serial::write_str(location.file());
emergency_serial::write_str("\n");
}
loop {
x86_64::instructions::hlt();
}
}

This handler gives up some formatted detail in exchange for reducing dependencies. It writes directly to the serial port through a very small

emergency path. It prints the panic marker and, if available, the file path. This kind of fallback can be helpful when the formatted logging path is not safe to use. The tradeoff is that direct emergency output duplicates some serial access code. In early kernels, that can be acceptable if the duplicated code is tiny and clearly isolated.

A test kernel may need different panic behavior. During manual development, a panic should print and halt so you can inspect the output. During automated tests, a panic should report failure and exit QEMU with a failure code. That difference should be explicit, usually controlled through conditional compilation. The normal kernel and test kernel do not have to share exactly the same panic handler.

use core::panic::PanicInfo;
#[cfg(not(test))]
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
x86_64::instructions::interrupts::disable();
serial_println!();
serial_println!("kernel panic: {}", info);
loop {
x86_64::instructions::hlt();
}
}
#[cfg(test)]
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
serial_println!("test panic: {}", info);
crate::qemu::exit_failure();
}

This version assumes a later qemu module can exit the emulator with a failure code. The important design point is that panic behavior can depend on the execution mode. Manual runs and automated tests have different needs. In both cases, the panic handler must never return.

Panic messages should be written with care. A panic should explain the violated condition, not merely say that something failed. In a kernel, a vague panic can cost a lot of time because the failure may occur before the debugger or screen is ready. A message such as memory map missing is better than init failed. A message such as heap virtual range is not page aligned is better than bad heap. The panic handler prints the information, but the panic sites must provide meaningful messages.

pub fn init_heap(heap_start: usize, heap_size: usize) {
assert!(heap_start % 4096 == 0, "heap start address is not page aligned");
assert!(heap_size >= 4096, "heap size is smaller than one page");
unsafe {
init_heap_unchecked(heap_start, heap_size);
}
}
unsafe fn init_heap_unchecked(_heap_start: usize, _heap_size: usize) {
// Heap setup is added after paging and allocation are available.
}

This code shows a useful pattern. Safe initialization code checks invariants and gives clear panic messages. The unsafe operation is placed behind those checks. If the condition fails, the panic output tells you what assumption was invalid. This is how Rust helps kernel development. It cannot prove that the heap region is truly mapped unless your code establishes that fact, but it can help you centralize checks and stop early when an invariant is violated.

The panic handler is not an error-recovery system. It is the final diagnostic path when continuing would be unsafe or meaningless. Later kernels may distinguish recoverable errors from fatal kernel panics, but early kernel code should keep the distinction simple. If the kernel cannot trust memory, interrupts, or core initialization state, it should print and stop. Controlled failure is far better than continuing into corruption.

3.3: Printing to VGA Text Mode and Framebuffer Output

Section titled “3.3: Printing to VGA Text Mode and Framebuffer Output”

Serial output is reliable, but screen output is still useful. It gives immediate visual confirmation that the kernel is alive, and it prepares the path for later console features. On x86_64 kernel projects, two early screen-output paths are common: VGA text mode and framebuffer output. They solve similar needs but work very differently.

VGA text mode is simple on compatible emulator setups. It exposes a memory region where each screen cell is represented by a character byte and an attribute byte. The common text buffer address is 0xb8000, with an 80-column by 25-row layout. Writing a character to the correct memory location can make text appear on the screen. This is convenient because it does not require font rendering or pixel drawing. The hardware text mode handles character display.

The simplest VGA write places one character at a known position. Because the target is memory-mapped device memory, use volatile writes. A normal write may be optimized in ways that are not appropriate for device memory. Volatile access tells the compiler that the write itself is an observable operation.

use core::ptr;
const VGA_BUFFER: *mut u8 = 0xb8000 as *mut u8;
pub fn write_byte_at_start(byte: u8) {
unsafe {
ptr::write_volatile(VGA_BUFFER, byte);
ptr::write_volatile(VGA_BUFFER.add(1), 0x0f);
}
}

This function writes a character byte and an attribute byte to the first cell of the VGA text buffer. The attribute 0x0f represents a common bright foreground on a dark background in the basic VGA color format. This proves

the concept, but it is not a console. It does not track cursor position, handle newlines, scroll, protect bounds, or synchronize access.

A more useful VGA writer tracks row and column positions. It writes characters in sequence and moves to a new line when needed. It keeps unsafe volatile access inside the writer rather than exposing raw offsets everywhere.

Rust

use core::ptr;
const VGA_WIDTH: usize = 80;
const VGA_HEIGHT: usize = 25;
const VGA_BUFFER: *mut u8 = 0xb8000 as *mut u8;
pub struct VgaWriter {
row: usize,
column: usize,
color: u8,
}
impl VgaWriter {
pub const fn new(color: u8) -> Self {
Self {
row: 0,
column: 0,
color,
}
}
pub fn write_byte(&mut self, byte: u8) {
match byte {
b'\n' => self.new_line(),
byte => {
if self.column >= VGA_WIDTH {
self.new_line();
}
if self.row < VGA_HEIGHT {
let offset = (self.row * VGA_WIDTH + self.column) * 2;
unsafe {
ptr::write_volatile(VGA_BUFFER.add(offset), byte);
}
}
}
}
}
}

ptr::write_volatile(VGA_BUFFER.add(offset + 1), self.color);

self.column += 1;

pub fn write_str(&mut self, text: &str) { for byte in text.bytes() { self.write_byte(byte); } }

fn new_line(&mut self) { self.column = 0;

if self.row + 1 < VGA_HEIGHT {
self.row += 1;
}

}

This writer is useful but incomplete. When it reaches the last row, it stops advancing. A better console scrolls existing lines upward and clears the last line. Scrolling requires reading and writing the buffer, still through volatile operations. It also requires careful bounds logic because a mistake in screen indexing can write outside the expected memory region.

use core::ptr;
const VGA_WIDTH: usize = 80;
const VGA_HEIGHT: usize = 25;
const VGA_BUFFER: *mut u8 = 0xb8000 as *mut u8;
pub struct VgaWriter {
row: usize,
column: usize,
color: u8,
}
impl VgaWriter {
pub const fn new(color: u8) -> Self {
<!-- page: 080 -->
rust
Self {
row: 0,
column: 0,
color,
}
pub fn write_byte(&mut self, byte: u8) {
match byte {
b'\n' => self.new_line(),
byte => {
if self.column >= VGA_WIDTH {
self.new_line();
}
let offset = (self.row * VGA_WIDTH + self.column) * 2;
unsafe {
ptr::write_volatile(VGA_BUFFER.add(offset), byte);
ptr::write_volatile(VGA_BUFFER.add(offset + 1), self.color);
}
self.column += 1;
}
}
}
pub fn write_str(&mut self, text: &str) {
for byte in text.bytes() {
self.write_byte(byte);
}
}
fn new_line(&mut self) {
self.column = 0;
if self.row + 1 >= VGA_HEIGHT {
self.scroll();
} else {
self.row += 1;
}
}
fn scroll(&mut self) {
for row in 1..VGA_HEIGHT {
for column in 0..VGA_WIDTH {
let from = (row * VGA_WIDTH + column) * 2;
let to = ((row - 1) * VGA_WIDTH + column) * 2;
unsafe {
let byte =
ptr::read_volatile(VGA_BUFFER.add(from));
let color =
ptr::read_volatile(VGA_BUFFER.add(from + 1));
ptr::write_volatile(VGA_BUFFER.add(to),
byte);
ptr::write_volatile(VGA_BUFFER.add(to + 1),
color);
}
self.clear_row(VGA_HEIGHT - 1);
}
fn clear_row(&mut self, row: usize) {
for column in 0..VGA_WIDTH {
let offset = (row * VGA_WIDTH + column) * 2;
unsafe {
ptr::write_volatile(VGA_BUFFER.add(offset), b'
');
ptr::write_volatile(VGA_BUFFER.add(offset + 1),
self.color);
}
}
}

This version behaves more like a small console. It scrolls when it reaches the bottom of the screen and clears the last row. The unsafe code is still there, but it is inside the VGA writer. The rest of the kernel can ask the writer to write text without manually calculating buffer offsets.

To make VGA output support formatted text, implement core::fmt::Write for the writer. This gives the same formatting approach used for serial output.

Rust

use core::fmt::{self, Write};
use spin::Mutex;
pub static VGA_WRITER: Mutex<VgaWriter> =
Mutex::new(VgaWriter::new(0x0f));
impl Write for VgaWriter {
fn write_str(&mut self, text: &str) -> fmt::Result {
VgaWriter::write_str(self, text);
Ok(())
}
}
pub fn print(args: fmt::Arguments) {
use x86_64::instructions::interrupts;
interrupts::without_interrupts(|| {
let mut writer = VGA_WRITER.lock();
let _ = writer.write_fmt(args);
});
}
#[macro_export]
macro_rules! screen_print {
($($arg:tt)*) => {
$crate::vga::print(format_args!($($arg)*))
};
}
#[macro_export]
macro_rules! screen_println {
() => {
$crate::screen_print!("\n")
};
($fmt:expr) => {
$crate::screen_print!(concat!($fmt, "\n"))
};
($fmt:expr, $($arg:tt)*) => {
$crate::screen_print!(concat!($fmt, "\n"), $($arg)*)
};
}

The lock protects the writer state. Without it, two code paths could update the row and column at the same time and corrupt output. Disabling interrupts while holding the lock reduces the chance of deadlock on a single CPU when an interrupt handler also prints. This is still a basic synchronization model, but it is enough for early kernel output.

VGA text mode is not universal. Some boot environments may not provide it, and some modern display paths use framebuffer output instead. A framebuffer is a region of memory where pixels are stored directly. The bootloader may provide its address, width, height, stride, pixel format, and bytes per pixel. The kernel can draw by writing pixel values into that memory. Unlike VGA text mode, the framebuffer does not understand characters. If you want text, the kernel must draw glyphs or use a small bitmap font.

The first framebuffer operation is to fill the screen with a color. This confirms that the kernel can access the framebuffer and that the boot information is being interpreted correctly.

Rust

use core::ptr;
pub struct Framebuffer {
address: *mut u8,
width: usize,
height: usize,
stride: usize,
bytes_per_pixel: usize,
}
impl Framebuffer {
pub unsafe fn new(
address: *mut u8,
width: usize,
height: usize,
stride: usize,
bytes_per_pixel: usize,
) -> Self {
Self {
address,
width,
height,
stride,
bytes_per_pixel,
}
}
pub fn clear_rgb(&mut self, red: u8, green: u8, blue: u8) {
for y in 0..self.height {
for x in 0..self.width {

self.write_pixel_rgb(x, y, red, green, blue);

pub fn write_pixel_rgb(&mut self, x: usize, y: usize, red: u8, green: u8, blue: u8) { if x >= self.width || y >= self.height { return; }

let offset = y * self.stride + x * self.bytes_per_pixel;
unsafe {
ptr::write_volatile(self.address.add(offset), blue);
ptr::write_volatile(self.address.add(offset + 1), green);
ptr::write_volatile(self.address.add(offset + 2), red);
}

}

This example assumes a pixel format where the byte order is blue, green, red. That is common in some framebuffer configurations, but it is not guaranteed. A real framebuffer writer must respect the pixel format provided by the bootloader. If the color channels are reversed, the screen may show unexpected colors. If the stride is handled incorrectly, pixels may appear skewed or lines may overwrite the wrong memory. If bytes per pixel is wrong, writes can corrupt adjacent pixels or memory beyond the framebuffer.

A more careful framebuffer writer should store the pixel format explicitly and use it when writing pixels.

use core::ptr;
pub enum PixelFormat {
Rgb,
Bgr,
}
pub struct Framebuffer {
<!-- page: 085 -->
address: *mut u8,
width: usize,
height: usize,
stride: usize,
bytes_per_pixel: usize,
pixel_format: PixelFormat,
impl Framebuffer {
pub unsafe fn new(
address: *mut u8,
width: usize,
height: usize,
stride: usize,
bytes_per_pixel: usize,
pixel_format: PixelFormat,
) -> Self {
Self {
address,
width,
height,
stride,
bytes_per_pixel,
pixel_format,
}
}
pub fn write_pixel(&mut self, x: usize, y: usize, red: u8,
green: u8, blue: u8) {
if x >= self.width || y >= self.height {
return;
}
if self.bytes_per_pixel < 3 {
return;
}
let offset = y * self.stride + x * self.bytes_per_pixel;
unsafe {
match self.pixel_format {
PixelFormat::Rgb => {
ptr::write_volatile(self.address.add(offset), red);
ptr::write_volatile(self.address.add(offset + 1), green);
ptr::write_volatile(self.address.add(offset + 2), blue);
}
PixelFormat::Bgr => {
ptr::write_volatile(self.address.add(offset), blue);
ptr::write_volatile(self.address.add(offset + 1), green);
ptr::write_volatile(self.address.add(offset + 2), red);
}
}
}
}
}
<!-- page: 086 -->
blue);
ptr::write_volatile(self.address.add(offset),
1), green);
ptr::write_volatile(self.address.add(offset),
2), red);
}
}
pub fn clear(&mut self, red: u8, green: u8, blue: u8) {
for y in 0..self.height {
for x in 0..self.width {
self.write_pixel(x, y, red, green, blue);
}
}
}
This version is safer in design because it does not assume one byte order for every framebuffer. It also checks that the pixel size is at least three bytes before writing red, green, and blue components. It still relies on the caller to provide a valid framebuffer address and correct metadata. The new function is unsafe because Rust cannot verify that the address points to a mapped framebuffer. That fact must come from the bootloader handoff and memory mapping.
Framebuffer text output requires a font. For early debugging, it is acceptable to start with serial output and use the framebuffer only for simple visual confirmation. A small kernel console can later draw characters using a bitmap font. Text rendering is not conceptually difficult, but it adds enough code that it should not block panic reporting or serial logs. Serial remains the primary early diagnostic path. Screen output is helpful, but should not be the only way to see failure.
A practical kernel can write to both serial and screen through a shared logging path. This gives you terminal logs and visible output at the same time. The serial path may work even when the framebuffer is wrong. The screen path may help when serial is not attached. Combining them improves visibility, as long as the implementation avoids deadlocks.
<!-- page: 087 -->
# Rust
rust
use core::fmt::{self, Write};
pub struct KernelConsole;
impl Write for KernelConsole {
fn write_str(&mut self, text: &str) -> fmt::Result {
crate::serial::write_str(text);
crate::vga::write_str(text);
Ok(())
}
}
pub fn print(args: fmt::Arguments) {
let mut console = KernelConsole;
let _ = console.write_fmt(args);
}
#[macro_export]
macro_rules! kprint {
($($arg:tt)*) => {
$crate::kernel_console::print(format_args!($($arg)*))
};
}
#[macro_export]
macro_rules! kprintln {
() => {
$crate::kprint!("\n")
};
($fmt:expr) => {
$crate::kprint!(concat!($fmt, "\n"))
};
($fmt:expr, $($arg:tt)*) => {
$crate::kprint!(concat!($fmt, "\n"), $($arg)*)
};
}

This code presents a common idea: one kernel print macro can write to multiple output devices. In a more complete implementation, the console should check whether each device has been initialized. Early startup code may want serial output before VGA or framebuffer output is ready. A global output path should not fault just because one backend is not available yet.

Bare-metal output should be treated as a kernel subsystem, not just temporary scaffolding. It will support panic messages, initialization

checkpoints, test reporting, exception diagnostics, memory-map dumps, page-fault reports, and later shell output. The early design does not need to be perfect, but it should be clean enough to grow. Keep hardware writes behind modules. Keep formatting separate from device access. Use volatile operations for device memory. Avoid heap allocation. Protect shared writer state when interrupts arrive. These habits prevent early output code from becoming the first source of hard-to-find bugs.

3.4: Diagnosing Black Screens, Reboots, and Silent Failures

Section titled “3.4: Diagnosing Black Screens, Reboots, and Silent Failures”

A black screen is not a diagnosis. It is only a symptom. The kernel might not have been loaded. It might have been loaded but never entered. It might have entered and halted before output. It might be printing to serial while you are watching the graphical window. It might have faulted before the output device was initialized. It might have triple-faulted and reset the virtual machine. Treating all of these as “the screen is black” leads to random changes and wasted time. A better approach is to separate the boot path, entry point, output path, and fault behavior.

The first question is whether QEMU is booting the artifact you think it is booting. A common mistake is building a kernel binary but launching an old disk image. Another common mistake is inspecting the ELF file while QEMU boots a different image. The build process should clearly produce or update the bootable image, and the run command should point to that exact image. If the image is stale, every code change appears to have no effect.

A run script helps reduce that risk by building first and then launching the updated image.

#!/bin/sh
set -eu
cargo build
qemu-system-x86_64 \

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

This script is only correct if cargo build also causes the boot image to be updated. If your project requires a separate packaging command, the script must include it. The rule is simple: do not run QEMU against an artifact that may not contain the code you just compiled.

The second question is whether the entry symbol exists and matches the boot path. If your bootloader expects _start, check that _start appears in the compiled binary. If your bootloader uses a generated entry and calls kernel_main, check the symbol or generated path expected by that integration. Do not assume that all boot strategies use the same symbol name.

bash
rust-objdump --syms target/x86_64-kernel/debug/rust_kernel

Symbol inspection tells you whether the compiled file contains the function you expect. If the symbol is missing, the problem is in the source, attributes, linker behavior, or bootloader integration. If the symbol exists but is never reached, the problem is likely earlier in the boot path or in how the image is packaged.

The third question is whether serial output is attached. If the kernel writes only to serial, the graphical QEMU window may remain blank forever. That does not mean the kernel failed. It may be printing correctly to a serial device you did not connect. Always run early kernels with serial attached to the terminal.

Shell

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

If serial output still does not appear, add the earliest possible raw serial write near the entry point. Do this before any complex initialization. If the byte appears, the kernel reached the entry function. If it does not, either the entry function was not reached, serial is not configured as expected, or the port write is not valid in the current environment.

#[unsafe(no_mangle)]
pub extern "C" fn _start() -> ! {
unsafe {
core::arch::asm!(
"out dx, al",
in("dx") 0x3f8u16,
in("al") b'X',
options(nomem, nostack, preserves_flags)
);
}
loop {
core::hint::spin_loop();
}
}

This is not a final output strategy. It is a diagnostic probe. A single visible byte can prove that control reached _start. Once that is known, restore the structured serial module. Diagnostic probes should be temporary and precise. They are useful when the normal output stack may itself be broken.

Reboots usually mean a more serious early failure. On x86_64, a severe exception during early startup can lead to a double fault. If the CPU cannot handle the double fault correctly, it can triple-fault and reset. Before the interrupt descriptor table is configured, many exceptions cannot be reported gracefully. This is why QEMU may appear to restart with no message. The kernel did not choose to reboot. The CPU reset because exception handling failed.

Use QEMU options that preserve failure state and log CPU events.

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 can show exceptions, resets, and interrupt-related events. It may be noisy, but it is valuable when the kernel fails before printing. If the log shows repeated CPU resets, suspect a triple fault or boot loop. If it shows a page fault before you have an IDT, suspect invalid memory access, wrong mapping, or execution at an unexpected address.

The fourth question is whether the binary format and target are correct. A kernel compiled for the wrong target may still produce a file, but it may not be bootable in the way you expect. Inspect the file headers and sections.

rust-readobj --file-headers --sections target/x86_64-kernel/debug/rust_kernel
Check that the architecture matches the target and that the sections make sense for your boot strategy. If the binary is not in the expected format, the bootloader may reject it or load it incorrectly. If sections are missing or placed unexpectedly, linker configuration may be wrong. At this stage, binary inspection is not optional technical trivia. It is part of the debugging workflow.
The fifth question is whether the kernel is halting correctly. A kernel that reaches the end of the entry function or returns to a nonexistent caller is broken. Entry functions should return !, and the final path should halt or loop forever. If the entry function accidentally returns, the CPU may execute garbage or return into a bootloader context that is no longer valid.
Rust
pub fn halt_loop() -> ! {
loop {

x86_64::instructions::hlt(); }

Use a halt loop rather than letting control fall through. If interrupts are disabled, hlt may stop the CPU indefinitely. If interrupts are enabled, the CPU can wake and then halt again. In early code, this gives a controlled ending point.

Silent failures can also come from panic handling. If the panic handler loop without printing, a panic looks like a freeze. Once serial output exists, the panic handler should print. To test it, deliberately trigger a panic after serial initialization.

#[unsafe(no_mangle)]
pub extern "C" fn _start() -> ! {
serial::init();
serial_println!("before test panic");
panic!("panic handler test");
}

If you see the message before the panic but not the panic output, the panic handler or formatting path is broken. If you see nothing, the kernel did not reach serial initialization or serial output is not attached. If QEMU resets, the panic path may be causing a fault, possibly through a broken output function or invalid instruction use.

After testing, remove deliberate panics from normal startup. Keep the habit though. Each subsystem should be tested in isolation when possible. If adding VGA output breaks serial panic reporting, you know the new code disturbed something essential.

A black graphical window may also be caused by writing to the wrong output device. VGA text mode assumes a compatible text buffer at 0xb8000. If the boot path uses a graphics framebuffer and does not preserve VGA text mode in the way you expect, writes to 0xb8000 may not produce visible output. Conversely, framebuffer output requires correct framebuffer information.

If the address, stride, dimensions, or pixel format are wrong, drawing may fail or corrupt memory. Serial output should remain the trusted path while screen output is being developed.

When screen output fails, test the smallest possible write. For VGA, write one character to the first cell. For a framebuffer, fill the entire screen with one color. Do not start by debugging formatted text rendering, scrolling, cursor state, and font drawing at the same time. Reduce the problem until one visible operation succeeds.

Rust

pub fn vga_probe() {
let buffer = 0xb8000 as *mut u8;
unsafe {
core::ptr::write_volatile(buffer, b'V');
core::ptr::write_volatile(buffer.add(1), 0x0f);
}
}

This probe tells you whether basic VGA text output is visible. It does not prove a full console is correct, but it separates hardware visibility from console logic. If this works and your console does not, the bug is likely in cursor handling, scrolling, locking, or formatting. If this does not work, the environment may not support the VGA path you are using, or the address may not be mapped as expected.

For framebuffer output, use a similarly small test.

Rust

pub unsafe fn framebuffer_probe(address: *mut u8, length: usize)
{
for offset in 0..length {
unsafe {
core::ptr::write_volatile(address.add(offset), 0);
}
}
}

This clears a raw framebuffer memory range to zero. It is unsafe because the function trusts the caller to provide a valid mapped framebuffer address and length. It should be used only with information from the bootloader. A real framebuffer writer should respect width, height, stride, and pixel format. As a diagnostic probe, clearing the range can confirm whether writes affect the display.

GDB becomes useful when output and logs are not enough. You can start QEMU paused and connect a debugger before the CPU runs. This lets you set a breakpoint at the entry point and prove whether execution reaches it.

Terminal window
qemu-system-x86_64 \
-drive format=raw,file=target/kernel.img \
-serial stdio \
-no-reboot \
-no-shutdown \
-S \
-s

Then connect with a debugger using the kernel symbol file.

Terminal window
target remote :1234
break _start
continue

If the breakpoint is hit, the bootloader reached your entry symbol. You can step instruction by instruction, inspect registers, and check the stack pointer. If the breakpoint is not hit, verify the entry symbol, boot image, and bootloader configuration. If the debugger cannot match symbols to execution addresses, investigate linker layout and how the bootloader loads the kernel.

A disciplined diagnosis sequence saves time. First confirm the right image is booted. Then confirm the entry symbol exists. Then confirm serial is attached. Then place an earliest-entry serial probe. Then inspect QEMU logs for resets or exceptions. Then inspect binary headers and sections.

Then use GDB to check whether the entry point is reached. This sequence is not a formal checklist in the code, but it is a practical mental order. It moves from the outside of the boot chain inward, instead of changing random kernel code and hoping the symptom changes.

Early kernel debugging is about reducing uncertainty. A black screen gives almost no information. A serial byte gives one fact. A panic message gives another. A QEMU log gives another. A symbol table gives another. A breakpoint gives another. When those facts line up, the problem becomes smaller and more manageable. That is the real value of bare-metal output and early debugging. They turn silence into evidence before the kernel grows complex enough to fail in more interesting ways.