Module 10 · Lesson 3 of 112

Building and booting the riscv64gc kernel

Write a custom riscv64gc target and linker script and wire the assembly trampoline that starts the kernel and zeroes .bss.

  • Beginner to advanced
  • 10 min read
  • 10 min lab
What you will need

A Linux machine (Ubuntu 24.04 in WSL2, a VM, or a container); Rust nightly plus the rust-src component; llvm-tools-preview and cargo-binutils; QEMU with qemu-system-riscv64 for the booting lesson that follows

Your place in the module
By the end you can 3 objectives
  • Write a custom riscv64gc target JSON and a linker script that places .text.boot first and links no libc.
  • Set linker flags in .cargo/config.toml to use the linker script and enable --gc-sections
  • Write the assembly trampoline that sets the stack and global pointer, calls rust_main, and zeroes .bss before any static is read
Video coming soonBuilding and booting the riscv64gc kernel
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from no_std, no_main, and the panic handler
  • #![no_std] removes the std prelude, and #![no_main] removes the runtime that normally calls main.
  • The #[panic_handler] lang item is the one piece of runtime you must supply, and panic = abort is the only strategy bare metal supports.
  • PanicInfo exposes location() and message() as references, and write! into a core::fmt::Write implementation formats output with zero allocation
01

A custom target for riscv64gc

3 min read

The crate so far compiles only for the host. This lesson gives it a riscv64gc bare-metal target, a linker script, and an assembly entry, answering how a freestanding kernel is built and starts running in Rust.

So far the crate only compiles in theory; cargo build against your host triple still tries to link crt0 and libc. The fix is to compile for a different destination. Rust names that destination with a . The part that matters here is none: no operating system.

The easy path is a target rustup already ships. RISC-V 64 general-purpose bare metal is a tier-2 target, so you can install its prebuilt libraries directly:

bash
rustup target add riscv64gc-unknown-none-elf
cargo build --target riscv64gc-unknown-none-elf

The target name unpacks as RV64GC: 64-bit RISC-V with the G extension (integer, multiply-divide, atomics, single and double float) plus C for compressed instructions. unknown-none-elf means no vendor, no OS, ELF object format. With this target, rustup supplies a precompiled core and alloc, and the linker no longer assumes a C runtime, so the crate links.

The harder path, and the one this module needs, is a custom target. You will eventually want to change link details and ABI choices that a stock target fixes, and Rust lets you describe a whole target in a single JSON file. The authoritative way to start is to ask rustc to print a known target's spec and edit it:

bash
rustc -Z unstable-options --print target-spec-json --target riscv64gc-unknown-none-elf

Save the result as riscv64gc-qemu.json at the crate root. The fields that matter, with a few trimmed, look like this:

json
{
  "arch": "riscv64",
  "data-layout": "e-m:e-p:64:64-i64:64-i128:128-n32:64-S128",
  "llvm-target": "riscv64-unknown-none-elf",
  "target-pointer-width": "64",
  "max-atomic-width": 64,
  "os": "none",
  "executables": true,
  "features": "+m,+a,+f,+d,+c",
  "llvm-abiname": "lp64d",
  "panic-strategy": "abort",
  "relocation-model": "static",
  "linker": "rust-lld",
  "linker-flavor": "gnu-lld"
}

Each field is a contract with the backend. arch and llvm-target name the architecture for code generation. data-layout tells LLVM the size and alignment of integers and pointers, in a compact string: little-endian, mangling style e, 64-bit pointers and integers, 128-bit integers, 64-bit natural alignment. features lists the ISA extensions as +m,+a,+f,+d,+c, with no spaces between them or LLVM rejects the string. max-atomic-width: 64 promises the backend can emit 64-bit atomics. os: "none" is the whole point: it tells the toolchain there is no operating system, which disables the C-runtime assumptions and lets panic-strategy: "abort" apply to any recompiled core. relocation-model: "static" and linker: "rust-lld" with linker-flavor: "gnu-lld" say the output is a fixed-address, statically linked ELF linked by the LLVM linker bundled with Rust, so the build needs no system C compiler.

A custom target also triggers a consequence the stock target avoided: rustup has no precompiled core for a JSON file it has never heard of. Section 9 deals with that.

Stock target versus a custom JSON targetrustup targetadd riscv64gc-unknown-none-elfcustom riscv64gc-qemu.jsonWhere core comesfromprebuilt andshipped byrustupcompiled bybuild-stdfrom rust-srcRequires nightlynoyes, forbuild-stdFields you canchangenoneos, features,linker, panicstrategyWhen to usestandardbare-metalRISC-Vtweaking ABIor linkdetails
The stock riscv64gc target versus a custom JSON target and when each is the right tool
02

The linker script

5 min read

A compiler emits code and data into units called s. The linker's default arrangement of those sections is designed for a hosted program, not for a kernel that must start at a hard-coded address. A overrides that arrangement. Ours is src/linker.ld:

ld
OUTPUT_ARCH(riscv)
ENTRY(_start)

MEMORY
{
    RAM (rwx) : ORIGIN = 0x80200000, LENGTH = 126M
}

SECTIONS
{
    . = ORIGIN(RAM);

    .text.boot : {
        KEEP(*(.text.boot))
    } >RAM

    .text : {
        *(.text .text.*)
    } >RAM

    .rodata : ALIGN(4K) : {
        *(.rodata .rodata.*)
        *(.srodata .srodata.*)
    } >RAM

    .data : ALIGN(4K) : {
        *(.data .data.*)
        *(.sdata .sdata.*)
    } >RAM

    PROVIDE(__global_pointer$ = .);

    .bss : ALIGN(4K) : {
        *(.bss.stack)
        PROVIDE(__bss_start = .);
        *(.bss .bss.*)
        *(.sbss .sbss.*)
        PROVIDE(__bss_end = .);
    } >RAM

    /DISCARD/ : {
        *(.eh_frame)
        *(.comment)
    }
}

Read it top to bottom. OUTPUT_ARCH(riscv) sets the machine type, and ENTRY(_start) names the entry point. The MEMORY block declares one region, RAM, starting at 0x80200000. That number is not arbitrary: it is where OpenSBI, the RISC-V firmware this module uses, jumps after it finishes, so the kernel's first instruction must sit exactly there. The QEMU virt machine's RAM begins at 0x80000000 and the firmware occupies the first 2 MiB, leaving the kernel the address space from 0x80200000 upward.

QEMU virt RAM starts at 0x80000000: OpenSBI firmware takes the first 2 MiB (0x80000000 to 0x801FFFFF), and the 126 MiB kernel region follows at 0x80200000, where _start is linked and OpenSBI jumps after it finishes.

  • regions: [{"name": "OpenSBI firmware", "start": "0x80000000", "size": "0x200000", "detail": "First 2 MiB of QEMU virt RAM, occupied by OpenSBI; it finishes by jumping to 0x80200000."}, {"name": "Kernel RAM", "start": "0x80200000", "size": "0x7E00000", "detail": "126 MiB for the kernel (linker script RAM: ORIGIN = 0x80200000, LENGTH = 126M); _start is linked here."}]

Inside SECTIONS, the location counter . starts at ORIGIN(RAM). The first output section is .text.boot, and it holds our entry assembly because of the KEEP(*(.text.boot)) directive. The input section .text.boot is referenced by no code, only by the entry point address, so the --gc-sections flag (below) would otherwise discard it as dead; KEEP forbids that. Placing it first, ahead of .text, guarantees the very first byte of the image is _start. Then come .text (code), .rodata (constants), .data (initialised globals), and .bss (zero-initialised globals), each aligned to a 4 KiB page boundary by ALIGN(4K).

PROVIDE(__bss_start = .) and PROVIDE(__bss_end = .) define the symbols your Rust code will use to zero .bss, and .bss.stack sits before __bss_start so the boot stack is deliberately outside the zeroed range, for a reason the next section explains. /DISCARD/ throws away .eh_frame, the unwinding metadata that abort mode makes pointless, shrinking the image.

The flags come from .cargo/config.toml, which also sets the default target so a bare cargo build works:

toml
[build]
target = "riscv64gc-qemu.json"

[target.riscv64gc-qemu]
rustflags = [
    "-Clink-arg=-Tsrc/linker.ld",
    "-Clink-arg=--gc-sections",
]

-Clink-arg=-Tsrc/linker.ld hands the script to the linker. -Clink-arg=--gc-sections enables link-time dead-code elimination: any function or section that nothing references is dropped, which with the linker script's KEEP still protects the entry point. Two further flags appear in many kernels: -no-pie and -static. They are the linker-level way to ask for a fixed-address, self-contained binary, but our target JSON already encodes both through "relocation-model": "static" and "os": "none", so they are redundant here and matter mainly when you link against the host's own linker driver.

Going deeperThe location counter and what PROVIDE really does

The . in a linker script is a cursor. It always points at the next free address, and you can both read it and assign to it. ALIGN(4K) bumps the cursor up to the next 4 KiB boundary, which is why sections start on page boundaries; . = ORIGIN(RAM) plants the cursor at the start of the region.

PROVIDE(sym = .) is subtler than a plain sym = .. It defines a symbol only if the program did not already define one with that name, so a future version of the kernel can override the boundary markers without editing the script. This matters for symbols like __bss_start that your Rust code imports across the language boundary: the script says where the boundary is, and PROVIDE lets your code win the argument if it ever disagrees. Symbols such as __bss_start are not variables; they are bare addresses with no storage. The correct way to touch them from Rust is to declare them as extern statics and take their address, which the next section shows.

The kernel memory layout from the linker scripthighBoot stack.bss.stack, 64 KiB.bsszeroed globals.datainitialised globals.rodataconstants, string literals.textcompiled code.text.boot_start, placed firstlowOpenSBI firmware0x80000000..0x80200000highBoot stack.bss.stack, 64 KiB.bsszeroed globals.datainitialised globals.rodataconstants, string literals.textcompiled code.text.boot_start, placed firstlowOpenSBI firmware0x80000000..0x80200000
The kernel memory layout the linker script produces, from .text.boot at 0x80200000 to the boot stack
03

The boot trampoline: from _start to Rust

4 min read

When OpenSBI finishes its own setup it jumps to 0x80200000, our entry point, leaving the CPU in supervisor mode with the memory-management unit still off. It hands the kernel exactly two pieces of information in registers: a0 holds the running hart id (which hardware thread this is), and a1 holds the address of the flattened device tree describing the machine. It does not hand over a usable long-term stack, and it does not zero your globals. Those are the trampoline's jobs, done in assembly because Rust cannot run before its stack exists. This is src/entry.asm:

asm
    .section .text.boot
    .globl _start
_start:
    la   sp, boot_stack_top     # stack grows down from here
    la   gp, __global_pointer$  # global pointer for small-data access
    call rust_main              # never returns
    j    .                      # park here if it somehow does

    .section .bss.stack
    .align 4
    .space 4096 * 16            # 64 KiB boot stack
    .globl boot_stack_top
boot_stack_top:

The sequence is short but each line exists for a reason:

Step by stepWhat runs before the first line of Rust
  1. Receive the handoff: OpenSBI enters in S-mode with a0 = hart id and a1 = device tree pointer, MMU off.

  2. Set the stack pointer: la sp, boot_stack_top loads sp with the top of a 64 KiB region; RISC-V stacks grow downward into it.

  3. Set the global pointer: la gp, __global_pointer$ loads the anchor for gp-relative addressing of global data.

  4. Call into Rust: call rust_main jumps to the Rust entry, which then zeroes .bss and takes over.

  5. Guard the return: the j . after the call parks the hart forever if rust_main ever returns, which it must not.

The Rust side is embedded with core::arch::global_asm!, then defines rust_main, which first zeroes .bss using the symbols the linker script provided:

rust
#![no_std]
#![no_main]

use core::arch::global_asm;
use core::panic::PanicInfo;

global_asm!(include_str!("entry.asm"));

unsafe extern "C" {
    static __bss_start: u8;
    static __bss_end: u8;
}

#[unsafe(no_mangle)]
extern "C" fn rust_main() -> ! {
    clear_bss();
    loop {}
}

fn clear_bss() {
    let start = unsafe { core::ptr::addr_of!(__bss_start) } as usize;
    let end = unsafe { core::ptr::addr_of!(__bss_end) } as usize;
    for addr in start..end {
        unsafe { (addr as *mut u8).write_volatile(0) };
    }
}

#[panic_handler]
fn panic(_info: &PanicInfo) -> ! {
    loop {}
}

Three details carry the depth here. First, the linker symbols are declared as extern "C" statics of type u8, then read with core::ptr::addr_of!. A linker symbol is an address, not a value, so you must never dereference it; you take its address and convert it to an integer, which is exactly what addr_of! plus as usize does. Second, .bss must be zeroed before any global variable is read, because Rust guarantees static variables start at zero, and that guarantee is one the kernel itself has to keep on hardware that does not zero memory for it. Third, notice that .bss.stack sits before __bss_start in the linker script, so the boot stack is excluded from the zeroing loop. That ordering is essential: by the time clear_bss runs, rust_main already has a stack frame whose saved return address lives in .bss.stack; zeroing the stack would erase it.

Going deeperThe global pointer, linker relaxation, and a classic bug

The is an ABI concept, not a hardware requirement. Linker relaxation can rewrite a two-instruction address load into a single lw or sw relative to gp, but only for globals that lie within about 2 KiB of the symbol __global_pointer$. The catch is that the rewrite assumes gp holds that symbol's address at runtime.

With rustc and LLVM, small-data sections such as .sdata are not generated by default, so gp-relative loads are not emitted and setting gp is currently a harmless no-op. The trampoline sets it anyway because the RISC-V psABI reserves the register for this purpose, and the moment you link in C or hand-written assembly that does use small data, an uninitialised gp produces reads and writes to wrong addresses: a bug that corrupts a globals-adjacent region while looking like anything else. The discipline is simple and it is why the la gp, __global_pointer$ line exists even when nothing uses it yet.

The boot trampoline in _startOpenSBIhandoffa0 hart id,a1 devicetreela sp, boot_stack_topestablishthe stackla gp, __global_pointer$globalpointerclear .bsszero theglobalscallrust_mainenter RustOpenSBIhandoffa0 hart id,a1 devicetreela sp, boot_stack_topestablishthe stackla gp, __global_pointer$globalpointerclear .bsszero theglobalscallrust_mainenter Rust
The sequence from the OpenSBI handoff through stack setup to the call into rust_main

Key takeaways

  • A freestanding binary starts at _start, which your linker script names and your trampoline implements.
  • The linker script is what pins .text.boot at 0x80200000 and defines the __bss_start/__bss_end symbols your code zeroes.
  • A linker symbol such as __bss_start is a bare address, not a value; read it with core::ptr::addr_of! and never dereference it
  • .bss.stack is placed before __bss_start so the boot stack is excluded from the zeroing loop, protecting the saved return address
Reflect
  1. Explain to a colleague, in two sentences: write a custom riscv64gc target JSON and a linker script that places .text.boot first and links no libc.
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Find your next step

↑ ↓ to move · Enter to open · Esc to close