
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
A custom target for riscv64gc
3 min readThe 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 a short name describing the CPU architecture, vendor, operating system, and ABI a binary is built for, for example riscv64gc-unknown-none-elf. 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:
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:
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:
{
"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.
The linker script
5 min readA compiler emits code and data into units called a named region of an object file holding code or data of one kind, such as .text for instructions or .data for globalss. 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 a file of directives to the linker describing how input sections are arranged and addressed in the output binary overrides that arrangement. Ours is src/linker.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.
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:
[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 boot trampoline: from _start to Rust
4 min readWhen 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:
.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:
Receive the handoff: OpenSBI enters in S-mode with a0 = hart id and a1 = device tree pointer, MMU off.
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.
Set the global pointer: la gp, __global_pointer$ loads the anchor for gp-relative addressing of global data.
Call into Rust: call rust_main jumps to the Rust entry, which then zeroes .bss and takes over.
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:
#![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 register x3 (gp), which RISC-V code uses as a fixed anchor for addressing nearby global data in a single instruction 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.
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
- 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.
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- 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
- Official docsrustc: custom target specification
- Official docsUsing LD, the GNU linker (the script language)
- SpecificationRISC-V Supervisor Binary Interface (SBI) specification
- SpecificationRISC-V ELF psABI specification
Official documentation first. Links checked when the lesson was published.