Chapter 4: Startup and Initialization in Bare-Metal Rust
This chapter introduction previews how Chapter 4 will build on project and build-system foundations to cover bare-metal startup, memory layout, runtime setup, and interrupt handling in no_std Rust.
After this chapter you will be able to
- Bare-metal memory placement. Explain why a bare-metal Cortex-M program must explicitly place its components in memory and how a microcontroller-specific linker script provides that layout.
- Load and execution addresses. Distinguish a section’s Load Memory Address (LMA), where it is stored after loading, from its Virtual Memory Address (VMA), where it resides during execution. Explain that “virtual” does not imply address translation on the microcontrollers discussed here.
- Program section memory placement. Describe where .text, .rodata, .data, and .bss belong and why initialized and zero-initialized static variables need different preparation.
- Pre-main RAM initialization. Explain the two RAM initialization tasks startup code performs before main and when a runtime crate can perform them instead.
- Physical memory region definitions. Describe how a linker script defines FLASH and RAM regions using ORIGIN for each starting address and LENGTH for its available size. Explain why the values must match the microcontroller vendor’s datasheet.
- Load and runtime section placement. Explain how the SECTIONS block places code, read-only data, and writable data across FLASH and RAM, including why .data has different load and runtime locations and .bss has no load image.
- Vector table startup entries. Describe where the vector table is placed and what its first two entries provide at reset; explain how the linker-script block supplies and retains those entries.
- Complete linker script purpose. State that the example linker script defines a viable memory layout for a bare-metal embedded Rust program targeting a Cortex-M microcontroller, specifically one from the STM32 family.
- Built Section Memory Placement. Describe how to verify a built program’s section placement from its headers and memory mapping, and explain what the example shows about FLASH, RAM, and runtime initialization.
- Vector table address mapping. Explain how a Cortex-M core finds the vector table at address 0x00000000 even when the physical Flash containing it starts at a higher address.
- Initialized data and BSS setup. Distinguish the required startup treatment of .data and .bss from the optional copying of code to RAM.
- Reset vector execution handoff. Trace how an Arm Cortex-M processor starts execution after reset: it loads the Main Stack Pointer from the first vector-table entry, then loads the Program Counter from the second to enter the reset handler. Explain that hardware performs these steps before user-defined startup routines run.
- Vector table entry layout. Describe how a manually constructed vector table represents its entries and arranges exception handlers.
- Vector table linker placement. Explain how the Rust attributes and linker script work together to place and link the exception-handler array.
- Special vector table entries. Distinguish the initial main stack pointer and reset handler entries from ordinary handler entries, including the execution mode entered after reset.
- Critical first four entries. State which four vector-table entries are especially critical and explain what can happen if they are defined incorrectly.
- Reset handler startup role. Explain why a bare-metal program needs a reset handler and what it does before handing control to the main Rust application.
- Reset handler entry behavior. Explain that the reset handler runs the program’s first instructions and has a `-> !` return type because it must never return.
- Reset vector placement and naming. Describe how the link-section attribute places `RESET_VECTOR` at the second vector-table entry in FLASH, and how `no_mangle` preserves the symbol name needed by the linker.
- Reset handler memory preparation. Trace how the reset handler copies initialized globals in .data from FLASH to RAM, zeros .bss in RAM, and only then enters main(), which must not return.
- Optional reset handler setup. Explain that .data and .bss initialization are essential, while other reset-handler tasks depend on application needs and microcontroller capabilities. Give examples and say why each might be done.
- Linker symbols for memory initialization. Explain how linker-script symbols identify the .data and .bss boundaries and the FLASH source of initialized data, allowing the reset handler to copy and zero memory.
- Bare-metal runtime requirements. Explain why an application running directly on a microcontroller without an operating system must disable Rust’s standard library and provide the required runtime infrastructure itself.
- Bare-Metal Crate Attributes. Explain why `src/main.rs` begins with `#![no_std]` and `#![no_main]`, and distinguish what each attribute changes.
- Custom entry point selection. Explain how the linker identifies the program’s starting location after the default entry point is disabled, and why this example uses `_start` instead of a `reset()` function.
- Entry function declaration requirements. Describe what `#[unsafe(no_mangle)]`, `extern "C"`, and the `-> !` return type contribute to the custom entry function.
- Minimal no_std panic handling. Explain why a no_std application defines a panic handler, how Rust identifies it, and why a minimal handler can loop forever.
- Reset handler and main roles. Explain why an application may use an explicitly designated reset handler as its entry point, and distinguish its runtime setup from the application logic in main.
- Custom linker script role. Explain that a working no_std application needs a custom linker script to place code and data in memory, and that the build must reference the correct script for the target hardware.
- Minimal no_std application structure. Describe the four parts identified in the example: disabling the standard library, providing a custom entry point, implementing a panic handler, and separating initialization from core application logic.
- Runtime crates and minimal pattern. Explain what runtime crates simplify and why it is still useful to understand the minimal startup pattern.
- Interrupt handling and Rust safety. Explain why exception and interrupt handling matters to embedded firmware and what Rust offers for writing low-level handlers.
- Exception and interrupt origins. Distinguish processor-generated exceptions from interrupts that generally originate in external peripherals, using examples from the section.
- Shared handler routing mechanism. Explain how Cortex-M associates exceptions and interrupts with handlers and what the NVIC manages.
- Handler entry and return. Trace how a higher-priority event preempts running code, transfers control to its handler, and returns to the interrupted code.
- Automatic exception entry sequence. Trace what the Cortex-M processor does when it detects an exception or interrupt, from saving the interrupted application's context to entering the handler.
- Vector table entries and positions. Describe how a basic Cortex-M vector table represents reserved entries and handler pointers, and explain how to locate a peripheral interrupt handler from its IRQ number.
- External interrupt vector positions. Explain that device-specific external interrupts follow the first 16 vector-table entries and that each NVIC IRQ line corresponds to a specific table index, requiring the correct handler address at that position.
- External interrupt linker placement. Describe how a Rust external-interrupt array is assigned to a named linker section and how the linker script uses KEEP() to place it contiguously in flash after the core exceptions.
- NVIC interrupt controls. Describe how the NVIC can control individual interrupts by enabling or disabling them, setting priorities, and clearing pending flags.
- Hard-fault diagnostic evidence. Explain that a hard-fault signals a serious system error and that fault status and address registers, together with stacked context, can help identify its cause. Give the UFSR as an example of a register to inspect for an undefined-instruction fault.
- Runtime handler mapping. Explain how cortex-m-rt replaces manual handler placement: annotate functions with #[exception] or #[interrupt], and the runtime generates the mappings.
- Interrupt-Driven Sharing Risks. Explain how interrupt and exception handlers can preempt the main program, and why access to the same data or peripherals can cause races, corruption, or logic bugs despite Rust’s ownership rules.
- Safety of mutable statics. Explain why `static mut` requires unsafe access and why sharing it between an interrupt handler and main can cause a race. Describe the exclusive-access guarantee needed to use it safely.
- Atomic sharing of simple values. Explain why an atomic counter or flag can be shared between main code and an interrupt handler, using the SysTick increment and main-context load as the example.
- Atomic memory ordering guarantees. Distinguish atomicity from synchronization with other data, and describe the ordering guarantees of Relaxed, Acquire, Release, AcqRel, and SeqCst at the level presented here.
- Purpose of interior mutability. Explain why sharing a buffer, struct, or peripheral may require interior mutability instead of atomics, and what interior mutability permits.
- Cell and RefCell tradeoffs. Distinguish Cell<T> from RefCell<T> by the types they support, how borrowing is checked, and when the section recommends each.
- Concurrency limit of interior mutability. Explain why Cell<T> or RefCell<T> alone cannot make data sharing between main and interrupt contexts safe.
- Critical Section Mutex Protection. Explain how a cortex_m::interrupt::Mutex protects data shared between main and interrupt contexts.
- Protected Data Access Sequence. Trace how code obtains and mutates data inside a mutex-protected RefCell.
- Safe shared peripheral access. Describe how a global Mutex<RefCell<Option<T>>> lets main code and interrupt handlers share a peripheral: main moves it into the initially empty Option inside a critical section, and both contexts later borrow it mutably inside critical sections.
- Critical-section feature configuration. Explain that cortex-m::interrupt::Mutex relies on the critical-section crate for atomic critical sections and that correct behavior on a single-core MCU requires enabling the appropriate feature flag in Cargo.toml.
What it builds on
- Defining memory layout with memory.x (chapter 3) · Defining a memory layout with memory.x introduces the linker configuration used here.
- Minimal runtime setup (step 2 to 4) (chapter 1) · Minimal runtime setup before transfer to user code.
- What does no_std mean in embedded Rust? (chapter 3) · Introduces what no_std means in embedded Rust.
Section by section
Introduction
This chapter introduction previews how Chapter 4 will build on project and build-system foundations to cover bare-metal startup, memory layout, runtime setup, and interrupt handling in no_std Rust.
4.1 Defining the memory layout for your embedded Rust program
This section explains why a bare-metal Cortex-M program needs an explicit memory layout and identifies the linker script as the means of specifying it.
- Bare-metal memory placement: Explain why a bare-metal Cortex-M program must explicitly place its components in memory and how a microcontroller-specific linker script provides that layout.
Why it matters: The memory layout tells the bare-metal program where its components belong when there is no operating system to manage their placement.
Key terms: bare-metal, linker script, interrupt vector table, memory regions
4.1.1 Memory initialization: LMA, VMA, and data movement
This section explains where program sections are stored and used, and why startup code must initialize RAM before main runs.
- Load and execution addresses: Distinguish a section’s Load Memory Address (LMA), where it is stored after loading, from its Virtual Memory Address (VMA), where it resides during execution. Explain that “virtual” does not imply address translation on the microcontrollers discussed here.
Why it matters: The distinction explains why some program data must move before it can be used. - Program section memory placement: Describe where .text, .rodata, .data, and .bss belong and why initialized and zero-initialized static variables need different preparation.
Why it matters: Section placement determines which contents can remain in FLASH and which must be prepared in RAM. - Pre-main RAM initialization: Explain the two RAM initialization tasks startup code performs before main and when a runtime crate can perform them instead.
Why it matters: RAM must contain the expected initial values before application code uses its static variables.
Key terms: Load Memory Address (LMA), Virtual Memory Address (VMA), FLASH, RAM, .text, .rodata, .data, .bss, startup code, LMA
4.1.2 Defining physical memory regions
This section explains how to define a device’s physical FLASH and RAM regions in a linker script using hardware-correct addresses and sizes.
- Physical memory region definitions: Describe how a linker script defines FLASH and RAM regions using ORIGIN for each starting address and LENGTH for its available size. Explain why the values must match the microcontroller vendor’s datasheet.
Why it matters: The linker needs an accurate description of the device’s memory to avoid placing program or data at incorrect locations.
Key terms: linker script, FLASH, RAM, ORIGIN, LENGTH
4.1.3 Mapping output sections
Explains how a linker script maps program sections to FLASH and RAM, sets up the vector table and stack pointer, and preserves required alignment.
- Load and runtime section placement: Explain how the SECTIONS block places code, read-only data, and writable data across FLASH and RAM, including why .data has different load and runtime locations and .bss has no load image.
Why it matters: This layout explains what initialization must do before writable variables can be used. - Vector table startup entries: Describe where the vector table is placed and what its first two entries provide at reset; explain how the linker-script block supplies and retains those entries.
Why it matters: These entries give the processor a stack and a place to begin executing after reset. - Downward-growing stack space: Explain what the linker script establishes for the stack and why RAM usage must leave room for it.
Why it matters: An initial stack address alone does not guarantee enough space for the program’s stack use. - Eight-byte section and stack alignment: Justify eight-byte alignment for the stack pointer and RAM data sections, and describe the role of ALIGN(8).
Why it matters: Correct alignment helps prevent faulty accesses to 64-bit values.
Key terms: SECTIONS, LMA, VMA, .text, .rodata, .data, vector table, initial stack pointer, reset handler, LONG(ORIGIN(RAM) + LENGTH(RAM))
4.1.4 A Complete minimal linker script example
This subsection presents a complete linker script as a viable memory layout for a bare-metal Rust program on an STM32 Cortex-M microcontroller.
- Complete linker script purpose: State that the example linker script defines a viable memory layout for a bare-metal embedded Rust program targeting a Cortex-M microcontroller, specifically one from the STM32 family.
Why it matters: It identifies what the complete linker script is meant to provide and the target for which it is presented.
Key terms: linker script, memory layout, bare-metal, Cortex-M, STM32
4.1.5 Inspecting the memory layout
This section shows how to inspect a built program’s section mapping and recognize whether its FLASH and RAM placement supports initialization.
- Built Section Memory Placement: Describe how to verify a built program’s section placement from its headers and memory mapping, and explain what the example shows about FLASH, RAM, and runtime initialization.
Why it matters: Checking the built layout helps catch misplaced sections before relying on startup initialization.
Key terms: headers, memory mapping, FLASH, RAM, .data, .bss
4.2 Understanding the reset sequence & processor initialization
Introduces the upcoming explanation of Cortex-M reset and processor initialization, from power-on to the start of Rust code.
4.2.1 Overview of the MCU boot sequence
This section traces the Cortex-M boot sequence from locating the vector table through reset-handler initialization, data setup, and stack setup.
- Vector table address mapping: Explain how a Cortex-M core finds the vector table at address 0x00000000 even when the physical Flash containing it starts at a higher address.
Why it matters: It explains why the core can boot from Flash that is not physically located at address zero. - Early processor configuration: Describe the low-level initialization that follows the initial MSP load and jump to the reset handler, and why it precedes most application code.
Why it matters: Application code cannot assume essential hardware is ready immediately after reset. - Initialized data and BSS setup: Distinguish the required startup treatment of .data and .bss from the optional copying of code to RAM.
Why it matters: Without this setup, RAM would not contain the initial values the program expects. - Main and process stack setup: Explain where the main stack's starting value comes from on a cold reset and when further stack-pointer setup may be needed.
Why it matters: It separates the stack setup supplied by a cold reset from additional setup some applications require.
Key terms: vector table, memory remapping, aliasing, BOOT0, low-level processor initialization, core clock sources, bridges, device registers, .data, .bss
4.2.2 A detailed look at reset vector fetching and execution
This section explains how Cortex-M hardware uses the first two vector-table entries to establish execution state and enter the reset handler.
- Reset vector execution handoff: Trace how an Arm Cortex-M processor starts execution after reset: it loads the Main Stack Pointer from the first vector-table entry, then loads the Program Counter from the second to enter the reset handler. Explain that hardware performs these steps before user-defined startup routines run.
Why it matters: It identifies what hardware establishes automatically before your startup code begins.
Key terms: vector table, Main Stack Pointer (MSP), Program Counter (PC), reset handler, micro-coded logic
4.2.3 Manually creating a vector table in Rust
This section explains how to construct the exception-handler portion of a Cortex-M vector table in Rust and place it for correct linkage.
- Vector table entry layout: Describe how a manually constructed vector table represents its entries and arranges exception handlers.
Why it matters: The table must represent different entry kinds while keeping handlers in the positions expected by the processor. - Vector table linker placement: Explain how the Rust attributes and linker script work together to place and link the exception-handler array.
Why it matters: Defining the array in Rust is not enough; its section and symbol must also link into the intended location.
Key terms: vector table, union, exception handler, reserved, #[unsafe(link_section = ".vector_table.exceptions")], #[unsafe(no_mangle)], KEEP(*(.vector_table.exceptions)), FLASH
4.2.4 A side note on the vector table’s configuration
This section explains the special roles of the stack-pointer and reset entries in a Cortex-M vector table and why its first four entries must be correct.
- Special vector table entries: Distinguish the initial main stack pointer and reset handler entries from ordinary handler entries, including the execution mode entered after reset.
Why it matters: These differences explain why the first vector-table entries need particular care. - Critical first four entries: State which four vector-table entries are especially critical and explain what can happen if they are defined incorrectly.
Why it matters: Checking these entries can prevent a device from failing to boot or locking up.
Key terms: vector table, main stack pointer, MSP, reset handler, privileged, thread-mode, handler mode, initial MSP value, NMI, hard fault handler
4.3 Initializing Rust’s runtime in a bare-metal environment
This section explains why bare-metal Rust needs a reset handler to prepare memory before the application runs.
- Reset handler startup role: Explain why a bare-metal program needs a reset handler and what it does before handing control to the main Rust application.
Why it matters: The application cannot rely on someone else to prepare its memory before it runs. - Nonreturning reset handler convention: State how the reset handler conventionally ends after startup.
Why it matters: This clarifies what happens to control flow after startup.
Key terms: reset handler, runtime environment, main Rust application, never-returning main routine, infinite loop
4.3.1 Defining the reset handler
This section defines the reset handler and explains how its address is placed in the vector table so the processor starts executing it after reset.
- Reset handler entry behavior: Explain that the reset handler runs the program’s first instructions and has a `-> !` return type because it must never return.
Why it matters: This explains why startup code cannot treat the reset handler like an ordinary returning function. - Reset vector placement and naming: Describe how the link-section attribute places `RESET_VECTOR` at the second vector-table entry in FLASH, and how `no_mangle` preserves the symbol name needed by the linker.
Why it matters: Correct vector placement lets the processor find and execute the reset handler after reset.
Key terms: reset handler, → !, undefined behavior, RESET_VECTOR, #[unsafe(link_section = ".vector_table.reset_vector")], #[unsafe(no_mangle)], vector table, FLASH
4.3.2 Writing a minimal startup routine in Rust
This section explains how a Rust reset handler prepares global-variable memory before entering an application that never returns.
- Reset handler memory preparation: Trace how the reset handler copies initialized globals in .data from FLASH to RAM, zeros .bss in RAM, and only then enters main(), which must not return.
Why it matters: This sequence ensures global variables are in their expected state before application code uses them. - Linker-defined section boundaries: Explain where the reset handler gets the boundaries needed to initialize .data and .bss, and how those boundaries are made available in Rust.
Why it matters: The handler needs those boundaries to identify the memory regions it prepares.
Key terms: reset handler, .data, .bss, FLASH, RAM, main(), linker script, linker, symbols, extern declarations
4.3.3 Optional additional initialization steps
This subsection describes optional reset-handler setup tasks chosen according to the application and microcontroller.
- Optional reset handler setup: Explain that .data and .bss initialization are essential, while other reset-handler tasks depend on application needs and microcontroller capabilities. Give examples and say why each might be done.
Why it matters: It helps you distinguish required startup work from setup that serves a particular system’s needs.
Key terms: reset handler, .data, .bss, stack, VTOR, FPU
4.3.4 Linker script reference for initialization symbols
This subsection explains how linker-script symbols give the reset handler the addresses it needs to initialize memory.
- Linker symbols for memory initialization: Explain how linker-script symbols identify the .data and .bss boundaries and the FLASH source of initialized data, allowing the reset handler to copy and zero memory.
Why it matters: The reset handler needs these linker-provided addresses to initialize memory correctly.
Key terms: linker script, reset handler, _glob_RW, _eglob_RW, _glob_ZI, _eglob_ZI
4.4 Writing a minimal no_std Rust application
Explains why a bare-metal microcontroller application needs no_std and its own runtime infrastructure.
- Bare-metal runtime requirements: Explain why an application running directly on a microcontroller without an operating system must disable Rust’s standard library and provide the required runtime infrastructure itself.
Why it matters: This explains why a microcontroller application cannot simply use the usual desktop Rust setup.
Key terms: freestanding, bare-metal, std, no_std, runtime infrastructure
4.4.1 Disabling the standard library and the default entry point
This subsection shows how two crate attributes remove the standard-library and default-entry-point assumptions from a bare-metal Rust program.
- Bare-Metal Crate Attributes: Explain why `src/main.rs` begins with `#![no_std]` and `#![no_main]`, and distinguish what each attribute changes.
Why it matters: These attributes let a bare-metal program avoid assuming an operating system or its usual startup path.
Key terms: #![no_std], #![no_main], core library, default entry point
4.4.2 Defining a custom entry point function
Explains how to provide a linker-recognized entry point for a bare-metal Rust program and why its declaration has particular attributes and types.
- Custom entry point selection: Explain how the linker identifies the program’s starting location after the default entry point is disabled, and why this example uses `_start` instead of a `reset()` function.
Why it matters: The linker needs an identifiable place for the program to begin. - Entry function declaration requirements: Describe what `#[unsafe(no_mangle)]`, `extern "C"`, and the `-> !` return type contribute to the custom entry function.
Why it matters: These declaration choices make the function findable and express how it is entered and whether it returns.
Key terms: entry point, linker, ENTRY(), _start, #[unsafe(no_mangle)], extern "C", C calling convention, -> !, divergent
4.4.3 Implementing the panic handler
Explains why a bare-metal no_std application needs its own panic handler and what a minimal handler does.
- Minimal no_std panic handling: Explain why a no_std application defines a panic handler, how Rust identifies it, and why a minimal handler can loop forever.
Why it matters: A bare-metal application must specify what happens if it panics.
Key terms: no_std, panic handler, #[panic_handler], run-time panic
4.4.4 Structuring the application’s main function
This section separates startup work from application logic in a bare-metal program and explains why main must not return.
- Reset handler and main roles: Explain why an application may use an explicitly designated reset handler as its entry point, and distinguish its runtime setup from the application logic in main.
Why it matters: This separation makes it clear which code prepares the program to run and which code runs the application. - Nonreturning bare-metal main: Explain why main in this bare-metal application should be a divergent function.
Why it matters: It explains why the application’s main function is structured to keep running rather than finish normally.
Key terms: reset_handler, reset, entry point, main, run-time, divergent function, bare-metal
4.4.5 Providing a custom linker script
This subsection explains why a bare-metal no_std application needs a target-appropriate linker script and what to check in the build process.
- Custom linker script role: Explain that a working no_std application needs a custom linker script to place code and data in memory, and that the build must reference the correct script for the target hardware.
Why it matters: Even correct Rust code needs a memory layout suited to the device to start and access its data.
Key terms: no_std, custom linker script, linker.ld, linker.x
4.4.6 A complete minimal example
This subsection brings together the basic parts of a minimal bare-metal Rust application.
- Minimal no_std application structure: Describe the four parts identified in the example: disabling the standard library, providing a custom entry point, implementing a panic handler, and separating initialization from core application logic.
Why it matters: These parts give you a checklist for recognizing the structure of a minimal bare-metal application.
Key terms: no_std, custom entry point, panic handler, initialization, core application logic
4.4.7 Optional simplifications and use of crates
Established runtime crates can simplify bare-metal startup, but understanding the minimal pattern remains useful.
- Runtime crates and minimal pattern: Explain what runtime crates simplify and why it is still useful to understand the minimal startup pattern.
Why it matters: You can use a runtime crate for convenience without losing the ability to reason about startup when something goes wrong.
Key terms: run-time crates, cortex-m-rt, riscv-rt, minimal pattern, boilerplate code
4.5 Handling exceptions & interrupts in embedded Rust
Introduces why exception and interrupt handling matters in embedded firmware and the balance Rust offers between low-level control and safety.
- Interrupt handling and Rust safety: Explain why exception and interrupt handling matters to embedded firmware and what Rust offers for writing low-level handlers.
Why it matters: This gives a reason to study interrupt handling without assuming the details of later sections.
Key terms: exceptions, interrupts, interrupt handlers, safety model
4.5.1 Exceptions and interrupts: Concepts and distinctions
This section distinguishes Cortex-M exceptions from interrupts and explains how the processor enters a handler and resumes interrupted code.
- Exception and interrupt origins: Distinguish processor-generated exceptions from interrupts that generally originate in external peripherals, using examples from the section.
Why it matters: The event’s origin helps explain why the processor needs a handler. - Shared handler routing mechanism: Explain how Cortex-M associates exceptions and interrupts with handlers and what the NVIC manages.
Why it matters: Both kinds of event enter the same basic handler machinery. - Handler entry and return: Trace how a higher-priority event preempts running code, transfers control to its handler, and returns to the interrupted code.
Why it matters: Automatic context saving and restoration explain how a handler can interrupt code without making it restart.
Key terms: exceptions, interrupts, SysTick, HardFault, vector table, handler, Nested Vectored Interrupt Controller, NVIC, preemption, Program Counter
4.5.2 The Cortex-M exception handling model
Explains how Cortex-M hardware saves processor context on an exception or interrupt before transferring execution to a handler.
- Automatic exception entry sequence: Trace what the Cortex-M processor does when it detects an exception or interrupt, from saving the interrupted application's context to entering the handler.
Why it matters: This explains why a handler can focus on its control logic rather than the processor's initial context-saving work. - Exception stack frame contents: Describe the registers saved for a processor without an FPU and what is additionally stacked when an enabled floating-point co-processor is active at exception time.
Why it matters: The saved registers show what the processor preserves for the interrupted application and when the stack frame grows.
Key terms: exception, interrupt, context, stack, Stack Pointer, vector table, exception stack frame, FPU, R0–R3, R12
4.5.3 Revisiting the vector table structure
Explains how a Cortex-M vector table represents handlers and where peripheral interrupt entries belong.
- Vector table entries and positions: Describe how a basic Cortex-M vector table represents reserved entries and handler pointers, and explain how to locate a peripheral interrupt handler from its IRQ number.
Why it matters: The vector table must put each handler in the position corresponding to its exception or interrupt.
Key terms: vector table, union values, reserved entry, system exceptions, external interrupts, IRQ
4.5.4 Taking external interrupts in consideration
This section explains where device-specific external interrupts belong in the Cortex-M vector table and how linker placement puts their handler addresses there.
- External interrupt vector positions: Explain that device-specific external interrupts follow the first 16 vector-table entries and that each NVIC IRQ line corresponds to a specific table index, requiring the correct handler address at that position.
Why it matters: A handler in the wrong vector-table slot will not serve its intended IRQ. - External interrupt linker placement: Describe how a Rust external-interrupt array is assigned to a named linker section and how the linker script uses KEEP() to place it contiguously in flash after the core exceptions.
Why it matters: Defining the array in Rust alone does not ensure its entries land where the processor expects them.
Key terms: vector table, external interrupts, NVIC IRQ line, __INTERRUPTS, #[unsafe(link_section = ".vector_table.interrupts")], KEEP(), linker script
4.5.5 Configuring and controlling interrupts with the Nested Vectored Interrupt Controller
This section introduces selective interrupt control through the NVIC and global masking of maskable interrupts through PRIMASK.
- NVIC interrupt controls: Describe how the NVIC can control individual interrupts by enabling or disabling them, setting priorities, and clearing pending flags.
Why it matters: These are the basic controls available when configuring interrupt behavior. - PRIMASK global interrupt masking: Explain that setting PRIMASK disables all maskable interrupts for certain critical sections, while noting that the section does not favor this as the way to create critical sections.
Why it matters: Global masking is different from configuring one interrupt, and the section cautions against treating it as the preferred critical-section method.
Key terms: NVIC, priorities, pending interrupt flags, PRIMASK, maskable interrupts, critical sections
4.5.6 Advanced fault handling: The hard-fault example
This subsection explains how fault registers and stacked context can help diagnose a hard-fault, and notes why the example uses unsafe Rust rather than a PAC.
- Hard-fault diagnostic evidence: Explain that a hard-fault signals a serious system error and that fault status and address registers, together with stacked context, can help identify its cause. Give the UFSR as an example of a register to inspect for an undefined-instruction fault.
Why it matters: These clues can turn a system crash into a diagnosable fault. - Unsafe access and PACs: Distinguish the example’s deliberate use of unsafe Rust without a PAC from the more idiomatic use of a PAC in normal circumstances.
Why it matters: It keeps the example’s unsafe approach from being mistaken for the usual recommended style.
Key terms: hard-fault, fault status and address registers, stacked context, Usage-Fault Status Register (UFSR), Configurable Fault Status Register (CFSR), unsafe Rust code, Peripheral Access Crate (PAC)
4.5.7 Simplifying exception and interrupt handling with a run-time crate
This section shows how cortex-m-rt simplifies handler setup and explains how to identify exception and target-specific interrupt handler names.
- Runtime handler mapping: Explain how cortex-m-rt replaces manual handler placement: annotate functions with #[exception] or #[interrupt], and the runtime generates the mappings.
Why it matters: You can focus on what a handler does rather than placing it manually. - Common exception handler roles: Describe the roles of representative named exception handlers, such as DefaultHandler, HardFault, and SysTick.
Why it matters: The handler name tells you which kind of exception your function handles. - Target-specific interrupt names: Explain where an external interrupt handler name such as TIM2 comes from and where to check its valid name and signature.
Why it matters: Checking the target’s PAC prevents you from guessing an interrupt handler name or signature.
Key terms: cortex-m-rt, #[exception], #[interrupt], vector table, DefaultHandler, HardFault, SysTick, Peripheral Access Crate (PAC), TIM2, external interrupt handler
4.6 Sharing data and peripherals between handlers and the application
This section explains why sharing data or peripherals between the main program and interrupt handlers needs special care.
- Interrupt-Driven Sharing Risks: Explain how interrupt and exception handlers can preempt the main program, and why access to the same data or peripherals can cause races, corruption, or logic bugs despite Rust’s ownership rules.
Why it matters: Recognizing the risk explains why shared access needs more than ordinary ownership and borrowing.
Key terms: interrupt and exception handlers, preempt, race conditions, ownership and borrowing, shared access
4.6.1 Sharing data unsafely with static mut
This section explains why sharing data with `static mut` is unsafe and when its use can be justified.
- Safety of mutable statics: Explain why `static mut` requires unsafe access and why sharing it between an interrupt handler and main can cause a race. Describe the exclusive-access guarantee needed to use it safely.
Why it matters: Marking an access `unsafe` does not prevent an interrupt from racing with it.
Key terms: static mut, unsafe block, race condition, exclusive access
4.6.2 Atomics for simple, lock-free data sharing
This section explains how atomics safely share simple values between main code and interrupt handlers, what memory orderings guarantee, and where atomics are insufficient.
- Atomic sharing of simple values: Explain why an atomic counter or flag can be shared between main code and an interrupt handler, using the SysTick increment and main-context load as the example.
Why it matters: Atomics provide a safer way to share a counter or flag across an interrupt boundary. - Atomic memory ordering guarantees: Distinguish atomicity from synchronization with other data, and describe the ordering guarantees of Relaxed, Acquire, Release, AcqRel, and SeqCst at the level presented here.
Why it matters: A race-free flag or counter does not, by itself, order accesses to other data. - Limits of atomic values: State which kinds of shared values atomics suit here and which kinds cannot be shared directly using these atomic types.
Why it matters: Recognizing this boundary helps you avoid treating atomics as a solution for every shared resource.
Key terms: core::sync::atomic, atomic, SysTick, Ordering::Relaxed, Acquire, Release, AcqRel, SeqCst, read-modify-write, atomic types
4.6.3 Interior mutability: Cell, RefCell, and safe synchronization
This section explains how interior mutability supports shared access to complex data, how Cell and RefCell differ, and why interrupt-safe sharing still requires synchronization.
- Purpose of interior mutability: Explain why sharing a buffer, struct, or peripheral may require interior mutability instead of atomics, and what interior mutability permits.
Why it matters: It explains why shared complex data needs a different approach from simple atomics. - Cell and RefCell tradeoffs: Distinguish Cell<T> from RefCell<T> by the types they support, how borrowing is checked, and when the section recommends each.
Why it matters: The choice affects both what data you can share and whether borrowing errors can occur at runtime. - Concurrency limit of interior mutability: Explain why Cell<T> or RefCell<T> alone cannot make data sharing between main and interrupt contexts safe.
Why it matters: Being able to mutate through a shared reference is not the same as preventing conflicting concurrent access.
Key terms: interior mutability, shared reference, atomics, Cell<T>, RefCell<T>, Copy types, borrowing rules, main and interrupt contexts, exclusive access, critical sections
4.6.4 Safe shared access using cortex_m::interrupt::Mutex
This subsection shows how a Cortex-M mutex and critical section let main code and interrupt handlers share mutable data safely.
- Critical Section Mutex Protection: Explain how a cortex_m::interrupt::Mutex protects data shared between main and interrupt contexts.
Why it matters: It explains why main code and an interrupt handler can access the same data without racing. - Protected Data Access Sequence: Trace how code obtains and mutates data inside a mutex-protected RefCell.
Why it matters: The token makes access to the shared value depend on being inside the critical section. - Cell Versus RefCell Choice: Distinguish why Cell<u32> would suffice in the example but RefCell is needed for the stated non-Copy case.
Why it matters: It helps you choose an appropriate interior-mutability wrapper for the value being shared.
Key terms: cortex_m::interrupt::Mutex, critical section, PRIMASK, FAULTMASK, free(), CriticalSection, .borrow(cs), .borrow_mut(), RefCell, Cell<u32>
4.6.5 Sharing peripherals with mutex and interior mutability
This section explains how to share a peripheral safely between main code and interrupt handlers using a mutex, interior mutability, and one-time ownership transfer.
- Safe shared peripheral access: Describe how a global Mutex<RefCell<Option<T>>> lets main code and interrupt handlers share a peripheral: main moves it into the initially empty Option inside a critical section, and both contexts later borrow it mutably inside critical sections.
Why it matters: It provides a way for main code and interrupt handlers to use the same peripheral without competing for mutable access.
Key terms: Mutex<RefCell<Option<T>>>, global static, critical section, .replace(), peripheral
4.6.6 Feature flags and the role of the critical-section crate
Explains why a Cortex-M mutex needs a hardware-appropriate critical-section feature enabled.
- Critical-section feature configuration: Explain that cortex-m::interrupt::Mutex relies on the critical-section crate for atomic critical sections and that correct behavior on a single-core MCU requires enabling the appropriate feature flag in Cargo.toml.
Why it matters: The mutex needs an appropriate critical-section implementation to behave correctly on the target MCU.
Key terms: cortex-m::interrupt::Mutex, critical-section crate, feature flag, Cargo.toml
4.7 Summary
Where this is used later
- (chapter intro) (chapter 7) · Establishes where firmware memory lives.
- Section placement with #[unsafe(link_section)] (chapter 5) · Assumes physical memory regions are defined for the target device.
- What is memory-mapped? (chapter 5) · Firmware sections are placed within a defined memory layout.
- How stack overflows happen (chapter 7) · Stack overflow risks build on the possibility of exhausting available stack space.
- Understanding data alignment and layout (chapter 5) · Later discussion of data alignment builds on why placement boundaries matter.
- Revisiting Vector Table Placement (chapter 5) · reset vector fetching and execution
- Consuming the library from C (chapter 8) · the bare-metal reset handler and startup initialization
- Minimal handler implementation (chapter 6) · Builds on the minimal handler when discussing panic-handler implementations.
Concepts explained in this chapter
- reset handlerA reset handler is the startup routine executed after a processor reset to initialize execution and transfer control to application code.
- interrupt vector tableA table of memory addresses that supplies the initial stack pointer and exception or interrupt handler addresses used by a processor.
- bss sectionThe .bss section represents zero-initialized or uninitialized static storage that is cleared during startup.
- data sectionThe .data section contains initialized writable data whose initial values are copied to writable memory during startup.
- flash memoryFlash memory is nonvolatile semiconductor memory that retains data without power and can be electrically erased and rewritten.
- initial stack pointerThe initial stack pointer is the stack address loaded by a processor when it begins executing an image.
- load memory addressA load memory address (LMA) is the address where a program section's contents are stored in the loadable image.
- virtual addressA virtual address is the runtime address at which a program section or object is located and accessed.
- HardFaultHardFault is a Cortex-M processor exception raised when a fault cannot be handled by a more specific enabled fault handler or escalates to HardFault.
- alignmentMemory alignment is the placement of data or code at addresses satisfying the alignment requirements of the target architecture.
- read-only data sectionThe .rodata section contains read-only static data in a program image.
- text sectionThe .text section is an executable program section containing machine code.
- linker scriptA linker script is a script that directs a linker when arranging input sections and assigning addresses in an output image.
- NOLOADNOLOAD is a linker-script directive that reserves runtime memory for a section without storing its contents in the loadable image.
- application binary interfaceAn application binary interface specifies binary-level conventions for calling functions, representing data, and interoperating between compiled software components.
- output sectionAn output section is a linker-generated memory-image section formed by collecting selected input sections and assigning them an address and region.
- sections blockA SECTIONS block is a linker-script construct that maps output sections to declared memory regions and controls their placement.
- stackA stack is a last-in, first-out memory structure used for nested execution state and temporary data.
- vector table sectionA linker output section containing the processor’s vector table.
- main stack pointerMSP is the Cortex-M Main Stack Pointer system register holding the active main-stack address.
- Arm Cortex-MArm Cortex-M is a family of energy-efficient processor cores designed primarily for microcontrollers and embedded systems.
- memory layoutA memory layout specifies the placement of a program's code, data, stack, and other regions in memory.
- process stack pointerThe process stack pointer is a processor register that identifies the stack used by process or unprivileged execution contexts.
- memory locationA memory region is a contiguous address range with a defined role or access behavior in a processor's address space.
- peripheral access crateA peripheral access crate is a typically auto-generated Rust library that exposes fine-grained access to the registers and bit fields of a specific microcontroller family.
- no_mangleThe Rust no_mangle attribute preserves an item's externally visible symbol name instead of applying name mangling.
- interruptAn interrupt is a hardware or software event that requests processor attention and can trigger execution of an associated handler.
- cortex-m-rtcortex-m-rt is a Rust runtime crate that provides startup and exception-handling support for Cortex-M microcontrollers.
- embedded RustEmbedded Rust is the practice of developing firmware for embedded or bare-metal targets using Rust.
- linker sectionA linker section is a named region of an object or executable image containing input or output data such as code, initialized data, or uninitialized data.
- no_std programno_std is a Rust crate configuration that excludes the standard library.
- critical-sectionA Rust crate that provides a portable abstraction for entering and executing code within critical sections.
- link_section attributeThe Rust link_section attribute places an item in a named object-file section.
- entry pointThe function or location at which execution begins for a program or runtime path.
- memory placementMemory-region placement is the assignment of an object or section to a specific address range in a program's memory layout.
- runtime crateA runtime crate supplies target-specific startup and exception-handling support for an embedded application.
- interrupt handlerAn interrupt handler is a routine invoked asynchronously in response to a hardware or software interrupt.
- execution environmentA runtime environment is the collection of execution support, hardware state, and software facilities available to a running program.
- stack overflowStack overflow is the exhaustion of a thread's stack space by nested calls, local data, or other stack allocation.
- panic handlerA panic handler is the Rust-defined function that determines how a panic is handled in a target without the hosted panic runtime.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.
