Bootloaders and the First Kernel Entry Point
local graph
Chapter 2 — Bootloaders and the First Kernel Entry Point
Section titled “Chapter 2 — Bootloaders and the First Kernel Entry Point”Chapter 2: Bootloaders and the First Kernel Entry Point
Section titled “Chapter 2: Bootloaders and the First Kernel Entry Point”A Rust kernel does not begin like an ordinary Rust application. There is no operating system to create a process for it, no runtime to prepare a friendly call to main, and no standard output stream waiting for text. Before the kernel can manage memory, handle interrupts, or communicate with devices, it must be loaded into memory and started in a CPU state it can actually use. That early transfer of control is the job of the boot path.
The boot path is one of the first places where kernel development becomes practical rather than theoretical. A file full of correct Rust code is not enough. The binary must be shaped in a way the bootloader understands, placed somewhere the bootloader can load, and started through an entry point whose calling convention and assumptions match the handoff. If any part of that chain is wrong, the result is often silence. There may be no panic message, no stack trace, and no useful screen output. The kernel may not have reached your code at all.
This is why the bootloader deserves careful attention early. The goal is not to turn the first kernel milestone into a full bootloader engineering project. The goal is to understand what the bootloader contributes, what assumptions it creates, and how your kernel receives control. Once that boundary is clear, the first bootable Rust kernel becomes less mysterious. You can reason about what happened before your code ran, what information the kernel receives, and what the kernel must avoid doing too soon.
A practical kernel project should choose a boot strategy that supports learning and progress. It should give enough structure to boot reliably, but not hide so much that the kernel becomes dependent on magic. The best early path is one where the bootloader prepares the machine, passes boot information, and allows the kernel to focus on its first responsibilities: entering Rust code, proving execution with visible output, halting safely, and creating a foundation for later memory and interrupt work.
2.1: BIOS, UEFI, and the Kernel Handoff Process
Section titled “2.1: BIOS, UEFI, and the Kernel Handoff Process”A computer does not start by running your kernel. It starts by running firmware. Firmware is the first software layer that takes control after reset. Its job is to initialize enough of the platform to locate something bootable and transfer control to it. On x86_64 systems, the two boot environments you will commonly encounter are BIOS-style booting and UEFI-style booting. They differ in design, capabilities, file formats, firmware interfaces, and the type of bootloader they expect, but both exist to solve the same early problem: how to get from a powered-on machine to executable operating-system code.
BIOS-style booting is older and more constrained. In the traditional BIOS path, the firmware searches for a boot device, reads a small boot sector, and starts executing code from that sector. That first piece of code is tiny, so it usually cannot load a complete modern kernel by itself. It often loads a larger second-stage bootloader, which then loads the kernel, prepares the CPU, and transfers control. The BIOS path has historical importance because it shaped much of early operating-system development. It also teaches useful low-level ideas, such as boot sectors, real mode, and staged loading. For a modern Rust kernel project, however, writing a BIOS boot sector first is usually not the best way to make progress. It introduces old CPU modes, tight size limits, and assembly-heavy setup before the kernel has any debugging support.
UEFI booting is more modern and more structured. Instead of loading a raw boot sector, UEFI firmware can load an executable file from a filesystem on an EFI system partition. A UEFI application can call firmware services, obtain a memory map, access graphics output information, allocate memory, read files, and eventually call a function that exits boot services. After that point, the operating system takes responsibility for the platform. UEFI gives the bootloader more facilities than BIOS, but it also introduces its own rules. The memory map must be handled carefully. Runtime-service memory must be preserved correctly. Firmware services are available only during the correct phase. If a loader continues to depend on boot services after exiting them, the design is broken.
For the kernel developer, the most important point is that BIOS and UEFI are not just two names for the same process. They offer different boot environments. A BIOS bootloader may begin in 16-bit real mode and perform a long sequence of CPU setup steps before the kernel ever runs. A UEFI loader usually begins as a firmware-loaded executable with access to structured boot services. In both cases, by the time your Rust kernel starts, the bootloader may have already performed major setup work. It may have loaded the kernel into memory, selected a stack, entered 64-bit long mode, created page tables, prepared a framebuffer, and created a boot information structure.
The handoff process is the boundary between the bootloader and the kernel. It is not a casual function call. It is a contract. The bootloader promises that certain machine conditions are true. The kernel promises to interpret the entry state correctly. If the bootloader says the kernel entry receives a pointer to boot information, the kernel must use the correct function signature and the correct data layout. If the bootloader says the CPU is already in long mode, the kernel can begin executing 64-bit code, but it still needs to understand what page mappings exist. If the bootloader provides a memory map, the kernel must treat that map as the basis for early physical memory decisions. If the bootloader provides framebuffer information, the kernel must respect its address, size, pixel format, and stride.
One common mistake is assuming that a bootloader simply “starts the kernel” and nothing more. A useful bootloader does much more than jump to an address. It solves the early loading problem. It finds the kernel image, loads it into memory, handles whatever file or image format it supports, prepares processor state, and provides information the kernel would otherwise have to obtain from firmware directly. Without a bootloader, the kernel would need to know how to speak to firmware, read storage devices or filesystems, place itself correctly in memory, and transition the CPU into a usable execution mode. Those tasks are valuable to study, but they are not the same as building the kernel.
The kernel should treat bootloader-provided data with respect, not blind trust. During early development, the bootloader may provide a physical memory offset, a memory map, framebuffer details, and possibly ACPI-
related information. These values become the starting point for later subsystems. The memory manager depends on the memory map. The console may depend on the framebuffer. The page mapper may depend on how physical memory is mapped into virtual memory. If the kernel stores these values carelessly or modifies memory before understanding them, it can destroy the same information it needs to continue.
The handoff also affects the first Rust function. In an ordinary program, the entry point is usually main, and the environment prepares arguments, stack state, and runtime support. In a kernel, the entry function is defined by the boot strategy. Some bootloaders expect a symbol with a known name. Some provide a macro that creates the correct low-level entry and calls a Rust function with typed boot information. Some protocols pass registers with pointers or values. Some use request-and-response structures placed in special sections. The kernel entry must match the chosen boot path exactly.
CPU state is another part of the handoff. The kernel needs to know which mode the CPU is in, what stack is active, whether interrupts are enabled, which page tables are active, and which memory ranges are mapped. On x86_64, a Rust kernel expects to run in 64-bit mode. If the CPU is still in an earlier mode, ordinary 64-bit Rust code cannot execute correctly. In many Rust kernel projects, the bootloader handles the transition to long mode so the kernel can start as 64-bit code. That is helpful, but it does not remove the need to understand long mode later. The kernel will eventually set up its own descriptor tables, interrupt tables, and memory mappings. The bootloader may prepare an initial state, but the kernel must eventually own its execution environment.
The stack is another quiet but critical part of startup. Rust functions need a valid stack. Local variables, return addresses, function calls, and some compiler-generated operations depend on it. If the bootloader provides the initial stack, the kernel can begin executing Rust functions. Later, the kernel may create its own stacks for kernel execution, interrupt handling, double-fault recovery, and future task switching. At the first entry point, however, the important fact is that a stack exists and is mapped. If it does not, the first function call can fault immediately.
Memory mappings determine whether addresses used by the kernel are valid. The CPU translates virtual addresses through page tables when paging is active. If the kernel is linked to run at one virtual address but loaded or mapped differently, execution can fail before any output appears. The bootloader and linker must agree on how the kernel is placed and addressed. Some boot strategies use identity mapping, where virtual addresses match physical addresses for early memory. Others place the kernel in the higher half of the address space. Some provide a direct mapping of physical memory at a fixed virtual offset. These decisions shape how the kernel accesses its own image, boot information, page tables, and device memory.
Firmware services are also part of the boundary. In a UEFI-based path, the loader can use firmware services before the operating system takes full control. Once boot services are exited, the kernel should not call them as if they are still available. This is a major difference between writing a UEFI loader and writing the kernel after the loader has completed its work. If your kernel relies on a bootloader, the bootloader should collect the required firmware information before the kernel begins. The kernel then works from the handed-off data rather than repeatedly calling firmware.
The handoff process should leave the kernel with enough information to begin responsibly. It should know where useful memory exists, where reserved memory exists, how to produce early output, and what assumptions exist about virtual memory. It should also know what not to touch. A professional kernel is careful with early memory because it has not yet built the tools that would let it recover from mistakes. Before the frame allocator is initialized, memory should not be treated as a free pool. Before the interrupt descriptor table is ready, interrupts should not be casually enabled. Before the panic path can print, failure may be silent.
A clean understanding of BIOS, UEFI, and handoff mechanics prevents confusion later. When the kernel reaches its first Rust function, it is not starting from nothing. It is inheriting a prepared machine state. That inherited state is useful, but temporary. The kernel’s task is to use it long enough to build its own control over memory, interrupts, devices, and execution policy.
2.2: Choosing a Practical Boot Strategy for the Project
Section titled “2.2: Choosing a Practical Boot Strategy for the Project”A kernel project can fail early by choosing the wrong boot strategy for its goal. If the goal is to learn boot sectors, firmware calling conventions, and CPU mode transitions from the first instruction after reset, then writing a custom bootloader is appropriate. If the goal is to build a Rust kernel that teaches memory management, interrupts, device access, and low-level system programming, then starting with a reliable bootloader is the stronger decision. The choice should serve the project, not distract from it.
A practical boot strategy should satisfy several needs at once. It should support x86_64 code. It should allow the kernel to receive reliable boot information. It should work well in QEMU. It should avoid unnecessary early assembly. It should make early debugging possible. It should be stable enough that most failures come from the kernel code rather than from the boot path. It should also leave room to discuss modern alternatives without forcing the main project to support all of them from the beginning.
The first possible strategy is to write a custom BIOS bootloader. This gives maximum control and educational value at the firmware boundary, but it is not the best early choice for a Rust kernel development guide. BIOS booting begins with severe constraints. The first boot sector is tiny. The CPU starts in a legacy execution mode. Loading more code from disk requires low-level disk access or a second-stage loader. Entering protected mode and then long mode requires careful setup. None of this is impossible, but it delays the first meaningful Rust kernel milestone. You can spend a long time solving bootloader problems before learning much about kernel design.
The second strategy is to write a custom UEFI loader. This is more modern than BIOS booting and more pleasant in several ways. A UEFI loader can be written as an executable file, can use firmware services, and can load the kernel from a filesystem. It can obtain a framebuffer and memory map through defined interfaces. It can then exit boot services and transfer control to the kernel. This approach is realistic and valuable, especially for advanced work. The tradeoff is that it still requires careful loader engineering. The loader must manage memory-map changes, align loaded
segments, handle graphics output, preserve required memory types, and define a private handoff structure. That is excellent material once the kernel foundation is working, but it is too much overhead for the first kernel entry point.
The third strategy is to use a general bootloader protocol, such as a multiboot-style or modern request-based boot protocol. This can be a good choice, especially when the bootloader is well maintained and the protocol passes useful information. The kernel can focus on interpreting a structured handoff instead of implementing firmware interaction directly. The tradeoff is that each protocol has its own data structures and expectations. A kernel written tightly around one boot protocol can become hard to adapt unless you isolate the boot-specific code behind a clean internal interface.
The fourth strategy is to use a Rust-oriented bootloader crate or ecosystem tool that is designed to load Rust kernels. This is usually the most practical starting point. It lets the project boot quickly, receive typed boot information, and begin kernel work in Rust without building a loader from scratch. It also aligns with the rest of the Rust tooling. The risk is that a convenient bootloader can hide important details if you let it. The right approach is to use it, but explain what it is doing. Convenience should reduce mechanical friction, not replace understanding.
For this project, the best main path is to use a bootloader that prepares an x86_64 environment and hands control to a Rust kernel with usable boot information. The kernel should not begin by writing a disk driver, parsing a filesystem, or switching CPU modes manually. Those topics are meaningful, but they are not the most direct route to a working Rust kernel. The early priority is to produce a bootable kernel, establish visible output, confirm control flow, and create a stable base for memory and interrupt work.
This decision is realistic. Professional systems work often relies on existing firmware, existing bootloaders, and well-defined handoff protocols. Writing everything yourself is not automatically better. A kernel engineer should know where the boundary is and why it exists. If a trusted bootloader already solves loading, CPU mode setup, and basic handoff, then the kernel can focus on the responsibilities that define it as a kernel. Later, when the
project has a stronger debugging base, a custom UEFI loader or a modern alternative protocol can be examined with much less guesswork.
The project should still discuss BIOS and UEFI because the bootloader’s work depends on them. Even if you do not write BIOS boot code, you need to understand why BIOS-style booting is constrained. Even if you do not write a complete UEFI loader at the beginning, you need to understand why UEFI memory maps and boot-service transitions matter. This background prevents the bootloader from becoming an unexplained black box. The kernel receives boot information because some earlier software obtained it. The kernel starts in a usable CPU state because some earlier software created it. Understanding that chain helps you debug when the assumptions do not match reality.
The boot strategy should also support a clean internal handoff model. The kernel should not let bootloader-specific structures spread into every subsystem. Instead, the entry code should receive the bootloader’s information and translate it into kernel-owned startup data. That internal representation can include memory regions, framebuffer information, physical memory offset, kernel image boundaries, and any other data needed by early subsystems. This translation layer gives the project flexibility. If you later support another boot protocol, most of the kernel can remain unchanged.
A good boot strategy also improves testing. QEMU should be able to launch the kernel repeatably. The build should create the same kind of image each time. Serial output should be attached to the terminal. Reboots should be disabled during debugging. Later, tests should be able to exit QEMU with a known code. If the boot path requires too many manual steps, the development workflow becomes fragile. Kernel work is already hard enough. The boot and run commands should be boring, repeatable, and easy to inspect.
The chosen strategy should not promise real hardware compatibility too early. QEMU is the right early target because it gives a controlled environment. Real hardware introduces device differences, firmware quirks, timing differences, missing output, and greater risk. A kernel that
segments, handle graphics output, preserve required memory types, and define a private handoff structure. That is excellent material once the kernel foundation is working, but it is too much overhead for the first kernel entry point.
The third strategy is to use a general bootloader protocol, such as a multiboot-style or modern request-based boot protocol. This can be a good choice, especially when the bootloader is well maintained and the protocol passes useful information. The kernel can focus on interpreting a structured handoff instead of implementing firmware interaction directly. The tradeoff is that each protocol has its own data structures and expectations. A kernel written tightly around one boot protocol can become hard to adapt unless you isolate the boot-specific code behind a clean internal interface.
The fourth strategy is to use a Rust-oriented bootloader crate or ecosystem tool that is designed to load Rust kernels. This is usually the most practical starting point. It lets the project boot quickly, receive typed boot information, and begin kernel work in Rust without building a loader from scratch. It also aligns with the rest of the Rust tooling. The risk is that a convenient bootloader can hide important details if you let it. The right approach is to use it, but explain what it is doing. Convenience should reduce mechanical friction, not replace understanding.
For this project, the best main path is to use a bootloader that prepares an x86_64 environment and hands control to a Rust kernel with usable boot information. The kernel should not begin by writing a disk driver, parsing a filesystem, or switching CPU modes manually. Those topics are meaningful, but they are not the most direct route to a working Rust kernel. The early priority is to produce a bootable kernel, establish visible output, confirm control flow, and create a stable base for memory and interrupt work.
This decision is realistic. Professional systems work often relies on existing firmware, existing bootloaders, and well-defined handoff protocols. Writing everything yourself is not automatically better. A kernel engineer should know where the boundary is and why it exists. If a trusted bootloader already solves loading, CPU mode setup, and basic handoff, then the kernel can focus on the responsibilities that define it as a kernel. Later, when the
project has a stronger debugging base, a custom UEFI loader or a modern alternative protocol can be examined with much less guesswork.
The project should still discuss BIOS and UEFI because the bootloader’s work depends on them. Even if you do not write BIOS boot code, you need to understand why BIOS-style booting is constrained. Even if you do not write a complete UEFI loader at the beginning, you need to understand why UEFI memory maps and boot-service transitions matter. This background prevents the bootloader from becoming an unexplained black box. The kernel receives boot information because some earlier software obtained it. The kernel starts in a usable CPU state because some earlier software created it. Understanding that chain helps you debug when the assumptions do not match reality.
The boot strategy should also support a clean internal handoff model. The kernel should not let bootloader-specific structures spread into every subsystem. Instead, the entry code should receive the bootloader’s information and translate it into kernel-owned startup data. That internal representation can include memory regions, framebuffer information, physical memory offset, kernel image boundaries, and any other data needed by early subsystems. This translation layer gives the project flexibility. If you later support another boot protocol, most of the kernel can remain unchanged.
A good boot strategy also improves testing. QEMU should be able to launch the kernel repeatably. The build should create the same kind of image each time. Serial output should be attached to the terminal. Reboots should be disabled during debugging. Later, tests should be able to exit QEMU with a known code. If the boot path requires too many manual steps, the development workflow becomes fragile. Kernel work is already hard enough. The boot and run commands should be boring, repeatable, and easy to inspect.
The chosen strategy should not promise real hardware compatibility too early. QEMU is the right early target because it gives a controlled environment. Real hardware introduces device differences, firmware quirks, timing differences, missing output, and greater risk. A kernel that
does not yet have reliable exception handling, memory protection, and logging should not be treated as a real-hardware-ready system. The project can be designed with real hardware concepts in mind, but QEMU is the correct first execution environment.
There is also a maintenance concern. Bootloader tools and crates evolve. A manuscript, code repository, or project template should avoid scattering version-specific details through the conceptual explanation. The code can pin versions in configuration files, while the prose focuses on the concepts that remain stable: the bootloader loads the kernel, prepares machine state, passes boot information, and jumps to the entry point. That separation keeps the learning durable even when tooling changes.
Choosing a practical boot strategy is not a shortcut. It is an engineering decision. It allows the kernel work to begin at the right level of abstraction. You still need to understand the handoff. You still need to understand where the stack comes from, how memory is mapped, how boot information is represented, and what the kernel can safely do first. You simply do not need to implement every firmware and loader detail before reaching the first line of Rust kernel code.
2.3: Building the First Bootable Rust Kernel
Section titled “2.3: Building the First Bootable Rust Kernel”The first bootable Rust kernel should prove three things clearly. The build system can produce a freestanding binary. The bootloader can load that binary and transfer control to it. The kernel can execute a known entry function and remain in control without returning. At this stage, the kernel does not need a memory manager, interrupt handling, or a display driver. It needs a correct beginning.
Start with a kernel crate that does not depend on the standard library. The crate needs a manifest, profile settings that abort on panic, and source code that defines a freestanding entry point and panic handler. Depending on the selected bootloader, the exact entry mechanism may differ. The simplest correct Rust shape is still useful because it shows the essential pieces: no standard library, no normal main, a non-returning entry point, and a panic handler.
[package]name = "rust_kernel"version = "0.1.0"edition = "2024"
[dependencies]
[profile.dev]panic = "abort"
[profile.release]panic = "abort"This manifest keeps the first kernel crate intentionally small. The edition setting enables current language behavior for the crate. The panic strategy is set to abort for development and release builds because stack unwinding is not appropriate in this early freestanding environment. The dependency section starts empty because the first goal is to prove that the kernel can enter Rust code without relying on external abstractions.
The first source file defines the crate as freestanding and supplies the entry point. This version does not print anything yet. It simply enters the kernel and stops in a controlled loop.
#![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(); }}The important feature of this file is not what it does, but what it refuses to assume. It does not assume a normal main function. It does not assume a standard library. It does not return. It does not allocate. It does not print. It does not call operating-system services. That restraint is correct. The first bootable kernel should begin with only the assumptions that the boot path can satisfy.
The _start function is exported with a fixed symbol name. In some toolchains, that symbol may be what the bootloader or linker uses as the entry point. In other bootloader integrations, you may not define _start directly because the bootloader support code generates the real low-level entry and calls a Rust function that you provide. This distinction is important. You should not mix entry styles. If the selected bootloader expects a macro-based entry declaration, use that style. If it expects a raw symbol, provide the symbol. The kernel entry must match the boot strategy exactly.
A bootloader-integrated project often looks different because the bootloader library defines the low-level entry point and passes a boot information structure into your Rust function. The source code then focuses on the kernel’s main function rather than the raw entry symbol. The following example shows the shape of such an approach without depending on a specific bootloader API name.
Rust
#![no_std]#![no_main]
use core::panic::PanicInfo;
pub struct BootInfo { pub physical_memory_offset: u64,}
pub fn kernel_main(boot_info: &'static BootInfo) -> ! { let _physical_memory_offset = boot_info.physical_memory_offset;loop { core::hint::spin_loop();}
#[panic_handler]fn panic(_info: &PanicInfo) -> ! { loop { core::hint::spin_loop(); }}This version shows the shape of a typed handoff. The kernel receives information from the bootloader and can begin storing or interpreting it. In real code, the BootInfo type must come from the chosen boot interface or match it exactly. You should never invent a boot information type and treat arbitrary memory as that type unless the boot protocol actually guarantees the layout. At the boundary between bootloader and kernel, a wrong type is not just a compile-time issue. It can cause invalid memory reads, wrong addresses, or immediate faults.
The next piece is the target configuration. A kernel should not compile as a normal host application. It needs a freestanding target that expresses the correct architecture and disables assumptions that do not fit kernel code. A target file can describe x86_64 code with no operating system, aborting panics, no red zone, and linker settings suitable for a freestanding binary.
{ "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"}The disable-redzone setting is especially important for kernels. The red zone is an optimization used by ordinary x86_64 code, but it can conflict with interrupts because the CPU may push interrupt state onto the active stack. Kernel code should not rely on stack space below the stack pointer remaining untouched. Disabling it removes that class of early stack corruption.
The feature settings also avoid accidental use of floating-point and SIMD instructions. Early kernel code usually does not manage floating-point state. If the compiler emits instructions whose state the kernel does not save and restore, later interrupt handling and task switching can become incorrect. Avoiding those features early keeps the project honest about what CPU state it actually manages.
Cargo needs to know to build for this target. A .cargo/config.toml file can define the default target and request the core components needed for a freestanding build.
TOML
[build]target = "x86_64-kernel.json"
[unstable]build-std = ["core", "compiler_builtins"]This configuration tells Cargo to use the custom target file. It also requests that the required core library components be built for the target. Freestanding targets may not have prebuilt core artifacts available, so the build process needs access to Rust source components. This is why the toolchain configuration should include the source component.
A toolchain file makes the required components explicit.
TOML
[toolchain]channel = “nightly” components = [“rust-src”, “llvm-tools-preview”]
Using nightly here is a practical choice when the build uses unstable Cargo features for building core components. The rest of the kernel code should not become a playground for unnecessary unstable language features. Keep nightly use tied to the build requirements unless there is a clear reason to do otherwise.
With these pieces in place, the kernel crate can be built as a freestanding binary.
cargo buildA successful compile is not the same as a successful boot. It only proves the Rust code can be compiled for the selected target. To boot, the binary must be placed into a format that the chosen bootloader can load. Depending on the boot strategy, this might involve creating a disk image, generating an ISO, producing a UEFI boot directory, or using a bootloader tool that wraps the kernel artifact. The specific packaging step belongs to the chosen boot path. The key principle is that kernel compilation and boot image creation are related but distinct. The compiler produces the kernel binary. The boot packaging step makes it loadable.
Before adding more features, add some kind of visible proof of execution. A pure spin loop can boot successfully and show nothing. That is not useful for long. The earliest reliable output is often serial output because it can be captured in the terminal. A complete serial driver will come later, but a very small port-output function can provide early confirmation if the boot environment and emulator support it.
#![no_std]#![no_main]
use core::panic::PanicInfo;const COM1: u16 = 0x3f8;
#[unsafe(no_mangle)]pub extern "C" fn _start() -> ! { unsafe { outb(COM1, b'O'); outb(COM1, b'K'); 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 uses inline assembly to write bytes to the first serial port. The operation is unsafe because port I/O directly interacts with hardware. The compiler cannot verify that the port is valid, initialized, or appropriate for the current platform. This is not a full serial driver, and it does not configure the UART. Many emulated setups still make early serial output easy, but a proper serial initialization routine should be added in the next stage.
A more controlled version hides port output behind a small serial function. It still uses unsafe code internally, but the entry point no longer performs raw assembly itself.
<!-- page: 051 -->
rust#![no_std]#![no_main]
use core::panic::PanicInfo;
mod serial { const COM1: u16 = 0x3f8;
pub fn write_byte(byte: u8) { unsafe { outb(COM1, byte); } }
pub fn write_str(text: &str) { for byte in text.bytes() { 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::write_str("kernel entered\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 early code, but it is shaped better. The unsafe port operation stays inside the serial module. The entry point says what it wants to do rather than how the hardware instruction works. The panic handler also reports failure through the same early output path. Once proper serial initialization and formatting support are added, this structure can grow without rewriting the whole entry file.
At this stage, every line should be treated as part of startup correctness. The entry function must not return. The panic handler must not return. The target must disable the red zone. Panic unwinding must be disabled. The boot image must match the chosen loader. The serial output path must not require allocation. The first code should not enable interrupts, allocate heap memory, or assume that memory mappings beyond the initial boot environment are valid.
The first bootable kernel is deliberately small because it is establishing trust. Once it can boot and print a line, later failures become easier to diagnose. If adding a framebuffer breaks the kernel, you can compare against the last known booting version. If setting up the interrupt descriptor table causes a reset, you know the boot path itself worked before that change. This style of incremental work is not slow. It is how kernel code stays understandable while the machine gives very little feedback.
2.4: Running and Inspecting the Kernel in QEMU
Section titled “2.4: Running and Inspecting the Kernel in QEMU”QEMU is the right first execution environment for a Rust kernel because it gives you control, repeatability, and visibility. Running on physical hardware too early adds too many variables. Firmware behavior, display output, keyboard controllers, storage devices, and timing can differ across machines. QEMU gives you a stable virtual machine where the same image can be launched repeatedly while you build the early kernel. It also provides debugging options that are difficult or inconvenient on physical hardware.
The first run command depends on the boot image produced by your boot strategy. If your build produces a raw disk image, QEMU can boot that image as a virtual drive. If your build produces a UEFI application layout, QEMU may need firmware support and a virtual FAT drive or disk image.
If your bootloader tooling provides a runner, Cargo may be able to launch QEMU through configuration. The important point is not the exact command at this stage. The important point is that the command must be repeatable and must show early output.
A practical early QEMU command for a raw bootable image attaches serial output to the terminal and prevents immediate reset on failure.
Shell
qemu-system-x86_64 \-drive format=raw,file=target/kernel.img \-serial stdio \-no-reboot \-no-shutdownThe -serial stdio option connects the guest serial port to the terminal. If the kernel writes to COM1, the text can appear where you launched QEMU. This is often more useful than graphical output during early startup. The -no-reboot option prevents the virtual machine from resetting immediately after a serious fault. The -no-shutdown option keeps the QEMU window or session available after shutdown behavior. Together, these options make early failure less invisible.
If the kernel prints kernel entered, you have confirmed that the bootloader loaded the image, transferred control to the Rust entry path, and the serial output path worked at least enough to send bytes. That may sound modest, but it is a major milestone. It proves the build and boot chain is alive. From that point, each new subsystem can be added with visible checkpoints.
A small runner script can make QEMU invocation consistent. Scripts are valuable because QEMU commands grow quickly. Once you add debugging logs, GDB support, UEFI firmware, disk images, or test exit devices, manually typing the command becomes error-prone.
Shell
#!/bin/shset -euIMAGE=“target/kernel.img”
qemu-system-x86_64
-drive format=raw,file=“$IMAGE”
-serial stdio
-no-reboot
-no-shutdown
This script does not add new behavior, but it gives the command a stable home. The set -eu line makes the script stop on errors and on unset variables. Kernel development benefits from this kind of strictness. Silent script failures can waste time because they may look like kernel failures.
A more useful runner adds logging for CPU resets and interrupts. These logs can be noisy, but they are helpful when the machine resets before your kernel prints anything.
bash#!/bin/shset -eu
IMAGE="target/kernel.img"
qemu-system-x86_64 \-drive format=raw,file="$IMAGE" \-serial stdio \-no-reboot \-no-shutdown \-d int,cpu_reset \-D target/qemu.logThis version writes QEMU diagnostic output to target/qemu.log. The int logging category can help reveal exceptions and interrupt behavior. The cpu_reset category can help identify reset loops. When the kernel triple faults, the virtual CPU may reset so quickly that terminal output shows nothing. A log file gives you another source of evidence.
Inspecting the kernel binary is just as important as running it. If QEMU does not print anything, the problem may be in the Rust code, the bootloader configuration, the image packaging, the linker output, or the
entry symbol. Binary inspection helps narrow the problem before you start changing code randomly.
cargo build
rust-readobj --file-headers --sections target/x86_64-kernel/debug/rust_kernel
rust-objdump --syms target/x86_64-kernel/debug/rust_kernelThe exact output path will depend on your package name and target directory. The habit matters more than the specific path. You should inspect the file headers to confirm the target architecture. You should inspect sections to see how code and data are laid out. You should inspect symbols to confirm that the expected entry point exists. If your bootloader expects _start but no _start symbol appears in the binary, the bootloader cannot enter your code through that symbol. If the kernel was linked for the wrong target, QEMU may not be the problem at all.
When using a bootloader that generates or wraps the actual entry point, the symbol you inspect may differ. In that case, inspect the symbols expected by that boot path. Do not assume all tutorials use the same entry name. Some bootloader integrations intentionally hide the raw entry and expose a safe Rust-level kernel_main function. That is fine as long as the build output and bootloader agree.
The file format also matters. A compiled ELF kernel is not always directly bootable as a disk image. A disk image may contain bootloader code plus the kernel in a layout the bootloader understands. A UEFI setup may contain a FAT filesystem with an EFI executable at a specific path. An ISO image may use a different boot catalog. If QEMU says it cannot boot, the kernel code may be perfectly fine. The problem may be that you gave QEMU the wrong artifact. Learn to distinguish the kernel binary from the bootable image.
A reliable workflow gives different names to different artifacts. The kernel binary is the compiled output from Rust. The boot image is what QEMU
boots. The debug symbol file may be the unstripped kernel ELF used by a debugger. Keeping those roles clear prevents confusion. A common mistake is to inspect one artifact, run another, and then draw the wrong conclusion from the results.
QEMU can also expose a GDB stub. This lets a debugger connect to the virtual machine, set breakpoints, inspect registers, and step through code. Early debugging with GDB is slower than serial logging, but it becomes essential when the kernel fails before output works.
Shell
qemu-system-x86_64 \-drive format=raw,file=target/kernel.img \-serial stdio \-no-reboot \-no-shutdown \-S \-sThe -s option starts the CPU paused. The -S option opens a default GDB server. With the virtual CPU paused at startup, you can connect a debugger before the kernel runs. This is useful when you need to break at the entry point or inspect early state.
A debugger session can load symbols from the kernel ELF and connect to QEMU. The exact debugger name may vary, but the flow is consistent: load the symbol file, connect to the remote target, set a breakpoint, and continue.
Shell
gdb target/x86_64-kernel/debug/rust_kernelInside the debugger, the commands would connect to QEMU and set a breakpoint at the expected entry symbol.
GDB
target remote :1234break _startcontinue
If the breakpoint is hit, the boot path reached the entry symbol. If it is not hit, the problem lies earlier or the symbol name is not the one used by the chosen boot strategy. This distinction is valuable. Without a debugger, both cases may look like a black screen.
Once stopped at the entry point, you can inspect registers, disassemble instructions, and step carefully. Register values can show stack pointer state, instruction pointer state, and values passed through registers by the bootloader. Disassembly can show whether the code being executed matches what you expected. If the debugger cannot load symbols or the symbol addresses do not match execution, that points back to linker or boot image issues.
QEMU logging and GDB should not replace serial output. They complement it. Serial output is fast, cheap, and suitable for continuous feedback. QEMU logs help when faults occur below your own diagnostic layer. GDB helps when you need exact CPU state. A strong kernel workflow uses all three. At the beginning, serial output confirms progress. When serial output disappears, QEMU logs and GDB help identify where control was lost.
The first QEMU inspection habit should be checking for reset behavior. If the virtual machine instantly restarts or exits, suspect an early fault. A triple fault often occurs when the CPU tries to handle an exception but cannot use the required handler path. Early in the project, this can happen because there is no valid interrupt descriptor table, the stack is invalid, the code address is unmapped, or a page fault happens while trying to report another fault. Before exception handling is implemented, many serious errors collapse into a reset. That is why -no-reboot and QEMU logs matter.
The second habit should be checking the last successful print. As initialization grows, print after each major step. If the output stops after gdt loaded, then the next operation is suspicious. If it stops after idt loaded, then memory initialization may be the problem. This style of checkpointing is not crude. It is practical. Early kernel environments do not provide stack traces or crash reporters. You build your own visibility one line at a time.
The third habit should be inspecting the binary after configuration changes. If you change the target file, linker settings, bootloader configuration, or entry point, inspect the output again. Many startup failures are not caused by the logic inside the entry function. They are caused by the binary not matching the boot path. If the artifact shape is wrong, changing Rust logic will not fix the boot.
A useful run script can combine build and run steps. This keeps the workflow consistent and reduces the chance of booting an old image after changing code.
Shell
#!/bin/shset -eu
cargo build
qemu-system-x86_64 \-drive format=raw,file=target/kernel.img \-serial stdio \-no-reboot \-no-shutdownThis script assumes that the build process produces or updates target/kernel.img. If your boot image requires a separate packaging command, include it between the build and QEMU invocation. The script should reflect the real artifact process. Do not let it boot a stale file. Few mistakes are more frustrating than debugging code that is not actually running.
A test-oriented runner will eventually need a way for the guest to exit QEMU with a status code. That comes later, after the kernel has more structure. For now, the goal is manual boot confirmation and early inspection. Still, design the workflow with testing in mind. Keep commands scriptable. Keep output predictable. Keep debug logs in known locations. Avoid one-off manual steps that cannot be repeated.
QEMU is not a perfect substitute for physical hardware. It is a controlled environment. Some device behavior is simplified, some timing is different,
and some firmware paths depend on how QEMU is configured. That is acceptable for early work. The purpose at this stage is to build the kernel’s foundation under conditions where failures can be reproduced and inspected. Physical hardware can come later, after the kernel has better diagnostics and more complete initialization.
By the end of this stage, the kernel should be more than compiled code. It should be a bootable artifact with a repeatable run command, visible serial output, a known entry point, panic behavior that does not return, and basic inspection tools ready when startup fails. That foundation changes the way you work. Instead of hoping the machine does what you meant, you can check what binary was built, what image was booted, whether the entry point was reached, what the CPU did on failure, and where execution stopped. That is the practical beginning of kernel development in Rust.