
Embedded Rust from Scratch
I recently got a small microcontroller, and I thought it would be a good opportunity to learn the fundamentals of ARM-based microcontrollers at a deeper level, and how to write Rust code for them.
以下正文同步自 Hacker News 最新,版权归原站所有,已转换为易读排版。
I recently got a small microcontroller, and I thought it would be a good opportunity to learn the fundamentals of ARM-based microcontrollers at a deeper level, and how to write Rust code for them.
Throughout this post, I will go over how to create a Rust application for a microcontroller without relying on any third-party solutions. I will try not to assume any prior knowledge of microcontrollers or Rust on the reader’s part, so I hope you can follow along even if you are not familiar with them (though the post will not teach you Rust).
All the code in this post can be found in this repository, and many code blocks include a direct link to a specific revision of the corresponding file.
First thing, we need to know what kind of hardware we are targeting. In my case, I have a Microchip PIC32CM PL10 Curiosity Nano Evaluation Kit, which includes the PIC32CM6408PL10048 microcontroller, a “Nano Debugger” USB interface (for powering and accessing the debug and serial ports of the microcontroller), an LED, a button and a capacitive touch button.
The microcontroller is the main point of attention. The first thing we need to know about it is its Instruction Set Architecture (ISA). The ISA defines what instructions the microcontroller CPU is capable of running, and how they are encoded and organized in machine code.
When we compile Rust or C code to binary, it compiles down to a particular ISA. Different CPU implementations may use different micro-architectures, and may even include extra instructions and extensions on top of the baseline ISA, but the same binary will work on them regardless.
Most desktop and server computers today use the x86-64 ISA, or, more specifically, some extension of the baseline. Our microcontroller is ARM based: it includes the CPU core implementation ARM Cortex-M0+, which uses the ARMv6-M instruction set architecture (which is one of the many ISAs defined by ARM).
Besides the ISA, this core implementation also specifies some memory mapped core peripherals (like an interrupt controller, and a timer), and the microcontroller overall specifies many other peripherals (GPIO controllers, more timers, serial interfaces, etc.).
By default, the Rust compiler builds for the same ISA as the platform it is currently running on. To tell the compiler to build for another ISA we need to pass a target tuple (historically called target triples) to it. The target tuple specifies not only the ISA, but the overall platform (which includes calling conventions, the binary interface, system libraries, etc.). For example, Windows and GNU/Linux may run on the same ISA, but they are identified by different target tuples (x86_64-pc-windows-msvc vs x86_64-unknown-linux-gnu).
In the case of ARMv6-M, we will use the target tuple thumbv6m-none-eabi, which targets the ARMv6-M ISA on bare metal, with no specific platform on top. We can use the --target option to tell rustc or cargo the target tuple we want to compile to.
Let’s start by setting up a minimal cargo project:
$ cargo init --bin ./embedded-rust-from-scratch
src/main.rs
#![no_std] #![no_main]
use core::panic::PanicInfo;
#[panic_handler] fn panic_handler(_: &PanicInfo) -> ! { loop {} }
#[unsafe(no_mangle)] fn _start() { loop {} }
By default Rust programs include the Rust standard library (std), which includes abstractions for doing file IO, querying time, spawning processes, etc. The target we are using does not support any of that by itself, so the standard library is not available, and we need to explicitly disable it with the #![no_std] attribute at the top of main.rs. We instead only use the core library. The main function also depends on the standard library, so we also need to disable it with #![no_main].
Instead of main, we declare a function named _start with the unsafe attribute no_mangle, to make the generated binary have a _start symbol which the linker uses as the entry point of the program1.
The linker entry point is only used if the generated binary would be executed by an OS. It is not really necessary in our case, I just include it to avoid a link warning.
Rust also needs a panic_handler, which is called when the panic! macro runs (Rust’s equivalent of a runtime exception).
Then we can compile our Rust program to ARMv6-M. We first need to install the target using rustup and then pass --target to cargo build.
$ rustup target add thumbv6m-none-eabi $ cargo build --target thumbv6m-none-eabi
With this we should have an ELF file in target/thumbv6m-none-eabi/debug/embedded-rust-from-scratch! We can use readelf and objdump to check that the file was correctly generated for our target.
First with readelf, with h for the ELF header, and A for parsing architecture specific sections:
$ readelf -hA target/thumbv6m-none-eabi/debug/embedded-rust-from-scratch ELF Header: Magic: 7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00 Class: ELF32 Data: 2's complement, little endian Version: 1 (current) OS/ABI: UNIX - System V ABI Version: 0 Type: EXEC (Executable file) Machine: ARM Version: 0x1 Entry point address: 0x200e5 Start of program headers: 52 (bytes into file) Start of section headers: 3512 (bytes into file) Flags: 0x5000200, Version5 EABI, soft-float ABI Size of this header: 52 (bytes) Size of program headers: 32 (bytes) Number of program headers: 5 Size of section headers: 40 (bytes) Number of section headers: 15 Section header string table index: 13 Attribute Section: aeabi File Attributes Tag_conformance: "2.09" Tag_CPU_arch: v6S-M Tag_CPU_arch_profile: Microcontroller Tag_ARM_ISA_use: No Tag_THUMB_ISA_use: Thumb-1 Tag_ABI_PCS_R9_use: V6 Tag_ABI_PCS_GOT_use: direct Tag_ABI_PCS_wchar_t: 4 Tag_ABI_FP_denormal: Needed Tag_ABI_FP_exceptions: Needed Tag_ABI_FP_number_model: IEEE 754 Tag_ABI_align_needed: 8-byte Tag_ABI_align_preserved: 8-byte, except leaf SP Tag_ABI_optimization_goals: Prefer Debug Tag_CPU_unaligned_access: None Tag_ABI_FP_16bit_format: IEEE 754
In the ELF header we see Machine: ARM and in the ARM attribute section we see Tag_CPU_arch: v6S-M, which refers to the ARMv6-M ISA.
To use objdump we need a version compiled with support for this architecture. The easiest way of acquiring one is by installing the llvm-tools rustup component (which includes tools with support for all targets Rust supports), and using them through cargo-binutils:
$ rustup component add llvm-tools $ cargo install cargo-binutils
Then we can, for example, check the machine code generated for our _start function:
$ cargo objdump --target thumbv6m-none-eabi -- --disassemble=_start
Finished dev profile [unoptimized + debuginfo] target(s) in 0.01s
embedded-rust-from-scratch: file format elf32-littlearm
Disassembly of section .text:
000200e4 <_start>: 200e4: b580 push {r7, lr} 200e6: af00 add r7, sp, #0x0 200e8: e7ff b 0x200ea <_start+0x6> @ imm = #-0x2 200ea: e7fe b 0x200ea <_start+0x6> @ imm = #-0x4
We can see our function has four 16-bit ARM Thumb instructions. The instructions are saving the frame pointer (r7) and link register (lr) on the stack, updating the frame pointer to the new frame, and then jumping into the loop, which just jumps back to itself indefinitely2.
If we compile with optimizations (cargo build --release --target=...) the two jumps would become one and the frame pointer update should be omitted (although in Rust 1.100, the version used in this post, rustc never omits the frame pointer on Thumb targets).
Okay, we built an ELF file with some code. But that is not enough for flashing it onto our microcontroller, much less running it.
To make it flashable we need to specify where exactly the binary data and runtime data will be mapped in memory, so that after linking, any jumps, loads and similar instructions point to the correct memory addresses, and to indicate to the programming tool where things should be written in the microcontroller flash.
First, let’s configure our cargo project so it builds to our desired target by default, without needing to pass --target every time. We will also use this file to specify additional parameters later.
We add a .cargo/config.toml file, specifying the build.target option:
[build] target = "thumbv6m-none-eabi"
Now, to tell the linker where the code, static data and runtime data should be stored and mapped, we need to create a linker script.
rustc first compiles the code to object files with relocatable code, which means all addresses the instructions refer to are just dummy addresses, and later it invokes a linker program (for this target, it is lld by default) to combine them in a single executable file, where all the code is put in different parts of memory, and all instruction addresses are resolved3.
Actually, on most general purpose operating systems the code is not mapped to specific addresses. Instead, the compiler generates position-independent code, and the linker produces a position-independent executable, which can be loaded at any address. Then the dynamic loader applies relocations each time the program is loaded in memory. The OS also uses it to do address space layout randomization (ASLR), to mitigate certain vulnerability exploits. But none of that applies to the kind of microcontrollers we are targeting here.
Both the intermediate object files and the final executable file organize their content in sections, and the executable also maps those sections to segments. Later the programming tool parses those to figure out where in flash it should write them.
To explore that, let’s first make our Rust program a little more interesting:
#![no_std] #![no_main]
use core::panic::PanicInfo;
#[used] #[unsafe(no_mangle)] static mut ZEROS: [u8; 256] = [0; 256];
#[used] #[unsafe(no_mangle)] static mut STRING_PTR: &str = "This is a string";
#[panic_handler] fn panic_handler(_: &PanicInfo) -> ! { loop {} }
#[unsafe(no_mangle)] fn _start() { loop {} }
Here I just added a mutable static buffer, made entirely out of zeros, and a mutable static string reference, which is a pointer to a read-only string. I marked them with the #[used] attribute so they are not discarded as unused by the compiler and linker.
We can then compile our new executable, and use readelf -Sls (S to show sections, l for program headers/segments and s for symbols) to see how the linker has laid out the sections:
$ readelf -Sls target/thumbv6m-none-eabi/debug/embedded-rust-from-scratch There are 18 section headers, starting at offset 0xea8:
Section Headers: [Nr] Name Type Addr Off Size ES Flg Lk Inf Al [ 0] NULL 00000000 000000 000000 00 0 0 0 [ 1] .ARM.exidx ARM_EXIDX 000100f4 0000f4 000010 00 AL 3 0 4 [ 2] .rodata PROGBITS 00010104 000104 000010 10 AM 0 0 1 [ 3] .text PROGBITS 00020114 000114 000008 00 AX 0 0 2 [ 4] .data PROGBITS 0003011c 00011c 000008 00 WAR 0 0 4 [ 5] .bss NOBITS 00030124 000124 000100 00 WAR 0 0 1 [ 6] .debug_abbrev PROGBITS 00000000 000124 00013f 00 0 0 1 [ 7] .debug_info PROGBITS 00000000 000263 0004a8 00 0 0 1 [ 8] .debug_aranges PROGBITS 00000000 00070b 000038 00 0 0 1 [ 9] .debug_ranges PROGBITS 00000000 000743 000018 00 0 0 1 [10] .debug_str PROGBITS 00000000 00075b 00049e 01 MS 0 0 1 [11] .comment PROGBITS 00000000 000bf9 00008c 01 MS 0 0 1 [12] .ARM.attributes ARM_ATTRIBUTES 00000000 000c85 000034 00 0 0 1 [13] .debug_frame PROGBITS 00000000 000cbc 00004c 00 0 0 4 [14] .debug_line PROGBITS 00000000 000d08 000053 00 0 0 1 [15] .symtab SYMTAB 00000000 000d5c 000060 10 17 3 4 [16] .shstrtab STRTAB 00000000 000dbc 0000b3 00 0 0 1 [17] .strtab STRTAB 00000000 000e6f 000036 00 0 0 1 Key to Flags: W (write), A (alloc), X (execute), M (merge), S (strings), I (info), L (link order), O (extra OS processing required), G (group), T (TLS), C (compressed), x (unknown), o (OS specific), E (exclude), R (retain), D (mbind), y (purecode), p (processor specific)
Elf file type is EXEC (Executable file) Entry point 0x20115 There are 6 program headers, starting at offset 52
Program Headers
正文由 探How 从来源站点 RSS 同步,内容未经改写;遇到排版缺失或需要图片、视频时请以原文为准。
