Kernel Development Foundations in Rust
local graph
Chapter 1 — Kernel Development Foundations in Rust
Section titled “Chapter 1 — Kernel Development Foundations in Rust”Chapter 1: Kernel Development Foundations in Rust
Section titled “Chapter 1: Kernel Development Foundations in Rust”Kernel development changes the rules that most application programming depends on. In an ordinary Rust program, the operating system has already done an enormous amount of work before your code begins. It has created a process, mapped memory, prepared a stack, connected standard input and output, exposed files and sockets through system calls, and arranged a runtime environment where the standard library can assume that many services already exist. A kernel does not receive that comfort. A kernel is the software that starts taking responsibility for those services.
Writing a kernel in Rust is both practical and demanding. Rust gives you a strong type system, ownership rules, pattern matching, clear module boundaries, and a culture of making unsafe behavior explicit. Those strengths are valuable in low-level systems programming, but they do not cancel the responsibilities of kernel development. The CPU will not forgive a wrong page-table entry because the code was written in Rust. A bad interrupt stack can still reset the machine. A mistaken memory map can still corrupt the kernel image. A device register written with the wrong width can still produce undefined hardware behavior. Rust helps you build better boundaries around those risks, but you still need to understand what is happening below the language.
The first task is to establish a clean foundation. You need to know what the bootloader prepares, what the kernel must take over, how Rust behaves when there is no standard library, how the build system produces a freestanding binary, and how to structure the project so it can grow without becoming fragile. These foundations are not optional setup details. They shape every later decision involving memory management, interrupts, drivers, allocation, and debugging.
The kernel built through this material begins as a small freestanding Rust program and grows into a controlled execution environment. At first, it has
almost nothing: no heap, no files, no threads, no process model, no clock, no keyboard input, and no ordinary console. Those services will appear only when the kernel provides them or when the bootloader passes usable information that the kernel can safely interpret. That is why the early structure matters. A clean kernel foundation allows you to add features deliberately instead of stacking fragile code on top of unknown assumptions.
1.1: What the Kernel Owns and What the Bootloader Prepares
Section titled “1.1: What the Kernel Owns and What the Bootloader Prepares”A kernel does not begin execution in a vacuum. Before the first Rust instruction in the kernel runs, firmware has already powered through hardware initialization, selected a boot device, and transferred control to a bootloader or boot manager. The exact path depends on the platform and boot method, but the practical result is the same: some earlier software prepares enough machine state for the kernel to start.
The bootloader’s job is to bridge the gap between firmware and the kernel. Firmware is designed to initialize the machine and find bootable software. The kernel is designed to manage the machine after startup. Between those two responsibilities sits the bootloader. It locates the kernel image, loads it into memory, prepares a handoff structure, and transfers control to the kernel entry point. In many modern educational kernels, the bootloader also places the CPU into a usable execution mode, prepares page tables, gives the kernel a memory map, provides framebuffer details, and passes other boot information.
This division of labor matters because it keeps the early project realistic. Writing a bootloader first can be educational, but it also introduces a large amount of firmware-specific and architecture-specific complexity before the kernel has any useful debugging tools. A professional workflow does not require proving skill by writing every byte of the boot path immediately. It is often better to rely on a known bootloader while learning how to build the kernel itself. Later, after the kernel has serial logging, exception handling,
and a working memory manager, you can study alternative boot protocols or write a custom loader with much better visibility into failures.
The kernel owns the machine progressively. At the instant it starts, it may still depend on decisions made by the bootloader. The bootloader may have chosen where the kernel image lives in physical memory, where the stack starts, how virtual memory is initially mapped, and where boot information is stored. The kernel must treat that information carefully. It should not overwrite memory just because an address looks unused. It should not assume all RAM is free. It should not assume firmware memory, framebuffer memory, bootloader data, kernel code, kernel data, and stack memory can be treated the same way.
Ownership begins with knowledge. The kernel needs to know which memory regions are usable, which are reserved, which contain the kernel image, which contain the boot information, which belong to firmware data, and which correspond to devices such as the framebuffer. That knowledge normally arrives through a memory map. The memory map is not merely a convenience. It is the first contract between the boot environment and the kernel’s memory manager. If the kernel ignores it, frame allocation becomes dangerous. If it misinterprets it, the kernel may hand out frames that still contain active structures. A frame allocator built on bad input is not a memory manager. It is a corruption engine with a polite interface.
The bootloader may also provide output information. If it sets up a framebuffer, the kernel can write pixels to a memory region representing the display. If it does not, the kernel may initially rely on text-mode video memory, serial output, or no output at all. This is why serial logging is usually introduced early. Screen output depends on display mode and boot information. Serial output is far less elegant, but it is one of the most reliable ways to understand what the kernel is doing while the rest of the machine is not yet under your control.
The kernel must eventually take responsibility for interrupts. At startup, interrupt handling may be disabled, partially configured, or configured in a way that is not suitable for your kernel’s design. Interrupts are not just messages. They are asynchronous changes in control flow. A timer can
interrupt the kernel while it is modifying shared state. A keyboard interrupt can arrive while another handler is running. A page fault can occur inside code that was trying to handle a different problem. Before enabling hardware interrupts, the kernel needs a valid interrupt descriptor table, appropriate handler functions, correct stack handling, and a plan for acknowledging the interrupt controller. Turning interrupts on too early is a common way to produce unstable behavior that looks random but is completely deterministic at the hardware level.
The kernel also owns the meaning of safety inside its own boundaries. Rust code in user applications receives safety support from the operating system as well as from the language. Process isolation, virtual memory, file permissions, thread scheduling, and system calls are all part of the environment that makes application code manageable. Inside the kernel, those protections are either not available yet or are being implemented by the kernel itself. When the kernel writes through a raw pointer, the CPU will attempt the access according to the current page tables and hardware permissions. Rust’s borrow checker cannot verify that a physical address supplied by a bootloader is still safe to use. It cannot prove that a device register is ready for a write. It cannot infer that an interrupt handler uses the correct stack. These conditions must be established by design.
A useful way to think about the early kernel is that it inherits temporary facts and must convert them into deliberate policy. The bootloader may provide a stack, but the kernel should later create known-good stacks for interrupts. The bootloader may provide page tables, but the kernel should eventually understand, verify, and extend the mappings. The bootloader may provide a memory map, but the kernel must turn it into allocator state. The bootloader may provide a framebuffer, but the kernel must wrap it in code that respects pitch, pixel format, bounds, and volatile access. The bootloader may provide a handoff structure, but the kernel must copy or preserve what it needs before modifying memory management.
This boundary also affects how you name and organize the code. Code that depends on bootloader-provided data should not be scattered across unrelated modules. A memory map parser belongs near boot information and memory initialization. Framebuffer initialization belongs near early
output. Entry code belongs near architecture-specific startup. Keeping these responsibilities separate prevents accidental dependencies. It also makes future bootloader changes less painful. If the project later supports a different boot protocol, the kernel should not require a rewrite of every subsystem. The handoff layer can translate bootloader-specific data into kernel-owned structures.
There is a temptation in early kernel development to treat the bootloader as magic. That is understandable, but it becomes a problem when something fails. If the kernel triple faults immediately after entry, the cause may be a bad stack, invalid code address, wrong binary format, incompatible bootloader configuration, missing page mapping, or incorrect entry symbol. If the screen is black, the kernel may not have booted, may have booted but printed to the wrong device, may have faulted before output, or may be running in a halt loop with no visible output. The more clearly you understand the bootloader’s responsibilities, the easier it becomes to locate the boundary where the failure happened.
The kernel’s first responsibility is not to do everything. Its first responsibility is to establish trustworthy control. That means having a known entry point, predictable build output, early logging, a clear panic path, and a disciplined interpretation of boot information. From there, the kernel can grow. Without that foundation, later features such as paging, heap allocation, interrupts, and device drivers become much harder to trust because you cannot separate new bugs from old startup assumptions.
1.2: Rust in a Freestanding Environment
Section titled “1.2: Rust in a Freestanding Environment”A freestanding Rust environment is one where Rust code runs without the ordinary operating-system services expected by the standard library. In normal Rust development, the std crate provides threads, file access, networking, heap-backed collections, process interaction, standard output, environment variables, and other facilities that depend on an existing operating system. A kernel cannot depend on std because the kernel is the component that would need to provide many of those services.
The first visible change is #![no_std]. This crate-level attribute tells the compiler that the crate should not link the standard library. It still allows the use of core, which contains fundamental Rust features that do not require an operating system. Types such as Option, Result, slices, references, raw pointers, formatting traits, atomics for supported targets, and many basic language facilities remain available through core. This is important because no_std does not mean “no Rust.” It means Rust without the host operating-system layer.
The second major change is #![no_main]. A normal Rust program begins with main, but that main function is part of a larger startup sequence. In a hosted environment, runtime startup code prepares the process before calling main. In a freestanding kernel, there may be no runtime startup code unless you provide it or the bootloader transfers control to a known function. The kernel needs its own entry point with a symbol name and calling convention that match the boot path.
Rust
#![no_std]#![no_main]
use core::panic::PanicInfo;
#[unsafe(no_mangle)]pub extern "C" fn _start() -> ! { loop { core::hint::spin_loop(); }}
#[panic_handler]fn panic(_info: &PanicInfo) -> ! { loop { core::hint::spin_loop(); }}This is the smallest shape of a freestanding Rust kernel entry file. The #![no_std] attribute removes the standard library dependency. The #![no_main] attribute prevents the compiler from expecting the normal Rust entry path. The _start function is marked with extern "C" so the
external interrupt. In early kernel code, interrupts may be disabled, so this often behaves as a low-power stop. The difference matters less than the principle: a panic must not fall through, return, or call unavailable operating-system services. It should provide the best available diagnostic output and then stop in a controlled way.
Freestanding Rust also changes how memory allocation works. Without std, heap allocation is not available automatically. Types such as Box, Vec, and String belong to the allocation layer, not to core. They can become available through the alloc crate, but only after the kernel provides a global allocator. This ordering is crucial. You cannot use heap-backed structures to build the first heap allocator unless you already have some other allocation strategy. Early kernel code should rely on static storage, stack values, fixed-size buffers, and carefully controlled memory regions until heap allocation is initialized.
Another major issue is panic strategy. In kernel development, unwinding is usually not supported. Unwinding requires runtime support and stack metadata that are not appropriate in a basic freestanding kernel. The build profile should use aborting panics. With aborting panics, a panic transfers to the panic handler without trying to unwind the stack. This matches the practical reality of early kernel code.
[profile.dev]panic = "abort"
[profile.release]panic = "abort"This profile setting belongs in the project’s Cargo configuration file. It makes the panic behavior explicit for development and release builds. Kernel builds should avoid hidden assumptions. If the project relies on aborting panics, the configuration should say so clearly.
The freestanding environment also changes how you think about formatted output. The familiar println! macro is not available because there is no
standard output stream. Formatting itself can still be used through core::fmt, but the destination must be provided by the kernel. For example, a serial writer or VGA writer can implement core::fmt::Write, then macros can format text into that writer. This is a good example of Rust’s strength in kernel code. The formatting traits are available without std, while the kernel provides the device-specific output path.
use core::fmt;
struct EarlyWriter;
impl fmt::Write for EarlyWriter { fn write_str(&mut self, s: &str) -> fmt::Result { for byte in s.bytes() { write_byte_to_device(byte); } Ok(()) }}
fn write_byte_to_device(_byte: u8) { // Device-specific output is added after early hardware // access is available.}This code is intentionally incomplete at the device boundary. The structure is the important part. The formatting layer can be safe and generic, while the byte-writing function will eventually contain the unsafe hardware access. Good kernel Rust tries to keep that separation clear. Formatting text is not unsafe. Writing to a hardware port or memory-mapped device might be. Mixing those responsibilities makes unsafe code harder to audit.
Unsafe code is unavoidable in a kernel, but it should not spread without discipline. The kernel will need raw pointers, inline assembly, volatile operations, control register access, port I/O, memory-mapped I/O, and manual layout decisions. These operations sit outside what Rust can verify on its own. A professional Rust kernel does not avoid unsafe; it contains it. Each unsafe block should have a narrow purpose and a clear reason why the surrounding abstraction makes it valid.
For example, writing to a fixed memory address may be necessary for text-mode video output. The compiler cannot prove that the address is mapped, valid, aligned, exclusive, or appropriate for the operation. Those facts come from the hardware model and boot configuration. The unsafe operation should be wrapped behind a type that limits how the rest of the kernel can use it.
Rust
use core::ptr;
const VGA_BUFFER: *mut u8 = 0xb8000 as *mut u8;
pub fn write_vga_byte(offset: usize, byte: u8) { let address = unsafe { VGA_BUFFER.add(offset) };
unsafe { ptr::write_volatile(address, byte); }}This code writes one byte to the VGA text buffer area using a volatile write. The volatile operation matters because device memory is not ordinary memory. The compiler must not remove or reorder the access as if it were just writing to a normal unused location. This example is still not a complete console driver because it does not validate screen bounds, character attributes, locking, or cursor behavior. It shows the boundary: a hardware access requires unsafe code, and the kernel should build a safer interface around it.
A more controlled version would avoid exposing arbitrary offsets to the rest of the kernel. It would store the buffer dimensions, calculate positions internally, and keep volatile access in one location. That does not make the hardware magically safe. It makes misuse harder.
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 VgaTextWriter { column: usize, row: usize, color: u8, }
impl VgaTextWriter { pub const fn new(color: u8) -> Self { Self { column: 0, row: 0, color, } }
pub fn write_byte(&mut self, byte: u8) { if self.row >= VGA_HEIGHT { return; }
let cell = (self.row * VGA_WIDTH + self.column) * 2;
unsafe { ptr::write_volatile(VGA_BUFFER.add(cell), byte); ptr::write_volatile(VGA_BUFFER.add(cell + 1), self.color); }
self.column += 1;
if self.column >= VGA_WIDTH { self.column = 0; self.row += 1; }}}
The stronger version does not allow the caller to write to any byte offset. The writer tracks rows and columns, writes both the character byte and color byte, and keeps the unsafe operation internal. It is still early code, and it still needs scrolling, newline handling, synchronization, and error behavior. The design is heading in the correct direction because the unsafe memory operation is not the public interface.
Freestanding Rust also requires careful handling of global state. Many kernel subsystems are naturally global. There may be one early serial device, one interrupt descriptor table, one frame allocator, one current page-table mapper during initialization, and one console. In ordinary Rust, global mutable state is discouraged because it creates aliasing and data-race risks. In kernel development, global state must exist, but it must be controlled. The answer is not to scatter mutable statics throughout the code. The better approach is to wrap shared state in synchronization primitives or initialization cells that make access rules explicit.
At this early stage, the kernel may run on a single CPU with interrupts disabled. That does not justify careless global mutation. The project will grow. Interrupts will be enabled. Later code may run inside interrupt handlers. A lock that works before interrupts are enabled may deadlock if acquired again inside an interrupt handler. A global writer that is safe during boot may become unsafe when timer interrupts start printing diagnostics. These issues are easier to handle when the code starts with clear ownership and locking boundaries.
Rust’s value in a kernel becomes most visible when unsafe code is pushed downward and safe APIs are built above it. The entry point is unsafe by nature because an external loader jumps into it. Hardware output is unsafe by nature because raw addresses and device registers are involved. Page-table manipulation is unsafe because an incorrect mapping can break the entire address space. Interrupt setup is unsafe because the CPU will call handlers according to structures you create manually. The rest of the kernel should not need to know every detail of those dangers. It should use carefully designed types and functions that preserve invariants.
The freestanding environment is not a limitation to work around as quickly as possible. It is the condition that teaches what an operating system normally provides. Each missing facility becomes a feature the kernel must either implement or intentionally avoid. No standard output leads to serial and framebuffer drivers. No heap leads to frame allocation and heap allocation. No process runtime leads to a custom entry point. No panic runtime leads to a custom panic handler. No operating-system threads leads
to later scheduler design. Rust can express these systems cleanly, but it will not create them by default.
1.3: Setting Up the Toolchain, Target, and Build Workflow
Section titled “1.3: Setting Up the Toolchain, Target, and Build Workflow”A kernel build is not the same as a normal application build. A normal Rust binary targets an existing operating system and produces an executable file in that system’s expected format. The generated program assumes a process loader, system calls, a standard runtime environment, and libraries that match the host target. A kernel build must produce code that can run without those assumptions. The toolchain has to know that it is building for a freestanding target, not for the operating system you are using to compile the project.
The first requirement is a Rust toolchain with the components needed for low-level compilation. The project should use a stable toolchain wherever practical, but some freestanding workflows require nightly-only features, especially when building parts of the Rust core libraries for a custom target. The important habit is to keep the toolchain choice explicit. Kernel projects should not depend on whatever compiler happens to be installed globally. A pinned or declared toolchain makes builds repeatable across machines.
A rust-toolchain.toml file can declare the channel and components used by the project. The exact channel can be adjusted as the project requirements change, but the file should exist so the project does not depend on hidden local state.
[toolchain]channel = "nightly"components = ["rust-src", "llvm-tools-preview"]The rust-src component is needed when the build process compiles core library components for a target that does not already have precompiled standard library artifacts. The llvm-tools-preview component provides
tools useful for inspecting compiled binaries. Kernel development benefits from binary inspection because addresses, sections, symbols, and entry points matter. If a kernel does not boot, one of the first questions should be whether the binary actually contains the expected entry symbol and whether the sections are laid out at the expected addresses.
A custom target file tells Rust what kind of machine and binary environment the kernel is targeting. The target is not just “x86_64.” A normal x86_64 target usually means x86_64 with a host operating system and ABI. A freestanding kernel target needs different assumptions. It should disable ordinary OS dependencies, define the architecture, specify the linker behavior, control panic strategy indirectly through profiles, and avoid features such as stack unwinding.
{ "llvm-target": "x86_64-unknown-none", "data-layout": "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-i128:128-f80:128-n8:16:32:64-S128", "arch": "x86_64", "target-endian": "little", "target-pointer-width": "64", "target-c-int-width": "32", "os": "none", "executables": true, "linker-flavor": "ld.lld", "linker": "rust-lld", "panic-strategy": "abort", "disable-redzone": true, "features": "-mmx,-sse,+soft-float"}This target file expresses several important choices. The operating system is set to none, which matches a freestanding kernel. The panic strategy aborts instead of unwinding. The red zone is disabled. On x86_64, the red zone is a small area below the stack pointer that ordinary functions may use without adjusting the stack pointer. That behavior is unsafe for kernel code that can be interrupted, because an interrupt may use the same stack and overwrite data stored in that area. Disabling the red zone is a standard kernel requirement.
The floating-point and SIMD-related feature choices also matter. Early kernels usually avoid floating-point and SIMD instructions because using them correctly requires saving and restoring additional CPU state during context switches and interrupt handling. A kernel should not accidentally generate instructions that depend on state it does not manage yet. Later, if the kernel supports floating-point use, it must do so deliberately.
The project also needs Cargo configuration that tells Cargo which target to build and how to build core library components when necessary. A .cargo/config.toml file keeps those settings inside the project.
[build]target = "x86_64-kernel.json"
[unstable]build-std = ["core", "compiler_builtins"]
[target.'cfg(target_os = "none")']runner = "qemu-system-x86_64"This configuration points the build at a custom target file and requests the core components needed for the freestanding build. The runner line shown here is only a starting point. In a real kernel workflow, QEMU usually needs more arguments than a plain command name. You may need to provide a bootable disk image, disable rebooting, attach a serial device, use a firmware image, or enable a debugging stub. The value of placing the runner in Cargo configuration is that cargo run can become part of the kernel workflow rather than a separate manual step.
A more useful runner is often a small script. The script can call QEMU with arguments that support debugging and repeatable output. When a command becomes long enough to hide important details, place it in a script and keep the script under version control.
#!/bin/shset -euqemu-system-x86_64 \-drive format=raw,file=target/kernel.img \-serial stdio \-no-reboot \-no-shutdownThis script starts QEMU, attaches serial output to the terminal, and prevents QEMU from immediately closing or rebooting when the guest crashes. Those two options are important for kernel debugging. Without them, a triple fault may look like QEMU simply restarted or disappeared. Keeping the virtual machine open gives you a chance to see the last output and inspect behavior.
The build workflow should produce an artifact the bootloader can load. Depending on the boot strategy, this may be an ELF kernel, a bootable disk image, an ISO image, or a UEFI application. The early project should not mix all possible formats at once. Choose one primary path, make it reliable, and add alternatives later. A clean build path is worth more than a clever build path. The build should answer three questions consistently: what binary was produced, how was it placed into a bootable format, and how was that format launched in QEMU.
The Rust source itself must match the build strategy. The entry point, symbol name, and linker behavior have to agree with the bootloader. If the bootloader expects an ELF kernel with a specific entry symbol, that symbol must exist. If the bootloader passes a boot information pointer to the entry function, the Rust function signature must match that calling convention. If a bootloader crate provides a macro that defines the entry point, then manually defining _start may be wrong. The early code should not treat examples from different boot methods as interchangeable.
A direct _start entry is useful for understanding freestanding Rust, but many bootloader integrations provide their own entry mechanism. In that case, the kernel entry function may receive boot information through a typed reference or pointer. The exact type depends on the boot interface, but the pattern is consistent: the bootloader transfers control to a function, and the kernel begins by validating and storing the information it needs.
#![no_std]#![no_main]
use core::panic::PanicInfo;
pub struct BootInfo { pub physical_memory_offset: u64,}
#[unsafe(no_mangle)]pub extern "C" fn kernel_main(boot_info: &'static BootInfo) -> ! { let _memory_offset = boot_info.physical_memory_offset;
loop { core::hint::spin_loop(); }}
#[panic_handler]fn panic(_info: &PanicInfo) -> ! { loop { core::hint::spin_loop(); }}This code is not tied to a specific bootloader crate. It shows the shape of a kernel handoff where boot information arrives as a reference. In production-quality kernel code, you would not invent this structure without matching the real boot protocol. The point is that the Rust signature must express the actual handoff contract. If the bootloader passes a pointer and the kernel treats it as a reference with the wrong lifetime or layout, the type system cannot rescue the program. At the ABI boundary, correctness depends on matching the contract exactly.
The linker step is another area where kernel projects often fail. Application developers rarely need to think about linker scripts, section addresses, or symbol placement. Kernel developers do. The bootloader needs to know where the entry point is. The CPU needs executable code mapped at the address it will fetch from. Static data, read-only data, uninitialized data, stacks, and special tables may require alignment. Later, page-table setup
may depend on knowing where the kernel starts and ends. Linker mistakes can produce binaries that compile perfectly and fail instantly.
Some bootloader-based workflows hide much of the linker complexity at first, which is fine. You should still understand that the binary has sections and symbols. Inspecting the kernel artifact is part of the workflow, not a last resort. If the kernel fails before printing anything, binary inspection may be the fastest way to find a missing symbol, wrong architecture, unexpected relocation, or incorrectly placed section.
cargo build
rust-readobj --file-headers --sections target/x86_64-kernel/debug/kernel
rust-objdump --syms target/x86_64-kernel/debug/kernelThe exact output path depends on the package name and target configuration. These commands show the habit that matters. Build the kernel, inspect the headers and sections, then inspect the symbols. If the expected entry point is not present, the bootloader cannot call it. If sections are not where the linker or boot protocol expects them to be, startup may fail before Rust code has a chance to report anything.
A kernel project also needs a clean distinction between host tools and target code. Host tools run on your development machine. Kernel code runs inside the virtual machine or on hardware. A build script or image builder may use std because it is a host program. The kernel crate may not. Mixing those assumptions leads to confusion. If the project needs helper programs, put them in separate crates or clearly separate directories. Do not let a host-only dependency accidentally enter the kernel crate.
Cargo workspaces are useful once the project grows. The kernel crate can stay no_std, while an image builder, test runner, or tool crate can use std. This gives you the convenience of Rust for development tools without polluting the kernel environment.
[workspace]members = [ "kernel", "tools/image-builder"]resolver = "2"This workspace layout keeps responsibilities clear. The kernel package builds freestanding code. The tools/image-builder package can run on the host and prepare boot images. The resolver setting helps Cargo handle features more predictably across workspace members. The exact layout can change, but the separation should remain.
The build workflow should also include failure visibility from the beginning. A kernel that only shows success on screen is hard to debug. A better workflow prints early serial output, uses QEMU options that preserve failure state, and later returns exit codes for automated tests. When a kernel panics, it should print the panic location. When it faults, it should print the exception name and relevant CPU information. When it reaches a test success condition, QEMU should be able to exit with a known code. These capabilities are not luxuries. They are how you avoid guessing.
The first build system is not final. It will change as the kernel gains paging, heap allocation, tests, boot protocol support, and possibly UEFI or Limine alternatives. The goal is not to predict every future need. The goal is to start with a build structure that is explicit, inspectable, and not dependent on hidden machine state. A kernel that builds only on one laptop because of global tools and undocumented paths is already fragile. A kernel that declares its toolchain, target, profile, runner, and artifact process gives you a stable base for the technical work ahead.
1.4: Project Structure for a Maintainable Rust Kernel
Section titled “1.4: Project Structure for a Maintainable Rust Kernel”A kernel grows quickly. What begins as one file with an entry point and a panic handler soon needs output, architecture setup, interrupts, memory maps, frame allocation, page mapping, heap allocation, device input,
synchronization, tests, and debugging support. If all of that code remains in one file, the kernel becomes harder to reason about exactly when correctness matters most. A maintainable structure is not about making the project look polished. It is about keeping responsibilities separate so mistakes are easier to locate and unsafe code is easier to audit.
The structure should reflect the kernel’s real boundaries. Some code is architecture-specific. On x86_64, this includes descriptor tables, control registers, port I/O, interrupt setup, and page-table details. Some code is device-specific. Serial output, keyboard input, timers, and framebuffer access belong near drivers or hardware modules. Some code is kernel-policy code. Memory allocation, logging, panic behavior, shell commands, and testing support belong at a higher level. When these layers are mixed together, the project becomes harder to extend. A keyboard driver should not need to know how the frame allocator parses the boot memory map. A heap allocator should not be coupled to the details of the serial port. The entry point should coordinate initialization, not contain every subsystem.
A practical early layout can start small while leaving room to grow.
#![no_std]#![no_main]
mod arch;mod boot;mod console;mod panic;mod serial;
#[unsafe(no_mangle)]pub extern "C" fn _start() -> ! { serial::init(); console::init();
serial_println!("kernel started");
loop { arch::halt(); }}This entry file shows the desired shape. It does not implement everything directly. It calls subsystem initialization functions and then halts. The entry point should remain readable. Later, it may initialize the GDT, IDT, memory map, frame allocator, heap, interrupts, timer, keyboard, and shell. Even then, it should remain a coordinator. When startup becomes a long sequence, each step should have a name that explains what responsibility is being initialized.
The module tree should keep architecture-specific code under an architecture module. That module can expose a small set of functions used by the rest of the kernel. For example, the rest of the kernel may need to halt the CPU, enable interrupts, disable interrupts, read control registers, or perform port I/O. Those details should not be scattered across unrelated modules.
Rust
pub mod interrupts;pub mod memory;pub mod port;
pub fn halt() -> ! { loop { x86_64::instructions::hlt(); }}
pub fn enable_interrupts() { x86_64::instructions::interrupts::enable();}
pub fn disable_interrupts() { x86_64::instructions::interrupts::disable();}This kind of architecture facade makes dependencies clearer. Higher-level kernel code can call arch::halt() without knowing which instruction is used. Interrupt setup can live under arch::interrupts. Page-table code can live under arch::memory while a more general memory module owns allocation policy. This separation becomes valuable if you later compare
boot protocols or add limited support for another architecture. Even if the project remains x86_64 only, the code is easier to understand.
The boot module should translate bootloader-specific information into kernel-owned initialization data. This is especially important because boot protocols differ. One bootloader may provide a memory map in one format. Another may provide framebuffer information differently. One may pass a physical memory offset, another may provide a higher-half direct map. The rest of the kernel should not be filled with bootloader-specific types. A boot module can receive raw boot information and convert it into internal structures that the memory manager, console, and device layers can use.
pub struct KernelBootInfo { pub physical_memory_offset: u64, pub framebuffer_address: Option<u64>, pub framebuffer_size: Option<usize>,}
impl KernelBootInfo { pub fn new( physical_memory_offset: u64, framebuffer_address: Option<u64>, framebuffer_size: Option<usize>, ) -> Self { Self { physical_memory_offset, framebuffer_address, framebuffer_size, } }}This is only a small example, but it shows the design direction. The kernel can define its own internal representation rather than letting external bootloader data leak everywhere. The internal structure should contain only information the kernel has validated or intentionally preserved. Later, memory maps will need richer structures with region types, start addresses, lengths, and ownership rules. Even then, the principle remains the same. Translate at the boundary. Keep the rest of the kernel working with kernel-owned concepts.
The console layer should separate formatted output from hardware output. Early kernels often begin by printing directly to VGA memory or serial ports from macros. That is fine for the first step, but it becomes a problem if formatting, locking, device access, and panic behavior become tangled. A cleaner design gives the kernel a common output interface, then sends output to one or more backends such as serial and framebuffer.
Rust
use core::fmt::{self, Write};
pub struct KernelWriter;
impl Write for KernelWriter { fn write_str(&mut self, s: &str) -> fmt::Result { crate::serial::write_str(s); crate::console::write_str(s); Ok(()) }}
pub fn print(args: fmt::Arguments) { let mut writer = KernelWriter; let _ = writer.write_fmt(args);}This code uses core::fmt::Write, which works in a no_std environment. The formatting logic does not depend on std. The destination is controlled by the kernel. At first, serial::write_str and console::write_str may be small functions. Later, they may acquire locks, handle scrolling, support colors, or check device initialization state. The rest of the kernel can keep using a common print path.
Macros can make this print path convenient without pretending that standard output exists.
Rust
#[macro_export]macro_rules! kprint { ($($arg:tt)*) => { $crate::console_writer::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)*) };}The macro names avoid pretending to be the standard library’s print! and println!, although some kernels intentionally define familiar names. Using kernel-specific names can make the distinction clearer. Output is not going to a process stream. It is going to whatever devices the kernel has initialized.
Panic handling deserves its own module even when it is short. Panic behavior changes over time. Early on, the panic handler may only spin. After serial output exists, it should print. After interrupt handling exists, it may disable interrupts before printing. After framebuffer output exists, it may print to screen as well. After tests exist, panic behavior may differ between normal kernel runs and test kernels. Keeping panic code isolated prevents these changes from spreading through unrelated modules.
use core::panic::PanicInfo;
#[panic_handler]fn panic(info: &PanicInfo) -> ! { crate::arch::disable_interrupts(); crate::kprintln!("kernel panic: {}", info); crate::arch::halt();}This panic handler disables interrupts, prints diagnostic information, and halts. That sequence is reasonable once the architecture layer and output path are available. In earlier code, disabling interrupts or printing may not
be possible yet. The structure allows the panic behavior to improve as the kernel becomes more capable.
Memory code should be split carefully from the beginning. Physical frame allocation, virtual memory mapping, heap allocation, and memory-map parsing are connected, but they are not the same responsibility. A frame allocator hands out physical frames. A mapper creates virtual-to-physical mappings. A heap allocator manages dynamic allocation within a mapped virtual memory range. A memory-map parser interprets bootloader or firmware information. Combining these into one large module makes it hard to audit invariants.
A reasonable structure uses a top-level memory module for policy and smaller modules for specific tasks.
Rust
pub mod frame;pub mod heap;pub mod map;pub mod region;
pub fn init() { // Memory initialization is added once boot memory // information is available.}The frame module can own frame allocation. The map module can own page-table mapping. The heap module can own global allocator setup. The region module can define memory-region types used across the memory system. As the kernel grows, this separation prevents heap allocation code from directly parsing bootloader memory maps or page-table code from knowing too much about console output.
Unsafe code should be placed where the underlying operation requires it, not where it happens to be convenient. For example, if a serial driver needs unsafe port I/O, the unsafe block belongs inside the serial or port abstraction. Higher-level logging code should not perform raw port writes directly. If page-table code needs unsafe access to active page tables, that
unsafe behavior should be located inside memory-mapping functions with clear invariants. If a global allocator needs unsafe pointer manipulation, the allocator should contain it rather than exposing raw heap internals to callers.
This placement matters because unsafe code is not only a compiler marker. It is a maintenance signal. When you later review the kernel, unsafe blocks tell you where Rust’s usual guarantees are being extended by manual reasoning. If unsafe blocks appear everywhere, that signal becomes useless. If they are concentrated behind well-named abstractions, you can review them carefully and trust more of the surrounding code.
The project should also keep initialization order explicit. Kernel subsystems depend on each other. Serial output can often start before memory allocation. The GDT should be loaded before relying on certain CPU structures. The IDT should be ready before enabling interrupts. The frame allocator needs a valid memory map. The heap needs mapped memory and a global allocator. The keyboard driver should not receive interrupts before the interrupt controller and IDT are configured. A shell should not run before input and output are ready.
The entry point can express this order clearly.
Rust
#[unsafe(no_mangle)]pub extern "C" fn _start() -> ! { crate::serial::init(); crate::kprintln!("serial online");
crate::arch::gdt::init(); crate::kprintln!("gdt loaded");
crate::arch::interrupts::init_idt(); crate::kprintln!("idt loaded");
crate::memory::init(); crate::kprintln!("memory initialized");
crate::allocator::init(); crate::kprintln!("heap initialized");}crate::arch::interrupts::enable();crate::kprintln!("interrupts enabled");
crate::kernel_main()This code is a sketch of the final shape, not the first file you write. It shows how initialization should read. Each line has a clear purpose. Diagnostic output after each major step helps identify where failure occurs. If the kernel prints “idt loaded” but not “memory initialized,” the failure window is narrow. That kind of visibility saves enormous time.
The actual implementation should also account for failure. Early kernels often use functions that panic on failure because there is no recovery path yet. That is acceptable if the panic message is clear. As the kernel matures, initialization functions can return Result values and report specific errors. Even in kernel code, expressive error types are useful. A failed memory initialization caused by an absent boot memory map is not the same as one caused by an invalid region alignment.
pub enum InitError { MissingMemoryMap, InvalidMemoryRegion, HeapAlreadyInitialized,}
pub type InitResult<T> = Result<T, InitError>;The kernel may still panic when initialization fails, but the error structure improves the code. It prevents every failure from becoming a vague “init failed” message. Clear failure types are a professional habit that pays off when debugging low-level code.
Tests should also influence structure early. Kernel testing is different from ordinary application testing, but the project can still be organized for testability. Pure functions should stay pure where possible. Parsers for memory regions, address alignment helpers, range checks, and allocator bookkeeping can often be tested without booting the entire kernel. Code
that directly touches hardware should be isolated so it can be tested with controlled wrappers or exercised in QEMU integration tests. If every function reaches into global hardware state, testing becomes much harder.
A maintainable kernel is not one that avoids complexity. Kernel development is inherently full of sharp edges. A maintainable kernel is one where the sharp edges are named, isolated, and checked. The project structure should make it obvious which code depends on x86_64, which code depends on a boot protocol, which code performs unsafe memory access, which code owns initialization, and which code provides reusable kernel services.
The best early structure is modest but intentional. It should not create dozens of empty modules for features that do not exist yet. It should also not trap the whole kernel in one file. Start with entry, architecture, boot, serial, console, panic, and memory boundaries. Add interrupt, allocator, driver, shell, and test modules as those features arrive. Let the structure follow actual responsibilities, not decoration.
By the end of the foundation stage, you should have a kernel project that can compile as freestanding Rust, expose a controlled entry point, build for a custom target, run under QEMU, print early diagnostics, handle panics without relying on an operating system, and keep code organized around real kernel boundaries. That foundation does not yet make a complete operating system, but it creates the conditions required to build one correctly.