Chapter 6: Debugging, observability, and profiling
The introduction explains why observing a bare-metal Rust program requires an explicit path for information to reach the developer.
After this chapter you will be able to
- Bare-metal observability constraints. Explain why a bare-metal Rust program cannot rely on ordinary terminal or operating-system feedback, and describe how information about its execution can reach the developer.
- Embedded debugging constraints and access. Explain why debugging an embedded target differs from debugging a desktop program and how the host can observe it.
- Timing impact of debugging. Explain why synchronous logging, breakpoints, and semihosting are poor choices for timing-sensitive or interrupt-driven paths, and contrast them with ITM, RTT, and DWT cycle counters.
- Host-to-target debugging layers. Trace the debugging pipeline from the host’s front-end tool through a GDB server or runtime backend and a hardware debug probe to the target MCU’s debug port.
- JTAG and SWD platform choices. Distinguish JTAG from SWD as microcontroller debug interfaces, and explain why SWD is common on Arm Cortex-M while RISC-V generally uses JTAG or a vendor-specific interface.
- Debug probe bridge. Explain that a debug probe is hardware connecting the host toolchain to an MCU’s debug port.
- Probe options and selection. Distinguish the common probe options and explain why selection depends on the target and workflow, including cost, tool support, speed, and device coverage.
- Explicit runtime observability choices. Explain why no_std firmware needs an explicit way to emit debug messages and describe the factors that guide the choice among the approaches named here.
- Semihosted printing path. Trace how hprintln!() gets formatted text from no_std firmware to the host debugger, including why target execution pauses.
- Standalone breakpoint failure. Explain why leftover semihosting calls can crash standalone Cortex-M0/M0+/M23 firmware and how the crate's no-semihosting feature avoids that risk.
- UART logging properties. Explain why UART is useful for embedded logging: it is widely available for serial output, works independently of the debugger, and is reliable in production.
- ITM logging capabilities and requirements. Explain how ITM logging sends messages over SWO, what iprintln!() outputs to, and why this approach suits real-time systems while requiring compatible trace hardware.
- ITM capture and host decoding. Describe why the trace capture clock must match the target's actual core clock, and how itmdump selects a port and follows incoming output.
- RTT background memory transfer. Explain how RTT produces debug output while firmware runs: a host probe reads a memory-resident ring buffer through SWD or JTAG without halting the target.
- Probe-rs tool workflow trade-off. Distinguish probe-rs run from cargo-embed by where each gets its configuration and when each workflow is convenient.
- RTT RAM and probe requirements. Explain why RTT needs an intact control block in MCU RAM and an attached debug probe throughout logging, and what that means for its use.
- defmt binary logging model. Explain how defmt records a log message and why this is cheaper than formatting it on the device.
- Panic message routing. Explain what defmt provides and how panic-probe’s print feature determines whether a panic message is emitted.
- Log generation and transport. Explain that defmt creates binary log frames while a separate transport crate delivers them to the host, independently of the logging API.
- Transport choices and exclusivity. Distinguish when to use defmt-rtt, defmt-itm, and defmt-semihosting, and state why a firmware image must link only one transport.
- defmt linker metadata setup. Explain why defmt needs a dedicated linker section and how it is normally set up.
- Host-side defmt log decoding. Explain why defmt logs need a host tool for decoding. Describe how probe-rs run flashes the binary and streams decoded logs, and how cargo-embed provides an alternative using Embed.toml.
- Embed.toml profiles and selection. Explain where cargo-embed reads its configuration, how settings are organized into profiles and sections, and how to select a profile.
- RISC-V logging options. Distinguish which logging techniques carry over to RISC-V: UART and semihosting are available, ITM is not, and RTT depends on probe support for background memory reads.
- Panic handling in no_std. Explain why a no_std program needs a panic handler to link and why embedded projects typically disable stack unwinding.
- Panic message transport channels. Describe how embedded panic handlers send messages using the printing channels already used for ordinary logs.
- Common panic triggers. Explain when a panic can occur, giving examples from the section: out-of-bounds slice indexing, unwrapping an error or absent value, an explicit panic, or a failed debug assertion.
- Stop and restart behaviors. Distinguish the halt, abort, and custom-reset responses to a panic, and explain when a watchdog-backed halt or a restart may suit a device.
- Panic handler crate selection. Explain how an apparently unused import selects a crate-provided panic handler without calling any of the crate's items.
- Minimal panic handler contract. Explain when an application must supply its own #[panic_handler], what information it receives, and why a minimal handler halts rather than returns.
- Logging panic crate selection. Explain that a corresponding panic crate can be selected for the previously covered transports by adding a dependency and a wildcard import, with no further wiring. State that UART has no dedicated panic crate because its peripheral setup is board-specific.
- Feature-selected panic behavior. Explain how the debug-panic feature and mutually exclusive cfg attributes select a panic handler, and describe the behavior of builds with and without the feature.
- HardFault context reporting. Explain how a Cortex-M fault saves execution context and how a HardFault handler can send its ExceptionFrame through an existing panic output channel.
- Fault address interpretation. Describe what the pc and lr fields tell you about a HardFault, and how to resolve the pc address to source using the flashed ELF file.
- Configurable fault classification. Distinguish the three configurable fault exceptions from HardFault and explain why enabling them improves diagnosis.
- Embedded debugging constraints. Explain why inspecting an embedded program differs from desktop debugging: the target has no operating system to mediate introspection, its internal state is accessible through dedicated debug pins, and getting a value onto the host screen requires a path through software and hardware.
- Debug toolchain selection tradeoffs. Distinguish the strengths and costs of probe-rs and GDB with OpenOCD, and justify the section’s suggested choice for routine versus more demanding debugging.
- GDB and server roles. Explain what GDB does for the developer and why a separate GDB server is needed to communicate with a microcontroller.
- Terminal GDB interface options. Distinguish GDB’s built-in terminal UI from GDB-Dashboard by describing how each presents debugging information.
- Graphical debugging front ends. Describe the graphical options named here and distinguish VSCode’s Cortex-Debug connection from its direct probe-rs alternative.
- Remote debug connection. Describe how GDB connects to an already-running GDB server and what extended-remote mode permits.
- Remote loading and reset. Trace the typical remote-debug sequence and explain the roles of load, monitor reset halt, and continue instead of run.
- OpenOCD debugging pipeline. Trace how GDB communicates through OpenOCD and a debug probe to reach the target. Explain what OpenOCD controls during a debugging session.
- OpenOCD configuration and startup. Describe the two configurations OpenOCD needs and how a project starts a server that GDB can connect to.
- OpenOCD and GDB session. Describe the two-terminal setup and the steps performed inside GDB: connect to OpenOCD’s server on port 3333, flash the target, and enable semihosting interception.
- Explicit GDB configuration loading. Explain how to put startup commands in a project-root .gdbinit file and why to invoke it with -x instead of assuming GDB will load it automatically.
- Deadline-Based Timing Measurements. Explain why embedded code must be timed against its deadlines rather than judged by guesswork, and why cycle counts are useful for doing so.
- Profiling Output Distortion. Explain why semihosting should not be used for profiling output and name the alternatives given here.
- DWT cycle-count measurement. Explain that the Arm Cortex-M DWT unit contains a 32-bit CYCCNT counter that advances every CPU clock cycle, and that reading it before and after code gives the code region’s cycle count.
- Safe DWT register access. Explain why direct DWT register access involves unsafe raw pointers and how the cortex-m crate provides access to the DWT and Debug Control Block (DCB).
- Cycle Counter Task Timing. Describe how the example times two tasks and reports their durations, and explain why it uses wrapping subtraction for the elapsed cycle count.
- SysTick as a timing substitute. Explain how SysTick can estimate the cycles spent in a short region of code on a core without DWT.
- Down-counter arithmetic and wraps. Describe how to calculate elapsed counts from SysTick readings and why the measurement must fit within one reload period unless wraps are tracked separately.
- GPIO pulse timing alternative. Describe how to measure a code region on a core without DWT by toggling a dedicated GPIO pin at its start and end, then measuring the resulting pulse width with an external logic analyzer or oscilloscope.
What it builds on
- Common debug interfaces (chapter 2) · Earlier coverage of common debug interfaces.
- What does no_std mean in embedded Rust? (chapter 3) · The meaning of no_std in an embedded project.
- Advanced fault handling: The hard-fault example (chapter 4) · The idea of a HardFault in Cortex-M fault handling.
- Installing and using OpenOCD (chapter 2) · Using OpenOCD as a debugging tool.
- Peripheral access crates (PACs), Hardware Abstraction Layers (HALs), and Board Support Packages (BSPs) (chapter 3) · The distinction between hardware-specific HALs and other embedded crates.
- Defining memory layout with memory.x (chapter 3) · The role of memory.x in defining an embedded project's memory layout.
- A detailed look at reset vector fetching and execution (chapter 4) · The reset vector’s role at the start of execution.
- Implementing the panic handler (chapter 4) · The role of a panic handler in a bare-metal application.
Section by section
Introduction
The introduction explains why observing a bare-metal Rust program requires an explicit path for information to reach the developer.
- Bare-metal observability constraints: Explain why a bare-metal Rust program cannot rely on ordinary terminal or operating-system feedback, and describe how information about its execution can reach the developer.
Why it matters: It explains why embedded debugging needs a deliberate way to get information off the device.
Key terms: bare-metal Rust application, debug probe
6.1 Debugging fundamentals: methods, interfaces, and protocols
The section explains why embedded debugging differs from desktop debugging and how a host gains visibility into a constrained target.
- Embedded debugging constraints and access: Explain why debugging an embedded target differs from debugging a desktop program and how the host can observe it.
Why it matters: These constraints explain why embedded debugging needs a hardware path between the host and the target.
Key terms: target, host, debug probe, microcontroller
6.1.1 Overview of debugging techniques
This subsection compares debugging approaches by their effect on timing and hardware requirements, and identifies the Arm targets and debug interfaces relevant to the chapter.
- Timing impact of debugging: Explain why synchronous logging, breakpoints, and semihosting are poor choices for timing-sensitive or interrupt-driven paths, and contrast them with ITM, RTT, and DWT cycle counters.
Why it matters: A debugging method can change the timing of the code you are trying to investigate. - Target debug feature availability: Describe why the debugging options discussed here depend on the microcontroller family and why the chapter focuses on particular Arm targets.
Why it matters: Check what the target implements before choosing a debugging technique. - Shared flashing and debugging interface: State how a physical debug interface is commonly used in embedded development toolchains.
Why it matters: A probe used to load firmware may also provide the connection for runtime debugging.
Key terms: synchronous logging, breakpoints, semihosting, ITM, RTT, DWT cycle counters, Armv6-M, Armv8-M baseline, Armv7-M, Armv7E-M
6.1.2 The debugging pipeline from host to target
This section maps the four layers of an embedded debugging connection and explains the debug probe’s roles in programming and live debugging.
- Host-to-target debugging layers: Trace the debugging pipeline from the host’s front-end tool through a GDB server or runtime backend and a hardware debug probe to the target MCU’s debug port.
Why it matters: Keeping the software backend, physical probe, and target distinct makes the debugging setup easier to understand. - Debug probe roles and responsiveness: Explain that the debug probe both programs firmware and carries live debugging information between host and MCU, and state what affects the pipeline’s responsiveness.
Why it matters: The probe is not just a flashing tool; it also affects how live debugging feels.
Key terms: debug host, GDB server or runtime backend, hardware debug probe, target MCU, debug port, debug probe, firmware images, live debug traffic, memory reads, register access
6.1.3 Debug interfaces: JTAG vs. SWD
This section contrasts JTAG and SWD debug interfaces and explains which is commonly used on Cortex-M and RISC-V platforms.
- JTAG and SWD platform choices: Distinguish JTAG from SWD as microcontroller debug interfaces, and explain why SWD is common on Arm Cortex-M while RISC-V generally uses JTAG or a vendor-specific interface.
Why it matters: The target architecture helps determine which debug interface to expect.
Key terms: JTAG, SWD, Arm Cortex-M, RISC-V, Debug Module Interfaces
6.1.4 Debug probes: hardware interfaces
This section identifies the hardware that connects host debugging tools to an MCU and explains how probe choice and trace support affect a debugging workflow.
- Debug probe bridge: Explain that a debug probe is hardware connecting the host toolchain to an MCU’s debug port.
Why it matters: It identifies the physical link needed for host tools to reach the target’s debug port. - Probe options and selection: Distinguish the common probe options and explain why selection depends on the target and workflow, including cost, tool support, speed, and device coverage.
Why it matters: A probe is useful only if it fits the target and the tools you intend to use. - Trace support limits: Explain why trace support must be checked on both probe and target before choosing an ITM-based workflow, and describe the trace limitations noted for MCUs.
Why it matters: Checking trace support early prevents choosing a logging workflow the hardware cannot provide.
Key terms: debug probe, host toolchain, MCU’s debug port, ST-Link, MCU-Link, J-Link, CMSIS-DAP, SWO, ITM-based workflow, data trace
6.2 Printing debug messages in embedded Rust
This section explains why bare-metal Rust needs explicit ways to print debug information and what factors guide the choice.
- Explicit runtime observability choices: Explain why no_std firmware needs an explicit way to emit debug messages and describe the factors that guide the choice among the approaches named here.
Why it matters: Debug output needs a deliberate choice that fits the device and its operating constraints.
Key terms: bare-metal, no_std, runtime observability, semihosting, UART, ITM
6.2.1 Semihosting with hprintln!()
This section explains how hprintln!() prints through semihosting, how to enable it in OpenOCD, and why it is unsuitable for some standalone or time-sensitive firmware.
- Semihosted printing path: Trace how hprintln!() gets formatted text from no_std firmware to the host debugger, including why target execution pauses.
Why it matters: This explains why a familiar-looking print call depends on a debugger and interrupts normal execution. - Standalone breakpoint failure: Explain why leftover semihosting calls can crash standalone Cortex-M0/M0+/M23 firmware and how the crate's no-semihosting feature avoids that risk.
Why it matters: A diagnostic call left in a release build can become a crash when the device runs without a debugger. - OpenOCD semihosting enablement: Describe the two ways to enable semihosting in OpenOCD and what the GDB monitor prefix does.
Why it matters: Enabling it in the debug server is necessary for the printing path to work. - Appropriate diagnostic use: Justify why semihosting fits minimal, infrequent early-development diagnostics but not time-sensitive or production deployments.
Why it matters: It helps you avoid choosing a debug-print method that disrupts timing or does not fit deployment.
Key terms: semihosting, hprintln!(), cortex-m-semihosting, BKPT 0xAB, debug probe, HardFault, DebugMonitor, no-semihosting, Cortex-M0/M0+, Cortex-M23
6.2.2 UART logging with writeln!()
This section presents UART as a production-capable logging output and notes how the chip-specific example’s output can be viewed on a host computer.
- UART logging properties: Explain why UART is useful for embedded logging: it is widely available for serial output, works independently of the debugger, and is reliable in production.
Why it matters: UART can provide log output even when a debugger is not part of the deployed system. - Chip-specific setup and output viewing: Describe the example’s STM32F103-specific HAL dependency and how a host can view UART output with a serial terminal program.
Why it matters: The board-specific dependency and host terminal both matter when adapting the example or looking for its output.
Key terms: UART, serial output, debugger, STM32F103, Blue Pill, stm32f1xx-hal, minicom, screen, PuTTY
6.2.3 ITM logging with iprintln!()
This section explains how ITM sends embedded debug messages over SWO and how to capture and view them on a host.
- ITM logging capabilities and requirements: Explain how ITM logging sends messages over SWO, what iprintln!() outputs to, and why this approach suits real-time systems while requiring compatible trace hardware.
Why it matters: These properties help you decide whether ITM is a practical logging option for your target. - ITM capture and host decoding: Describe why the trace capture clock must match the target's actual core clock, and how itmdump selects a port and follows incoming output.
Why it matters: The correct clock and decoder options make captured trace readable and let you watch the intended message stream.
Key terms: ITM, CoreSight, SWO, ITM port, iprintln!(), <CPU_CLOCK_HZ>, itmdump, -s <port>, -F, OpenOCD
6.2.4 RTT logging with rtt-target
Explains how RTT carries debug output through target RAM, how host tools capture it, and when its probe-dependent logging is useful.
- RTT background memory transfer: Explain how RTT produces debug output while firmware runs: a host probe reads a memory-resident ring buffer through SWD or JTAG without halting the target.
Why it matters: This explains why RTT is useful when stopping the firmware would interfere with debugging. - Probe-rs tool workflow trade-off: Distinguish probe-rs run from cargo-embed by where each gets its configuration and when each workflow is convenient.
Why it matters: Choosing where configuration lives can make repeated debug sessions simpler and reproducible. - Alternative RTT host tools: Describe when OpenOCD with GDB or the Segger J-Link RTT viewer makes sense for capturing RTT, including the extra setup or probe restriction involved.
Why it matters: An existing debugger or probe workflow may make an alternative RTT viewer worth using. - RTT RAM and probe requirements: Explain why RTT needs an intact control block in MCU RAM and an attached debug probe throughout logging, and what that means for its use.
Why it matters: These requirements determine whether RTT will keep providing logs in a given deployment.
Key terms: Real-Time Transfer (RTT), ring buffer, SWD, JTAG, probe-rs run, cargo-embed, probe-rs crate, Embed.toml, OpenOCD, GDB
6.3 Structured logging with defmt
This section explains how defmt moves log-message formatting from no_std firmware to a host decoder, reducing firmware size and log-call cost.
- defmt binary logging model: Explain how defmt records a log message and why this is cheaper than formatting it on the device.
Why it matters: It explains why defmt can provide logs without paying the usual on-device formatting cost.
Key terms: defmt, no_std, token, interned, ELF binary, host decoder
6.3.1 A minimal example
This section clarifies how panic messages reach a defmt transport and how release-build debug information enables source locations in logs.
- Panic message routing: Explain what defmt provides and how panic-probe’s print feature determines whether a panic message is emitted.
Why it matters: A panic can be detected without its message unless the appropriate print feature is enabled. - Release-build source locations: Explain why release builds should retain full DWARF information when viewing defmt logs with probe-rs.
Why it matters: Source locations make release-build log messages easier to trace back to code.
Key terms: defmt, Format trait, panic-probe, print-defmt, print-rtt, RTT, DWARF, debug=2, probe-rs
6.3.2 Transport backends
This section separates defmt’s binary log generation from transport to the host and explains how to choose one transport backend.
- Log generation and transport: Explain that defmt creates binary log frames while a separate transport crate delivers them to the host, independently of the logging API.
Why it matters: This distinction helps you separate how firmware logs from how those logs reach your computer. - Transport choices and exclusivity: Distinguish when to use defmt-rtt, defmt-itm, and defmt-semihosting, and state why a firmware image must link only one transport.
Why it matters: The available probe or emulator determines a practical transport, and choosing two prevents the firmware from linking.
Key terms: defmt, binary log frames, transport crate, logging API, defmt-rtt, RTT, defmt-itm, SWO, defmt-semihosting, QEMU
6.3.3 Linker setup
Explains how defmt’s linker metadata is provided without requiring a manual change to memory.x in normal use.
- defmt linker metadata setup: Explain why defmt needs a dedicated linker section and how it is normally set up.
Why it matters: You can recognize what linker support defmt needs without making an unnecessary memory.x change.
Key terms: defmt, dedicated linker section, interned format strings, log metadata, transport crates, build scripts
6.3.4 Host-side tooling
This section explains how host tools use ELF metadata to decode defmt logs and flash and monitor a target.
- Host-side defmt log decoding: Explain why defmt logs need a host tool for decoding. Describe how probe-rs run flashes the binary and streams decoded logs, and how cargo-embed provides an alternative using Embed.toml.
Why it matters: It connects the log data produced on the device to readable messages on your computer.
Key terms: defmt, ELF symbol table, metadata section, log frame, probe-rs run, cargo-embed
6.3.5 Configuring cargo-embed with Embed.toml
Explains how Embed.toml profiles configure cargo-embed and how target, probe, and reset settings affect a flashing session.
- Embed.toml profiles and selection: Explain where cargo-embed reads its configuration, how settings are organized into profiles and sections, and how to select a profile.
Why it matters: Profiles let you switch cargo-embed settings without changing the command’s underlying workflow. - Chip and probe configuration: Describe what the chip setting names and when an explicit probe section is needed.
Why it matters: These settings identify the target while keeping the common single-probe SWD configuration simple. - Reset halt behavior: Explain what halt_afterwards does and when to enable it rather than leave its default value.
Why it matters: Choosing this setting determines whether the newly flashed program stops for startup debugging or runs normally.
Key terms: Embed.toml, cargo embed, default profile, named profiles, chip, probe-rs target identifier, probe-rs chip list, [default.probe], SWD, JTAG
6.3.6 Comparative summary
Compares the availability of Cortex-M debugging and logging techniques on RISC-V targets.
- RISC-V logging options: Distinguish which logging techniques carry over to RISC-V: UART and semihosting are available, ITM is not, and RTT depends on probe support for background memory reads.
Why it matters: The target architecture and probe determine which existing logging approach you can reuse. - RISC-V debug transports: Describe JTAG as the standard RISC-V debug transport and explain the stated exception in which some hybrid SoCs allow SWD debugging.
Why it matters: Knowing the standard and the exception helps you choose a compatible debug connection.
Key terms: RISC-V, UART, semihosting, riscv-semihosting, ITM, RTT, JTAG, SWD, ARM CoreSight DAP, hybrid SoCs
6.4 Handling panics in embedded applications
Explains why bare-metal Rust needs an explicit panic handler and how panic messages use existing logging channels.
- Panic handling in no_std: Explain why a no_std program needs a panic handler to link and why embedded projects typically disable stack unwinding.
Why it matters: This explains both a link requirement and a common embedded Cargo setting. - Panic message transport channels: Describe how embedded panic handlers send messages using the printing channels already used for ordinary logs.
Why it matters: The output path determines where a panic message can be observed.
Key terms: no_std, core, #[panic_handler], panic = "abort", stack unwinding, panic-semihosting, panic-itm, panic-probe, defmt, RTT
6.4.1 When and why panics occur
This subsection identifies operations that can trigger a panic in embedded Rust.
- Common panic triggers: Explain when a panic can occur, giving examples from the section: out-of-bounds slice indexing, unwrapping an error or absent value, an explicit panic, or a failed debug assertion.
Why it matters: Recognizing what triggers a panic helps you interpret one when it occurs.
Key terms: panic, runtime safety guarantees, Result::Err, Option::None, panic!(), debug_assert!()
6.4.2 Available panic handler crates
Compares ready-made panic behaviors for different deployment contexts and explains how importing a panic-handler crate selects its handler.
- Stop and restart behaviors: Distinguish the halt, abort, and custom-reset responses to a panic, and explain when a watchdog-backed halt or a restart may suit a device.
Why it matters: The panic response should match what the device needs to do after a fault. - Diagnostic panic handler choices: Describe what the semihosting, ITM, and probe panic handlers report, including the debugger requirement for semihosting.
Why it matters: A reporting handler is useful only when its output path fits how the firmware will run. - Panic handler crate selection: Explain how an apparently unused import selects a crate-provided panic handler without calling any of the crate's items.
Why it matters: The import can look unnecessary, but it is what includes the chosen panic behavior in the binary.
Key terms: panic-halt, panic-abort, HardFault handler, sys_reset(), panic-semihosting, panic-itm, panic-probe, ITM/SWO, print-defmt, use panic_xxx as _;
6.4.3 Minimal handler implementation
This section describes the minimal panic handler required without a pre-built crate and explains why it must never return.
- Minimal panic handler contract: Explain when an application must supply its own #[panic_handler], what information it receives, and why a minimal handler halts rather than returns.
Why it matters: A panic handler must define what the device does when execution cannot recover.
Key terms: #[panic_handler], PanicInfo, panic-halt, ! return type
6.4.4 Logging-integrated panic handlers
This section explains how to select a logging-integrated panic handler and why UART is an exception.
- Logging panic crate selection: Explain that a corresponding panic crate can be selected for the previously covered transports by adding a dependency and a wildcard import, with no further wiring. State that UART has no dedicated panic crate because its peripheral setup is board-specific.
Why it matters: This helps you choose a panic handler without assuming every logging transport has the same setup.
Key terms: transport, panic crate, dependency entry, wildcard import, UART
6.4.5 Conditional panic behavior with Cargo features
Shows how a Cargo feature selects a diagnostic or silent panic handler from the same firmware source tree.
- Feature-selected panic behavior: Explain how the debug-panic feature and mutually exclusive cfg attributes select a panic handler, and describe the behavior of builds with and without the feature.
Why it matters: You can get useful panic diagnostics during development without maintaining separate production firmware sources.
Key terms: debug-panic, Cargo feature flags, #[cfg(… )], panic handler, semihosting output
6.4.6 Fault handlers and exception frame recovery
This section shows how Cortex-M fault handlers can report saved execution context and fault-status information to help locate and classify failures.
- HardFault context reporting: Explain how a Cortex-M fault saves execution context and how a HardFault handler can send its ExceptionFrame through an existing panic output channel.
Why it matters: A fault report can use the panic output path you already have instead of disappearing without context. - Fault address interpretation: Describe what the pc and lr fields tell you about a HardFault, and how to resolve the pc address to source using the flashed ELF file.
Why it matters: The reported addresses become more useful when you can connect them to source code and the call chain. - Configurable fault classification: Distinguish the three configurable fault exceptions from HardFault and explain why enabling them improves diagnosis.
Why it matters: A specifically classified fault gives you a better starting point than a generic HardFault. - Configurable fault handler diagnostics: Explain how configurable-fault handlers differ from HardFault handlers and where they obtain fault-specific diagnostic information.
Why it matters: You need to read the SCB rather than expect an injected frame when diagnosing a configurable fault.
Key terms: HardFault, ExceptionFrame, panic!(), panic output channel, pc, lr, arm-none-eabi-addr2line, ELF file, MemoryManagement, BusFault
6.5 Interactive debugging & on-chip debugging
The section explains why inspecting a variable on an embedded target requires a debug toolchain rather than the direct introspection available in desktop debugging.
- Embedded debugging constraints: Explain why inspecting an embedded program differs from desktop debugging: the target has no operating system to mediate introspection, its internal state is accessible through dedicated debug pins, and getting a value onto the host screen requires a path through software and hardware.
Why it matters: These constraints explain why an interactive debugging session involves tools and a physical connection to the target.
Key terms: introspection, debug pins, GDB, OpenOCD, debug probe
6.5.1 Choosing a toolchain: GDB + OpenOCD vs. probe-rs
This section explains how GDB with OpenOCD and probe-rs differ, and how to choose between them for embedded Rust debugging.
- GDB and OpenOCD roles: Trace how OpenOCD connects GDB to an embedded target through a debug probe.
Why it matters: This explains why a GDB debugging session needs OpenOCD between the debugger and the probe. - Debug toolchain selection tradeoffs: Distinguish the strengths and costs of probe-rs and GDB with OpenOCD, and justify the section’s suggested choice for routine versus more demanding debugging.
Why it matters: Choosing by task can keep routine debugging simple without giving up more capable tools when needed.
Key terms: GNU GDB, OpenOCD, GDB remote serial protocol, debug probe, JTAG, SWD, probe-rs, GDB+OpenOCD, Cargo, RTT logging
6.5.2 GDB for embedded systems
This section explains GDB’s role in embedded debugging, why it needs a GDB server to reach the target, and how to choose a GDB build for the target architecture.
- GDB and server roles: Explain what GDB does for the developer and why a separate GDB server is needed to communicate with a microcontroller.
Why it matters: This distinction helps you understand which part of the debugging setup talks to the hardware. - Target-compatible GDB variants: Distinguish the GDB variants described here by the target architectures they support and identify the recommended Linux default.
Why it matters: Choosing a GDB build that supports your target is a prerequisite for using it to debug that device.
Key terms: GDB, GDB server, remote serial protocol, debug probe, JTAG, SWD, gdb-multiarch, arm-none-eabi-gdb, riscv32-unknown-elf-gdb, riscv64-unknown-elf-gdb
6.5.3 GDB interfaces: CLI, TUI, and GUIs
This section identifies terminal and graphical interfaces for interactive debugging and distinguishes VSCode’s GDB-based and direct probe-rs connections.
- Terminal GDB interface options: Distinguish GDB’s built-in terminal UI from GDB-Dashboard by describing how each presents debugging information.
Why it matters: The distinction helps you choose between a built-in terminal view and a more configurable one. - Graphical debugging front ends: Describe the graphical options named here and distinguish VSCode’s Cortex-Debug connection from its direct probe-rs alternative.
Why it matters: A graphical editor connection does not necessarily mean GDB is involved.
Key terms: gdb --tui, GDB-Dashboard, .gdbinit, GDBGUI, DDD, VSCode, Cortex-Debug, probe-rs, Debug Adapter Protocol
6.5.4 Common GDB command groups
This section groups GDB commands by their roles in a remote-debug session, from connecting and loading firmware to controlling execution and inspecting memory.
- Remote debug connection: Describe how GDB connects to an already-running GDB server and what extended-remote mode permits.
Why it matters: It clarifies which part of the debug setup GDB connects to and why the server can remain available. - Remote loading and reset: Trace the typical remote-debug sequence and explain the roles of load, monitor reset halt, and continue instead of run.
Why it matters: These commands establish a predictable starting point before execution resumes. - Memory examination format: Explain how to read the count, format, and size in a GDB x command format specification using the examples given.
Why it matters: Reading the format correctly helps you interpret what GDB displays when inspecting memory.
Key terms: GDB server, extended-remote, debug probe, load, monitor, reset halt, continue, run, breakpoints, x command
6.5.5 OpenOCD: GDB’s embedded debugging backend
This section explains OpenOCD’s role between GDB and an embedded target, and how to select its configuration files and start its GDB server.
- OpenOCD debugging pipeline: Trace how GDB communicates through OpenOCD and a debug probe to reach the target. Explain what OpenOCD controls during a debugging session.
Why it matters: The connection chain helps you identify which component handles each part of an interactive debug session. - OpenOCD configuration and startup: Describe the two configurations OpenOCD needs and how a project starts a server that GDB can connect to.
Why it matters: Selecting both the probe and target configurations lets OpenOCD start a server for the intended hardware.
Key terms: OpenOCD, GDB server, debug probe, GDB’s remote serial protocol, JTAG, SWD, interface/stlink.cfg, target/stm32f1x.cfg, openocd.cfg, port 3333
6.5.6 Launching a debugging session
This section describes how to start an OpenOCD–GDB session, load symbols, connect and flash the target, and enable semihosting.
- OpenOCD and GDB session: Describe the two-terminal setup and the steps performed inside GDB: connect to OpenOCD’s server on port 3333, flash the target, and enable semihosting interception.
Why it matters: These steps establish a usable debugging connection and keep semihosting calls from faulting the target. - ELF symbols for breakpoints: Explain why GDB is started with the ELF file when setting breakpoints by function name.
Why it matters: Loading the ELF lets GDB recognize function names used in breakpoint commands. - Extended remote session choice: Distinguish extended-remote from remote for the OpenOCD session described here.
Why it matters: The connection mode determines whether you can reuse the OpenOCD session for another flash and restart.
Key terms: OpenOCD, GDB, port 3333, semihosting interception, hprintln!(), ELF, symbol table, breakpoint, Function not defined, extended-remote
6.5.7 Automating GDB with a configuration file
This section explains how to reuse GDB startup commands from a project configuration file, why to load it explicitly, and what its breakpoint and optional ITM settings require.
- Explicit GDB configuration loading: Explain how to put startup commands in a project-root .gdbinit file and why to invoke it with -x instead of assuming GDB will load it automatically.
Why it matters: Explicit loading makes a project's GDB startup commands run despite GDB's default auto-load restrictions. - Diagnostic breakpoint targets: Distinguish what breakpoints on rust_begin_unwind, DefaultHandler, and HardFault catch, including when a HardFault breakpoint is useful.
Why it matters: These targets help distinguish panics from unhandled exceptions and avoid an unhelpful HardFault breakpoint. - Optional ITM trace prerequisites: Explain why the ITM block is commented out by default and what must be true of the clock-rate placeholder for trace output to work.
Why it matters: Checking these prerequisites helps explain missing or unreadable trace output without expecting a clear configuration error.
Key terms: .gdbinit, -x, auto-load safe-path, rust_begin_unwind, DefaultHandler, HardFault, #[panic_handler], ITM, SWO, TPIU
6.6 Profiling & Performance analysis in embedded Rust
This section explains why embedded profiling needs measured execution time and why the way measurements are reported must not distort them.
- Deadline-Based Timing Measurements: Explain why embedded code must be timed against its deadlines rather than judged by guesswork, and why cycle counts are useful for doing so.
Why it matters: A timing measurement tells you whether code can finish before the event that depends on it. - Profiling Output Distortion: Explain why semihosting should not be used for profiling output and name the alternatives given here.
Why it matters: Reporting a measurement should not make the measured code appear much slower than it is.
Key terms: deadline, cycle counts, clock speed, wall-clock time, semihosting, RTT, direct register access
6.6.1 The DWT cycle counter
Explains how the Cortex-M DWT cycle counter measures code execution in CPU cycles, where it is available, and the corresponding RISC-V counter.
- DWT cycle-count measurement: Explain that the Arm Cortex-M DWT unit contains a 32-bit CYCCNT counter that advances every CPU clock cycle, and that reading it before and after code gives the code region’s cycle count.
Why it matters: This is the basis for measuring execution cost in cycles. - Cortex-M DWT availability: Distinguish Cortex-M cores with no DWT, guaranteed DWT/CYCCNT, or optional DWT, and explain the Cortex-M7 reset-lock caveat.
Why it matters: Whether DWT timing works depends on the target core and, sometimes, its reset state. - RISC-V cycle-counter reading: Describe the RISC-V mcycle counterpart and how RV32 obtains a consistent 64-bit reading from its two halves.
Why it matters: The RISC-V counterpart may need both an availability check and a careful read sequence.
Key terms: DWT, CYCCNT, CPU clock cycle, Cortex-M7, DWT::unlock(), mcycle, mcycleh, RV32, CSR
6.6.2 Setting up DWT in embedded Rust
This section explains how embedded Rust accesses the memory-mapped DWT safely through the cortex-m crate rather than raw pointers.
- Safe DWT register access: Explain why direct DWT register access involves unsafe raw pointers and how the cortex-m crate provides access to the DWT and Debug Control Block (DCB).
Why it matters: This distinction explains why the profiling setup uses crate-provided access instead of direct register pointers.
Key terms: Data Watchpoint and Trace unit, DWT, Debug Control Block, DCB, cortex-m crate, memory mapped
6.6.3 Example: Measuring function execution time
The section illustrates timing two tasks with a cycle counter and explains why wrapping subtraction gives the correct elapsed cycle count.
- Cycle Counter Task Timing: Describe how the example times two tasks and reports their durations, and explain why it uses wrapping subtraction for the elapsed cycle count.
Why it matters: Counter wraparound need not make a task-duration measurement incorrect.
Key terms: CYCCNT, wrapping_sub, RTT
6.6.4 Example: SysTick-based timing for cores without DWT
This section explains how to use SysTick to estimate elapsed CPU cycles when DWT is unavailable, including wraparound limits and conflicts with other uses of the timer.
- SysTick as a timing substitute: Explain how SysTick can estimate the cycles spent in a short region of code on a core without DWT.
Why it matters: SysTick offers a profiling option on Cortex-M0 and M0+ implementations that have it, where DWT is unavailable. - Down-counter arithmetic and wraps: Describe how to calculate elapsed counts from SysTick readings and why the measurement must fit within one reload period unless wraps are tracked separately.
Why it matters: Correct subtraction and wrap handling keep a timing result from silently becoming misleading. - Practical timer selection: Distinguish SysTick from DWT for profiling and explain when a general-purpose timer is the better choice.
Why it matters: A suitable counter must not interfere with timing services the application already uses.
Key terms: SysTick, DWT, core clock, 24-bit down-counter, start.wrapping_sub(end), 24-bit mask, reload period, software wrap counter, RTOS, delay routine
6.6.5 Platform notes
This section describes a GPIO-based way to time code on cores without a DWT cycle counter.
- GPIO pulse timing alternative: Describe how to measure a code region on a core without DWT by toggling a dedicated GPIO pin at its start and end, then measuring the resulting pulse width with an external logic analyzer or oscilloscope.
Why it matters: It gives you another way to time code when the core lacks DWT.
Key terms: DWT, SysTick, GPIO pin, pulse width, logic analyzer, oscilloscope
6.7 Summary
Concepts explained in this chapter
- semihostingSemihosting is a development technique in which code on a target device requests services such as text output from a host debugger through a debug connection.
- 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.
- RTT loggingReal-Time Transfer is a low-intrusion mechanism for exchanging data between a running embedded target and a host through target-memory buffers.
- ITMThe Instrumentation Trace Macrocell is an Arm trace component that emits instrumentation data through trace interfaces such as SWO.
- cargo-embedcargo-embed is a Cargo subcommand for flashing and debugging embedded targets with project-file-based configuration and RTT output streaming.
- defmtdefmt is a binary logging framework for no_std firmware that stores format strings in the binary and defers message reconstruction to a host decoder.
- GDB serverA GDB server is a program that mediates between GDB's remote protocol and a target debug probe, translating debugger requests into probe-specific operations.
- profilingProfiling is the measurement of a program's execution behavior to characterize its performance.
- Embed.tomlEmbed.toml is a project configuration file used by cargo-embed to specify embedded-target settings such as the chip, probe protocol, and enabled features.
- panic handlerA panic handler is the Rust-defined function that determines how a panic is handled in a target without the hosted panic runtime.
- probe-rsThe probe-rs crate is a Rust library for communicating with debug probes, flashing embedded targets, and capturing RTT data.
- GDBGDB is the GNU source-level debugger for controlling and inspecting program execution.
- OpenOCDOpen On-Chip Debugger is open-source software that provides debugging, in-system programming, and boundary-scan access through hardware probes.
- cycle-accurate timingCycle-accurate timing is timing behavior that matches the precise processor-cycle execution of the real hardware.
- cargo featureA Cargo feature is a named compile-time option that conditionally enables code or dependencies in a Rust package.
- 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.
- BKPT instructionBKPT is an Arm breakpoint instruction that generates a debug breakpoint event.
- CargoCargo is Rust's package manager and build system, providing dependency management, compilation, testing, and related project workflows.
- cargo.tomlCargo.toml is the TOML-formatted manifest file that declares a Rust package's metadata, dependencies, and build configuration.
- stm32f1xx-halstm32f1xx-hal is a Rust hardware abstraction layer crate for STM32F1 microcontrollers.
- Arm Cortex-MArm Cortex-M is a family of energy-efficient processor cores designed primarily for microcontrollers and embedded systems.
- 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.
- entry pointThe function or location at which execution begins for a program or runtime path.
- execution environmentA runtime environment is the collection of execution support, hardware state, and software facilities available to a running program.
- .cargo/config.toml.cargo/config.toml is Cargo's project configuration file for specifying build targets, linker arguments, and runner commands.
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.
