Chapter 7: Managing stack and heap in resource-constrained systems
The chapter introduction explains why embedded Rust programmers must make deliberate memory-placement choices despite Rust’s ownership guarantees.
After this chapter you will be able to
- Programmer responsibility for memory placement. Explain that Rust’s ownership model prevents many memory bugs but does not choose whether data lives on the stack, in static storage, or on a heap.
- Resource constrained memory failures. Describe why memory mistakes can be consequential on a microcontroller, using the introduction’s examples of heap fragmentation and stack growth.
- Stack frames and fixed capacity. Explain what the stack holds, how its use changes during calls and returns, and why its fixed capacity matters.
- Optional heap and allocation costs. Explain when heap storage is useful, why it is absent by default in a no_std build, and what costs it introduces.
- Memory region design trade-offs. Justify a choice among static memory, the stack, and the heap using the sizing, cleanup, and predictability trade-offs described here.
- Core and alloc boundaries. Distinguish the facilities available through core from heap-dependent types supplied by alloc in a no_std build.
- Alloc setup requirements. Describe the two steps needed to use alloc in a no_std build and why declaring the crate alone is insufficient.
- Default memory choice. Justify using core with stack or static storage by default and reserving alloc for a concrete need.
- Manual allocation obligations. Describe how Rust permits a C-like allocate, use, and free pattern, and identify the checks and layout requirements the programmer must handle.
- Meaning of unsafe blocks. Explain what an unsafe block permits and what safety checks remain in effect.
- Heap allocation prerequisites. Explain what must be supplied before a no_std program can use alloc’s growable collections: a global allocator and a region of RAM for it to manage.
- Explicit microcontroller heap setup. Explain why heap allocation is an explicit choice on a microcontroller and describe the three decisions needed to make it available: allocator implementation, RAM location, and heap size.
- Global allocator installation steps. Describe the four pieces used to set up LlffHeap as the global allocator and when its backing RAM is handed to it.
- Critical section implementation requirement. Explain why embedded-alloc needs a critical-section implementation and identify the Cortex-M feature named to provide one.
- Buddy block splitting and merging. Trace how a buddy allocator splits a heap block to satisfy a request and merges freed buddies back into a larger block.
- Fragmentation and allocator trade-offs. Distinguish the buddy system’s bounded fragmentation from its internal waste, and explain the section’s practical rule for choosing it over first-fit.
- Dynamic message log growth. Trace how the worked example uses a global allocator to grow a Vec<String> as events are recorded and later read for diagnostics.
- Allocation failure behavior. Distinguish the default response to an unsatisfied allocation request from using the fallible reserve methods named in the section.
- Practical allocator choice criteria. Justify starting a new project with embedded-alloc’s llff feature, and explain when profiling would warrant switching to tlsf or buddy_system_allocator. Describe the allocation patterns that make fragmentation a concern.
- Observed peak heap usage. Describe how to measure heap demand by polling allocator usage while exercising representative code paths, then use the observed peak to guide heap sizing.
- Vec capacity and reallocations. Explain how choosing Vec::with_capacity instead of growing a Vec from empty can reduce reallocations, fragmentation, and worst-case push time.
- Fixed-capacity container tradeoff. Explain when an inline-array, fixed-capacity container is useful in embedded Rust and what it offers compared with a heap-allocated container.
- Fixed Capacity Inline Storage. Explain that heapless containers store their backing data inline, with capacity specified in the type, rather than allocating it dynamically.
- Explicit Capacity Overflow Handling. Describe why operations that might exceed a heapless container’s capacity return a Result, including what happens to a value rejected by Vec::push.
- Overflow behavior in arrayvec. Distinguish arrayvec’s panicking push operations from its fallible counterparts, and explain when each suits a code path.
- Choosing arrayvec or heapless. Explain why a project might choose arrayvec for only a fixed-capacity vector or string, but retain heapless when it already uses its other collections.
- Inline storage and heap spill. Explain that tinyvec and smallvec begin with inline array storage and allocate on the heap when that capacity is exceeded, avoiding allocation while the collection remains small.
- Allocator requirement in no_std. State that TinyVec and SmallVec still need extern crate alloc and an installed global allocator in a no_std crate; they eliminate common-case allocation, not the need for a heap.
- Tinyvec and smallvec tradeoff. Distinguish tinyvec's safe-Rust implementation and Default requirement from smallvec's use of internal unsafe to support any element type, and explain the section's preference between them.
- Hybrid versus fixed capacity. Justify using a hybrid container when typical collections are small but rare, much larger cases must be retained; describe when a fixed-capacity container is simpler.
- Allocator-free container choice. Explain why heapless is the default for most embedded programs and when arrayvec is the smaller alternative.
- Hybrid container suitability. Describe the conditions under which tinyvec or smallvec is worth considering instead of an allocator-free container.
- Stack contents and overflow risk. Describe what the stack holds and explain how an overflow can silently corrupt adjacent data, unlike a failed heap allocation.
- Limits of stack analysis. Explain why the Rust compiler cannot generally prove that worst-case stack usage fits and why stack safety needs complementary forms of detection and prevention.
- Downward Stack Growth and Overflow. Explain that the Cortex-M stack pointer starts at the top of its reserved region and moves downward, and describe how recursion, large local buffers, or nested interrupts can push it below the region’s bottom.
- Silent Static Memory Corruption. Trace what an unprotected overflow can do in the default cortex-m-rt layout: a push beyond the stack region can overwrite .bss or .data, producing incorrect behavior without an immediate crash.
- Static stack analysis workflow. Describe how compiler stack-size metadata and cargo-call-stack produce a worst-case stack estimate, and how to compare it with the stack region in memory.x.
- Indirect call blind spots. Explain why indirect calls can make the cargo-call-stack result incomplete.
- Interrupt stack contribution. Explain why an interrupt handler's stack depth must be added to the stack use of code it preempts, including when interrupts nest.
- Estimate safety margin. Justify treating the static estimate as a lower bound and state the production-firmware margin given in the section.
- Overflow detection through memory layout. Trace how flip-link’s rearranged memory layout turns a main-stack overflow into a precise bus fault.
- Stack canary usage measurement. Explain how painting unused stack memory with a recognizable pattern at startup and inspecting it later reveals the highest stack depth reached.
- MPU stack guard operation. Explain how a no-access MPU region placed below the stack detects overflow and what happens when the stack enters it.
- Dedicated stack limit registers. Explain when MSPLIM and PSPLIM can replace an MPU guard and how they relate to the two stack pointers.
What it builds on
- Defining the memory layout for your embedded Rust program (chapter 4) · Establishes where firmware memory lives.
- Mapping output sections (chapter 4) · The placement of output sections in FLASH and RAM.
- What no_std excludes and what core provides (chapter 1) · Introduces what no_std excludes and what core provides.
- Feature flags and the role of the critical-section crate (chapter 4) · The role of the critical-section crate and feature flags.
- Section placement with #[unsafe(link_section)] (chapter 5) · The idea of explicitly placing data in a memory section.
- Exceptions and interrupts: Concepts and distinctions (chapter 4) · The distinction between interrupt handlers and ordinary application execution.
- Defining memory layout with memory.x (chapter 3) · The memory layout defined with memory.x.
- Advanced fault handling: The hard-fault example (chapter 4) · Hard-fault handling
Section by section
Introduction
The chapter introduction explains why embedded Rust programmers must make deliberate memory-placement choices despite Rust’s ownership guarantees.
- Programmer responsibility for memory placement: Explain that Rust’s ownership model prevents many memory bugs but does not choose whether data lives on the stack, in static storage, or on a heap.
Why it matters: Memory placement is a design decision that Rust does not make for you. - Resource constrained memory failures: Describe why memory mistakes can be consequential on a microcontroller, using the introduction’s examples of heap fragmentation and stack growth.
Why it matters: A memory choice that appears to work in testing can still fail later in deployed firmware.
Key terms: ownership model, stack, static storage, heap, RAM, virtual memory, fragmentation, static data
7.1 Understanding memory in embedded Rust
This section introduces the memory concepts needed for later discussions of allocation, fixed-capacity containers, and stack protection.
7.1.1 The three memory regions of an embedded Rust program
This section explains where embedded Rust programs place data and how static memory, the stack, and an optional heap differ in lifetime, sizing, and cost.
- Static memory placement and lifetime: Describe what static memory contains, where it resides, and why it suits data that must persist throughout the program.
Why it matters: Static memory is useful when predictable access and program-long persistence matter more than flexible sizing. - Stack frames and fixed capacity: Explain what the stack holds, how its use changes during calls and returns, and why its fixed capacity matters.
Why it matters: Fast, automatic stack storage is only safe while its peak use stays within the reserved RAM. - Optional heap and allocation costs: Explain when heap storage is useful, why it is absent by default in a no_std build, and what costs it introduces.
Why it matters: Heap flexibility is an explicit design choice rather than a free default on a microcontroller. - Memory region design trade-offs: Justify a choice among static memory, the stack, and the heap using the sizing, cleanup, and predictability trade-offs described here.
Why it matters: Choosing a memory region means balancing flexibility against predictable resource use.
Key terms: static memory, .text, .data, .bss, stack, stack pointer, stack frame, heap, no_std, allocator
7.1.2 What core provides and what alloc adds
This section distinguishes heap-free core from heap-dependent alloc in no_std Rust and explains when and how to use allocation on a microcontroller.
- Core and alloc boundaries: Distinguish the facilities available through core from heap-dependent types supplied by alloc in a no_std build.
Why it matters: This distinction tells you which Rust facilities you can use without introducing a heap. - Alloc setup requirements: Describe the two steps needed to use alloc in a no_std build and why declaring the crate alone is insufficient.
Why it matters: Importing alloc does not itself provide the RAM-management implementation that allocation calls need. - Default memory choice: Justify using core with stack or static storage by default and reserving alloc for a concrete need.
Why it matters: A deliberate choice about allocation helps avoid complexity and a realistic failure mode on small devices.
Key terms: no_std, core, alloc, stack and static memory, dynamic allocation, extern crate alloc, global allocator, designated region of RAM, stack/static storage, allocation failure
7.1.3 Manual memory management: from C to unsafe Rust
This section compares C-style manual heap allocation with unsafe Rust and explains why safe abstractions are normally preferred.
- Manual allocation obligations: Describe how Rust permits a C-like allocate, use, and free pattern, and identify the checks and layout requirements the programmer must handle.
Why it matters: Rust makes the obligations of pointer-level heap management visible rather than removing them. - Meaning of unsafe blocks: Explain what an unsafe block permits and what safety checks remain in effect.
Why it matters: Understanding unsafe prevents you from mistaking a local responsibility for a complete suspension of Rust's checks. - Box versus manual allocation: Contrast pointer-level allocation with the Box example in this section.
Why it matters: Box shows why ordinary Rust code rarely needs to manage allocation and deallocation at pointer level.
Key terms: unsafe, Layout, null check, deallocation, borrow checker, raw pointer dereferences, invariants, Box::new, dealloc, scope
7.2 Custom allocators for heap usage in embedded Rust
This section introduces the setup needed to use heap-backed collections in a no_std embedded Rust program.
- Heap allocation prerequisites: Explain what must be supplied before a no_std program can use alloc’s growable collections: a global allocator and a region of RAM for it to manage.
Why it matters: This is the prerequisite for using heap-backed collections in a no_std program.
Key terms: alloc crate, no_std, global allocator, region of RAM, Box, Vec
7.2.1 Why heap allocation is an explicit choice in no_std
Explains why heap allocation on a no_std microcontroller requires explicit setup rather than working automatically as it does on a desktop.
- Explicit microcontroller heap setup: Explain why heap allocation is an explicit choice on a microcontroller and describe the three decisions needed to make it available: allocator implementation, RAM location, and heap size.
Why it matters: This setup is what lets allocation-backed operations such as Box::new and Vec::push work on a microcontroller.
Key terms: no_std, GlobalAlloc, #[global_allocator], static byte array, Box::new, Vec::push
7.2.2 Installing a global allocator with embedded-alloc
This section explains how to install and initialize an embedded-alloc global allocator on Cortex-M, including its backing RAM, allocator choices, and critical-section requirement.
- Embedded allocator strategy choices: Distinguish embedded-alloc’s linked-list first-fit and two-level segregated fit strategies, including the trade-off described for each.
Why it matters: The choice affects allocation behavior as well as code size. - Global allocator installation steps: Describe the four pieces used to set up LlffHeap as the global allocator and when its backing RAM is handed to it.
Why it matters: Declaring an allocator alone does not provide it with RAM to manage. - Heap backing store initialization: Explain why the backing store uses MaybeUninit<u8> and what the convenience macro changes.
Why it matters: It explains both the backing store’s declaration and why the shorter setup is equivalent. - Critical section implementation requirement: Explain why embedded-alloc needs a critical-section implementation and identify the Cortex-M feature named to provide one.
Why it matters: The allocator setup requires this implementation in addition to a declared and initialized heap.
Key terms: LlffHeap, llff, TlsfHeap, tlsf, first-fit, alloc, #[global_allocator], backing store, init, MaybeUninit<u8>
7.2.3 An alternative: the buddy system
This section explains how a buddy allocator splits and rejoins heap blocks, what that costs in wasted space, and when it may be preferable to first-fit allocation.
- Buddy block splitting and merging: Trace how a buddy allocator splits a heap block to satisfy a request and merges freed buddies back into a larger block.
Why it matters: Splitting and rejoining blocks explains both the allocator’s behavior and its fragmentation trade-off. - Fragmentation and allocator trade-offs: Distinguish the buddy system’s bounded fragmentation from its internal waste, and explain the section’s practical rule for choosing it over first-fit.
Why it matters: The choice depends on the firmware’s allocation pattern, not on one allocator being universally better. - Buddy allocator setup difference: Describe the setup difference the section identifies between buddy_system_allocator and embedded-alloc.
Why it matters: It identifies the concrete change needed to use the buddy allocator in the setup discussed here.
Key terms: buddy allocator, buddies, split, merge, first-fit, buddy system, internal fragmentation, bounded fragmentation, embedded-alloc, buddy_system_allocator
7.2.4 Using the heap: a worked example
The section uses a dynamic firmware message log to show what a global allocator enables, then explains the default response to failed allocations and a fallible alternative.
- Dynamic message log growth: Trace how the worked example uses a global allocator to grow a Vec<String> as events are recorded and later read for diagnostics.
Why it matters: Familiar collection operations can hide several heap allocations in firmware. - Formatted messages and heap alternatives: Explain why format! is useful for firmware messages with runtime-determined length and name the buffer-based alternatives described here.
Why it matters: Formatting a message is a practical reason to choose heap allocation—or plan for a bounded buffer. - Allocation failure behavior: Distinguish the default response to an unsatisfied allocation request from using the fallible reserve methods named in the section.
Why it matters: On a memory-limited device, the choice between panicking and handling allocation failure affects firmware behavior.
Key terms: global allocator, Vec<String>, record_event, capacity, backing array, format!, String, alloc, fixed-size buffer, write!
7.2.5 Choosing between allocators in practice
Recommends a default heap allocator for new embedded Rust projects and explains when evidence warrants a different choice.
- Practical allocator choice criteria: Justify starting a new project with embedded-alloc’s llff feature, and explain when profiling would warrant switching to tlsf or buddy_system_allocator. Describe the allocation patterns that make fragmentation a concern.
Why it matters: This helps you avoid choosing a more complex allocator before your firmware shows a need for one.
Key terms: embedded-alloc, llff, tlsf, buddy_system_allocator, profiling, allocator-induced fragmentation
7.2.6 Sizing the heap and avoiding allocation pitfalls
The section shows how to size an embedded heap from observed usage, reduce avoidable Vec reallocations, and place DMA buffers where the peripheral can reach them.
- Observed peak heap usage: Describe how to measure heap demand by polling allocator usage while exercising representative code paths, then use the observed peak to guide heap sizing.
Why it matters: Measured usage can free scarce RAM for static buffers or stack headroom. - Vec capacity and reallocations: Explain how choosing Vec::with_capacity instead of growing a Vec from empty can reduce reallocations, fragmentation, and worst-case push time.
Why it matters: Changing an allocation pattern can address heap problems without changing allocators. - DMA buffer memory placement: Explain why a heap-allocated buffer may be unsuitable for DMA and describe the safer buffer-placement pattern given here.
Why it matters: A buffer must be in memory the specific DMA peripheral can access, not merely in available RAM.
Key terms: HEAP.used(), HEAP.free(), PEAK_USAGE, Vec::with_capacity, Vec::new, reallocation, fragmentation, DMA, allocator’s backing region, statically allocated buffers
7.3 Alternatives to heap allocation in embedded Rust
The section explains why a known maximum buffer size can make fixed-capacity, inline-array containers a useful alternative to heap allocation.
- Fixed-capacity container tradeoff: Explain when an inline-array, fixed-capacity container is useful in embedded Rust and what it offers compared with a heap-allocated container.
Why it matters: It helps you recognize when a heap allocator may be more than an embedded program needs.
Key terms: fixed-capacity container, inline array, allocator overhead, fragmentation risk
7.3.1 Fixed-capacity containers with heapless
Introduces heapless fixed-capacity containers, their explicit overflow handling, and their use in a UART parser and an interrupt-to-main-loop queue.
- Fixed Capacity Inline Storage: Explain that heapless containers store their backing data inline, with capacity specified in the type, rather than allocating it dynamically.
Why it matters: The fixed capacity makes a container’s storage requirements explicit in firmware. - Explicit Capacity Overflow Handling: Describe why operations that might exceed a heapless container’s capacity return a Result, including what happens to a value rejected by Vec::push.
Why it matters: Explicit failure lets firmware decide what to do when a real capacity limit is reached. - Reusable UART Parser Buffers: Trace how the UART command parser accumulates bytes, handles a full line buffer, and reuses its buffer across lines.
Why it matters: The parser shows how a fixed limit and buffer reuse shape real firmware behavior. - Single Producer Consumer Queue: Describe the stated role and division of heapless::spsc::Queue for passing data between an interrupt handler and the main loop.
Why it matters: It identifies a heapless container suited to a common interrupt-to-main-loop data path.
Key terms: heapless, fixed-capacity, inline-storage, Vec<T, N>, String<N>, Result<(), T>, Vec::push, String::push_str, fixed capacity, UART command parser
7.3.2 Lighter-weight alternative: arrayvec
This section explains when arrayvec is a lighter fixed-capacity alternative to heapless and how to choose between its panicking and fallible overflow APIs.
- Overflow behavior in arrayvec: Distinguish arrayvec’s panicking push operations from its fallible counterparts, and explain when each suits a code path.
Why it matters: Choosing the right operation determines whether exceeding capacity is treated as a bug or a possible runtime outcome. - Choosing arrayvec or heapless: Explain why a project might choose arrayvec for only a fixed-capacity vector or string, but retain heapless when it already uses its other collections.
Why it matters: The choice is about the crate and API that fit the project, not a presumed major difference in the resulting container code.
Key terms: ArrayVec::push, ArrayString::push_str, panic on overflow, fallible counterparts, arrayvec, ArrayVec<T, N>, ArrayString<N>, heapless::Vec, heapless::String
7.3.3 Hybrid containers: tinyvec and smallvec
Explains how tinyvec and smallvec avoid common-case heap allocation, what they still require in no_std firmware, and when to choose them over fixed-capacity containers.
- Inline storage and heap spill: Explain that tinyvec and smallvec begin with inline array storage and allocate on the heap when that capacity is exceeded, avoiding allocation while the collection remains small.
Why it matters: This explains both the common-case savings and what happens when a buffer grows unusually large. - Allocator requirement in no_std: State that TinyVec and SmallVec still need extern crate alloc and an installed global allocator in a no_std crate; they eliminate common-case allocation, not the need for a heap.
Why it matters: Firmware cannot use these containers safely under the assumption that no allocator is needed. - Tinyvec and smallvec tradeoff: Distinguish tinyvec's safe-Rust implementation and Default requirement from smallvec's use of internal unsafe to support any element type, and explain the section's preference between them.
Why it matters: The element type determines whether the safer recommended option is available. - Hybrid versus fixed capacity: Justify using a hybrid container when typical collections are small but rare, much larger cases must be retained; describe when a fixed-capacity container is simpler.
Why it matters: This helps avoid adding heap dependence where a simpler bounded collection will do.
Key terms: tinyvec, smallvec, inline array, inline capacity, heap allocation, no_std, extern crate alloc, global allocator, Default, unsafe
7.3.4 Choosing among the alternatives
This section gives criteria for choosing heapless, arrayvec, or a hybrid container in embedded firmware.
- Allocator-free container choice: Explain why heapless is the default for most embedded programs and when arrayvec is the smaller alternative.
Why it matters: This choice keeps container capacity and overflow handling explicit without adding an allocator. - Hybrid container suitability: Describe the conditions under which tinyvec or smallvec is worth considering instead of an allocator-free container.
Why it matters: The hybrid option makes sense only when occasional large buffers justify allocation that the project can already support.
Key terms: heapless, arrayvec, allocator, Result-returning APIs, tinyvec, smallvec, hybrid pattern, worst-case buffer size
7.4 Managing the stack for memory safety
This section explains why stack overflow can silently corrupt an embedded Rust program and why stack safety requires more than compiler analysis alone.
- Stack contents and overflow risk: Describe what the stack holds and explain how an overflow can silently corrupt adjacent data, unlike a failed heap allocation.
Why it matters: Silent corruption makes a stack overflow harder to recognize than a failed heap allocation. - Limits of stack analysis: Explain why the Rust compiler cannot generally prove that worst-case stack usage fits and why stack safety needs complementary forms of detection and prevention.
Why it matters: It explains why no single compiler check is presented as a complete stack-safety solution.
Key terms: stack, stack overflow, exception entry, worst-case stack usage, static analysis, recursion, function pointers, interrupt nesting
7.4.1 How stack overflows happen
This subsection explains how a Cortex-M stack can exceed its reserved region and silently corrupt static data.
- Downward Stack Growth and Overflow: Explain that the Cortex-M stack pointer starts at the top of its reserved region and moves downward, and describe how recursion, large local buffers, or nested interrupts can push it below the region’s bottom.
Why it matters: Recognizing what drives the stack past its boundary helps explain the failure that stack-safety techniques address. - Silent Static Memory Corruption: Trace what an unprotected overflow can do in the default cortex-m-rt layout: a push beyond the stack region can overwrite .bss or .data, producing incorrect behavior without an immediate crash.
Why it matters: A stack overflow may look like an unrelated bug much later, rather than an immediate crash.
Key terms: stack pointer (SP), stack overflow, stack region, interrupt nesting, cortex-m-rt, .bss, .data, static memory, deterministic fault
7.4.2 Estimating stack usage with static analysis
This section shows how to estimate stack usage with cargo-call-stack, account for what its estimate misses, and distinguish stack analysis from section-size checks.
- Static stack analysis workflow: Describe how compiler stack-size metadata and cargo-call-stack produce a worst-case stack estimate, and how to compare it with the stack region in memory.x.
Why it matters: An estimate is useful only when you check it against the stack space the firmware actually reserves. - Indirect call blind spots: Explain why indirect calls can make the cargo-call-stack result incomplete.
Why it matters: An unknown call path can use stack that the reported worst case does not count. - Interrupt stack contribution: Explain why an interrupt handler's stack depth must be added to the stack use of code it preempts, including when interrupts nest.
Why it matters: Sizing the stack from ordinary code paths alone can miss the space needed during interrupts. - Estimate safety margin: Justify treating the static estimate as a lower bound and state the production-firmware margin given in the section.
Why it matters: A margin helps prevent an incomplete static estimate from becoming an undersized production stack. - Section sizes versus stack: Distinguish what arm-none-eabi-size shows about RAM use from what must be checked separately for stack use.
Why it matters: A section-size report can show that static data fits in RAM without proving that the stack does.
Key terms: cargo-call-stack, -Z emit-stack-sizes, rust-src, LTO, memory.x, indirect calls, function pointers, trait objects, dyn Trait, interrupt handlers
7.4.3 Detecting overflow at link time with flip-link
This section explains how flip-link changes the Cortex-M memory layout so a main-stack overflow causes a diagnosable fault instead of silent memory corruption.
- Overflow detection through memory layout: Trace how flip-link’s rearranged memory layout turns a main-stack overflow into a precise bus fault.
Why it matters: A fault at the overflowing write is much easier to diagnose than unexplained corruption elsewhere in RAM. - Linker wrapper integration: Describe how flip-link fits into the build and why the section presents it as a low-effort choice for Cortex-M projects.
Why it matters: You can gain overflow fault detection through the build setup without changing application code or the standard memory script. - Main stack protection limit: Distinguish the main stack protected by flip-link from RTOS task stacks that it does not protect.
Why it matters: Relying on flip-link alone would leave RTOS task-stack overflows unprotected. - Useful overflow fault handling: Explain what a fault handler must do to make a flip-link-detected overflow useful for debugging.
Why it matters: A detectable overflow is most useful when the fault handler exposes information you can inspect.
Key terms: flip-link, main stack, .bss, .data, bus fault, linker wrapper, .cargo/config.toml, rustc, rust-lld, memory.x
7.4.4 Software canaries as a fallback
This section explains how software canaries estimate actual stack usage by painting unused stack memory and checking it later.
- Stack canary usage measurement: Explain how painting unused stack memory with a recognizable pattern at startup and inspecting it later reveals the highest stack depth reached.
Why it matters: This gives you evidence of how much stack the program actually uses. - Canary stack boundaries: Describe the two linker symbols used to bound the stack region and the assumption made by paint_stack while it writes the pattern.
Why it matters: The boundaries and painting assumption keep the measurement tied to the intended stack region. - Periodic usage observations: Describe how periodic checks and logging can track stack usage over time, and state their costs.
Why it matters: Repeated observations show usage during execution rather than only an estimate from static analysis.
Key terms: software canaries, stack depth, _stack_start, _stack_bottom, paint_stack, memory.x, unused_stack_words(), defmt, RTT
7.4.5 Hardware-enforced guard regions with the MPU
This section explains how MPU guard regions and, on supported Armv8-M cores, stack limit registers detect stack overflow in hardware.
- MPU stack guard operation: Explain how a no-access MPU region placed below the stack detects overflow and what happens when the stack enters it.
Why it matters: A hardware guard turns an otherwise silent stack overflow into a fault that can be diagnosed. - MPU guard configuration constraints: Describe how this section configures an MPU stack guard and why stack-bottom alignment and region availability matter.
Why it matters: A guard must fit both the linker layout and the device's limited MPU-region budget. - Guard technique and architecture differences: Distinguish MPU guards from flip-link protection and describe the MPU encoding difference on Armv8-M.
Why it matters: These differences determine where a guard can be placed and whether an MPU configuration transfers unchanged to another core. - Dedicated stack limit registers: Explain when MSPLIM and PSPLIM can replace an MPU guard and how they relate to the two stack pointers.
Why it matters: On supported cores, a dedicated stack limit can detect overflow without consuming an MPU region. - Stack limit fault handling: Describe when to install MSPLIM and what fault an over-limit stack push produces.
Why it matters: Installing the limit early and recognizing its fault path makes overflow detectable and diagnosable.
Key terms: Memory Protection Unit, MPU, no-access guard region, memory management fault, MemoryManagement exception, RegisterBlock, CTRL, RNR, RBAR, RASR
7.5 Summary
Concepts explained in this chapter
- stack overflowStack overflow is the exhaustion of a thread's stack space by nested calls, local data, or other stack allocation.
- alloc crateRust’s allocation library, providing heap-allocated collections and related types when an allocator is available.
- memory fragmentationThe division of free memory into separated regions that can make allocation requests harder to satisfy.
- global allocatorThe program-wide provider used to allocate and release heap memory.
- heaplessheapless is a Rust library providing statically allocated, fixed-capacity collections and related data structures for environments where heap allocation is unavailable or undesirable.
- heapA heap is a region of dynamically managed memory used for runtime allocation.
- smallvecA Rust crate providing vector-like collections that store a limited number of elements inline before spilling to the heap.
- tinyvecA Rust crate providing vector-like collections with inline storage and optional heap-backed growth.
- dynamic allocationHeap allocation is the dynamic reservation of memory from a program's heap.
- guard regionAn MPU guard region is a memory-protection boundary configured to make accesses beyond a permitted region fault.
- stackA stack is a last-in, first-out memory structure used for nested execution state and temporary data.
- static storageMemory whose allocation persists for the entire execution of a program.
- arrayvecarrayvec is a Rust library providing vector-like collections backed by fixed-capacity inline arrays and supporting no_std environments.
- cargo-call-stackcargo-call-stack is a Rust analysis tool that estimates program stack usage from compiler-emitted per-function stack-size metadata and call paths.
- Memory Protection UnitA Memory Protection Unit (MPU) is processor hardware that enforces access permissions for configured memory regions without providing virtual-memory translation.
- flip-linkflip-link is a linker wrapper that rearranges embedded memory layouts to place the main stack below other RAM sections and detect downward stack overflow.
- static analysisStatic analysis is the examination of program properties from source or compiled artifacts without executing the program.
- stack sizeStack usage is the amount of stack memory required by a program or execution path, including nested calls and interrupt handling.
- embedded-allocembedded-alloc is a Rust crate providing heap allocators for resource-constrained embedded targets, including Cortex-M systems.
- fixed-capacity structureA fixed-capacity container is a container whose maximum number of stored elements is bounded in advance and whose storage can be provided without dynamic allocation.
- memory allocatorA memory-management component that reserves and releases dynamically managed storage.
- MemManage FaultA memory management fault is a processor exception raised when an access violates a memory protection region's permissions.
- UsageFaultUsageFault is a configurable Cortex-M fault exception raised for prohibited or undefined processor usage such as certain instructions, alignment violations, or trapped division by zero.
- vectorA vector is Rust's owned, growable vector type for storing elements contiguously on dynamically allocated storage.
- core libraryRust's core crate provides fundamental types, traits, and APIs without depending on an operating system or heap.
- no_std programno_std is a Rust crate configuration that excludes the standard library.
- memory placementMemory-region placement is the assignment of an object or section to a specific address range in a program's memory layout.
- raw pointerRaw pointer dereferencing accesses memory through a Rust raw pointer without the safety guarantees of an ordinary reference.
- unsafe blockAn unsafe block is a Rust construct in which operations requiring explicit programmer verification, such as raw-pointer dereferencing, are permitted.
- stringA string is a sequence of characters represented as data.
- critical-sectionA Rust crate that provides a portable abstraction for entering and executing code within critical sections.
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.
