BaddCafe OS: learning Rust with a small x86-64 kernel
BaddCafe OS is an educational x86-64 kernel written in bare-metal Rust. It boots in QEMU, handles exceptions and hardware interrupts, manages a heap and runs cooperative async tasks. It has no userspace or filesystem.
The project follows Philipp Oppermann's Writing an OS in Rust series, including its progression and several allocator designs. I used AI assistance for explanations, implementation and verification. The learning work includes revisiting those implementations and checking the invariants behind them.
The engineering questions are concrete: who owns a physical frame, how long must an interrupt table remain valid, and what happens if an interrupt arrives while the interrupted code holds a lock? This article follows those boundaries through the implementation and its tests.
Getting to the first instruction
The first obstacle was getting a Rust binary that did not expect to be a normal application.
#![no_std]
#![no_main]
no_std removes the standard library, which depends on services an operating system normally supplies. core is still available: types, traits, iterators and formatting machinery. no_main removes the usual Rust entry-point setup. The kernel supplies its own entry point and panic handler.
Those two attributes were not enough. An early build still failed with linker errors:
error: undefined symbol: main
error: undefined symbol: __libc_start_main
The target was still a Linux executable. The linker was bringing in startup code that expected a C runtime and an application entry point, even though the Rust source had opted out of the normal setup.
The fix involved a custom bare-metal target and Cargo configuration that rebuilds the required libraries for it. This was an early lesson in separating compiler errors from linker errors: the types can be fine while the executable is still being assembled for the wrong environment.
I use the bootloader crate to load the kernel and enter 64-bit mode with initial paging in place. I did not write that bootloader. By the time the kernel's _start runs, it receives a BootInfo containing information such as the physical memory map.
Printing means talking to hardware
At first, a successful boot produced a black screen. There was no terminal and no existing println! to call.
The first output used VGA text memory at 0xb8000, accessible through the bootloader's mapping. Each screen cell holds a character byte and a colour byte. Writing the right bytes changes what appears on screen.
The VGA writer uses volatile memory accesses. These accesses have effects outside the ordinary Rust program, so the compiler must actually perform them. Volatile does not make them thread-safe or solve aliasing; those remain separate responsibilities.
From there, the writer gained scrolling and an implementation of core::fmt::Write. That allowed the kernel's own print! and println! macros to use Rust's formatting machinery without needing the standard library.
This also made unsafe less abstract. Dereferencing a pointer made from an integer address asks me to establish facts the compiler cannot: that the address is mapped, that the layout matches the device, and that access is coordinated correctly. Putting the operation in an unsafe block does not establish those facts for me.
Interrupts change the locking problem
The next layers were exception handling and hardware interrupts. The kernel has a handwritten Interrupt Descriptor Table (IDT), which tells the CPU where to transfer control for supported exceptions and interrupts. The handlers cover breakpoints, double faults, page faults, the timer and the keyboard.
Once interrupts exist, even one active CPU can interrupt itself at an inconvenient moment.
Suppose normal code holds the screen writer's spinlock. A handler interrupts it and tries to print. The handler spins waiting for the lock, but the code that would release it cannot resume until the handler returns. That is a deadlock without a second CPU anywhere in the picture.
The printing paths therefore disable interrupts while holding their locks, then restore the previous interrupt state. This is deliberately a single-CPU design; disabling interrupts locally would not exclude another processor.
Stack overflow introduced another dependency. Delivering an exception normally requires stack space. If the current stack is unusable, delivery can fail too. The GDT and Task State Segment setup provides a separate stack for the double-fault handler through the Interrupt Stack Table. That gives the CPU somewhere usable to enter the handler when the normal stack has failed.
There is a whole test kernel whose job is to overflow its stack and check that this path works.
A heap needs more than an address
Before Box or Vec can work, two different allocation problems need solving.
A physical frame allocator identifies usable chunks of RAM. A page-table mapping connects virtual addresses to those frames. Then a heap allocator divides a mapped virtual region into allocations with the sizes and alignments Rust asks for.
The memory module implements the four-level page-table walk directly, rather than using the x86_64 crate. It reads the top-level table address from CR3, follows the entries through the bootloader's physical-memory mapping, and handles the larger page sizes it can encounter along the way.
That does not mean the kernel creates the machine's initial address space. It starts from the bootloader's tables and adds mappings, including a fixed 1 MiB heap. The heap pages are writable and marked non-executable.
The allocators then developed in three stages:
| Allocator | How it works | Main limitation here |
|---|---|---|
| Bump | Align a cursor, hand out space, advance it | Can reset only when all allocations are freed |
| Linked list | Store free-region headers inside the free memory | Does not merge neighbouring free regions |
| Fixed-size blocks | Reuse blocks from size classes, with the linked list as fallback | Blocks stay assigned to their size class |
A useful test exposed the bump allocator's limitation: keep one Box alive while repeatedly creating and dropping short-lived boxes. The total requested memory exceeded the heap size, although very little needed to stay live at once.
heap_allocation::long_lived_box_does_not_pin_the_heap... [failed]
memory allocation of 8 bytes failed
The live-allocation count never reached zero, so the bump cursor never reset. Switching to the linked-list allocator made that test pass because individual freed regions could be reused.
The linked-list tests caught a subtler mistake too. An initial use of pad_to_align() rounded a 16-byte allocation with 256-byte alignment up to a 256-byte size. The allocation needed to start at that alignment; the allocator did not need to reserve all those bytes. The bookkeeping only required rounding the size to the free-list node's alignment.
That distinction is easy to miss when a program still runs. It wastes memory rather than immediately crashing. The allocator implementations and tests make the trade-offs much easier to inspect than a successful boot does.
Async needs something to run it
With the heap available, the next step was cooperative multitasking.
Calling an async fn creates a future. The compiler builds a state machine containing the state needed across suspension points. Something still has to call poll to advance it. In this kernel, that something is a small executor.
The task representation is short:
pub struct Task {
future: Pin<Box<dyn Future<Output = ()>>>,
}
The Box provides heap storage. dyn Future allows different future types in the same task collection. Pinning keeps the stored future in place, which matters when its state contains references to its own data across an .await. Moving the box handle is still fine; moving the pinned future out of its allocation is the issue.
A Waker tells the executor that a task should be polled again. It does not execute the task itself.
This executor uses one ready flag per task. Repeated wakeups set the same flag, so there is no ready queue to overflow. The cost is scanning the task collection on each pass. Only ready tasks are polled, but finding them is still linear in the number of tasks.
The order of operations matters:
if !entry.wake.ready.swap(false, Ordering::AcqRel) {
return true;
}
let mut context = Context::from_waker(&entry.waker);
entry.task.poll(&mut context).is_pending()
This is from the retain_mut pass in the executor. Returning true keeps the task. A completed task is removed.
The ready flag is cleared before polling. If the task wakes itself during poll, the flag is set again for the next pass. Clearing it afterwards could erase that wakeup.
Even going idle needs coordination. An interrupt could make a task ready between an idle check and a hlt instruction. The executor disables interrupts, checks again, and, if there is still no work, executes sti; hlt together. With interrupts previously disabled, x86's delayed interrupt recognition after sti closes that gap.
Moving keyboard work out of the handler
The keyboard path ties these pieces together:
keyboard interrupt
-> bounded scancode queue
-> wake the waiting task
-> executor polls it
-> decode the scancode
-> print the character
Earlier, decoding and printing happened inside the interrupt handler. The async version keeps the handler's work small and moves that processing into task context.
The queue holds 128 scancodes and has one consumer. Checking whether it is empty and registering the waiting waker happen in the same critical section. Otherwise, input could arrive after the empty check but before registration, leaving a waiting task with unread input and no wakeup.
Overflow needs more thought than dropping a character. If a Shift-release scancode disappears, the decoder can be left believing Shift is still held. The queue reports the gap and the consumer resets its decoder state.
The task also yields after processing 32 scancodes, even if more input is available. An .await does not necessarily suspend: if input is already buffered, the read can complete immediately. The explicit budget gives other tasks a turn under sustained input.
Testing the failures on purpose
There is no host test runtime inside the kernel. The project has its own runner, writes results over a serial port and uses QEMU's debug-exit device to return a pass/fail result to Cargo. Tests that deliberately fault can run as separate kernels.
One of the most useful checks is the non-executable heap test. It writes a ret instruction into heap memory and tries to execute it. Success means getting the expected instruction-fetch page fault.
Temporarily removing the non-executable mapping flag made the test fail:
executed an instruction fetched from the heap
That check mattered because it showed the test was sensitive to the protection being tested. A green result alone would not have established that.
The completed learning track has 42 tests, verified in debug and release. There is also a Python/QEMU check that sends keyboard events to the production kernel, reads back VGA memory and checks idle sleep. These cover useful behaviours; they are not a proof that every unsafe operation is sound.
Current scope and limits
The current endpoint is a kernel with interrupt-driven input, memory allocation and cooperative async tasks on one active CPU. There are still clear limits: a fixed heap, fragmentation, physical frames that are never reclaimed, incomplete exception coverage and no preemption. A task that never returns from poll can keep its peers from running.
The next review work is at the boundaries between these layers. A Box depends on an allocator, mapped pages and usable physical frames. A keyboard character depends on an interrupt, a queue, a wakeup and a task getting another turn. Rust's ownership rules sit inside those mechanisms, but they do not replace the hardware assumptions underneath them.
The full implementation is in BaddCafe OS on GitHub. The running journal keeps the individual steps and actual compiler and test output. For the broader tutorial behind the project, start with Writing an OS in Rust.