crossing the boundary, part 1: freestanding kernel
contents
hello again! a little while ago i promised a tutorial series in my first entry, and here it is, not a short time later.
when i started getting into OS development with rust, i read every tutorial i could find. there are so many amazing tutorials out there, but hardly any of them actually cross into userspace, the part where your kernel can become an OS.
that’s what crossing the boundary is about. we are gonna write a kernel in rust from nothing, and the finish line is dropping into ring 3, running a userspace program, and then having that program call back into the kernel.
this chapter will take you from a blank slate, to a minimal kernel that can boot and say hello to you!
multiboot info @ 0x2db660..0x2dbd00
bootloader GRUB 2.12
command line ""
memory map
0x000000000000..0x00000009fc00 Available
0x00000009fc00..0x0000000a0000 Reserved
0x0000000f0000..0x000000100000 Reserved
0x000000100000..0x000007fe0000 Available
0x000007fe0000..0x000008000000 Reserved
0x0000fffc0000..0x000100000000 Reserved
0x00fd00000000..0x010000000000 Reserved
hello from the kernel! chapter 1
if you get stuck, the finished code for this chapter page will be hosted on my Forgejo instance if you need some help.
what you’ll need
rustup(each chapter has a rust-toolchain.toml)just, for running the build recipesnasm, for assembling the boot code- GNU
ld(binutils) qemu-system-x86_64, for running the kernel in a virtual machinegrub-mkrescue/grub2-mkrescue,xorriso,mtoolsfor creating a bootable ISO with GRUB
# install rustup
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
# fedora
sudo dnf install git just nasm binutils qemu-system-x86 xorriso mtools grub2-tools-extra grub2-pc-modules
# debian 13+ or ubuntu 24.04+
sudo apt install -y just nasm binutils qemu-system-x86 xorriso mtools grub-pc-bin grub-commonsetting up the scaffold
create the project and cd into it!
mkdir freestanding && cd freestanding
mkdir -p .cargo kernel/src/{log,drivers/serial,arch/x86_64/{cpu,boot}}
the project is a Cargo workspace with just one member for now, kernel/. don’t worry, it won’t be lonely for too long.
Cargo.toml
[workspace]
resolver = "3"
members = ["kernel"]
[workspace.package]
version = "0.1.0"
edition = "2024"
license = "MIT"
publish = false
[workspace.lints.rust]
unsafe_op_in_unsafe_fn = "deny"
[workspace.lints.clippy]
undocumented_unsafe_blocks = "warn"
[profile.dev]
panic = "abort"
[profile.release]
panic = "abort"
debug = true
this goes in the root of the project. [workspace.package] holds settings every crate in the workspace can inherit, so you don’t have to repeat them in each crate’s Cargo.toml.
a kernel has a lot of unsafe, so the lints keep us honest:
unsafe_op_in_unsafe_fnmeans that even inside anunsafe fn, every unsafe operation must be marked with anunsafe { ... }block.undocumented_unsafe_blockswarns if anunsafeblock is not documented with a// SAFETY: ...comment explaining why it’s safe.
panic = "abort" turns off unwinding. normally, a panic walks back up the stack, running destructors along the way, but that needs support from the runtime. in a freestanding kernel, we don’t have that, so we just abort immediately on panic.
next, let’s set up the kernel/Cargo.toml file for our kernel project.
kernel/Cargo.toml:
[package]
name = "kernel"
version.workspace = true
edition.workspace = true
license.workspace = true
publish.workspace = true
[features]
test = []
[lib]
crate-type = ["staticlib"]
[dependencies]
spin = { version = "0.12", default-features = false, features = ["spin_mutex"] }
[target.'cfg(target_arch = "x86_64")'.dependencies]
multiboot2 = { version = "0.23", default-features = false }
x86_64 = { version = "0.15.5", default-features = false, features = ["instructions"] }
[lints]
workspace = true
the kernel is a static library (staticlib), not a binary. cargo compiles our rust into libkernel.a, and we link that with the boot assembly. that gives us full control over where every byte ends up, which we’ll need for the higher half.
the test feature doesn’t enable anything by itself. it’s a switch: building with --features test runs the test harness, which we’ll set up at the end.
for now, we only need 3 dependencies:
spinprovides a spinlockMutex, since we don’t have access tostd::syncmultiboot2parses the boot information GRUB hands usx86_64will be extremely useful for working with x86_64-specific instructions, structures, and paging. for now, it wraps CPU instructions likehlt,cli, and port I/O, so we don’t have to write inline assembly.
all three have default-features = false, because default features often assume std or an allocator, and we have neither. the last two only get pulled in when building for x86_64, since they’re x86-specific.
[lints] workspace = true tells this crate to use the workspace’s lints. don’t skip it: without it, the lints we set up a moment ago silently do nothing!
now, create a new file in your project: rust-toolchain.toml
[toolchain]
channel = "nightly"
components = ["rust-src", "rustfmt", "clippy", "llvm-tools"]
targets = ["x86_64-unknown-none"]
profile = "minimal"
rustup reads rust-toolchain.toml automatically, so anyone who builds the project gets the same toolchain without having to manually install or select it.
nightly: kernel development often requires unstable rust features sooner or laterrust-src: the source code of the standard library, which tools like rust-analyzer use to look insidecore.rustfmtandclippyare the formatter and linter, andllvm-toolsgives us tools for inspecting the binaries we build.targets: specifies the target triple(s) we want to build for, in this casex86_64-unknown-noneprofile: selects the toolchain profile,minimalinstalls only the essential components, skipping things we don’t need, like offline docs
now, put this in the .cargo directory as config.toml.
[build]
target = "x86_64-unknown-none"
[target.x86_64-unknown-none]
rustflags = ["-C", "force-frame-pointers=yes"]
setting the default target means we don’t have to pass --target x86_64-unknown-none to every cargo command. it also ensures that all dependencies are built for the correct target automatically.
force-frame-pointers makes every function keep a pointer to its caller’s stack frame in rbp. that forms a chain we can walk later to print backtraces when something goes wrong, which is also why boot.asm zeroes rbp before calling into rust: it marks the end of the chain.
booting into 64-bit mode
before we write any boot code, we need to decide where our kernel lives in memory.
we want a higher-half kernel. every program on x86_64 sees its own huge virtual address space, and we put the kernel at the very top of it, at 0xFFFFFFFF80000000, the last 2 GiB. the bottom half stays free for userspace programs later, so they can use whatever addresses they like without bumping into the kernel!
rust’s
x86_64-unknown-nonetarget expects this too: it compiles code assuming it lives in the higher-half of the address space.
the catch: GRUB doesn’t know any of this. it loads our kernel at 1 MiB in physical memory with paging off, so those high addresses are not yet valid. the kernel has to be linked to run in the higher-half, but it’s loaded low:
virtual address physical address
kernel ──► 0xFFFFFFFF80100000 ──┐
├──► 0x00100000, 1 MiB
boot ──► 0x0000000000100000 ──┘the linker: deciding memory layout
the linker script is how we tell the linker about those addresses.
kernel/src/arch/x86_64/boot/linker.ld:
ENTRY(start)
/*
* base virtual address of the higher-half kernel: the top 2 GB of the
* 64-bit address space (-2 GiB, sign-extended)
*/
KERNEL_VMA = 0xFFFFFFFF80000000;
SECTIONS {
. = 1M;
.boot :
{
/*
* the multiboot2 header goes first, because GRUB only looks for
* it in the first 32 KiB of the image, 8-byte aligned. KEEP stops
* --gc-sections from dropping it, since nothing references it
*/
KEEP(*(.multiboot_header))
*(.boot.text)
*(.boot.rodata)
}
.boot.bss :
{
*(.boot.bss)
}
. = ALIGN(4K) + KERNEL_VMA;
.text : AT(ADDR(.text) - KERNEL_VMA)
{
*(.text .text.*)
}
. = ALIGN(4K);
.rodata : AT(ADDR(.rodata) - KERNEL_VMA)
{
*(.rodata .rodata.*)
}
.tests : AT(ADDR(.tests) - KERNEL_VMA)
{
. = ALIGN(8);
__tests_start = .;
KEEP(*(.tests))
__tests_end = .;
}
. = ALIGN(4K);
.data : AT(ADDR(.data) - KERNEL_VMA)
{
*(.data .data.*)
*(.got .got.plt)
}
. = ALIGN(4K);
.bss : AT(ADDR(.bss) - KERNEL_VMA)
{
*(.bss .bss.*)
}
}
there are two halves to consider:
- boot sections are sitting at 1 MiB, and they’re linked and loaded there. this is the code that runs before we jump to the higher-half.
- higher-half is linked at
KERNEL_VMA, butAT(...)tells the linker to load it at that address minusKERNEL_VMA, so.textends up right after the boot code, but every address inside it points into the higher-half.
so every section has two addresses: where it sits in memory, which GRUB uses, and where it thinks it is, which our code uses.
now, the goal of our boot code is to bridge the gap.
boot.asm: getting ready for the higher-half
when GRUB gives us control, the CPU is in 32-bit protected mode with paging off, with no stack. before we can get to rust, we need to:
- check that we were booted by a multiboot2-compliant bootloader, that the CPU supports the CPUID instruction, and that it supports long mode
- build page tables that map the same 1 GiB of memory twice, once at
0and once at the top - turn on paging and switch to 64-bit long mode
- jump to the higher-half and call
kernel_main
kernel/src/arch/x86_64/boot/boot.asm:
global start
extern kernel_main
KERNEL_P4 equ 511
KERNEL_P3 equ 510
section .boot.text progbits alloc exec nowrite align=16
bits 32
start:
mov esp, boot_stack_top ; set up a stack pointer
mov edi, ebx ; save the multiboot info pointer in edi
call check_multiboot
call check_cpuid
call check_long_mode
call set_up_page_tables
call enable_paging
lgdt [gdt64.pointer] ; load the GDT for 64-bit mode
jmp gdt64.code:long_mode_low ; jump to the 64-bit code segment
now, we check if the bootloader is multiboot2-compliant, and then whether the CPU supports the CPUID instruction:
; checks if the system was booted by a multiboot2-compliant bootloader
check_multiboot:
cmp eax, 0x36d76289
jne .no_multiboot
ret
.no_multiboot:
mov al, "M"
jmp error
; checks if the CPU supports the CPUID instruction
check_cpuid:
pushfd
pop eax
mov ecx, eax
xor eax, 1 << 21 ; flip the ID bit
push eax
popfd
pushfd
pop eax
push ecx
popfd
cmp eax, ecx
je .no_cpuid
ret ; bit flipped so CPUID is supported
.no_cpuid:
mov al, "C"
jmp error
the last check is whether the CPU supports long mode, and the NX bit:
; check if the CPU supports long mode and NX bit
check_long_mode:
mov eax, 0x80000000 ; ask CPUID for the highest extended leaf
cpuid
cmp eax, 0x80000001
jb .no_long_mode
mov eax, 0x80000001
cpuid
test edx, 1 << 29
jz .no_long_mode
test edx, 1 << 20 ; NX bit support
jz .no_nx
ret ; long mode and NX are supported, return
.no_long_mode:
mov al, "L"
jmp error
.no_nx:
mov al, "N"
jmp error
now, we know the CPU can do everything we need, so we build the page tables from the diagram earlier: the same 1 GiB of memory, mapped twice.
; sets up the initial page tables for long mode
set_up_page_tables:
mov eax, p3_low
or eax, 0b11
mov [p4_table], eax
mov eax, p3_high
or eax, 0b11
mov [p4_table + KERNEL_P4 * 8], eax
mov eax, p2_table
or eax, 0b11
mov [p3_low], eax
mov [p3_high + KERNEL_P3 * 8], eax
xor ecx, ecx
; maps the P2 table entries for the kernel
.map_p2_table:
mov eax, ecx
shl eax, 21
or eax, 0b10000011
mov [p2_table + ecx * 8], eax
inc ecx
cmp ecx, 512
jne .map_p2_table
ret
a quick bit of background: the CPU turns a virtual address into a physical address by walking four levels of page tables: P4 → P3 → P2 → P1. each table is 4 KiB and has 512 entries, and each entry points to the next table down. we skip P1 entirely with huge pages, where a single P2 entry maps a whole 2 MiB.
set_up_page_tables builds the tables in a few steps:
- P4 gets two entries, with entry 0 pointing to
p3_lowfor the bottom of the address space, and entry 511 (KERNEL_P4) pointing top3_high, for the very top of the address space - P3: both tables get one entry each, pointing to the same P2 table.
p3_lowuses entry 0 andp3_highuses entry 510 (KERNEL_P3). 511 and 510 are where0xFFFFFFFF80000000lands when the CPU splits it into table indices - P2 is filled by the loop. entry
nmaps the 2 MiB starting at physical addressn * 2 MiB(shl eax, 21multiplies by 2 MiB). 512 entries cover the first 1 GiB of physical memory
the or lines set flags on each entry: 0b11 sets the present and writable bits, while 0b10000011 also sets the huge bit (bit 7).
since both paths lead to the same P2 table, both addresses end up at the same memory:
p4[0] ──► p3_low[0] ──┐
├──► p2[0..512] ──► physical 0..1 GiB
p4[511] ──► p3_high[510] ──┘
that’s the diagram from earlier, built for real: 0x100000 and 0xFFFFFFFF80100000 now point at the same byte!
the tables are ready, so we can enable paging and switch to long mode:
; enables paging and sets up the necessary control registers for long mode
enable_paging:
mov eax, p4_table
mov cr3, eax
mov eax, cr4
or eax, 1 << 5
mov cr4, eax
mov ecx, 0xC0000080
rdmsr
or eax, (1 << 8) | (1 << 11)
wrmsr
mov eax, cr0 ; read cr0
or eax, (1 << 31) | (1 << 16) ; set paging and write protect bits
mov cr0, eax ; write back to cr0
; long mode is active from here but the CPU runs in 32-bit compatibility mode
; until the far jump through the 64-bit GDT code segment in start
ret
this does the following:
cr3gets the address of our P4 table so the CPU knows where to start looking for page tables- bit 5 of
cr4enables PAE (Physical Address Extension), which is required for long mode EFERregister (model-specific register0xC0000080, read withrdmsrand written withwrmsr) gets bit 8: long mode enable and bit 11: no-execute enable (so we can mark memory as non-executable later)cr0gets bit 31 (paging), and bit 16 (write protect), which makes read-only pages read-only even for the kernel, so a stray write crashes spectacularly instead of silently corrupting memory
the order matters! paging has to be last, after the CPU knows where the tables are and the format they use,
we’re not fully in 64-bit mode yet. we still need a 64-bit code segment, which is what the lgdt and far jump in start take care of.
before that, remember that every check jumped to error on failure:
; handle boot errors
error:
mov bl, al
mov esi, error_msg
.print:
lodsb
test al, al
jz .code
call serial_putc
jmp .print
.code:
mov al, bl
call serial_putc
mov al, 10
call serial_putc
.hang:
cli
hlt
jmp .hang
; outputs a character to the serial port (COM1)
serial_putc:
mov ah, al
mov dx, 0x3F8 + 5
.wait:
in al, dx
test al, 0x20
jz .wait
mov al, ah
mov dx, 0x3F8
out dx, al
ret
error prints boot error: followed by the letter indicating which check failed, then a newline, and then halts the CPU forever. lodsb loads a byte of the message at a time, and the loop stops at the null terminator of the string.
serial_putc talks to COM1 at I/O port 0x3F8. it waits until bit 5 of the line status register (0x3F8 + 5) says the port is ready for a new byte, and then sends another byte. we’ll write a serial driver in rust later, but this is enough for debugging and fixing early boot issues.
now, for the jump to 64-bit. do you remember the last two lines of start?
lgdt [gdt64.pointer]
jmp gdt64.code:long_mode_low
lgdt loads a GDT with a 64-bit code segment, which we’ll define momentarily, and the far jump switches to that segment, entering 64-bit mode. right now, we’re still running in the low, identity-mapped address space, and the rest of the kernel is linked to run in the higher half, so we need one more jump to get there.
a plain jmp long_mode_high won’t work, since direct jumps in 64-bit mode are relative and can only reach 2 GiB from either direction. the higher half is well beyond that.
instead, we load the full 64-bit address of long_mode_high into rax and jump to it:
bits 64
long_mode_low:
mov rax, long_mode_high
jmp rax
section .boot.rodata progbits alloc noexec nowrite align=8
error_msg:
db "boot error:", 0
this block also defines the read-only error message the error routine prints. it lives down here with the boot code, so it’s reachable before the higher-half kernel is mapped in.
next up is the GDT loaded earlier in start. in long mode, segmentation is mostly gone, so we only need the null descriptor every GDT needs to start with, and a single 64-bit code segment:
; 64-bit GDT for long mode
;
; contains the GDT entries and the pointer for long mode
gdt64:
dq 0
.code: equ $ - gdt64
dq (1<<43) | (1<<44) | (1<<47) | (1<<53)
.pointer:
dw $ - gdt64 - 1
dq gdt64
the code segment is just four bits:
- 43: executable, making this a code segment
- 44: code/data segment
- 47: present
- 53: 64-bit
.code is the segment’s offset into the table (8, right after the null entry) which is the number the far jump uses. .pointer is the structure lgdt expects: the table’s size minus one, followed by its address.
lastly, we need to reserve the memory everything is using. each table is one 4 KiB page, and the section is page-aligned. the boot stack gets a page too:
section .boot.bss nobits alloc noexec write align=4096
p4_table:
resb 4096
p3_low:
resb 4096
p3_high:
resb 4096
p2_table:
resb 4096
boot_stack_bottom:
resb 4096
boot_stack_top:
.bss sections take up no space in the kernel file. resb just reserves bytes, and they are zeroed when GRUB loads the kernel, so every page table entry starts out empty (not present)
finally, long_mode_high is the entry point for the higher-half kernel code. this is where we give control to rust, switching to the proper stack and calling kernel_main:
section .text
bits 64
long_mode_high:
mov ax, 0
mov ss, ax
mov ds, ax
mov es, ax
mov fs, ax
mov gs, ax
mov rsp, stack_top ; switch to the real kernel stack
xor ebp, ebp
mov edi, edi
call kernel_main ; never returns
cli
.hang:
hlt
jmp .hang
section .bss nobits alloc noexec write align=4096
stack_bottom:
resb 4096 * 16
stack_top:
the segment registers are cleared because they may still hold leftover values from GRUB. long mode ignores them, but it’s good practice to clear them to avoid any unexpected behavior.
next, the stack pointer is moved to the higher-half stack, which is the proper kernel stack, instead of the small stack set up by start.
xor ebp, ebp zeroes the frame pointer, ending the chain of previous stack frames. this’ll matter once we start printing backtraces.
mov edi, edi looks like it does nothing, but writing to a 32-bit register in 64-bit mode clears the top half of the 64-bit one. that leaves rdi holding exactly the multiboot pointer we saved at the very start, and rdi is where the first argument to kernel_main goes.
then, kernel_main is called with the multiboot information pointer in rdi. this is the entry point for the rust kernel.
multiboot_header.asm: introducing ourselves to GRUB
GRUB won’t boot any file you hand it. it scans the first 32 KiB of the kernel for a multiboot2 header: a small data structure that tells the bootloader how to load the kernel and what information it expects.
kernel/src/arch/x86_64/boot/multiboot_header.asm:
; multiboot2 header
;
; GRUB looks for it, 8-byte aligned, within the first 32 KiB of the kernel
; linker.ld ensures the header is placed correctly
section .multiboot_header progbits alloc noexec nowrite align=8
header_start:
dd 0xe85250d6 ; magic number
dd 0 ; architecture: 32-bit protected mode i386
dd header_end - header_start
; checksum -(magic + arch + length)
dd 0x100000000 - (0xe85250d6 + 0 + (header_end - header_start))
; end tag
align 8
dw 0
dw 0
dd 8
header_end:
the header starts with four 32-bit fields:
- the magic number:
0xe85250d6, which identifies the header as a multiboot2 header - the architecture:
0, indicating 32-bit protected mode on x86, which is the state GRUB will leave the CPU in when it jumps to the kernel - the header length: the size of the header in bytes
- the checksum, which is calculated so that the sum of the magic number, architecture, header length, and checksum equals zero. otherwise, GRUB will ignore the header.
after these fields, the header may contain various tags which act as requests to the bootloader, such as asking for a framebuffer. each tag starts with a type, flags, and a size.
we don’t need to ask for anything for now, so we just have the end tag: type 0, flags 0, size 8, which marks the end of the header.
the section name matters, too. .multiboot_header is the section the linker script puts first in the file, with KEEP, so that it always lands inside those first 32 KiB.
that’s all GRUB needs! in return, GRUB tells the kernel it understood by putting a magic number, 0x36d76289, in eax. that’s the number check_multiboot looks for in boot.asm.
ready for rust?
let’s write some rust. we’ll start at the bottom, with the hardware, and work up to kernel_main.
the root
kernel/src/lib.rs:
#![no_std]
#[macro_use]
mod log;
mod arch;
mod drivers;
mod init;
mod panic;
#[cfg(feature = "test")]
mod test;
/// `multiboot_info_ptr` is the physical address of the multiboot2 information structure provided by the bootloader.
#[unsafe(no_mangle)]
pub extern "C" fn kernel_main(multiboot_info_ptr: u64) -> ! {
#[cfg(not(feature = "test"))]
let entry = kernel_start;
#[cfg(feature = "test")]
let entry = test::run;
// SAFETY: this is the pointer the boot stub handed us
unsafe { init::init(multiboot_info_ptr, entry) }
}
#[cfg(not(feature = "test"))]
fn kernel_start() -> ! {
rawln!("hello from the kernel! chapter 1");
arch::halt_loop()
}
#![no_std] drops the standard library, since there’s nothing for it to talk to. we still get core, which has all the essential stuff: Option, iterators, slices, and so on.
notice there’s no #![no_main]. because we’re a static library, we don’t define a main function. instead, kernel_main serves as the entry point for the assembly.
#[unsafe(no_mangle)]tells the compiler not to mangle the function name, so it can be called from somewhere elseextern "C"gives it the C calling conventions-> !means it never returns
kernel_main picks an entry point (the kernel, or the test runner when built with --features test) and hands it off to init, which we’ll write soon.
don’t worry if it doesn’t compile yet; we’ll fill in the missing pieces as we go, one at a time!
architecture-specific code
all the architecture-specific code lives in arch, so that the rest of the kernel doesn’t need to care about what platform it runs on. there’s only x86_64 for now, but it keeps it tidy regardless, and keeps the door open for other architectures in the future! ;)
kernel/src/arch/mod.rs:
//! Architecture support.
//!
//! Each architecture exports the same interface, which is re-exported here
//! for the kernel to use.
#[cfg(target_arch = "x86_64")]
pub mod x86_64;
#[cfg(target_arch = "x86_64")]
pub use self::x86_64::*;
#[cfg(not(target_arch = "x86_64"))]
compile_error!("this kernel does not support this target architecture yet");
kernel/src/arch/x86_64/mod.rs:
//! x86_64 architecture support.
mod bringup;
mod cpu;
mod uart;
#[cfg(feature = "test")]
mod qemu;
#[cfg(feature = "test")]
pub use qemu::exit_qemu;
pub use bringup::init;
pub use cpu::{disable_interrupts, halt_loop, without_interrupts};
pub use uart::Uart16550 as ConsoleUart;
this is the architecture-specific layer, which provides the CPU, UART, and other low-level hardware interfaces for the kernel. it abstracts away the details of the underlying architecture, so the rest of the kernel can remain platform-agnostic.
support for isa-debug-exit
this device allows the kernel to signal to QEMU that it should exit, which is useful for our testing harness. we will use it to implement the exit_qemu function in the qemu module, which will be called by our test runner to indicate success or failure.
kernel/src/arch/x86_64/qemu.rs:
//! `isa-debug-exit` device support, so test runs can end with
//! a verdict.
//!
//! Writing `value` to its port exits QEMU with the status
//! `(value << 1) | 1`.
use super::{cpu::port::PortWriteOnly, halt_loop};
const PORT: u16 = 0xF4;
const PASSED: u32 = 0x10;
const FAILED: u32 = 0x11;
/// Stop QEMU, reporting if the tests passed or failed. Without
/// the device, this will halt instead.
pub fn exit_qemu(passed: bool) -> ! {
let code = if passed { PASSED } else { FAILED };
// SAFETY: the `isa-debug-exit` device is mapped to the specified
// port by QEMU, and writing to it is safe in this context
unsafe { PortWriteOnly::new(PORT).write(code) };
halt_loop()
}the CPU
kernel/src/arch/x86_64/cpu/mod.rs:
//! The CPU: interrupts, halting, and port I/O.
pub mod port;
pub use ::x86_64::instructions::interrupts::without_interrupts;
use ::x86_64::instructions::{self, interrupts};
/// Stops the CPU from handling interrupts.
#[inline]
pub fn disable_interrupts() {
interrupts::disable();
}
/// Idle the CPU indefinitely. Interrupts will be handled.
pub fn halt_loop() -> ! {
loop {
instructions::hlt();
}
}
halt_loop is how our kernel “ends”: hlt sleeps the CPU until next interrupt, and the loop ensures it keeps halting indefinitely.
kernel/src/arch/x86_64/cpu/port.rs:
//! Re-export port I/O types from [`x86_64`].
pub use ::x86_64::instructions::port::{PortReadOnly, PortWriteOnly};16550 UART
now, we implement the 16550 UART driver, allowing us to communicate with the serial console hardware directly. the kernel can use this to send bytes over the serial port, giving us a way to output information!
kernel/src/arch/x86_64/uart.rs:
//! The 16550 UART, reached via I/O ports.
use super::cpu::port::{PortReadOnly, PortWriteOnly};
use crate::drivers::serial::Uart;
const COM1: u16 = 0x3F8;
const LCTL_DLAB: u8 = 0x80;
const LCTL_8N1: u8 = 0x03;
const FCTL_ENABLE: u8 = 0xC7;
const MCTL_READY: u8 = 0x08;
const LSTS_TX_EMPTY: u8 = 0x20;
const DIVISOR: u16 = 1;
pub struct Uart16550 {
data: PortWriteOnly<u8>,
int_en: PortWriteOnly<u8>,
fifo_ctrl: PortWriteOnly<u8>,
line_ctrl: PortWriteOnly<u8>,
modem_ctrl: PortWriteOnly<u8>,
line_sts: PortReadOnly<u8>,
}
impl Uart16550 {
/// COM1, which the serial console runs on.
///
/// # Safety
/// Nothing else may drive COM1: call this only once.
pub const unsafe fn console() -> Self {
Self::new(COM1)
}
const fn new(base: u16) -> Self {
Self {
data: PortWriteOnly::new(base),
int_en: PortWriteOnly::new(base + 1),
fifo_ctrl: PortWriteOnly::new(base + 2),
line_ctrl: PortWriteOnly::new(base + 3),
modem_ctrl: PortWriteOnly::new(base + 4),
line_sts: PortReadOnly::new(base + 5),
}
}
}
impl Uart for Uart16550 {
fn init(&mut self) {
// SAFETY: these are the UART's registers, and we're the only ones
// accessing them
unsafe {
self.int_en.write(0x00);
self.line_ctrl.write(LCTL_DLAB);
self.data.write(DIVISOR as u8);
self.int_en.write((DIVISOR >> 8) as u8);
self.line_ctrl.write(LCTL_8N1);
self.fifo_ctrl.write(FCTL_ENABLE);
self.modem_ctrl.write(MCTL_READY);
}
}
fn send(&mut self, byte: u8) {
// SAFETY: as in `init`
unsafe {
while self.line_sts.read() & LSTS_TX_EMPTY == 0 {
core::hint::spin_loop();
}
self.data.write(byte);
}
}
}
the 16550 has a handful of registers, each at an offset from its base port (0x3F8 for COM1). new sets up a port per register:
| offset | register | purpose |
|---|---|---|
+0 | data | write a byte here to send it |
+1 | interrupt enable | which events make the UART raise an interrupt |
+2 | FIFO control | configure the chip’s internal byte queue |
+3 | line control | data format: bits per charactr, parity, stop bits |
+4 | modem control | control signals to the modem |
+5 | line status | status of the transmitter and receiver |
init sets up the UART, one register at a time:
- interrupts off. we don’t handle interrupts yet, so we’ll poll the chip instead and ask it whether it’s ready.
- set DLAB. bit 7 of the line control register is the divisor latch access bit. while it’s set, the data and interrupt enable registers temporarily turn into the low and high bytes of the baud rate divisor. it’s a weird bit of hardware history, but it’s how every 16550 works.
- write the divisor. the UART runs at
115200 / divisorbaud, so a divisor of1is the fastest it goes: 115200 baud. the low byte (1) goes into the data register, and the high byte (0) into the interrupt enable register, both still acting as the divisor thanks to DLAB. - set the line format.
0x03in line control means 8 data bits, no parity and 1 stop bit, usually written 8N1. - enable the FIFOs.
0xC7turns on the chip’s built-in buffers (bit 0), clears out anything left in them (bits 1 and 2), and sets the receive buffer’s threshold to 14 bytes (bits 6 and 7). - set OUT2.
0x08sets the OUT2 line in modem control. on PCs, OUT2 connects the UART’s interrupt line to the interrupt controller. we don’t need it while polling, but setting it now means the wiring is ready when we start handling interrupts.
send is much simpler: it spins until bit 5 of the line status register (transmitter empty) is set, which means the UART is ready to accept a new byte, and then writes the byte to the data register.
in QEMU, the baud rate doesn’t matter, since
-serial stdiojust pipes the serial output to your terminal. it’s only relevant on real hardware: both ends of a serial cable must agree on the same baud rate, or you’ll get garbage data.
the serial driver
the UART is x86-specific, but most of what sits on top of it isn’t: locking, formatting, and fixing up newlines work the same on any hardware. so the serial driver lives in drivers/, and talks to the hardware only through a small Uart trait. the arch module plugs in its implementation, Uart16550, under the name ConsoleUart.
kernel/src/drivers/serial/mod.rs:
//! The serial console.
//!
//! The UART itself belongs to the architecture, behind [`Uart`]; this
//! is everything above it, and handles locking, line editing,
//! and formatting.
use core::fmt::{self, Write};
use spin::Mutex;
use crate::arch::{ConsoleUart, without_interrupts};
/// A UART, as far as the serial driver is concerned.
pub trait Uart {
/// Bring the UART up: 8N1, fast as possible, interrupts off.
fn init(&mut self);
/// Send a byte over the UART, waiting for room if necessary.
fn send(&mut self, byte: u8);
}
struct Serial<U>(U);
impl<U: Uart> Write for Serial<U> {
fn write_str(&mut self, s: &str) -> fmt::Result {
for byte in s.bytes() {
if byte == b'\n' {
self.0.send(b'\r');
}
self.0.send(byte);
}
Ok(())
}
}
// SAFETY: the only place the console UART is created
static CONSOLE: Mutex<Serial<ConsoleUart>> = Mutex::new(Serial(unsafe { ConsoleUart::console() }));
pub fn init() {
CONSOLE.lock().0.init();
}
/// Retake the serial lock by force.
///
/// # Safety
/// Only the panic handler may call this function, and
/// interrupts must be disabled.
pub unsafe fn force_unlock() {
// SAFETY: upheld by the caller
unsafe { CONSOLE.force_unlock() };
}
pub fn write(args: fmt::Arguments) {
without_interrupts(|| {
// should never fail
let _ = CONSOLE.lock().write_fmt(args);
})
}
there are a few things going on here:
Uartis the whole interface the driver needs from the hardware:initto bring it up, andsendto push out one byte. anything that implements those two can be a serial port, which comes in handy for testing later.Serialwraps a UART and implementscore::fmt::Write. that trait only asks us for one method,write_str, and in return we get all of rust’s formatting machinery for free:{},{:#x},{:?}and friends just work.\r\n: terminals treat\nas “move down a line” and\ras “go back to the start of the line”. without the\r, every new line would start where the last one ended, and our output would slowly staircase across the screen. so we sneak a\rin before every\n.CONSOLEis the one and only serial console, living in astaticbehind aspin::Mutex. a spinlock just loops until the lock is free, because there’s no OS to put a waiting thread to sleep. we can build the UART right inside thestaticbecause its constructors areconst fns, and the// SAFETY:comment explains why calling theunsafeconsole()is fine here: this is the only place it ever happens.initlocks the console and calls the UART’sinit(.0is the UART insideSerial).writetakes the lock with interrupts disabled. we don’t handle interrupts yet, but once we do, picture this: the kernel is halfway through printing, holding the lock, and an interrupt arrives. if the interrupt handler tries to print too, it waits for a lock that will never be released, because the code holding it can’t run until the handler finishes. that’s a deadlock, and turning interrupts off while we hold the lock prevents it. better to build the habit now!let _ =ignores the result ofwrite_fmt. ourwrite_strnever fails, so there’s nothing useful to do with an error anyway.
force_unlock is an escape hatch for the panic handler. we’ll see why it needs one in a bit.
console, and logging
kernel/src/drivers/console.rs:
//! The kernel console: where the kernel talks!
//!
//! Not a device of its own, more like a fan-out over the ones that do. For
//! now, that's the serial port.
use core::fmt;
use crate::drivers::serial;
pub fn plain(args: fmt::Arguments) {
serial::write(args);
}
/// Retake every sink immediately.
///
/// # Safety
/// Only the panic handler may call this function, and
/// interrupts must be disabled with nothing else running.
pub unsafe fn force_unlock() {
// SAFETY: upheld by the caller
unsafe { serial::force_unlock() }
}
right now the console is just a thin wrapper around serial, but later on, this will change as more things are added.
kernel/src/drivers/mod.rs:
//! Drivers for hardware components.
pub mod console;
pub mod serial;
/// Initialize all available drivers.
pub fn init() {
serial::init();
}
and the macros we will actually use to print…
kernel/src/log/mod.rs:
//! Kernel output.
//!
//! Only the raw path exists right now: straight to console.
/// Write a raw output to the console.
#[macro_export]
macro_rules! raw {
($($arg:tt)*) => {
$crate::drivers::console::plain(format_args!($($arg)*))
};
}
/// Write a raw output to the console, with a newline.
#[macro_export]
macro_rules! rawln {
() => {
$crate::raw!("\n")
};
($($arg:tt)*) => {
$crate::raw!("{}\n", format_args!($($arg)*))
};
}
those are our equivalent of print! and println! for now. eventually, they will be proper logs, featuring module paths, exact timestamps, log levels with colors, filtering, and so on.
reading the boot info
remember that pointer GRUB gave? it points to a list of tags describing the machine, and the multiboot2 crate helps us parse all those tags.
kernel/src/arch/x86_64/bringup.rs:
//! Architecture bringup for x86_64.
use multiboot2::{BootInformation, BootInformationHeader, MemoryAreaType};
/// # Safety
/// `boot_info` must be a valid pointer to the multiboot2 information left by the bootloader.
/// Only call once.
pub unsafe fn init(boot_info: u64) {
let ptr = boot_info as *const BootInformationHeader;
// SAFETY: upheld by caller
let loaded = unsafe { BootInformation::load(ptr) };
let info = loaded.expect("failed to find the secrets you seek");
report(&info);
}
/// Report the multiboot2 information.
fn report(info: &BootInformation) {
let start = info.start_address();
let end = start + info.total_size();
rawln!("multiboot info @ {start:#x}..{end:#x}");
if let Some(tag) = info.boot_loader_name_tag() {
rawln!(" bootloader {}", tag.name().unwrap_or("?"));
}
if let Some(tag) = info.command_line_tag() {
rawln!(" command line {:?}", tag.cmdline().unwrap_or("?"));
}
match info.memory_map_tag() {
Some(map) => {
rawln!(" memory map");
for area in map.memory_areas() {
let start = area.start_address();
let end = start + area.size();
let kind = MemoryAreaType::from(area.typ());
rawln!(" {start:#014x}..{end:#014x} {kind:?}");
}
}
None => rawln!(" no memory map"),
}
}
the boot info sits at a physical address, but we can use it as a pointer because the first 1 GiB is still identity mapped (not forever, but enough for early bringup).
for this chapter, we just report what the bootloader gave us, without trying to interpret or act on it: the bootloader’s name, the kernel command line, and the memory map. the memory map is the most important; we’ll need to consult it once we start allocating memory.
initializing everything
kernel/src/init.rs:
//! Kernel bringup, in order.
use crate::{arch, drivers};
/// Bring the kernel from entry to a usable state before calling `entry`.
///
/// # Safety
/// `boot_info` must be the physical address of the multiboot2 info.
/// Call only once.
pub unsafe fn init(boot_info: u64, entry: fn() -> !) -> ! {
drivers::init();
// SAFETY: upheld by caller
unsafe { arch::init(boot_info) }
entry()
}
drivers first, so that everything after them can print. this file will grow a lot as the series grows: memory, interrupts, and eventually userspace!
when things go wrong
the panic handler disables interrupts, unlocks the console by force (force_unlock is needed because the lock might be held when the panic occurs), and then prints the panic information before halting, or exiting QEMU if we’re running under the test harness.
kernel/src/panic.rs:
//! Panic handling.
//!
//! Tells us what went wrong, then stops: halting for good,
//! or failing to continue execution.
use core::panic::PanicInfo;
use crate::{arch, drivers::console};
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
arch::disable_interrupts();
// SAFETY: interrupts are off and theres only one cpu
// so whoever held this can't anymore
unsafe { console::force_unlock() };
rawln!("kernel panic: {info}");
#[cfg(feature = "test")]
arch::exit_qemu(false);
#[cfg(not(feature = "test"))]
arch::halt_loop();
}testing, and making sure they don’t
every good program needs tests to ensure correct behavior, and a kernel is no exception!
earlier, we added a test feature to the kernel, we created a special area of memory in linker.ld to hold test cases, we added a module for interacting with isa-debug-exit in QEMU to signal test results, and now we need to implement the test framework itself.
kernel/src/test.rs:
//! A testing framework, backed by the `isa-debug-exit` device on QEMU.
//!
//! Built under `--features test`, where `kernel_main` runs [`run`] instead
//! of the normal kernel entry. A test is a `fn()`; failing tests panic, which
//! the panic handler reports and then fails a run.
//!
//! Tests register themselves with [`test!`]
use crate::arch;
/// A single test case, with a name and function.
pub struct Test {
pub name: &'static str,
pub run: fn(),
}
unsafe extern "C" {
static __tests_start: u8;
static __tests_end: u8;
}
/// Define one or more test cases and register them with the test framework.
///
/// ```ignore
/// crate::test! {
/// /// doc something here
/// fn it_works() {
/// assert_eq!(1 + 1, 2);
/// }
/// }
/// ```
#[macro_export]
macro_rules! test {
($($(#[$meta:meta])* fn $name:ident() $body:block)*) => {
$(
$(#[$meta])*
fn $name() $body
const _: () = {
#[used]
#[unsafe(link_section = ".tests")]
static ENTRY: $crate::test::Test = $crate::test::Test {
name: concat!(module_path!(), "::", stringify!($name)),
run: $name,
};
};
)*
};
}
/// Every [`Test`] collected into `.tests`.
fn collected() -> &'static [Test] {
let start = (&raw const __tests_start).cast::<Test>();
let end = (&raw const __tests_end).cast::<Test>();
let len = (end as usize - start as usize) / size_of::<Test>();
// SAFETY: linker.ld gathers every `test!` entry between these
// symbols back to back and 8-byte aligned, and nothing ever writes to them
unsafe { core::slice::from_raw_parts(start, len) }
}
/// Run all collected tests, and report their results. This function
/// does not return.
pub fn run() -> ! {
let tests = collected();
assert!(!tests.is_empty(), "no tests collected; check linker.ld");
rawln!();
rawln!("running {} tests", tests.len());
for test in tests {
raw!("test {} ... ", test.name);
(test.run)();
rawln!("ok !");
}
rawln!();
rawln!("all {} tests passed", tests.len());
arch::exit_qemu(true);
}
now, we can use the test! macro to define test cases for our kernel. each test! invocation puts a struct into .tests, the linker collects them between __tests_start and __tests_end, and #[used] plus KEEP ensure they aren’t thrown away. on a passing test, the framework will print ok ! for each test and all N tests passed at the end, and QEMU will exit successfully.
lastly, we need to write our first test case for the kernel, using the test! macro we defined.
kernel/src/drivers/serial/mod.rs:
we also are gonna add a test for the serial driver to make sure it works correctly. add this at the end of the file:
// ...
#[cfg(feature = "test")]
mod tests {
use core::fmt::Write;
use super::{Serial, Uart};
struct Recorder {
sent: [u8; 16],
len: usize,
}
impl Uart for Recorder {
fn init(&mut self) {}
fn send(&mut self, byte: u8) {
self.sent[self.len] = byte;
self.len += 1;
}
}
crate::test! {
fn newline_becomes_crlf() {
let mut serial = Serial(Recorder { sent: [0; 16], len: 0 });
write!(serial, "a\nb").unwrap();
assert_eq!(&serial.0.sent[..serial.0.len], b"a\r\nb");
}
}
}finishing up
writing the justfile
before we can say we’re finished, we still need to create our justfile, a file that defines named, reusable commands, called “recipes”, that we can invoke from the command line using the just command.
first, we need to define some variables for the architecture, build profile, command line arguments, and other settings that will be used by build and test recipes.
justfile:
# run `just` to list recipes. override a setting with `just <name>=<value> <recipe>`,
# e.g. `just profile=release run` or `just cmdline="foo=bar" run`
set shell := ["bash", "-euo", "pipefail", "-c"]
arch := "x86_64"
profile := "debug"
cmdline := ""
test_timeout := "60"
nasm := "nasm"
ld := "ld"
qemu := "qemu-system-" + arch
target := arch + "-unknown-none"
out := "build"
boot := "kernel/src/arch" / arch / "boot"
kernel_bin := out / "kernel.bin"
kernel_iso := out / "kernel.iso"
test_bin := out / "test.bin"
test_iso := out / "test.iso"
lib := "target" / target / profile / "libkernel.a"
linker := boot / "linker.ld"
cargo_flags := "--target " + target + if profile == "release" { " --release" } else { "" }
ldflags := "-n --gc-sections -z noexecstack --no-warn-rwx-segments"
qemu_flags := "-serial stdio -no-reboot -display none"
test_qemu_flags := qemu_flags + " -device isa-debug-exit,iobase=0xf4,iosize=0x04"
these variables configure settings for the build system, such as the target architecture, output files and directories, build tools, cargo flags, linker flags, and QEMU options.
now, let’s define recipes for building, running, debugging, running tests, checking our code with rustfmt and clippy, installing the toolchain, and cleaning up build artifacts:
# list the recipes
default:
@just --list
# build and link the kernel binary
build: (_link "" kernel_bin)
# build a bootable ISO image
iso: build (_iso kernel_bin kernel_iso)
# build and boot in QEMU; extra arguments go to QEMU
run *args: iso
{{qemu}} -cdrom {{kernel_iso}} {{qemu_flags}} {{args}}
# boot halted, waiting for gdb on :1234
debug: iso
{{qemu}} -cdrom {{kernel_iso}} {{qemu_flags}} -s -S
test: (_link "--features test" test_bin) (_iso test_bin test_iso)
#!/usr/bin/env bash
# isa-debug-exit makes QEMU exit with (code << 1) | 1, 33 is a pass
# timeout(1) exits 124 from a hanging test
set -uo pipefail
timeout --foreground {{test_timeout}} {{qemu}} -cdrom {{test_iso}} {{test_qemu_flags}} </dev/null
status=$?
case $status in
33) echo PASS ;;
124) echo TIMEOUT; exit 1 ;;
*) echo "FAIL (qemu exited $status)"; exit 1 ;;
esac
# rustfmt and clippy, with/without tests
check:
cargo fmt --all --check
cargo clippy {{cargo_flags}} --workspace -- -D warnings
cargo clippy {{cargo_flags}} -p kernel --features test -- -D warnings
# install the toolchain pinned in rust-toolchain.toml
toolchain:
rustup toolchain install
# remove build artifacts
clean:
rm -rf {{out}}
cargo clean
# assemble the boot code, build the kernel lib with `features`, and link
# them into `bin`. both builds share the library's path, so link after
_link features bin:
#!/usr/bin/env bash
set -euo pipefail
mkdir -p {{out}}/asm
objs=()
for src in {{boot}}/*.asm; do
obj="{{out}}/asm/$(basename "$src" .asm).o"
{{nasm}} -f elf64 "$src" -o "$obj"
objs+=("$obj")
done
cargo build {{cargo_flags}} -p kernel {{features}}
{{ld}} {{ldflags}} -T {{linker}} -o {{bin}} "${objs[@]}" --whole-archive {{lib}} --no-whole-archive
# wrap the kernel at `bin` in a bootable GRUB image at `image`
_iso bin image:
#!/usr/bin/env bash
set -euo pipefail
mkrescue="$(command -v grub2-mkrescue || command -v grub-mkrescue || true)"
if [[ -z "$mkrescue" ]]; then
echo "grub-mkrescue or grub2-mkrescue not found; install grub and xorriso" >&2
exit 1
fi
root={{out}}/isofiles
rm -rf "$root"
mkdir -p "$root/boot/grub"
cp {{bin}} "$root/boot/kernel.bin"
printf '%s\n' 'set timeout=0' 'set default=0' 'menuentry "Crossing the Boundary" {' \
' multiboot2 /boot/kernel.bin {{cmdline}}' \
' boot' '}' > "$root/boot/grub/grub.cfg"
"$mkrescue" -o {{image}} "$root" >{{out}}/grub.log 2>&1 || { cat {{out}}/grub.log; exit 1; }
rm -rf "$root"
that’s a lot of recipes, but most of them one or two lines. the public ones are what you’ll type, and the ones starting with _ are private and don’t show up in just --list.
recipes can depend on other recipes, listed after the colon, so running one runs everything it needs first:
run ──► iso ──► build ──► _link
└───────────────► _iso_link: building the kernel
this is where everything comes together:
- every
.asmfile inboot/is assembled bynasminto a 64-bit ELF object inbuild/asm/ cargo buildcompiles our rust intolibkernel.a, passing along any features (like--features test)ldlinks it all into one binary, using our linker script (-T)
the linker flags are worth a closer look:
-nstopsldfrom page-aligning sections inside the file. without it, padding could push the multiboot header past the first 32 KiB, and GRUB would never find it.--gc-sectionsthrows away any section nothing uses. that’s why the linker script needsKEEParound the multiboot header and the tests: nothing references them directly.-z noexecstackand--no-warn-rwx-segmentsquiet two warnings thatldgives about our hand-written assembly. they’re harmless for a kernel at this stage.--whole-archivemakesldinclude everything inlibkernel.a. normally, it only pulls in whatever is needed to resolve a symbol, which for us is justkernel_main. our tests are never called by name, so without this flag they’d silently disappear!
the build is a #!/usr/bin/env bash recipe, so it runs as one script. that lets the objs array carry over from the loop to the ld line. normal recipes run each line in a separate shell.
_iso: making it bootable
_iso wraps the kernel in a bootable CD image. it finds grub-mkrescue (some distros call it grub2-mkrescue), copies the kernel into a temporary folder, and writes a tiny grub.cfg:
set timeout=0
set default=0
menuentry "Crossing the Boundary" {
multiboot2 /boot/kernel.bin
boot
}
no menu and no waiting, just boot our kernel with the multiboot2 protocol. grub-mkrescue then turns the folder into an ISO with GRUB installed. its output goes to build/grub.log, which only gets printed if something fails.
the recipes you’ll actually use
just runbuilds everything and boots it in QEMU.-serial stdioconnects COM1 to your terminal,-display noneskips the window (we don’t have a screen yet anyway), and-no-rebootmakes QEMU quit instead of rebooting if the CPU hits a fatal error, so a crash doesn’t turn into an endless reboot loop. any extra arguments go straight to QEMU, likejust run -m 512M.just debugboots QEMU paused (-S), waiting for a debugger on port 1234 (-s). in another terminal, rungdb build/kernel.bin -ex 'target remote :1234'to attach.just testbuilds a second kernel with--features testand boots it with theisa-debug-exitdevice. QEMU’s exit code tells the recipe what happened:33means every test passed, and124meanstimeouthad to kill a test that hung. anything else is a failure.just checkrunsrustfmtandclippy, with and without the test feature, and treats every warning as an error.just toolchaininstalls the toolchain fromrust-toolchain.toml, andjust cleandeletes all build output.
you can override any variable from the command line, too:
just cmdline="hello=world" run # pass a command line to the kernel
just profile=release run # build with optimizationsrunning the kernel
the moment of truth! from the root of the project, run:
just run
the first build may take a little while, since cargo has to compile all dependencies and the kernel itself. subsequent builds will be faster. then, QEMU starts, GRUB boots our kernel, and you should see:
multiboot info @ 0x2db660..0x2dbd00
bootloader GRUB 2.12
command line ""
memory map
0x000000000000..0x00000009fc00 Available
0x00000009fc00..0x0000000a0000 Reserved
0x0000000f0000..0x000000100000 Reserved
0x000000100000..0x000007fe0000 Available
0x000007fe0000..0x000008000000 Reserved
0x0000fffc0000..0x000100000000 Reserved
0x00fd00000000..0x010000000000 Reserved
hello from the kernel! chapter 1
congratulations! you have successfully built and run your kernel! :)
don’t worry if your numbers don’t match exactly. the first line shows up wherever GRUB put the boot info, which can change between versions and machines.
the memory map is worth paying attention to. the big Available region from 1 MiB to about 128 MiB is all the RAM QEMU gives a VM by default, and the Reserved areas belong to firmware and devices.
things to try
now that it works, let’s mess around a bit.
give it a bit more memory, and watch the memory map change accordingly:
just run -m 512M 0x000000100000..0x00001ffe0000 Available
pass a command line to the kernel:
just cmdline="hello=world" run command line "hello=world"
and break something on purpose! add a panic! to kernel_start in lib.rs:
fn kernel_start() -> ! {
rawln!("hello from the kernel! chapter 1");
panic!("oops");
}hello from the kernel! chapter 1
kernel panic: panicked at kernel/src/lib.rs:30:5:
oops
that’s your panic handler in action! just remember to take the panic! back out afterwards.
running tests
just testrunning 1 tests
test kernel::drivers::serial::tests::newline_becomes_crlf ... ok !
all 1 tests passed
PASS
PASS comes from the justfile reading QEMU’s exit code, so this works in scripts and CI as well.
something wrong?
grub-mkrescue or grub2-mkrescue not found: install GRUB’s tools along withxorrisoandmtools, as listed at the start.boot error:and a letter: one of the checks inboot.asmfailed.Mmeans we weren’t booted by a multiboot2 bootloader,Cmeans nocpuid,Lmeans no long mode, andNmeans no NX bit. in QEMU, you shouldn’t ever see these.- QEMU exits immediately with no output: the CPU probably hit a triple fault, and
-no-rebootmade QEMU quit. double-checkboot.asmandlinker.ldagainst the code above, or compare with the finished code in the repo. - nothing at all, and QEMU just sits there: GRUB couldn’t find the multiboot header. make sure
multiboot_header.asmis inkernel/src/arch/x86_64/boot/, so the justfile picks it up.
conclusion
thank you for reading the first post in this series! i am super passionate about rust and osdev, and i hope you found it helpful and interesting. i plan to continue this series when i have more time, so stay tuned for future posts.
if you ever got stuck, the repository for this series is located here, or you can email me at saoirse@fawn.rest if you have any questions or feedback.
see you soon for part 2!