ESPHome 2026.12.0-dev
Loading...
Searching...
No Matches
crash_handler.cpp
Go to the documentation of this file.
1#ifdef USE_ESP32
2
4#ifdef USE_ESP32_CRASH_HANDLER
5
6#include "crash_handler.h"
9#include "esphome/core/log.h"
10
11#include <cinttypes>
12#include <cstring>
13#include <esp_attr.h>
14#include <esp_private/panic_internal.h>
15#include <soc/soc.h>
16
17#if CONFIG_IDF_TARGET_ARCH_XTENSA
18#include <esp_cpu_utils.h>
19#include <esp_debug_helpers.h>
20#include <xtensa_context.h>
21#elif CONFIG_IDF_TARGET_ARCH_RISCV
22#include <riscv/rvruntime-frames.h>
23#endif
24
25static constexpr uint32_t CRASH_MAGIC = 0xDEADBEEF;
26static constexpr size_t MAX_BACKTRACE = 16;
27
28// Check if an address looks like code (flash-mapped or IRAM).
29// Must be safe to call from panic context (no flash access needed).
30static inline bool IRAM_ATTR is_code_addr(uint32_t addr) {
31 return (addr >= SOC_IROM_LOW && addr < SOC_IROM_HIGH) || (addr >= SOC_IRAM_LOW && addr < SOC_IRAM_HIGH);
32}
33
34#if CONFIG_IDF_TARGET_ARCH_RISCV
35// Bounds of this image's flash-mapped code, from the ESP-IDF linker script.
38
39// Check that [start, end) lies in this image's flash-mapped code or in IRAM.
40// The IROM range is larger than what the MMU maps, and reading an unmapped
41// address faults.
42static inline bool is_readable_code(uint32_t start, uint32_t end) {
43 auto irom_start = reinterpret_cast<uint32_t>(&_instruction_reserved_start);
44 auto irom_end = reinterpret_cast<uint32_t>(&_instruction_reserved_end);
45 return (start >= irom_start && end <= irom_end) || (start >= SOC_IRAM_LOW && end <= SOC_IRAM_HIGH);
46}
47
48// Check if a code address is a real return address by verifying the preceding
49// instruction is a JAL or JALR with rd=ra (x1). Called at log time (not during
50// panic) so flash cache is available. The address may come from an earlier
51// build, so check that the bytes before it are mapped before reading them.
52static inline bool is_return_addr(uint32_t addr) {
53 if (!is_code_addr(addr) || !is_readable_code(addr - 4, addr))
54 return false;
55 // A return address on the stack points to the instruction after a call.
56 // Check for 4-byte JAL/JALR call instruction before this address.
57 // Use memcpy for alignment safety — RISC-V C extension means code addresses
58 // are only 2-byte aligned, so addr-4 may not be 4-byte aligned.
59 uint32_t inst;
60 // NOLINTNEXTLINE(performance-no-int-to-ptr) - reading code memory at a raw address is the point
61 memcpy(&inst, (const void *) (addr - 4), sizeof(inst));
62 // RISC-V instruction encoding: bits [6:0] = opcode, bits [11:7] = rd
63 uint32_t opcode = inst & 0x7f; // Extract 7-bit opcode
64 uint32_t rd = inst & 0xf80; // Extract rd field (bits 11:7)
65 // Match JAL (0x6f) or JALR (0x67) with rd=ra (x1, encoded as 0x80 = 1<<7)
66 if ((opcode == 0x6f || opcode == 0x67) && rd == 0x80)
67 return true;
68 // Check for 2-byte compressed c.jalr before this address (C extension).
69 // c.jalr saves to ra implicitly: funct4=1001, rs1!=0, rs2=0, op=10
70 if (addr >= 2) {
71 // NOLINTNEXTLINE(performance-no-int-to-ptr) - reading code memory at a raw address is the point
72 uint16_t c_inst = *(uint16_t *) (addr - 2);
73 if ((c_inst & 0xf07f) == 0x9002 && (c_inst & 0x0f80) != 0)
74 return true;
75 }
76 return false;
77}
78#endif
79
80// --- Architecture-specific backtrace helpers ---
81// These run from IRAM during panic (no flash access).
82
83#if CONFIG_IDF_TARGET_ARCH_XTENSA
84// Walk Xtensa backtrace from an exception frame, writing PCs to out[].
85// Returns number of entries written.
86static uint8_t IRAM_ATTR walk_xtensa_backtrace(XtExcFrame *frame, uint32_t *out, uint8_t max) {
87 esp_backtrace_frame_t bt_frame = {
88 .pc = (uint32_t) frame->pc,
89 .sp = (uint32_t) frame->a1,
90 .next_pc = (uint32_t) frame->a0,
91 .exc_frame = frame,
92 };
93 uint8_t count = 0;
94 uint32_t first_pc = esp_cpu_process_stack_pc(bt_frame.pc);
95 if (is_code_addr(first_pc)) {
96 out[count++] = first_pc;
97 }
98 while (count < max && bt_frame.next_pc != 0) {
99 if (!esp_backtrace_get_next_frame(&bt_frame))
100 break;
101 uint32_t pc = esp_cpu_process_stack_pc(bt_frame.pc);
102 if (is_code_addr(pc)) {
103 out[count++] = pc;
104 }
105 }
106 return count;
107}
108#endif
109
110#if CONFIG_IDF_TARGET_ARCH_RISCV
111// Capture RISC-V backtrace: MEPC + RA from registers, then stack scan.
112// Returns total count; *reg_count receives number of register-sourced entries.
113static uint8_t IRAM_ATTR capture_riscv_backtrace(RvExcFrame *frame, uint32_t *out, uint8_t max, uint8_t *reg_count) {
114 uint8_t count = 0;
115 if (is_code_addr(frame->mepc)) {
116 out[count++] = frame->mepc;
117 }
118 if (is_code_addr(frame->ra) && frame->ra != frame->mepc) {
119 out[count++] = frame->ra;
120 }
121 *reg_count = count;
122 // NOLINTNEXTLINE(performance-no-int-to-ptr) - walking the raw stack by address is the point
123 auto *scan_start = (uint32_t *) frame->sp;
124 for (uint32_t i = 0; i < 64 && count < max; i++) {
126 if (is_code_addr(val) && val != frame->mepc && val != frame->ra) {
127 out[count++] = val;
128 }
129 }
130 return count;
131}
132#endif
133
134// Raw crash data written by the panic handler wrapper.
135// Lives in .noinit so it survives software reset but contains garbage after power cycle.
136// Validated by magic marker. Static linkage since it's only used within this file.
137// Version field is first so future firmware can always identify the struct layout.
138// Magic is second to validate the data. Remaining fields can change between versions.
139// Version is uint32_t because it would be padded to 4 bytes anyway before the next
140// uint32_t field, so we use the full width rather than wasting 3 bytes of padding.
141static constexpr uint32_t CRASH_DATA_VERSION = 4;
142#if CONFIG_IDF_TARGET_ARCH_XTENSA
143// EXCCAUSE is a 6-bit register; larger recorded values mean the frame's
144// cause/vaddr slots were never written (not a real exception frame).
145static constexpr uint32_t XTENSA_EXCCAUSE_COUNT = XCHAL_EXCCAUSE_NUM;
146#elif CONFIG_IDF_TARGET_ARCH_RISCV
147// Synchronous mcause exception codes are small and have no interrupt bit;
148// anything else in a non-pseudo record is a stale slot.
149static constexpr uint32_t RISCV_EXCEPTION_CAUSE_COUNT = 32;
150#endif
151struct RawCrashData {
152 uint32_t version;
153 uint32_t magic;
154 uint32_t pc;
155 uint8_t backtrace_count;
156 uint8_t reg_frame_count; // Number of entries from registers (not stack-scanned)
157 uint8_t exception; // panic_exception_t enum (FAULT/ABORT/IWDT/TWDT/DEBUG)
158 uint8_t pseudo_excause; // Whether cause is a pseudo exception (Xtensa SoC-level panic)
159 uint32_t backtrace[MAX_BACKTRACE];
160 uint32_t cause; // Architecture-specific: exccause (Xtensa) or mcause (RISC-V)
161 uint32_t fault_addr; // Faulting memory address: excvaddr (Xtensa) or mtval (RISC-V)
162 uint32_t build_time; // ESPHOME_BUILD_TIME of the firmware that captured this record
163 uint8_t crashed_core;
164#if SOC_CPU_CORES_NUM > 1
165 static_assert(SOC_CPU_CORES_NUM == 2, "Dual-core logic assumes exactly 2 cores");
166 uint8_t other_backtrace_count;
167 uint8_t other_reg_frame_count;
168 uint32_t other_backtrace[MAX_BACKTRACE];
169#endif
170};
171static RawCrashData
172 __attribute__((section(".noinit"))) s_raw_crash_data; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
173
174// Whether crash data was found and validated this boot.
175static bool s_crash_data_valid = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
176
177namespace esphome::esp32 {
178
179ESPHOME_LOG_TAG(TAG, CRASH_LOG_TAG);
180
181// RAM copy of the build timestamp. The generated constant lives in flash,
182// which the panic handler must not read (cache may be disabled during
183// cache-error panics), so the wrapper stamps the record from this mirror
184// instead. Filled during C++ dynamic initialization, well before arch_init();
185// ESPHOME_BUILD_TIME itself is constant-initialized, so the read is ordered.
186// Unqualified name on purpose: the runtime header declares it in namespace
187// esphome, while the static-analysis stub defines it as a macro.
188// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
189static uint32_t s_current_build_time = static_cast<uint32_t>(ESPHOME_BUILD_TIME);
190
191// Validate the NOINIT record. Runs on every has_data() call; re-running is
192// harmless and the magic is left alone so the record survives an OTA
193// rollback reboot, crash_handler_clear() drops it once a log client has it
194// (logger::log_crash_to_client(), for the API and MQTT).
195static void read_crash_data() {
196 if (s_raw_crash_data.magic == CRASH_MAGIC && s_raw_crash_data.version == CRASH_DATA_VERSION) {
197 s_crash_data_valid = true;
198 // Clamp counts to prevent out-of-bounds reads from corrupt .noinit data
199 if (s_raw_crash_data.backtrace_count > MAX_BACKTRACE)
200 s_raw_crash_data.backtrace_count = MAX_BACKTRACE;
201 if (s_raw_crash_data.reg_frame_count > s_raw_crash_data.backtrace_count)
202 s_raw_crash_data.reg_frame_count = s_raw_crash_data.backtrace_count;
203 if (s_raw_crash_data.exception > 4) // panic_exception_t max value
204 s_raw_crash_data.exception = 4; // Default to PANIC_EXCEPTION_FAULT
205 if (s_raw_crash_data.pseudo_excause > 1)
206 s_raw_crash_data.pseudo_excause = 0;
207 if (s_raw_crash_data.crashed_core >= SOC_CPU_CORES_NUM)
208 s_raw_crash_data.crashed_core = 0;
209#if SOC_CPU_CORES_NUM > 1
210 if (s_raw_crash_data.other_backtrace_count > MAX_BACKTRACE)
211 s_raw_crash_data.other_backtrace_count = MAX_BACKTRACE;
212 if (s_raw_crash_data.other_reg_frame_count > s_raw_crash_data.other_backtrace_count)
213 s_raw_crash_data.other_reg_frame_count = s_raw_crash_data.other_backtrace_count;
214#endif
215 }
216}
217
219 read_crash_data();
220 return s_crash_data_valid;
221}
222
224 // Only clear the magic so data doesn't survive the next reboot.
225 // Keep s_crash_data_valid so crash_handler_log() still works for
226 // additional API clients connecting during this boot session.
227 s_raw_crash_data.magic = 0;
228}
229
230// Whether the cause slot was written by a real exception frame.
231static bool cause_slot_was_written() {
232#if CONFIG_IDF_TARGET_ARCH_XTENSA
233 return s_raw_crash_data.cause < XTENSA_EXCCAUSE_COUNT;
234#else
235 return s_raw_crash_data.cause < RISCV_EXCEPTION_CAUSE_COUNT;
236#endif
237}
238
239// Look up the exception cause as a human-readable string.
240// Tables mirror ESP-IDF's panic_arch_fill_info() which uses local static arrays
241// not exposed via any public API.
242static const char *get_exception_reason() {
243 uint8_t exception = s_raw_crash_data.exception;
244 if (exception == PANIC_EXCEPTION_ABORT || exception == PANIC_EXCEPTION_TWDT) {
245 // Abort-class panics carry no cause register
246 return nullptr;
247 }
248 if (!cause_slot_was_written()) {
249 // Garbage from old-build or corrupt records; report just the type
250 return nullptr;
251 }
252#if CONFIG_IDF_TARGET_ARCH_XTENSA
253 if (s_raw_crash_data.pseudo_excause) {
254 // SoC-level panic: watchdog, cache error, etc.
255 // Keep in sync with ESP-IDF's PANIC_RSN_* defines
256 static const char *const PSEUDO_REASON[] = {
257 "Unknown reason", // 0
258 "Unhandled debug exception", // 1
259 "Double exception", // 2
260 "Unhandled kernel exception", // 3
261 "Coprocessor exception", // 4
262 "Interrupt wdt timeout on CPU0", // 5
263 "Interrupt wdt timeout on CPU1", // 6
264 "Cache error", // 7
265 };
266 uint32_t cause = s_raw_crash_data.cause;
267 if (cause < sizeof(PSEUDO_REASON) / sizeof(PSEUDO_REASON[0]))
268 return PSEUDO_REASON[cause];
269 return PSEUDO_REASON[0];
270 }
271 // Real Xtensa exception
272 static const char *const REASON[] = {
273 "IllegalInstruction",
274 "Syscall",
275 "InstructionFetchError",
276 "LoadStoreError",
277 "Level1Interrupt",
278 "Alloca",
279 "IntegerDivideByZero",
280 "PCValue",
281 "Privileged",
282 "LoadStoreAlignment",
283 nullptr,
284 nullptr,
285 "InstrPDAddrError",
286 "LoadStorePIFDataError",
287 "InstrPIFAddrError",
288 "LoadStorePIFAddrError",
289 "InstTLBMiss",
290 "InstTLBMultiHit",
291 "InstFetchPrivilege",
292 nullptr,
293 "InstrFetchProhibited",
294 nullptr,
295 nullptr,
296 nullptr,
297 "LoadStoreTLBMiss",
298 "LoadStoreTLBMultihit",
299 "LoadStorePrivilege",
300 nullptr,
301 "LoadProhibited",
302 "StoreProhibited",
303 nullptr,
304 nullptr,
305 "Cp0Dis",
306 "Cp1Dis",
307 "Cp2Dis",
308 "Cp3Dis",
309 "Cp4Dis",
310 "Cp5Dis",
311 "Cp6Dis",
312 "Cp7Dis",
313 };
314 uint32_t cause = s_raw_crash_data.cause;
315 if (cause < sizeof(REASON) / sizeof(REASON[0]) && REASON[cause] != nullptr)
316 return REASON[cause];
317#elif CONFIG_IDF_TARGET_ARCH_RISCV
318 // For SoC-level panics (watchdog, cache error), mcause holds IDF-internal
319 // interrupt numbers, not standard RISC-V cause codes. The exception type
320 // field already identifies these, so just return null to use the type name.
321 if (s_raw_crash_data.pseudo_excause)
322 return nullptr;
323 static const char *const REASON[] = {
324 "Instruction address misaligned",
325 "Instruction access fault",
326 "Illegal instruction",
327 "Breakpoint",
328 "Load address misaligned",
329 "Load access fault",
330 "Store address misaligned",
331 "Store access fault",
332 "Environment call from U-mode",
333 "Environment call from S-mode",
334 nullptr,
335 "Environment call from M-mode",
336 "Instruction page fault",
337 "Load page fault",
338 nullptr,
339 "Store page fault",
340 };
341 uint32_t cause = s_raw_crash_data.cause;
342 if (cause < sizeof(REASON) / sizeof(REASON[0]) && REASON[cause] != nullptr)
343 return REASON[cause];
344#endif
345 return "Unknown";
346}
347
348// Exception type names matching panic_exception_t enum
349static const char *get_exception_type() {
350 static const char *const TYPES[] = {
351 "Debug exception", // PANIC_EXCEPTION_DEBUG
352 "Interrupt wdt", // PANIC_EXCEPTION_IWDT
353 "Task wdt", // PANIC_EXCEPTION_TWDT
354 "Abort", // PANIC_EXCEPTION_ABORT
355 "Fault", // PANIC_EXCEPTION_FAULT
356 };
357 uint8_t exc = s_raw_crash_data.exception;
358 if (exc < sizeof(TYPES) / sizeof(TYPES[0]))
359 return TYPES[exc];
360 return "Unknown";
361}
362
363// Log backtrace entries, filtering stack-scanned addresses on RISC-V.
364static void log_backtrace(const uint32_t *addrs, uint8_t count, uint8_t reg_frame_count) {
365 uint8_t bt_num = 0;
366 for (uint8_t i = 0; i < count; i++) {
367 uint32_t addr = addrs[i];
368#if CONFIG_IDF_TARGET_ARCH_RISCV
369 if (i >= reg_frame_count && !is_return_addr(addr))
370 continue;
371 const char *source = (i < reg_frame_count) ? "backtrace" : "stack scan";
372#else
373 const char *source = "backtrace";
374#endif
375 ESP_LOGE(TAG, " BT%d: 0x%08" PRIX32 " (%s)", bt_num++, addr, source);
376 }
377}
378
379// Append backtrace addresses to the addr2line hint buffer.
380static int append_addrs_to_hint(char *buf, int size, int pos, const uint32_t *addrs, uint8_t count,
381 uint8_t reg_frame_count) {
382 for (uint8_t i = 0; i < count && pos < size - 12; i++) {
383 uint32_t addr = addrs[i];
384#if CONFIG_IDF_TARGET_ARCH_RISCV
385 if (i >= reg_frame_count && !is_return_addr(addr))
386 continue;
387#endif
388 pos += snprintf(buf + pos, size - pos, " 0x%08" PRIX32, addr);
389 }
390 return pos;
391}
392
393// Register holding the faulting memory address, named as in ESP-IDF's live
394// register dump. The lowercase form is for old-build reports, where the
395// stacktrace decoders must not match the line.
396#if CONFIG_IDF_TARGET_ARCH_XTENSA
397static const char *const FAULT_ADDR_REG = "EXCVADDR";
398static const char *const FAULT_ADDR_REG_LOWER = "excvaddr";
399#elif CONFIG_IDF_TARGET_ARCH_RISCV
400static const char *const FAULT_ADDR_REG = "MTVAL";
401static const char *const FAULT_ADDR_REG_LOWER = "mtval";
402#endif
403
404// Whether the fault address is meaningful: real CPU faults with a validly
405// written frame only.
406static bool has_fault_addr() {
407 return s_raw_crash_data.exception == PANIC_EXCEPTION_FAULT && !s_raw_crash_data.pseudo_excause &&
408 cause_slot_was_written();
409}
410
411// The record was captured by a different firmware build (it survives soft
412// resets, including the OTA reboot), so symbolizing its addresses against the
413// current ELF would produce misleading symbols. Print them with lowercase
414// labels the stacktrace decoders deliberately do not match, and skip the
415// addr2line hint. One line per address so nothing is lost to a shared buffer.
416// No is_return_addr() filtering here: it would inspect the current build's
417// code bytes, which say nothing about addresses captured by the old build.
418static uint8_t log_foreign_backtrace(const uint32_t *addrs, uint8_t count, uint8_t bt_num) {
419 for (uint8_t i = 0; i < count; i++) {
420 ESP_LOGE(TAG, " bt%d: 0x%08" PRIX32, bt_num++, addrs[i]);
421 }
422 return bt_num;
423}
424
425static void log_foreign_addresses() {
426 ESP_LOGE(TAG, " Captured by a different firmware build; addresses belong to that build's ELF");
427 ESP_LOGE(TAG, " pc: 0x%08" PRIX32, s_raw_crash_data.pc);
428 if (has_fault_addr()) {
429 ESP_LOGE(TAG, " %s: 0x%08" PRIX32, FAULT_ADDR_REG_LOWER, s_raw_crash_data.fault_addr);
430 }
431 uint8_t bt_num = log_foreign_backtrace(s_raw_crash_data.backtrace, s_raw_crash_data.backtrace_count, 0);
432#if SOC_CPU_CORES_NUM > 1
433 if (s_raw_crash_data.other_backtrace_count > 0) {
434 // Lowercase like the address labels: carries no address, matches no decoder.
435 ESP_LOGE(TAG, " other core (%d):", 1 - s_raw_crash_data.crashed_core);
436 log_foreign_backtrace(s_raw_crash_data.other_backtrace, s_raw_crash_data.other_backtrace_count, bt_num);
437 }
438#else
439 (void) bt_num; // Single-core targets have no second list to continue numbering into.
440#endif
441}
442
443// Intentionally uses separate ESP_LOGE calls per line instead of combining into
444// one multi-line log message. This ensures each address appears as its own line
445// on the serial console, making it possible to see partial output if the device
446// crashes again during boot, and allowing the CLI's process_stacktrace to match
447// and decode each address individually.
450 return;
451
452 ESP_LOGE(TAG, "*** CRASH DETECTED ON PREVIOUS BOOT ***");
453 const char *reason = get_exception_reason();
454 if (reason != nullptr) {
455 ESP_LOGE(TAG, " Reason: %s - %s (cause %" PRIu32 ")", get_exception_type(), reason, s_raw_crash_data.cause);
456 } else {
457 ESP_LOGE(TAG, " Reason: %s", get_exception_type());
458 }
459 ESP_LOGE(TAG, " Crashed core: %d", s_raw_crash_data.crashed_core);
460 if (s_raw_crash_data.build_time != s_current_build_time) {
461 // Captured by a different firmware build: the record survives soft resets
462 // including the OTA reboot, so its addresses belong to a previous ELF.
463 log_foreign_addresses();
464 return;
465 }
466 ESP_LOGE(TAG, " PC: 0x%08" PRIX32 " (fault location)", s_raw_crash_data.pc);
467 // Uses the same register name as ESP-IDF's live register dump so the CLI
468 // decodes the address when it happens to be a code address.
469 if (has_fault_addr()) {
470 ESP_LOGE(TAG, " %s: 0x%08" PRIX32 " (faulting address)", FAULT_ADDR_REG, s_raw_crash_data.fault_addr);
471 }
472 log_backtrace(s_raw_crash_data.backtrace, s_raw_crash_data.backtrace_count, s_raw_crash_data.reg_frame_count);
473
474#if SOC_CPU_CORES_NUM > 1
475 if (s_raw_crash_data.other_backtrace_count > 0) {
476 int other_core = 1 - s_raw_crash_data.crashed_core;
477 ESP_LOGE(TAG, " Other core (%d) backtrace:", other_core);
478 log_backtrace(s_raw_crash_data.other_backtrace, s_raw_crash_data.other_backtrace_count,
479 s_raw_crash_data.other_reg_frame_count);
480 }
481#endif
482
483 // Build addr2line hints for easy copy-paste. One line per core: the two
484 // backtraces are separate stacks, and a combined list decodes as one
485 // impossible call chain (and can overflow the buffer, dropping addresses).
486 static const char *const ADDR2LINE_CMD = "addr2line -pfiaC -e firmware.elf";
487 char hint[256];
488 int pos = snprintf(hint, sizeof(hint), "Use: %s 0x%08" PRIX32, ADDR2LINE_CMD, s_raw_crash_data.pc);
489 append_addrs_to_hint(hint, sizeof(hint), pos, s_raw_crash_data.backtrace, s_raw_crash_data.backtrace_count,
490 s_raw_crash_data.reg_frame_count);
491 ESP_LOGE(TAG, "%s", hint);
492#if SOC_CPU_CORES_NUM > 1
493 if (s_raw_crash_data.other_backtrace_count > 0) {
494 pos = snprintf(hint, sizeof(hint), "Other core: %s", ADDR2LINE_CMD);
495 append_addrs_to_hint(hint, sizeof(hint), pos, s_raw_crash_data.other_backtrace,
496 s_raw_crash_data.other_backtrace_count, s_raw_crash_data.other_reg_frame_count);
497 ESP_LOGE(TAG, "%s", hint);
498 }
499#endif
500}
501
502} // namespace esphome::esp32
503
504namespace esphome {
505
506static_assert(MAX_BACKTRACE <= CRASH_REPORT_MAX_BACKTRACE, "Crash report backtrace too small for the record");
507
508// The record itself stays valid for log replay this boot
509static bool s_report_read = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
510
511// Filtered as in log_backtrace()
512static uint8_t copy_backtrace(const uint32_t *addrs, uint8_t count, [[maybe_unused]] uint8_t reg_frame_count,
513 [[maybe_unused]] bool filter, uint32_t *out) {
514 uint8_t out_count = 0;
515 for (uint8_t i = 0; i < count; i++) {
516#if CONFIG_IDF_TARGET_ARCH_RISCV
517 if (filter && i >= reg_frame_count && !is_return_addr(addrs[i]))
518 continue;
519#endif
520 out[out_count++] = addrs[i];
521 }
522 return out_count;
523}
524
525static CrashReason get_crash_reason() {
526 switch (s_raw_crash_data.exception) {
527 case PANIC_EXCEPTION_ABORT:
529 case PANIC_EXCEPTION_TWDT:
531 case PANIC_EXCEPTION_IWDT:
533 default:
535 }
536}
537
539 if (s_report_read || !esp32::crash_handler_has_data())
540 return false;
541 out = {};
543 const bool build_matches = s_raw_crash_data.build_time == esp32::s_current_build_time;
544 if (build_matches)
546 out.reason = get_crash_reason();
547 out.crashed_core = s_raw_crash_data.crashed_core;
548 out.pc = s_raw_crash_data.pc;
549 out.build_time = s_raw_crash_data.build_time;
550 // A pseudo cause is an IDF panic reason
551 if (s_raw_crash_data.exception != PANIC_EXCEPTION_ABORT && s_raw_crash_data.exception != PANIC_EXCEPTION_TWDT &&
552 !s_raw_crash_data.pseudo_excause && esp32::cause_slot_was_written()) {
554 out.cause = s_raw_crash_data.cause;
555 }
556 if (esp32::has_fault_addr()) {
558 out.fault_address = s_raw_crash_data.fault_addr;
559 }
560 auto &crashed = out.cores[out.core_count++];
561 crashed.core = s_raw_crash_data.crashed_core;
562 crashed.count = copy_backtrace(s_raw_crash_data.backtrace, s_raw_crash_data.backtrace_count,
563 s_raw_crash_data.reg_frame_count, build_matches, crashed.addresses.data());
564#if SOC_CPU_CORES_NUM > 1
565 if (s_raw_crash_data.other_backtrace_count > 0) {
566 auto &other = out.cores[out.core_count++];
567 other.core = 1 - s_raw_crash_data.crashed_core;
568 other.count = copy_backtrace(s_raw_crash_data.other_backtrace, s_raw_crash_data.other_backtrace_count,
569 s_raw_crash_data.other_reg_frame_count, build_matches, other.addresses.data());
570 }
571#endif
572 return true;
573}
574
576 s_report_read = true;
578}
579
580} // namespace esphome
581
582// --- Panic handler wrapper ---
583// Intercepts esp_panic_handler() via --wrap linker flag to capture crash data
584// into NOINIT memory before the normal panic handler runs.
585//
586extern "C" {
587// Set by IDF's task watchdog (task_wdt.c, no header) before it simulates an
588// abort; weak so builds without the task watchdog still link.
589extern bool g_twdt_isr __attribute__((weak));
590
591// NOLINTBEGIN(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp,readability-identifier-naming)
592// Names are mandated by the --wrap linker mechanism
593extern void __real_esp_panic_handler(panic_info_t *info);
594
595void IRAM_ATTR __wrap_esp_panic_handler(panic_info_t *info) {
596 // Save the faulting PC and exception info
597 s_raw_crash_data.pc = (uint32_t) info->addr;
598 s_raw_crash_data.backtrace_count = 0;
599 s_raw_crash_data.reg_frame_count = 0;
600 s_raw_crash_data.exception = (uint8_t) info->exception;
601 s_raw_crash_data.pseudo_excause = info->pseudo_excause ? 1 : 0;
602 s_raw_crash_data.crashed_core = (uint8_t) info->core;
603 if (g_panic_abort) {
604 // IDF reclassifies to ABORT only inside esp_panic_handler(), after this
605 // wrapper captured info->exception; correct it here. TWDT is our own
606 // distinction (IDF never assigns PANIC_EXCEPTION_TWDT). The abort text is
607 // not stored; the symbolized backtrace already identifies the site.
608 bool is_twdt = &g_twdt_isr != nullptr && g_twdt_isr;
609 s_raw_crash_data.exception = (uint8_t) (is_twdt ? PANIC_EXCEPTION_TWDT : PANIC_EXCEPTION_ABORT);
610 }
611 // Zero unconditionally so a null frame doesn't leave stale .noinit data from a previous boot
612 s_raw_crash_data.cause = 0;
613 s_raw_crash_data.fault_addr = 0;
614 // Record which build's ELF the captured addresses belong to (RAM read, panic-safe).
615 // Still 0 if the panic precedes C++ dynamic initialization, so such a crash
616 // reports as a foreign build — conservative: addresses are shown raw instead
617 // of decoded.
618 s_raw_crash_data.build_time = esphome::esp32::s_current_build_time;
619#if SOC_CPU_CORES_NUM > 1
620 s_raw_crash_data.other_backtrace_count = 0;
621 s_raw_crash_data.other_reg_frame_count = 0;
622#endif
623
624#if CONFIG_IDF_TARGET_ARCH_XTENSA
625 // Xtensa: walk the backtrace using the public API
626 if (info->frame != nullptr) {
627 auto *xt_frame = (XtExcFrame *) info->frame;
628 // IDF leaves addr unset for SoC-level panics (cache error, interrupt WDT)
629 if (info->pseudo_excause)
630 s_raw_crash_data.pc = xt_frame->pc;
631 if (!g_panic_abort) {
632 // Abort-class frames carry no useful cause/vaddr: TWDT task snapshots
633 // never wrote them and abort() traps describe only the synthetic trap.
634 s_raw_crash_data.cause = xt_frame->exccause;
635 s_raw_crash_data.fault_addr = xt_frame->excvaddr;
636 }
637 s_raw_crash_data.backtrace_count = walk_xtensa_backtrace(xt_frame, s_raw_crash_data.backtrace, MAX_BACKTRACE);
638 }
639
640#if SOC_CPU_CORES_NUM > 1
641 // Capture the other core's backtrace from the global frame array.
642 // Both cores save their frames to g_exc_frames[] before esp_panic_handler
643 // is called, so the other core's frame is available here.
644 if (info->core >= 0 && info->core < SOC_CPU_CORES_NUM) {
645 int other_core = 1 - info->core;
646 auto *other_frame = (XtExcFrame *) g_exc_frames[other_core];
647 if (other_frame != nullptr) {
648 s_raw_crash_data.other_backtrace_count =
649 walk_xtensa_backtrace(other_frame, s_raw_crash_data.other_backtrace, MAX_BACKTRACE);
650 }
651 }
652#endif
653
654#elif CONFIG_IDF_TARGET_ARCH_RISCV
655 // RISC-V: capture MEPC + RA, then scan stack for code addresses
656 if (info->frame != nullptr) {
657 auto *rv_frame = (RvExcFrame *) info->frame;
658 if (!g_panic_abort) {
659 // See the Xtensa branch: abort-class frames carry no valid cause/vaddr.
660 s_raw_crash_data.cause = rv_frame->mcause;
661 s_raw_crash_data.fault_addr = rv_frame->mtval;
662 }
663 s_raw_crash_data.backtrace_count =
664 capture_riscv_backtrace(rv_frame, s_raw_crash_data.backtrace, MAX_BACKTRACE, &s_raw_crash_data.reg_frame_count);
665 }
666
667#if SOC_CPU_CORES_NUM > 1
668 // Capture the other core's backtrace from the global frame array.
669 if (info->core >= 0 && info->core < SOC_CPU_CORES_NUM) {
670 int other_core = 1 - info->core;
671 auto *other_frame = (RvExcFrame *) g_exc_frames[other_core];
672 if (other_frame != nullptr) {
673 s_raw_crash_data.other_backtrace_count = capture_riscv_backtrace(
674 other_frame, s_raw_crash_data.other_backtrace, MAX_BACKTRACE, &s_raw_crash_data.other_reg_frame_count);
675 }
676 }
677#endif
678#endif
679
680 // Write version and magic last — ensures all data is written before we mark it valid
681 s_raw_crash_data.version = CRASH_DATA_VERSION;
682 s_raw_crash_data.magic = CRASH_MAGIC;
683
684 // Call the real panic handler (prints to UART, does core dump, reboots, etc.)
686}
687
688// NOLINTEND(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp,readability-identifier-naming)
689} // extern "C"
690
691#endif // USE_ESP32_CRASH_HANDLER
692#endif // USE_ESP32
struct @67::@68 __attribute__
Wake the main loop task from an ISR. ISR-safe.
Definition main_task.h:45
char _instruction_reserved_start
void __real_esp_panic_handler(panic_info_t *info)
char _instruction_reserved_end
void IRAM_ATTR __wrap_esp_panic_handler(panic_info_t *info)
std::vector< uint8_t > & out
Definition gif.cpp:49
unsigned count
Definition gif.cpp:51
ESPHOME_LOG_TAG(TAG, "hw_timer_esp_idf")
mopeka_std_values val[3]
bool crash_handler_has_data()
Returns true if crash data was found this boot, reading it first if needed.
void crash_handler_log()
Log crash data if a crash was detected on previous boot.
void crash_handler_clear()
Clear the magic marker and mark crash data as consumed.
void crash_report_clear()
Mark the report read; it also no longer survives a reboot.
CrashReason
Sent as is over the native API.
size_t size_t pos
Definition helpers.h:1530
@ CRASH_REPORT_FLAG_BUILD_MATCHES
@ CRASH_REPORT_FLAG_PRESENT
@ CRASH_REPORT_FLAG_CAUSE
@ CRASH_REPORT_FLAG_FAULT_ADDRESS
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
uint8_t end[39]
Definition sun_gtil2.cpp:17