Expand description
Startup code and minimal runtime for RISC-V CPUs
This crate contains all the required parts to build a no_std
application
(binary crate) that targets a RISC-V microcontroller.
§Features
This crates takes care of:
-
The memory layout of the program.
-
Initializing
static
variables before the program entry point. -
Enabling the FPU before the program entry point if the target has the
f
ord
extension. -
Support for a runtime in supervisor mode, that can be bootstrapped via Supervisor Binary Interface (SBI).
-
Support for bootstrapping a runtime with U-Boot.
This crate also provides the following attributes:
-
Before main initialization of the
.bss
and.data
sections. -
#[entry]
to declare the entry point of the program -
#[pre_init]
to run code beforestatic
variables are initialized -
#[exception]
to override an exception handler. -
#[core_interrupt]
to override a core interrupt handler. -
#[external_interrupt]
to override an external interrupt handler.
If not overridden, all exception and interrupt handlers default to an infinite loop.
The documentation for these attributes can be found in the Attribute Macros section.
§Requirements
§memory.x
This crate expects the user, or some other crate, to provide the memory layout of the target
device via a linker script, described in this section. We refer to this file as memory.x
.
§MEMORY
The main information that this file must provide is the memory layout of
the device in the form of the MEMORY
command. The command is documented
here, but at a minimum you’ll want to create at least one memory region.
To support different relocation models (RAM-only, FLASH+RAM) multiple regions are used:
REGION_TEXT
- for.init
,.trap
and.text
sectionsREGION_RODATA
- for.rodata
section and storing initial values for.data
sectionREGION_DATA
- for.data
sectionREGION_BSS
- for.bss
sectionREGION_HEAP
- for the heap areaREGION_STACK
- for hart stacks
These aliases must be mapped to a valid MEMORY
region. Usually, REGION_TEXT
and
REGION_RODATA
are mapped to the flash memory, while REGION_DATA
, REGION_BSS
,
REGION_HEAP
, and REGION_STACK
are mapped to the RAM.
§_stext
This symbol provides the loading address of .text
section. This value can be changed
to override the loading address of the firmware (for example, in case of bootloader present).
If omitted this symbol value will default to ORIGIN(REGION_TEXT)
.
§_heap_size
This symbol provides the size of a heap region. The default value is 0. You can set
_heap_size
to a non-zero value if you are planning to use heap allocations.
More information about using the heap can be found in the Using the heap section.
§_max_hart_id
This symbol defines the maximum hart id supported. All harts with id
greater than _max_hart_id
will be redirected to abort()
.
This symbol is supposed to be redefined in platform support crates for multi-core targets.
If omitted this symbol value will default to 0 (single core).
§_hart_stack_size
This symbol defines stack area size for one hart.
If omitted this symbol value will default to 2K.
§_stack_start
This symbol provides the address at which the call stack will be allocated. The call stack grows downwards so this address is usually set to the highest valid RAM address plus one (this is an invalid address but the processor will decrement the stack pointer before using its value as an address).
In case of multiple harts present, this address defines the initial stack pointer for hart 0.
Stack pointer for hart N
is calculated as _stack_start - N * _hart_stack_size
.
If omitted this symbol value will default to ORIGIN(REGION_STACK) + LENGTH(REGION_STACK)
.
§Example of a fully featured memory.x
file
Next, we present a memory.x
file that includes all the symbols
that can be defined in the file. It also allocates the stack on a different RAM region:
/* Fully featured memory.x file */
MEMORY
{
L2_LIM : ORIGIN = 0x08000000, LENGTH = 1M /* different RAM region for stack */
RAM : ORIGIN = 0x80000000, LENGTH = 16K
FLASH : ORIGIN = 0x20000000, LENGTH = 16M
}
REGION_ALIAS("REGION_TEXT", FLASH);
REGION_ALIAS("REGION_RODATA", FLASH);
REGION_ALIAS("REGION_DATA", RAM);
REGION_ALIAS("REGION_BSS", RAM);
REGION_ALIAS("REGION_HEAP", RAM);
REGION_ALIAS("REGION_STACK", L2_LIM);
_stext = ORIGIN(REGION_TEXT) + 0x400000; /* Skip first 4M of text region */
_heap_size = 1K; /* Set heap size to 1KB */
_max_hart_id = 1; /* Two harts present */
_hart_stack_size = 1K; /* Set stack size per hart to 1KB */
_stack_start = ORIGIN(L2_LIM) + LENGTH(L2_LIM);
§Starting a minimal application
This section presents a minimal application built on top of riscv-rt
.
Let’s create a new binary crate:
$ cargo new --bin app && cd $_
Next, we will add a few dependencies to the Cargo.toml
file:
# in Cargo.toml
[dependencies]
riscv-rt = "0.13.0" # <- this crate
panic-halt = "1.0.0" # <- a simple panic handler
Our application would look like this:
// src/main.rs
#![no_main]
#![no_std]
// make sure the panic handler is linked in
extern crate panic_halt;
// Use `main` as the entry point of this application, which may not return.
#[riscv_rt::entry]
fn main() -> ! {
// initialization
loop {
// application logic
}
}
To actually build this program you need to place a memory.x
linker script
somewhere the linker can find it, e.g., in the current directory:
/* memory.x */
MEMORY
{
RAM : ORIGIN = 0x80000000, LENGTH = 16K
FLASH : ORIGIN = 0x20000000, LENGTH = 16M
}
REGION_ALIAS("REGION_TEXT", FLASH);
REGION_ALIAS("REGION_RODATA", FLASH);
REGION_ALIAS("REGION_DATA", RAM);
REGION_ALIAS("REGION_BSS", RAM);
REGION_ALIAS("REGION_HEAP", RAM);
REGION_ALIAS("REGION_STACK", RAM);
Feel free to adjust the memory layout to your needs.
Next, let’s make sure that Cargo uses this linker script by adding a build script:
// build.rs
use std::env;
use std::fs;
use std::path::PathBuf;
fn main() {
let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
// Put the linker script somewhere the linker can find it.
fs::write(out_dir.join("memory.x"), include_bytes!("memory.x")).unwrap();
println!("cargo:rustc-link-search={}", out_dir.display());
println!("cargo:rerun-if-changed=memory.x");
println!("cargo:rerun-if-changed=build.rs");
}
In this way, the memory.x
file will be copied to the build directory so the linker can
find it. Also, we tell Cargo to re-run the build script if the memory.x
file changes.
Finally, we can add a .cargo/config.toml
file to specify the linker script to use, as well
as the target to build for when using cargo build
. In this case, we will build for the
riscv32imac-unknown-none-elf
target:
# .cargo/config.toml
[target.riscv32imac-unknown-none-elf]
rustflags = [
"-C", "link-arg=-Tmemory.x", # memory.x must appear BEFORE link.x
"-C", "link-arg=-Tlink.x",
]
[build]
target = "riscv32imac-unknown-none-elf"
$ cargo build
$ riscv32-unknown-elf-objdump -Cd $(find target -name app) | head
Disassembly of section .text:
20000000 <__stext>:
20000000: 200000b7 lui ra,0x20000
20000004: 00808067 jr 8(ra) # 20000008 <_abs_start>
§Using the heap
To use the heap, you need to define the _heap_size
symbol in the memory.x
file.
For instance, we can define a 1 K heap region like this:
/* memory.x */
/* ... */
_heap_size = 1K;
The heap region will start right after the .bss
and .data
sections.
If you plan to use heap allocations, you must include a heap allocator.
For example, you can use embedded-alloc
.
When initializing the heap, you must provide the start address and the size of the heap.
You can use the heap_start
function to get the start address of the heap.
This symbol is 4 byte aligned so that address will be a multiple of 4.
§Example
extern crate some_allocator; // e.g., embedded_alloc::LlffHeap
extern "C" {
static _heap_size: u8;
}
fn main() {
unsafe {
let heap_bottom = riscv_rt::heap_start() as usize;
let heap_size = &_heap_size as *const u8 as usize;
some_allocator::initialize(heap_bottom, heap_size);
}
}
§Additional weak functions
This crate uses additional functions to control the behavior of the runtime.
These functions are weakly defined in the riscv-rt
crate, but they can be redefined
in the user code. Next, we will describe these symbols and how to redefine them.
§_pre_init_trap
This function is set as a provisional trap handler for the early trap handling. If either an exception or an interrupt occurs during the boot process, this function is triggered. The default implementation of this function is a busy-loop.
§Note
While this function can be redefined, it is not recommended to do so, as it is
intended to be a temporary trap handler to detect bugs in the early boot process.
Recall that this trap is triggered before the .bss
and .data
sections are
initialized, so it is not safe to use any global variables in this function.
§_mp_hook
This function is called from all the harts and must return true only for one hart,
which will perform memory initialization. For other harts it must return false
and implement wake-up in platform-dependent way (e.g., after waiting for a user interrupt).
The parameter hartid
specifies the hartid of the caller.
This function can be redefined in the following way:
#[export_name = "_mp_hook"]
pub extern "Rust" fn mp_hook(hartid: usize) -> bool {
// ...
}
Default implementation of this function wakes hart 0 and busy-loops all the other harts.
§Note
_mp_hook
is only necessary in multi-core targets. If the single-hart
feature is enabled,
_mp_hook
is not included in the binary.
§_setup_interrupts
This function is called right before the main function and is responsible for setting up the interrupt controller.
Default implementation sets the trap vector to _start_trap
in direct mode.
If the v-trap
feature is enabled, the trap vector is set to _vector_table
in vectored mode. Users can override this function by defining their own _setup_interrupts
.
§Attributes
§Core exception handlers
This functions are called when corresponding exception occurs.
You can define an exception handler with the exception
attribute.
The attribute expects the path to the exception source as an argument.
The exception
attribute ensures at compile time that there is a valid
exception source for the given handler.
For example:
use riscv::interrupt::Exception; // or a target-specific exception enum
#[riscv_rt::exception(Exception::MachineEnvCall)]
fn custom_menv_call_handler(trap_frame: &mut riscv_rt::TrapFrame) {
todo!()
}
#[riscv_rt::exception(Exception::LoadFault)]
fn custom_load_fault_handler() -> ! {
loop {}
}
If exception handler is not explicitly defined, ExceptionHandler
is called.
§ExceptionHandler
This function is called when exception without defined exception handler is occured.
The exception reason can be decoded from the
mcause
/scause
register.
This function can be redefined in the following way:
#[export_name = "ExceptionHandler"]
fn custom_exception_handler(trap_frame: &riscv_rt::TrapFrame) -> ! {
// ...
}
or
#[no_mangle]
fn ExceptionHandler(trap_frame: &mut riscv_rt::TrapFrame) {
// ...
}
Default implementation of this function stucks in a busy-loop.
§Core interrupt handlers
This functions are called when corresponding interrupt is occured.
You can define a core interrupt handler with the core_interrupt
attribute.
The attribute expects the path to the interrupt source as an argument.
The core_interrupt
attribute ensures at compile time that there is a valid
core interrupt source for the given handler.
For example:
use riscv::interrupt::Interrupt; // or a target-specific core interrupt enum
#[riscv_rt::core_interrupt(Interrupt::MachineSoft)]
unsafe fn custom_machine_soft_handler() {
todo!()
}
#[riscv_rt::core_interrupt(Interrupt::MachineTimer)]
fn custom_machine_timer_handler() -> ! {
loop {}
}
In vectored mode, this macro will also generate a proper trap handler for the interrupt.
For example, MachineSoft
interrupt will generate a _start_MachineSoft_trap
trap handler.
If interrupt handler is not explicitly defined, DefaultHandler
is called.
§External interrupt handlers
This functions are called when corresponding interrupt is occured.
You can define an external interrupt handler with the external_interrupt
attribute.
The attribute expects the path to the interrupt source as an argument.
The external_interrupt
attribute ensures at compile time that there is a valid
external interrupt source for the given handler.
Note that external interrupts are target-specific and may not be available on all platforms.
If interrupt handler is not explicitly defined, DefaultHandler
is called.
§DefaultHandler
This function is called when interrupt without defined interrupt handler is occured.
The interrupt reason can be decoded from the mcause
/scause
register.
If it is an external interrupt, the interrupt reason can be decoded from a
target-specific peripheral interrupt controller.
This function can be redefined in the following way:
#[export_name = "DefaultHandler"]
unsafe fn custom_interrupt_handler() {
// ...
}
or
#[no_mangle]
fn DefaultHandler() -> ! {
loop {}
}
Default implementation of this function stucks in a busy-loop.
§Cargo Features
§single-hart
The single hart feature (`single-hart) can be activated via Cargo features.
For example:
[dependencies]
riscv-rt = {features=["single-hart"]}
This feature saves a little code size if there is only one hart on the target.
§s-mode
The supervisor mode feature (s-mode
) can be activated via Cargo features.
For example:
[dependencies]
riscv-rt = {features=["s-mode"]}
While most registers/instructions have variants for
both mcause
and scause
, the mhartid
hardware thread register is not available in supervisor
mode. Instead, the hartid is passed as parameter by a bootstrapping firmware (i.e., SBI).
Use case: QEMU supports OpenSBI as default firmware. Using the SBI requires riscv-rt to be run in supervisor mode instead of machine mode.
APP_BINARY=$(find target -name app)
sudo qemu-system-riscv64 -m 2G -nographic -machine virt -kernel $APP_BINARY
It requires the memory layout to be non-overlapping, like
MEMORY
{
RAM : ORIGIN = 0x80200000, LENGTH = 0x8000000
FLASH : ORIGIN = 0x20000000, LENGTH = 16M
}
§v-trap
The vectored trap feature (v-trap
) can be activated via Cargo features.
For example:
[dependencies]
riscv-rt = {features=["v-trap"]}
When the vectored trap feature is enabled, the trap vector is set to _vector_table
in vectored mode.
This table is a list of j _start_INTERRUPT_trap
instructions, where INTERRUPT
is the name of the core interrupt.
§u-boot
The U-boot support feature (u-boot
) can be activated via Cargo features.
For example:
[dependencies]
riscv-rt = { features = ["u-boot"] }
When the u-boot
feature is enabled, acceptable signature for #[entry]
macros is changed. This is required
because when booting from elf, U-boot passes argc
and argv
. This feature also implies single-hart
.
The only way to get boot-hart is through fdt, so other harts initialization is up to you.
Modules§
- exceptions
- Exception handling for targets that comply with the RISC-V exception handling standard.
- interrupts
- Interrupt handling for targets that comply with the RISC-V interrupt handling standard.
- result
Structs§
- Trap
Frame - Registers saved in trap handler
Traits§
- Core
Interrupt Number - Marker trait for enums of target-specific core interrupt numbers.
- Exception
Number - Trait for enums of target-specific exception numbers.
- External
Interrupt Number - Marker trait for enums of target-specific external interrupt numbers.
- Hart
IdNumber - Trait for enums of HART identifiers.
- Interrupt
Number - Trait for enums of target-specific interrupt numbers.
- Priority
Number - Trait for enums of priority levels.
Functions§
- heap_
start - Returns a pointer to the start of the heap
- start_
trap_ ⚠rust - Trap entry point rust (_start_trap_rust)
Attribute Macros§
- core_
interrupt - Attribute to declare a core interrupt handler.
- entry
- Attribute to declare the entry point of the program
- exception
- Attribute to declare an exception handler.
- external_
interrupt - Attribute to declare an external interrupt handler.
- pre_
init - Attribute to mark which function will be called at the beginning of the reset handler.