Skip to content
ImagineWorld

Heap Allocation and Safe Kernel Abstractions

node_idnode-book_writing-operating-systems-in-rust_chapter-08-heap-allocation-and-safe-kernel-abstractions
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num8
chapter_titleHeap Allocation and Safe Kernel Abstractions
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 8 — Heap Allocation and Safe Kernel Abstractions

Section titled “Chapter 8 — Heap Allocation and Safe Kernel Abstractions”

Chapter 8: Heap Allocation and Safe Kernel Abstractions

Section titled “Chapter 8: Heap Allocation and Safe Kernel Abstractions”

A kernel can do a surprising amount of work without a heap. It can boot, print to serial output, load descriptor tables, install exception handlers, parse a memory map, allocate physical frames, and create page mappings. For the early system, this restraint is useful because it forces every dependency to be clear. Static memory, stack values, fixed-size buffers, and page-sized physical frames are enough to establish control. Eventually, though, the kernel needs dynamic allocation.

Dynamic allocation is what allows the kernel to create data structures whose size is not fixed at compile time. A command history buffer, a list of loaded modules, a collection of tasks, a queue of keyboard scancodes, dynamically sized strings, path buffers, process structures, and future filesystem caches all benefit from heap allocation. In Rust, dynamic allocation also unlocks types from the alloc crate, such as Box, Vec, String, BTreeMap, and reference-counted pointers. These types are familiar from ordinary Rust development, but in a kernel they are available only after the kernel provides a global allocator.

That order is important. The alloc crate does not create memory by itself. It provides allocation-backed types and asks a global allocator to supply memory when those types grow, create objects, or release storage. In a normal Rust application, the standard library connects allocation requests to the operating system’s allocator. In a kernel, there is no operating system underneath. The kernel must map a heap range into virtual memory, provide physical frames behind that range, implement an allocator, register it as the global allocator, and define what happens when allocation fails.

Heap allocation should not be treated as a convenience switch. Once enabled, it becomes a core kernel service. Bad allocator logic can corrupt memory. A wrong heap range can overlap the kernel image or page tables. A missing mapping can turn the first Box::new into a page fault. A broken dealloc implementation can cause use-after-free or list corruption. A global

allocator accessed from interrupts without proper locking can deadlock or corrupt state. Rust’s type system helps the code above the allocator use memory safely, but the allocator itself sits at an unsafe boundary. That boundary must be small, audited, and designed around clear invariants.

The right way to build heap allocation is gradual. First, map a virtual heap range using the paging code and physical frame allocator. Then register a simple allocator that can serve allocation requests. Then test Box, Vec, and String in a controlled way. After that, study the limitations of a bump allocator and move toward allocators that can reuse freed memory. Finally, wrap unsafe allocator internals and global state behind safe kernel abstractions, so ordinary kernel code can use dynamic structures without spreading raw pointer manipulation everywhere.

8.1: Enabling Dynamic Allocation with the alloc Crate

Section titled “8.1: Enabling Dynamic Allocation with the alloc Crate”

The alloc crate provides heap-backed types without requiring the full standard library. That distinction matters in a kernel. The standard library depends on operating-system services, but alloc depends mainly on a global allocator. Once the kernel provides that allocator, it can use many familiar Rust collection and pointer types while still remaining no_std.

Using alloc begins at the crate root. The kernel remains #![no_std], but it explicitly links the allocation crate.

#![no_std]
#![no_main]
extern crate alloc;
use alloc::boxed::Box;
use alloc::vec::Vec;
use core::panic::PanicInfo;
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
serial_println!("kernel panic: {}", info);
}

loop { x86_64::instructions::hlt(); }

This declaration makes allocation-backed types available to the crate, but it does not make them usable yet. If you try to create a Box or push values into a Vec before setting up a global allocator and mapping heap memory, the kernel is not ready. The alloc crate supplies the types. The kernel must supply the memory service.

The global allocator is a type that implements Rust’s allocation interface. It receives requests containing a size and alignment, returns a pointer to usable memory, and accepts deallocation requests when memory is released. The allocator must uphold strict rules. It must return pointers that satisfy the requested alignment. It must not return overlapping memory for active allocations. It must not return memory outside the heap range. It must handle zero-sized or invalid layouts according to the allocator contract. It must not report memory as available if that memory still belongs to a live allocation.

Before the allocator can work, the kernel must choose a virtual heap range and map it to physical frames. The heap range should not overlap the kernel image, stacks, boot information, framebuffer, or direct physical memory mapping unless the design intentionally places it there. A clean layout uses a dedicated high virtual region for the kernel heap. This address is a virtual address. It becomes usable only after page tables map it to physical frames.

Rust

use x86_64::VirtAddr;
pub const HEAP_START: VirtAddr =
VirtAddr::new(0xffff_9000_0000_0000);
pub const HEAP_SIZE: u64 = 1024 * 1024;

These constants define a one-megabyte heap range. That is enough for early tests and small kernel structures. The exact size can grow later. Choosing a modest range at first makes testing easier. A huge heap range can hide

allocation waste and mapping mistakes. A small heap makes allocator behavior visible.

The heap range must be mapped before the allocator is initialized. The paging code already has the pieces needed to map a virtual range to newly allocated physical frames. The heap should be writable and non-executable. It should not be user-accessible in an early kernel. The present flag is added during mapping.

Rust

e x86_64::structures::paging::{
FrameAllocator,
Mapper,
Page,
PageTableFlags,
Size4KiB,
};
pub unsafe fn map_heap<M, A>(
mapper: &mut M,
frame_allocator: &mut A,
) -> Result<(), &'static str>
where
M: Mapper<Size4KiB>,
A: FrameAllocator<Size4KiB>,
{
let start_page = Page::containing_address(HEAP_START);
let end_address = HEAP_START + HEAP_SIZE - 1u64;
let end_page = Page::containing_address(end_address);
let page_range = Page::range_inclusive(start_page, end_page);
let flags = PageTableFlags::PRESENT
| PageTableFlags::WRITABLE
| PageTableFlags::NO_EXECUTE;
for page in page_range {
let frame = frame_allocator
.allocate_frame()
.ok_or("frame allocation failed while mapping heap")?;
let flush = unsafe {
mapper
.map_to(page, frame, flags, frame_allocator)
.map_err(|_| "heap page mapping failed")?
};
}
}

flush.flush(); }

Ok(()) }

This function maps every page in the heap range to a newly allocated physical frame. It uses the physical frame allocator as the source of backing memory. The heap appears contiguous in virtual memory even though the physical frames do not need to be contiguous. This is one of the main benefits of virtual memory. The allocator above the heap can treat the heap as a continuous virtual byte range, while the page tables connect each page to whichever physical frame was available.

This function is unsafe because mapping memory is a privileged operation with global consequences. The caller must ensure that the chosen heap virtual range is not already used for another purpose, that the frame allocator returns safe frames, and that the mapper really controls the active address space. If the heap range overlaps an important mapping, the kernel can corrupt itself. If the frames overlap protected physical memory, the allocator can overwrite the kernel image or boot information. The safety of heap setup depends on both the physical frame allocator and the virtual memory manager being correct.

Once the heap is mapped, the kernel can initialize the global allocator. A global allocator type is marked with the #[global_allocator] attribute. At the lowest level, it implements allocation and deallocation methods. The first allocator can be a bump allocator, which moves a pointer forward for each allocation. It is easy to implement and useful for proving the allocation path, but it cannot reuse freed memory until it is reset or redesigned.

Rust

use core::alloc::{GlobalAlloc, Layout}; use core::ptr::null_mut; use spin::Mutex;

pub struct Locked { inner: Mutex, }

impl Locked { pub const fn new(inner: A) -> Self { Self { inner: Mutex::new(inner), } }

pub fn lock(&self) -> spin::MutexGuard<'_, A> {
self.inner.lock()
}

}

pub struct BumpAllocator { heap_start: usize, heap_end: usize, next: usize, }

impl BumpAllocator { pub const fn new() -> Self { Self { heap_start: 0, heap_end: 0, next: 0, } }

pub unsafe fn init(&mut self, heap_start: usize, heap_size: usize) {
self.heap_start = heap_start;
self.heap_end = heap_start + heap_size;
self.next = heap_start;
}

}

#[global_allocator] static ALLOCATOR: Locked = Locked::new(BumpAllocator::new());

unsafe impl GlobalAlloc for Locked { unsafe fn alloc(&self, layout: Layout) -> *mut u8 { let mut allocator = self.lock();

let alloc_start = align_up_usize(allocator.next, layout.align());
let Some(alloc_end) = alloc_start.checked_add(layout.size()) else {
return null_mut();
}
};
if alloc_end > allocator.heap_end {
null_mut()
} else {
allocator.next = alloc_end;
alloc_start as *mut u8
}
unsafe fn dealloc(&self, _ptr: *mut u8, _layout: Layout) {}
fn align_up_usize(address: usize, alignment: usize) -> usize {
let mask = alignment - 1;
if address & mask == 0 {
address
} else {
(address + mask) & !mask
}
}

This code introduces several important ideas. The allocator is protected by a spin-based mutex because the global allocator may be accessed from different parts of the kernel. The alloc method aligns the next address to the requested alignment, checks that the requested size fits within the heap, advances the next pointer, and returns the allocation start. If the request cannot be satisfied, it returns a null pointer, which signals allocation failure to the allocation layer.

The dealloc method does nothing. That is the defining limitation of this bump allocator. Memory can be allocated but not reused. When a Box, Vec, or String is dropped, the allocator receives a deallocation call, but this implementation ignores it. That makes the allocator simple and safe from free-list corruption, but it also means repeated allocation and deallocation will eventually exhaust the heap.

The kernel must also provide an allocation error handler. This function is called when allocation fails in contexts where the allocation API cannot return an error. In an early kernel, the correct behavior is usually to panic with a clear message.

use core::alloc::Layout;
#[alloc_error_handler]
fn alloc_error_handler(layout: Layout) -> ! {
panic!(
"allocation error: size={}, align={}",
layout.size(),
layout.align()
);
}

This handler gives useful information about the failed allocation request. If the kernel runs out of heap while pushing into a vector, this message can show the size and alignment that failed. Later, the kernel can add better diagnostics, but a clear panic is already much better than silent failure.

A heap initialization function connects the mapped heap range to the allocator state.

pub fn init_heap_allocator() {
unsafe {
ALLOCATOR.lock().init(
HEAP_START.as_u64() as usize,
HEAP_SIZE as usize,
);
}
serial_println!("heap allocator initialized");
}

This function must be called only after the heap virtual range has been mapped. If the allocator is initialized before mapping, the first allocation may return a pointer inside an unmapped range. Writing through that pointer will cause a page fault. Initialization order is essential. First map the heap. Then initialize the allocator with the heap virtual start and size. Then test alloc types.

pub unsafe fn init_heap<M, A>( mapper: &mut M, frame_allocator: &mut A, ) where M: x86_64::structures::paging::Mapper<x86_64::structures::paging::Size4KiB>, A: x86_64::structures::paging::FrameAllocator<x86_64::structures::paging::Size4KiB>, { unsafe { map_heap(mapper, frame_allocator) .expect(“failed to map heap”); }

init_heap_allocator();
serial_println!("heap is ready");

}

This function gives the heap setup one clear entry point. It maps the virtual range, initializes the allocator, then prints success. If a page fault occurs during heap tests, you can check whether this function printed all expected checkpoints.

Once the heap is ready, the kernel can test allocation-backed types. These tests should be small and direct.

use alloc::boxed::Box;
use alloc::string::String;
use alloc::vec::Vec;
pub fn test_heap_allocation() {
let boxed = Box::new(42_u64);
serial_println!("box value: {}", *boxed);
let mut numbers = Vec::new();
for value in 0..10 {
numbers.push(value);
}
serial_println!("vec length: {}", numbers.len());
serial_println!("vec third value: {}", numbers[3]);
}
<!-- page: 222 -->
rust
let mut message = String::from("heap");
message.push_str(" allocation");
serial_println!("string: {}", message);

This test creates a Box, a Vec, and a String. It proves that the global allocator is being used by ordinary allocation-backed Rust types. It also proves that the heap range is mapped and writable. If Box::new page faults, the heap may not be mapped. If Vec::push panics with an allocation error, the allocator may be out of heap or returning null. If the output is corrupted, the allocator may be returning overlapping memory.

The first successful heap allocation is an important milestone, but it should not make the kernel careless. Dynamic allocation makes many designs easier, but it also makes allocation failure possible in more places. Kernel code should avoid allocating in panic handlers, exception handlers, and interrupt handlers unless the design specifically supports it. A timer interrupt that tries to allocate from a locked heap can deadlock. A page-fault handler that allocates while reporting a heap fault can recurse into more faults. Allocation is powerful, but early kernels should keep it out of emergency paths.

8.2: Implementing a Bump Allocator and Understanding Its Limits

Section titled “8.2: Implementing a Bump Allocator and Understanding Its Limits”

A bump allocator is the easiest allocator to understand because it has one main piece of state: the next free address. Each allocation moves that address forward. The allocator never searches a free list, never splits blocks, never merges adjacent regions, and never reuses memory after deallocation. That simplicity makes it a good first allocator for a kernel. It is also exactly why it is not enough for long-term use.

The bump allocator works well when allocations happen during initialization and are never freed. Many early kernel operations fit that pattern. The kernel may allocate page tables, boot-time structures, or static service state and keep them forever. For that kind of workload, a bump

allocator is fast and easy to audit. It also has very little internal metadata, so there is not much to corrupt.

The allocator becomes wasteful when memory is allocated and freed repeatedly. Since dealloc does nothing, freed memory is not reused. A Vec that grows and drops may leave its old buffer permanently consumed. A temporary String may consume heap space even after it goes out of scope. Repeated tests can exhaust the heap quickly. That behavior is acceptable only if you know it is happening.

The core bump allocation operation is alignment plus pointer advancement. Alignment is not optional. Rust allocations have layout requirements, and returning a misaligned pointer is undefined behavior for many types. A u64 may require 8-byte alignment. A page table may require 4096-byte alignment. Some structures may have larger alignment. The allocator must satisfy each request.

Rust

use core::alloc::Layout;
use core::ptr::null_mut;
pub struct BumpAllocator {
heap_start: usize,
heap_end: usize,
next: usize,
allocations: usize,
}
impl BumpAllocator {
pub const fn new() -> Self {
Self {
heap_start: 0,
heap_end: 0,
next: 0,
allocations: 0,
}
}
pub unsafe fn init(&mut self, heap_start: usize, heap_size: usize) {
self.heap_start = heap_start;
self.heap_end = heap_start + heap_size;
self.next = heap_start;
self.allocations = 0;
}
pub fn allocate(&mut self, layout: Layout) -> Result<NonNullMut<Layout>, Error> {
let alloc_start = align_up_usize(layout.align());
let Some(alloc_end) = alloc_start.checked_add(layout.size) else {
return null_mut();
};
if alloc_end > self.heap_end {
return null_mut();
} else {
self.next = alloc_end;
self.allocations += 1;
Ok(NonNullMut::from(alloc_start as *mut u8))
}
}
fn align_up_usize(address: usize, alignment: usize) -> usize {
let mask = alignment - 1;
(address + mask) & !mask
}

This code adds an allocation counter. The counter does not affect correctness, but it is useful for diagnostics. When testing memory behavior, printing the number of allocations can show whether code is allocating more often than expected. If a supposedly small operation performs hundreds of allocations, you may want to inspect it before using it in a sensitive path.

The alignment helper assumes a power-of-two alignment. Rust layouts use power-of-two alignments, so that is valid for allocation requests. Still, arithmetic must be handled carefully. The allocation end uses checked_add to avoid wrapping. Without that check, a very large allocation size could wrap around and appear to fit inside the heap. Kernel allocators must treat arithmetic overflow as allocation failure, not as permission to return a bad pointer.

The global allocator wrapper can call this internal allocate method.

<!-- page: 225 -->
A) -> Self {
new(inner),
-> spin::MutexGuard<'_, A> {
:()
}
}
unsafe impl LockF {
unsafe fn alloc(&self, _ptr: *mut u8, _layout: Layout) {}
}
The `GlobalAlloc` implementation is unsafe because it promises that the allocator satisfies Rust’s allocation rules. The compiler cannot inspect the allocator’s runtime state. It cannot prove the heap was initialized, mapped, or non-overlapping. It cannot prove that returned pointers are unique. Those facts come from the allocator implementation and initialization order.
The lock makes the allocator usable from multiple contexts at a basic level, but it is not a complete solution. If an interrupt handler tries to allocate while interrupted code already holds the allocator lock, the kernel can deadlock. If the allocator is used before interrupts are enabled and never from interrupt context, this is not a problem yet. Once interrupts and scheduling become more advanced, allocation policy must be stricter. A
<!-- page: 226 -->
rust
self.allocations = 0;
}
pub fn allocate(&mut self, layout: Layout) -> *mut u8 {
let alloc_start = align_up_usize(self.next,
layout.align());
let Some(alloc_end) =
alloc_start.checked_add(layout.size()) else {
return null_mut();
};
if alloc_end > self.heap_end {
null_mut()
} else {
self.next = alloc_end;
self.allocations += 1;
alloc_start as *mut u8
}
}
fn align_up_usize(address: usize, alignment: usize) -> usize {
let mask = alignment - 1;
(address + mask) & !mask
}

This code adds an allocation counter. The counter does not affect correctness, but it is useful for diagnostics. When testing heap behavior, printing the number of allocations can show whether code is allocating more often than expected. If a supposedly small operation performs hundreds of allocations, you may want to inspect it before using it in a sensitive path.

The alignment helper assumes a power-of-two alignment. Rust layouts use power-of-two alignments, so that is valid for allocation requests. Still, arithmetic must be handled carefully. The allocation end uses checked_add to avoid wrapping. Without that check, a very large allocation size could wrap around and appear to fit inside the heap. Kernel allocators must treat arithmetic overflow as allocation failure, not as permission to return a bad pointer.

The global allocator wrapper can call this internal allocate method.

Rust

use core::alloc::{GlobalAlloc, Layout}; use spin::Mutex;

pub struct Locked { inner: Mutex, }

impl Locked { pub const fn new(inner: A) -> Self { Self { inner: Mutex::new(inner), } }

pub fn lock(&self) -> spin::MutexGuard<'_, A> {
self.inner.lock()
}

}

#[global_allocator] static ALLOCATOR: Locked = Locked::new(BumpAllocator::new());

unsafe impl GlobalAlloc for Locked { unsafe fn alloc(&self, layout: Layout) -> *mut u8 { self.lock().allocate(layout) }

unsafe fn dealloc(&self, _ptr: *mut u8, _layout: Layout) {}

}

The GlobalAlloc implementation is unsafe because it promises that the allocator satisfies Rust’s allocation rules. The compiler cannot inspect the allocator’s runtime state. It cannot prove the heap was initialized, mapped, or non-overlapping. It cannot prove that returned pointers are unique. Those facts come from the allocator implementation and initialization order.

The lock makes the allocator usable from multiple contexts at a basic level, but it is not a complete solution. If an interrupt handler tries to allocate while interrupted code already holds the allocator lock, the kernel can deadlock. If the allocator is used before interrupts are enabled and never from interrupt context, this is not a problem yet. Once interrupts and scheduling become more advanced, allocation policy must be stricter. A

common early rule is that interrupt handlers do not allocate. They use preallocated buffers or fixed-size queues.

A bump allocator can support a limited reset behavior if every allocation has been freed. To do that, it needs to count active allocations. Since dealloc is called when allocation-backed values are dropped, the allocator can decrement the count. If the count reaches zero, it can reset next to the heap start. This allows reuse only when all allocations are gone. It does not support freeing individual blocks while others remain active.

use core::alloc::Layout;
use core::ptr::null_mut;
pub struct ResettableBumpAllocator {
heap_start: usize,
heap_end: usize,
next: usize,
allocations: usize,
}
impl ResettableBumpAllocator {
pub const fn new() -> Self {
Self {
heap_start: 0,
heap_end: 0,
next: 0,
allocations: 0,
}
}
pub unsafe fn init(&mut self, heap_start: usize, heap_size: usize) {
self.heap_start = heap_start;
self.heap_end = heap_start + heap_size;
self.next = heap_start;
self.allocations = 0;
}
pub fn allocate(&mut self, layout: Layout) -> *mut u8 {
let alloc_start = align_up_usize(self.next, layout.align());
let Some(alloc_end) = alloc_start.checked_add(layout.size()) else {
return null_mut();
};

};

if alloc_end > self.heap_end { null_mut() } else { self.next = alloc_end; self.allocations += 1; alloc_start as *mut u8 }

pub unsafe fn deallocate(&mut self, _ptr: *mut u8, _layout: Layout) { if self.allocations == 0 { return; }

self.allocations -= 1;
if self.allocations == 0 {
self.next = self.heap_start;
}

}

This version can reuse the entire heap after all active allocations are dropped. It is still not a general allocator. If allocation A is followed by allocation B, then A is dropped while B remains alive, A’s memory cannot be reused. The allocator only resets when the active allocation count reaches zero. That makes it useful for controlled phases where all temporary allocations are dropped together, but it is not suitable for a kernel with long-lived and short-lived allocations mixed together.

The global allocator can use this deallocation behavior.

#[global_allocator]
static ALLOCATOR: Locked<ResettableBumpAllocator> =
Locked::new(ResettableBumpAllocator::new());
unsafe impl GlobalAlloc for Locked<ResettableBumpAllocator> {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
self.lock().allocate(layout)
}
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
unsafe {
self.lock().deallocate(ptr, layout);
}
}

This improves reuse in a narrow case, but it also introduces a responsibility. The allocator must not reset while any allocation remains alive. The active count is supposed to prevent that, but it assumes every allocation and deallocation call is paired correctly. Rust’s allocation-backed types will generally call the allocator correctly, but unsafe code can still violate rules. If kernel code manually allocates and deallocates through low-level APIs, it must pass the same layout to deallocation that was used during allocation.

Testing the bump allocator should show both its success and its limitation. A small test can allocate values, drop them, then allocate again. With the resettable version, the allocator can reuse from the start only after all allocations are gone.

use alloc::boxed::Box;
use alloc::vec::Vec;
pub fn test_bump_allocator_behavior() {
serial_println!("testing bump allocator");
{
let first = Box::new(10_u64);
let second = Box::new(20_u64);
serial_println!("first={}, second={}", *first, *second);
}
let mut values = Vec::new();
for number in 0..16 {
values.push(number);
}
serial_println!("values length={}", values.len());
}

This test does not prove everything about the allocator, but it confirms that allocation-backed values can be created, dropped, and followed by other allocations. If the allocator is the resettable version, dropping the two boxes may allow reuse if no other allocations are alive. If the allocator is the non-resetting version, every allocation consumes new heap space permanently.

The bump allocator’s largest weakness is fragmentation by lifetime. It does not track free holes. It does not know that a block in the middle has been returned. It cannot satisfy a future allocation from a freed block. For startup-only allocations, that is fine. For a kernel shell, task list, input buffers, filesystem structures, or dynamically changing services, it is not enough.

The bump allocator also hides memory leaks by design because it never reuses most freed memory. If a temporary String is created repeatedly, the heap grows until it runs out. The code may look correct at the Rust ownership level because the string is dropped each time. The allocator simply ignores the returned memory. This is a good reminder that Rust ownership and allocator policy are connected but not identical. Rust can ensure that String calls deallocation when it is dropped. The allocator decides what deallocation means.

A bump allocator is therefore a learning and bootstrapping tool. It gives the kernel dynamic allocation quickly. It lets you use alloc types. It proves that heap pages are mapped correctly. It gives you a working global allocator interface. After that, its limitations become the reason to build better allocators.

8.3: Building Linked-List and Fixed-Size Block Allocators

Section titled “8.3: Building Linked-List and Fixed-Size Block Allocators”

A general-purpose kernel heap needs to reuse freed memory. A linked-list allocator is one of the most direct ways to do that. It treats free memory as a list of free regions. When an allocation request arrives, the allocator searches the list for a region large enough to satisfy the request. It then returns part or all of that region and leaves any remaining space in the free

list. When memory is deallocated, the allocator adds that region back to the list. A more complete version also merges adjacent free regions to reduce fragmentation.

The linked-list allocator is more capable than a bump allocator, but it is also easier to get wrong. The allocator stores metadata inside free memory itself. That means the free list nodes live in the heap regions they describe. This is efficient because it avoids separate metadata allocation, but it requires careful pointer handling. A free region must be large enough to store a list node. The node must be aligned. Deallocation must not add a block that overlaps an active allocation. The same block must not be freed twice. Adjacent blocks should be merged carefully, or the heap becomes fragmented.

A small free-list node can store the size of a free region and a pointer to the next free region.

Rust

pub struct ListNode {
size: usize,
next: Option<&'static mut ListNode>,
}
impl ListNode {
pub const fn new(size: usize) -> Self {
Self {
size,
next: None,
}
}
pub fn start_address(&self) -> usize {
self as *const Self as usize
}
pub fn end_address(&self) -> usize {
self.start_address() + self.size
}
}

The 'static mut reference in the next field represents a free region node that lives inside the heap. This is unsafe territory. The allocator must ensure

that there is only one mutable reference to each free node and that the node memory is not simultaneously used as an active allocation. Rust cannot prove this automatically because the allocator is manually managing raw heap memory. The safety must come from allocator invariants.

The linked-list allocator begins with a dummy head node and an initialization function that adds the entire heap as one free region.

Rust

use core::mem;
pub struct LinkedListAllocator {
head: ListNode,
}
impl LinkedListAllocator {
pub const fn new() -> Self {
Self {
head: ListNode::new(0),
}
}
pub unsafe fn init(&mut self, heap_start: usize, heap_size: usize) {
unsafe {
self.add_free_region(heap_start, heap_size);
}
}
unsafe fn add_free_region(&mut self, address: usize, size: usize) {
assert_eq!(
align_up_usize(address, mem::align_of::<ListNode>()),
address
);
assert!(size >= mem::size_of::<ListNode>());
let mut node = ListNode::new(size);
node.next = self.head.next.take();
let node_ptr = address as *mut ListNode;
unsafe {
node_ptr.write(node);
self.head.next = Some(&mut *node_ptr);
}
}
}

alloc_start as *mut u8 } else { null_mut() }

This code is much more involved than the bump allocator because it must search, split, and maintain a free list. The size_align function adjusts the requested layout so any deallocated block will be large and aligned enough to hold a free-list node. That is important because the allocator stores metadata inside free regions. If a deallocated block were smaller than a node, it could not be inserted into the free list safely.

The find_region function removes the selected region from the list and returns it with the allocation start. If the region has extra space after the allocation, that extra space is added back as a free region. This handles leftover memory at the end, but the code shown does not preserve leading padding before alloc_start if alignment forces the allocation to start after the region beginning. A production-ready linked-list allocator must handle that padding as well or design its region selection so it is not lost. This is one reason allocator code requires careful testing.

Deallocation adds a block back to the free list. In its simplest form, it inserts the freed block as a new free region.

Rust

impl LinkedListAllocator { pub unsafe fn deallocate(&mut self, ptr: *mut u8, layout: Layout) { let (size, _) = Self::size_align(layout);

unsafe {
self.add_free_region(ptr as usize, size);
}
}

}

This is enough to reuse freed memory, but it does not merge adjacent regions. Without merging, fragmentation grows over time. If two

neighboring blocks are freed separately, the allocator sees them as two small regions rather than one larger region. A later large allocation may fail even though the total free memory would be enough if the regions were merged.

A better allocator inserts free regions in address order and merges neighbors when possible. That design is more complex but much more useful for a kernel that allocates and frees over time. The following code shows the shape of ordered insertion and merging.

Rust

impl LinkedListAllocator {
unsafe fn add_free_region_sorted(&mut self, address: usize, size: usize) {
assert_eq!(
align_up_usize(address, core::mem::align_of::<ListNode>()),
address
);
assert!(size >= core::mem::size_of::<ListNode>());
let mut current = &mut self.head;
while let Some(ref next) = current.next {
if next.start_address() >= address {
break;
}
current = current.next.as_mut().unwrap();
}
let mut node = ListNode::new(size);
node.next = current.next.take();
let node_ptr = address as *mut ListNode;
unsafe {
node_ptr.write(node);
current.next = Some(&mut *node_ptr);
}
self.merge_adjacent();
}
fn merge_adjacent(&mut self) {
let mut current = &mut self.head;
while let Some(ref mut region) = current.next {
while let Some(ref next) = region.next {
if region.end_address() == next.start_address() {
let next_next =
region.next.as_mut().unwrap().next.take();
let next_size = next.size;
region.size += next_size;
region.next = next_next;
} else {
break;
}
}
current = current.next.as_mut().unwrap();
}

This version keeps the free list sorted by address, then merges adjacent regions. The code is more delicate because it manipulates references inside a linked list stored in heap memory. This is exactly where Rust requires unsafe design discipline. The public allocation API can be safe, but the allocator internals are manually maintaining memory ownership.

A fixed-size block allocator takes a different approach. Instead of managing arbitrary-size regions through one list, it keeps separate lists for common block sizes. For example, it may have lists for 8-byte, 16-byte, 32-byte, 64-byte, 128-byte, 256-byte, 512-byte, 1024-byte, and 2048-byte blocks. When an allocation request comes in, the allocator rounds it up to the nearest supported block size and returns a block from that list. If the list is empty, it allocates a new page or region and splits it into blocks of that size.

The advantage is speed and reduced fragmentation for small allocations. Many kernel allocations are small objects: nodes, descriptors, queue entries, handles, and short buffers. Fixed-size blocks make those allocations efficient. The disadvantage is internal waste. If a request for 129 bytes uses a 256-byte block, the unused space inside that block is not available to other allocations. Large allocations still need a fallback allocator or page-level allocation path.

A small fixed-size block allocator can store one free list per block size. Each free block stores a pointer to the next free block.

Rust

const BLOCK_SIZES: &[usize] = &[8, 16, 32, 64, 128, 256, 512, 1024, 2048];
struct FreeBlock {
next: Option<&'static mut FreeBlock>,
}
pub struct FixedSizeBlockAllocator {
list_heads: [Option<&'static mut FreeBlock>; 9],
fallback_allocator: LinkedListAllocator,
}
impl FixedSizeBlockAllocator {
pub const fn new() -> Self {
Self {
list_heads: [None, None, None, None, None, None, None, None, None],
fallback_allocator: LinkedListAllocator::new(),
}
}
pub unsafe fn init(&mut self, heap_start: usize, heap_size: usize) {
unsafe {
self.fallback_allocator.init(heap_start, heap_size);
}
}
}

The fixed-size allocator uses a linked-list allocator as a fallback. At first, all heap memory belongs to the fallback allocator. When a small allocation request arrives and the matching free list is empty, the allocator asks the fallback allocator for a new block. A more advanced version would allocate a full page and split it into many blocks, but requesting individual blocks from the fallback allocator is enough to show the structure.

A helper chooses the block-size list for a layout.

<!-- page: 238 -->
use core::alloc::Layout;
fn list_index(layout: &Layout) -> Option<usize> {
let required_size = layout.size().max(layout.align());
BLOCK_SIZES.iter().position(|&size| size >= required_size)
}
The required block size must satisfy both the allocation size and alignment. If a type requires 64-byte alignment, a smaller block cannot be used even if the requested size is small. This helper finds the first block size large enough for both.
Allocation first checks the matching free list. If a free block is available, it removes and returns it. If not, it allocates from the fallback allocator using a layout for the selected block size.
Rust
use core::alloc::Layout;
use core::ptr::null_mut;
impl FixedSizeBlockAllocator {
pub fn allocate(&mut self, layout: Layout) -> *mut u8 {
match list_index(&layout) {
Some(index) => {
match self.list_heads[index].take() {
Some(block) => {
self.list_heads[index] =
block.next.take();
block as *mut FreeBlock as *mut u8
}
None => {
let block_size = BLOCK_SIZES[index];
let block_align = block_size;
let layout =
Layout::from_size_align(block_size, block_align)
.expect("invalid block layout");
self.fallback_allocator.allocate(layout)
}
}
}
None => {
self.fallback_allocator.allocate(layout)
}
}
}
}
<!-- page: 239 -->
rust
}
}
pub unsafe fn deallocate(&mut self, ptr: *mut u8, layout: Layout) {
match list_index(&layout) {
Some(index) => {
let new_block = FreeBlock {
next: self.list_heads[index].take(),
};
let block_ptr = ptr as *mut FreeBlock;
unsafe {
block_ptr.write(new_block);
self.list_heads[index] = Some(&mut *block_ptr);
}
}
None => {
unsafe {
self.fallback_allocator.deallocate(ptr, layout);
}
}
}
}

This allocator reuses small freed blocks quickly. When a small allocation is deallocated, the memory becomes a FreeBlock node and is placed back onto the matching list. The next allocation of a compatible size can reuse it without searching the fallback allocator. This design is useful for repeated small allocations.

The implementation still depends on strong invariants. The pointer passed to deallocate must have come from this allocator. The layout must match the original allocation. The block must be large enough and aligned enough to store a FreeBlock. The same pointer must not be deallocated twice. Safe Rust code using Box, Vec, and String normally maintains allocation and deallocation pairing, but unsafe kernel code can break it. The allocator must be treated as a trusted low-level component.

The global allocator wrapper can use the fixed-size allocator.

#[global_allocator]
static ALLOCATOR: Locked<FixedSizeBlockAllocator> =
Locked::new(FixedSizeBlockAllocator::new());
unsafe impl GlobalAlloc for Locked<FixedSizeBlockAllocator> {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
self.lock().allocate(layout)
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
unsafe {
self.lock().dealloc(ptr, layout);
}
}
}

This gives the kernel a more realistic heap allocator. It can reuse freed small blocks and fall back to a linked-list allocator for larger requests. It is still not the final allocator used by a production system, but it is a serious step beyond a bump allocator. It also teaches the key tradeoffs: speed, fragmentation, metadata placement, alignment, locking, and deallocation correctness.

Allocator testing should include repeated allocation and deallocation. A test that only allocates once proves little. The allocator should be exercised with many small objects, dropped objects, and larger buffers.

use alloc::boxed::Box;
use alloc::vec::Vec;
pub fn test_reusing_allocator() {
serial_println!("testing allocator reuse");
for value in 0..100 {
let boxed = Box::new(value);
assert_eq!(*boxed, value);
}
let mut vectors = Vec::new();
for outer in 0..16 {

let mut inner = Vec::new();

for inner_value in 0..32 { inner.push(outer * inner_value); }

vectors.push(inner.len());

serial_println!(“allocator reuse test complete”);

This test creates many small boxed values and vectors. The boxes are dropped each loop iteration, so the allocator should be able to reuse those blocks. The vectors exercise growing allocations. If the heap exhausts too quickly, the allocator may not be reusing memory effectively. If values are corrupted, the allocator may be returning overlapping blocks or mishandling deallocation.

A linked-list allocator and a fixed-size block allocator give the kernel practical heap behavior, but they still require caution. They should not be used from every context without policy. They should not be called while holding unrelated locks unless the lock order is clear. They should not allocate inside fatal exception paths. They should be tested under QEMU before being trusted by larger subsystems. The allocator is now a central kernel service, and central services deserve careful boundaries.

8.4: Managing Unsafe Code, Global State, and Kernel Invariants

Section titled “8.4: Managing Unsafe Code, Global State, and Kernel Invariants”

Heap allocation forces the kernel to confront a broader design issue: safe abstractions often sit on top of unsafe machinery. This is normal in systems programming. The goal is not to eliminate unsafe code completely. The goal is to place it where the required invariants can be stated and checked. A kernel written in Rust should not scatter raw pointer manipulation, global mutable state, page-table edits, and hardware access across every module. It should build small unsafe foundations and expose safe interfaces above them.

An allocator is a perfect example. Its internals are unsafe because it turns raw heap memory into typed objects, stores metadata inside free memory, performs pointer arithmetic, and manages ownership manually. The interface above it can be safe. When kernel code writes Box::new(Task::new()), it should not need to know how free lists are maintained. The allocator promises to return valid, aligned, non-overlapping memory. The Rust type system then protects the code that uses that memory. If the allocator breaks its promise, safe code above it can become unsound. That is why allocator invariants matter so much.

A kernel invariant is a condition that must always hold for the system to remain correct. For the heap, important invariants include that the heap range is mapped before allocation begins, allocator metadata never overlaps active allocations, every active allocation has unique ownership of its returned memory, deallocation receives the same layout used for allocation, tree-list nodes exist only inside free memory, and the allocator does not return memory outside the heap. These are not comments for decoration. They are the reasoning that makes the unsafe code valid.

You can encode some invariants in types. For example, a heap range can be represented as its own type rather than passing raw start and size values everywhere.

Rust

#[derive(Debug, Clone, Copy)]
pub struct HeapRange {
start: usize,
size: usize,
}
impl HeapRange {
pub fn new(start: usize, size: usize) -> Result<Self, &'static str> {
if size == 0 {
return Err("heap size is zero");
}
if start % 4096 != 0 {
return Err("heap start is not page aligned");
}
}
}

if size % 4096 != 0 { return Err(“heap size is not page aligned”); }

let Some(_) = start.checked_add(size) else { return Err(“heap range overflows address space”); };

Ok(Self { start, size })

pub fn start(&self) -> usize { self.start }

pub fn size(&self) -> usize { self.size }

pub fn end(&self) -> usize { self.start + self.size }

This type prevents invalid heap ranges from moving through the system as ordinary numbers. The constructor checks page alignment, non-zero size, and overflow. Once a HeapRange exists, other code can rely on those properties. This does not prove the range is mapped, but it does prove basic layout validity. Strong types do not replace runtime checks. They reduce the number of places where invalid values can be created.

Allocator initialization can accept this type instead of separate integers.

impl FixedSizeBlockAllocator {
pub unsafe fn init_range(&mut self, range: HeapRange) {
unsafe {
self.init(range.start(), range.size());
}
}
}
pub fn init_heap_allocator(range: HeapRange) {
unsafe {

ALLOCATOR.lock().init_range(range); }

serial_println!( “heap allocator initialized: start={:#x}, end={:#x}”, range.start(), range.end() ); }

This is a small improvement, but small improvements accumulate in kernel code. The allocator initialization no longer accepts arbitrary unrelated values. It accepts a checked heap range. The unsafe operation remains because the function still assumes the range has been mapped and reserved for heap use, but the basic numeric validity is already established.

Global state is another area that requires discipline. Kernels naturally have global services. There may be a global allocator, global logger, global interrupt table, global task queue, global device registry, and global memory manager. Rust makes uncontrolled global mutation difficult for good reasons. In kernel development, the answer is not to bypass Rust with static mut everywhere. The answer is to place global state behind synchronization and one-time initialization rules.

A simple global service can be represented by a lock-protected optional value. Access before initialization should fail clearly. Initialization should happen once.

use spin::Mutex;
pub struct OnceCell<T> {
value: Mutex<Option<T>>,
}
impl<T> OnceCell<T> {
pub const fn new() -> Self {
Self {
value: Mutex::new(None),
}
}
}

pub fn init(&self, value: T) { let mut guard = self.value.lock();

if guard.is_some() {
panic!("global value initialized twice");
}
*guard = Some(value);

}

pub fn with(&self, function: impl FnOnce(&T) -> R) -> R { let guard = self.value.lock(); let value = guard.as_ref().expect(“global value is not initialized”);

function(value)

}

pub fn with_mut(&self, function: impl FnOnce(&mut T) -> R) -> R { let mut guard = self.value.lock(); let value = guard.as_mut().expect(“global value is not initialized”);

function(value)

}

This type is a basic kernel-owned one-time cell. It is not a complete substitute for mature synchronization primitives, but it expresses a useful rule: the value begins absent, is initialized once, and is accessed through controlled closures. The closures prevent references from escaping after the lock guard is dropped. That keeps the borrowing model tied to the lock lifetime.

This pattern can manage a global memory service.

pub struct MemoryManager {
heap: HeapRange,
allocations_started: bool,
}
impl MemoryManager {
pub fn new(heap: HeapRange) -> Self {
<!-- page: 246 -->
rust
Self {
heap,
allocations_started: false,
}
pub fn heap_range(&self) -> HeapRange {
self.heap
}
pub fn mark_allocations_started(&mut self) {
self.allocations_started = true;
}
static MEMORY_MANAGER: OnceCell<MemoryManager> = OnceCell::new();
ub fn init_memory_manager(heap: HeapRange) {
MEMORY_MANAGER.init(MemoryManager::new(heap));
}
ub fn with_memory_manager<R>(function: impl Once(&MemoryManager) -> R) -> R {
MEMORY_MANAGER.with(function)
}

This code shows how kernel services can be exposed without giving every module direct mutable access to global state. The memory manager controls its own data. Other code calls functions that enforce access rules. As the kernel grows, this pattern becomes more important. Direct access to global mutable structures makes it hard to understand who can change what and when.

Locks must be used carefully in a kernel. A spinlock loops until it can acquire the lock. That is acceptable for very short critical sections when there is no sleeping scheduler. It is dangerous if the lock can be held while waiting for an event that depends on the same CPU or interrupt. If interrupts are enabled and an interrupt handler tries to acquire a lock already held by interrupted code, the system can deadlock. To avoid this on a single CPU, critical sections that protect data also accessed from interrupts often disable interrupts while holding the lock.

<!-- page: 247 -->
use spin::Mutex;
use x86_64::instructions::interrupts;
pub struct InterruptSafeLock<T> {
inner: Mutex<T>,
}
impl<T> InterruptSafeLock<T> {
pub const fn new(value: T) -> Self {
Self {
inner: Mutex::new(value),
}
}
pub fn with<R>(&self, function: impl FnOnce(&mut T) -> R) -> R {
interrupts::without_interrupts(|| {
let mut guard = self.inner.lock();
function(&mut guard)
})
}
}
This wrapper disables interrupts while the lock is held. It is useful for early single-core code where an interrupt handler might access the same data. It is not a final synchronization solution for multicore systems. On multiple CPUs, disabling interrupts on one CPU does not prevent another CPU from accessing the same lock. Later, the kernel will need stronger rules for per-CPU data, interrupt context, lock ordering, and possibly scheduler-aware blocking. For now, this wrapper gives a safer shape for early shared state.
The allocator lock may also need interrupt-safe behavior if allocation can happen from interrupt-accessible paths. A better policy is to avoid allocating in interrupt handlers entirely. Use fixed-size ring buffers or preallocated structures for interrupt-time work. Interrupt handlers should do the minimum required work and defer larger processing to normal kernel context. This keeps the heap allocator out of the most timing-sensitive and deadlock-prone paths.
Unsafe code should come with local safety reasoning. In Rust source, that usually means comments explaining why the unsafe operation is valid. The comment should state the invariant, not merely repeat that the operation is unsafe.
<!-- page: 248 -->
# Rust
rust
pub unsafe fn write_heap_byte(range: HeapRange, offset: usize, value: u8) {
assert!(offset < range.size(), "heap write offset is out of range");
let address = range.start() + offset;
let pointer = address as *mut u8;
unsafe {
core::ptr::write_volatile(pointer, value);
}
}

This function checks that the offset is inside the heap range before writing. It still does not prove the page is mapped or that writing the byte will not corrupt allocator metadata. That is why this kind of function should not exist as a general public API. It is useful as a small example of local checking, but a real allocator should not expose arbitrary heap writes. The safer design is to keep raw heap memory manipulation inside allocator methods.

A more appropriate unsafe allocator helper makes its safety conditions clear through a narrow purpose.

impl LinkedListAllocator {
unsafe fn write_free_node(
&mut self,
address: usize,
size: usize,
next: Option<&'static mut ListNode>,
) -> &'static mut ListNode {
assert_eq!(
align_up_usize(address, core::mem::align_of::<ListNode>()),
address
);
assert!(size >= core::mem::size_of::<ListNode>());
let node_ptr = address as *mut ListNode;
unsafe {
node_ptr.write(ListNode { size, next });
}
}
}

&mut *node_ptr

This helper has one job: write a free-list node into a valid free heap region. It checks alignment and size before writing. It still relies on the caller to guarantee that the memory is free and belongs to the heap. That is a good boundary. The helper handles local mechanical conditions, while the allocator’s higher-level logic preserves ownership conditions.

Kernel invariants should also be checked at initialization boundaries. If the heap overlaps a protected range, initialization should stop. If the heap is not mapped, a test write should fail before ordinary allocation begins. If the allocator is initialized twice, panic. Silent acceptance of invalid state is worse than a clear early failure.

rust
pub fn validate_heap_range(
heap: HeapRange,
protected_ranges: &[ProtectedRange],
) -> Result<(), &'static str> {
for range in protected_ranges {
if range.overlaps(heap.start() as u64, heap.end() as u64) {
return Err("heap overlaps protected physical range");
}
}
Ok(())
}

This example assumes the heap range and protected ranges are in the same address space, which may not be true in a higher-half or offset-mapped kernel. That is an important lesson. Validation functions must compare like with like. A virtual heap range should be checked against virtual layout reservations. Physical protected ranges should be checked against physical frames backing the heap. Mixing virtual and physical addresses in the same comparison creates false confidence. Stronger types can help prevent that mistake.

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct VirtualAddress(usize);
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct PhysicalAddress(u64);
impl VirtualAddress {
pub const fn new(value: usize) -> Self {
Self(value)
}
pub fn as_usize(self) -> usize {
self.0
}
}
impl PhysicalAddress {
pub const fn new(value: u64) -> Self {
Self(value)
}
pub fn as_u64(self) -> u64 {
self.0
}
}

These wrapper types are simple, but they prevent physical and virtual addresses from being passed interchangeably without an explicit conversion. A real kernel may use architecture crate types for this purpose. The principle is the same: make address categories visible in the type system. Many memory bugs begin when a number loses its meaning.

Allocation failure policy is another invariant area. Some kernel paths can tolerate allocation failure and return an error. Other paths cannot proceed. The global allocation error handler panics because allocation-backed Rust APIs sometimes cannot return failure directly. Kernel APIs that allocate internally should be honest about whether they can fail. If a command parser creates a String, it may return an error. If early heap initialization cannot allocate page-table frames, it may panic. Being explicit prevents hidden failure behavior.

<!-- page: 251 -->
rust
use alloc::string::String;
pub fn build_status_message(name: &str) -> Result<String, &'static str> {
let mut message = String::try_with_capacity(name.len() + 16)
.map_err(|_| "failed to allocate status message")?;
message.push_str("service: ");
message.push_str(name);
message.push_str(" ready");
Ok(message)
}

This function uses a fallible allocation path. Not all allocation-backed APIs are fallible in every case, but when fallible options are available, kernel services should consider using them. A kernel that panics on every allocation failure may be acceptable early, but mature code should distinguish fatal initialization failure from recoverable service failure.

Safe kernel abstractions are not about hiding reality. They are about placing reality behind correct interfaces. A framebuffer writer can expose write_pixel while keeping volatile pointer writes inside. A port type can expose read_u8 and write_u8 while keeping inline assembly inside. A frame allocator can expose allocate_frame while protecting memory-map logic. A heap allocator can expose Box and Vec through the global allocator while keeping free-list manipulation private. Each abstraction should reduce the amount of code that can violate critical invariants.

At the end of this stage, the kernel has a mapped heap, a registered global allocator, access to alloc types, and a clearer model for unsafe code. The bump allocator proves the path. The linked-list allocator introduces reuse. The fixed-size block allocator improves small allocation behavior. The abstraction layer keeps global state and unsafe operations under control. This is a major step. The kernel can now build dynamic structures, but it also carries new responsibility. Every allocation depends on the heap being mapped, the allocator being initialized, locks being used correctly, and unsafe metadata code preserving its invariants. When those rules are respected, Rust’s higher-level allocation-backed types become practical tools inside the kernel rather than risky shortcuts