ESPHome 2026.12.0-dev
Loading...
Searching...
No Matches
crash_handler.cpp
Go to the documentation of this file.
1#ifdef USE_RP2
2
4#ifdef USE_RP2_CRASH_HANDLER
5
6#include "crash_handler.h"
8#include "esphome/core/log.h"
9
10#include <cinttypes>
11#include <hardware/regs/addressmap.h>
12#include <hardware/structs/watchdog.h>
13#include <hardware/watchdog.h>
14
15// Cortex-M0+ exception frame offsets (words)
16// When a fault occurs, the CPU pushes: R0, R1, R2, R3, R12, LR, PC, xPSR
17static constexpr uint32_t EF_LR = 5;
18static constexpr uint32_t EF_PC = 6;
19
20// Version encoded in the magic value: upper 16 bits are sentinel (0xDEAD),
21// lower 16 bits are the version number. This avoids using a separate scratch
22// register for versioning (we only have 8 total). Future firmware reads the
23// sentinel to confirm it's crash data, then the version to know the layout.
24static constexpr uint32_t CRASH_MAGIC_SENTINEL = 0xDEAD0000;
25static constexpr uint32_t CRASH_DATA_VERSION = 1;
26static constexpr uint32_t CRASH_MAGIC_V1 = CRASH_MAGIC_SENTINEL | CRASH_DATA_VERSION;
27
28// We only have 8 scratch registers (32 bytes) that survive watchdog reboot.
29// Use them for the most important data, then scan the stack for code addresses.
30//
31// Scratch register layout:
32// [0] = versioned magic (upper 16 bits = 0xDEAD sentinel, lower 16 bits = version)
33// [1] = PC (program counter at fault)
34// [2] = LR (link register from exception frame)
35// [3] = SP (stack pointer at fault)
36// [4..7] = up to 4 additional code addresses found by scanning the stack
37// (return addresses from callers, giving a deeper backtrace)
38
39// Flash is mapped at XIP_BASE (0x10000000). We use a conservative upper bound
40// to keep false positives low during stack scanning. Wider ranges would match
41// more stale data on the stack that happens to look like code addresses.
42#if defined(PICO_RP2350)
43static constexpr uint32_t FLASH_SCAN_END = XIP_BASE + 0x400000; // 4MB — RP2350 typical max
44#else
45static constexpr uint32_t FLASH_SCAN_END = XIP_BASE + 0x200000; // 2MB — RP2040 typical max
46#endif
47
48static inline bool is_code_addr(uint32_t val) {
49 uint32_t cleared = val & ~1u; // Clear Thumb bit
50 return cleared >= XIP_BASE && cleared < FLASH_SCAN_END;
51}
52
53static constexpr size_t MAX_BACKTRACE = 4;
54
55namespace esphome::rp2 {
56
57ESPHOME_LOG_TAG(TAG, "rp2.crash");
58
59// Filled from the watchdog scratch registers on the first read.
60static struct CrashData {
61 bool valid;
62 uint32_t pc;
63 uint32_t lr;
64 uint32_t sp;
65 uint32_t backtrace[MAX_BACKTRACE];
66 uint8_t backtrace_count;
67} s_crash_data; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
68
69// Logger::pre_setup() logs the record before App.pre_setup() reaches
70// arch_init(), so the first caller reads it and later calls are no-ops.
71// The read clears the scratch registers, so it must not run twice, and
72// arch_init() keeps its call so the read precedes watchdog_enable(), which
73// overwrites scratch[4].
74static bool s_crash_data_read = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
75
78 return s_crash_data.valid;
79}
80
82 if (s_crash_data_read)
83 return;
84 s_crash_data_read = true;
85 s_crash_data.valid = false;
86 uint32_t magic = watchdog_hw->scratch[0];
87 if ((magic & 0xFFFF0000) == CRASH_MAGIC_SENTINEL && (magic & 0xFFFF) == CRASH_DATA_VERSION) {
88 s_crash_data.valid = true;
89 s_crash_data.pc = watchdog_hw->scratch[1];
90 s_crash_data.lr = watchdog_hw->scratch[2];
91 s_crash_data.sp = watchdog_hw->scratch[3];
92 s_crash_data.backtrace_count = 0;
93 for (size_t i = 0; i < MAX_BACKTRACE; i++) {
94 uint32_t addr = watchdog_hw->scratch[4 + i];
95 if (addr == 0)
96 break;
97 s_crash_data.backtrace[i] = addr;
98 s_crash_data.backtrace_count++;
99 }
100 }
101 // Clear scratch registers regardless
102 for (int i = 0; i < 8; i++) {
103 watchdog_hw->scratch[i] = 0;
104 }
105}
106
107// Intentionally uses separate ESP_LOGE calls per line instead of combining into
108// one multi-line log message. This ensures each address appears as its own line
109// on the serial console (miniterm), making it possible to see partial output if
110// the device crashes again during boot, and allowing the CLI's process_stacktrace
111// to match and decode each address individually.
114 return;
115
116 ESP_LOGE(TAG, "*** CRASH DETECTED ON PREVIOUS BOOT ***");
117 ESP_LOGE(TAG, " PC: 0x%08" PRIX32 " (fault location)", s_crash_data.pc);
118 ESP_LOGE(TAG, " LR: 0x%08" PRIX32 " (return address)", s_crash_data.lr);
119 ESP_LOGE(TAG, " SP: 0x%08" PRIX32, s_crash_data.sp);
120 for (uint8_t i = 0; i < s_crash_data.backtrace_count; i++) {
121 ESP_LOGE(TAG, " BT%d: 0x%08" PRIX32 " (stack backtrace)", i, s_crash_data.backtrace[i]);
122 }
123 // Build addr2line hint with all captured addresses for easy copy-paste
124 char hint[160];
125 int pos = snprintf(hint, sizeof(hint), "Use: addr2line -pfiaC -e firmware.elf 0x%08" PRIX32 " 0x%08" PRIX32,
126 s_crash_data.pc, s_crash_data.lr);
127 for (uint8_t i = 0; i < s_crash_data.backtrace_count && pos < (int) sizeof(hint) - 12; i++) {
128 pos += snprintf(hint + pos, sizeof(hint) - pos, " 0x%08" PRIX32, s_crash_data.backtrace[i]);
129 }
130 ESP_LOGE(TAG, "%s", hint);
131}
132
133} // namespace esphome::rp2
134
135namespace esphome {
136
137static_assert(MAX_BACKTRACE + 1 <= CRASH_REPORT_MAX_BACKTRACE, "Crash report backtrace too small for the record");
138
139static bool s_report_read = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
140
141bool crash_report_get(CrashReport &out) {
142 if (s_report_read || !rp2::crash_handler_has_data())
143 return false;
144 out = {};
145 // Never survives into another build
148 out.pc = rp2::s_crash_data.pc;
149 auto &core = out.cores[out.core_count++];
150 core.addresses[core.count++] = rp2::s_crash_data.lr;
151 for (uint8_t i = 0; i < rp2::s_crash_data.backtrace_count; i++)
152 core.addresses[core.count++] = rp2::s_crash_data.backtrace[i];
153 return true;
154}
155
156void crash_report_clear() { s_report_read = true; }
157
158} // namespace esphome
159
160// --- HardFault handler ---
161// Overrides the weak isr_hardfault from arduino-pico's crt0.S.
162// On Cortex-M0+, the CPU pushes {R0,R1,R2,R3,R12,LR,PC,xPSR} onto the
163// active stack (MSP or PSP). We determine which stack was active,
164// extract key registers, store them in watchdog scratch registers
165// (which survive watchdog reboot), then trigger a reboot.
166
167// Check if a pointer falls within SRAM (valid for stack access).
168// SRAM_BASE and SRAM_END are chip-specific SDK defines:
169// RP2040: 0x20000000 - 0x20042000 (264KB)
170// RP2350: 0x20000000 - 0x20082000 (520KB)
171static inline bool is_valid_sram_ptr(const uint32_t *ptr) {
172 auto addr = reinterpret_cast<uintptr_t>(ptr);
173 // Exception frame is 8 words (32 bytes), so frame+7 must also be in SRAM.
174 // Check alignment (must be word-aligned) and that the full frame fits.
175 return (addr % 4 == 0) && addr >= SRAM_BASE && (addr + 32) <= SRAM_END;
176}
177
178// C handler called from the asm wrapper with the exception frame pointer.
179static void __attribute__((used, noreturn)) hard_fault_handler_c(uint32_t *frame, uint32_t /*exc_return*/) {
180 // watchdog_reboot() overwrites scratch[4]-[7], so we must call it first
181 // then write ALL our data after. The 10ms timeout gives us plenty of time.
182 watchdog_reboot(0, 0, 10);
183
184 // Validate frame pointer before dereferencing. If the HardFault was caused
185 // by a stacking error or corrupted SP, frame may be invalid. Write a minimal
186 // crash marker so we at least know a crash occurred.
187 if (!is_valid_sram_ptr(frame)) {
188 watchdog_hw->scratch[0] = CRASH_MAGIC_V1;
189 watchdog_hw->scratch[1] = 0; // PC unknown
190 watchdog_hw->scratch[2] = 0; // LR unknown
191 watchdog_hw->scratch[3] = reinterpret_cast<uintptr_t>(frame); // Record the bad SP for diagnosis
192 for (uint32_t i = 0; i < MAX_BACKTRACE; i++) {
193 watchdog_hw->scratch[4 + i] = 0;
194 }
195 while (true) {
196 __asm volatile("nop");
197 }
198 }
199
200 // Pre-fault SP: the exception frame is 8 words pushed onto the stack,
201 // so the SP before the fault was frame + 8 words. If xPSR bit 9 is set,
202 // the hardware pushed an extra alignment word to maintain 8-byte stack
203 // alignment (ARMv6-M/ARMv7-M spec), so add 1 more word.
204 static constexpr uint32_t EF_XPSR = 7;
205 uint32_t extra_align = (frame[EF_XPSR] & (1u << 9)) ? 1 : 0;
207 uint32_t pre_fault_sp = reinterpret_cast<uintptr_t>(post_frame);
208
209 // Write key registers
210 watchdog_hw->scratch[0] = CRASH_MAGIC_V1;
211 watchdog_hw->scratch[1] = frame[EF_PC];
212 watchdog_hw->scratch[2] = frame[EF_LR];
213 watchdog_hw->scratch[3] = pre_fault_sp;
214
215 // Scan stack for code addresses to build a deeper backtrace.
216 // The exception frame is 8 words (32 bytes) at 'frame', plus an optional
217 // alignment word. Walk up to 64 words looking for return addresses.
219 // SRAM_END is chip-specific: 0x20042000 (RP2040) or 0x20082000 (RP2350)
220 uint32_t *stack_top = reinterpret_cast<uint32_t *>(SRAM_END);
221 // Scan up to 64 words (256 bytes) — covers typical nested call frames
222 // without scanning too much stale stack data that could produce false positives.
224
225 for (uint32_t *p = scan_start; p < stack_top && p < scan_start + 64 && bt_count < MAX_BACKTRACE; p++) {
226 uint32_t val = *p;
227 // Check if this looks like a code address in flash
228 // Skip if it's the same as PC or LR we already saved
229 if (is_code_addr(val) && val != frame[EF_PC] && val != frame[EF_LR]) {
230 watchdog_hw->scratch[4 + bt_count] = val;
231 bt_count++;
232 }
233 }
234 // Zero remaining slots
235 for (uint32_t i = bt_count; i < MAX_BACKTRACE; i++) {
236 watchdog_hw->scratch[4 + i] = 0;
237 }
238
239 while (true) {
240 __asm volatile("nop");
241 }
242}
243
244// Naked asm wrapper - Cortex-M0+ compatible (no ITE/conditional execution).
245// Determines active stack pointer and branches to C handler.
246// Uses literal pool (.word) for addresses since M0+ has limited immediate encoding.
247//
248// Based on the standard Cortex-M0+ HardFault handler pattern described in:
249// - ARM Application Note AN209: "Using Cortex-M3/M4/M7 Fault Exceptions"
250// (adapted for M0+ which lacks conditional execution instructions)
251// - Memfault: "How to debug a HardFault on an ARM Cortex-M MCU"
252// https://interrupt.memfault.com/blog/cortex-m-hardfault-debug
253// - Raspberry Pi Forums: "Cortex-M0+ Hard Fault handler porting"
254// https://www.eevblog.com/forum/microcontrollers/cortex-m0-hard-fault-handler-porting/
255//
256// The key M0+ adaptation: replaces ITE/MRSEQ/MRSNE (Cortex-M3+) with
257// MOVS+TST+BEQ branch sequence, and uses a literal pool for the C handler address.
258extern "C" void __attribute__((naked, used)) isr_hardfault() {
259 __asm volatile("movs r0, #4 \n" // Prepare bit 2 mask
260 "mov r1, lr \n" // r1 = EXC_RETURN
261 "tst r1, r0 \n" // Test bit 2
262 "beq 1f \n" // If 0, was using MSP
263 "mrs r0, psp \n" // Bit 2 set = PSP was active
264 "b 2f \n"
265 "1: \n"
266 "mrs r0, msp \n" // Bit 2 clear = MSP was active
267 "2: \n"
268 // r0 = exception frame pointer, r1 = EXC_RETURN (still in r1)
269 "ldr r2, 3f \n" // Load C handler address from literal pool
270 "bx r2 \n" // Branch to handler (r0=frame, r1=exc_return)
271 ".align 2 \n"
272 "3: .word %c0 \n" // Literal pool: address of C handler
273 :
274 : "i"(hard_fault_handler_c));
275}
276
277#endif // USE_RP2_CRASH_HANDLER
278#endif // USE_RP2
struct @67::@68 __attribute__
Wake the main loop task from an ISR. ISR-safe.
Definition main_task.h:45
std::vector< uint8_t > & out
Definition gif.cpp:49
mopeka_std_values val[3]
static void int int int int const uint8_t * ptr
Definition display.cpp:62
bool crash_handler_has_data()
Returns true if crash data was found this boot, reading it first if needed.
void crash_handler_read_and_clear()
Read crash data from watchdog scratch registers and clear them.
ESPHOME_LOG_TAG(TAG, "rp2.crash")
void crash_handler_log()
Log crash data if a crash was detected on previous boot.
void crash_report_clear()
Mark the report read; it also no longer survives a reboot.
size_t size_t pos
Definition helpers.h:1530
@ CRASH_REPORT_FLAG_BUILD_MATCHES
@ CRASH_REPORT_FLAG_PRESENT
bool crash_report_get(CrashReport &out)
The previous boot's crash; false when there is none or it was read. Implemented per platform.
uint32_t * scan_start
static void uint32_t
uint32_t * stack_top
uint32_t bt_count
uint32_t extra_align
uint32_t pre_fault_sp
uint32_t * post_frame