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