ESPHome 2026.8.2
Loading...
Searching...
No Matches
crash_handler.cpp
Go to the documentation of this file.
1#ifdef USE_ESP8266
2
4#ifdef USE_ESP8266_CRASH_HANDLER
5
6#include "crash_handler.h"
7#include "esphome/core/log.h"
8
9#include <cinttypes>
10
11extern "C" {
12#include <user_interface.h>
13
14// Global reset info struct populated by SDK/Arduino core at boot
15extern struct rst_info resetInfo;
16}
17
18// Xtensa windowed-ABI: bits[31:30] encode call type (CALL0=00, CALL4=01,
19// CALL8=10, CALL12=11). Mask and force bit 30 to recover the real address.
20static constexpr uint32_t XTENSA_ADDR_MASK = 0x3FFFFFFF;
21static constexpr uint32_t XTENSA_CODE_BASE = 0x40000000;
22
23// ESP8266 memory map boundaries for code regions
24static constexpr uint32_t IRAM_START = 0x40100000;
25static constexpr uint32_t IRAM_END = 0x40108000; // 32KB
26
27// Linker symbols for the actual firmware IROM section.
28// Using these instead of a conservative upper bound (0x40400000) prevents
29// false positives from stale stack values beyond the actual flash mapping.
30extern "C" {
31// NOLINTBEGIN(bugprone-reserved-identifier,readability-identifier-naming,readability-redundant-declaration)
32extern void _irom0_text_start(void);
33extern void _irom0_text_end(void);
34// NOLINTEND(bugprone-reserved-identifier,readability-identifier-naming,readability-redundant-declaration)
35}
36
37// Check if a value looks like a code address in IRAM or flash-mapped IROM.
38// IRAM_ATTR as safety net — normally inlined into custom_crash_callback, but
39// ensures correctness if the compiler ever chooses not to inline.
40static inline bool IRAM_ATTR is_code_addr(uint32_t val) {
41 uint32_t addr = (val & XTENSA_ADDR_MASK) | XTENSA_CODE_BASE;
42 return (addr >= IRAM_START && addr < IRAM_END) ||
43 (addr >= (uint32_t) _irom0_text_start && addr < (uint32_t) _irom0_text_end);
44}
45
46// Recover the actual code address from a windowed-ABI return address on the stack.
47static inline uint32_t IRAM_ATTR recover_code_addr(uint32_t val) { return (val & XTENSA_ADDR_MASK) | XTENSA_CODE_BASE; }
48
49// RTC user memory layout for crash backtrace data.
50// User-accessible RTC memory: blocks 64-191 (each block = 4 bytes).
51// We use blocks 174-191 (last 18 blocks, 72 bytes) to minimize conflicts.
52// Store 16 raw candidates, filter to real return addresses at log time.
53static constexpr uint8_t RTC_CRASH_BASE = 174;
54static constexpr size_t MAX_BACKTRACE = 16;
55
56// Magic word packs sentinel, version, and count into one uint32_t:
57// bits[31:16] = sentinel
58// bits[15:8] = version
59// bits[7:0] = backtrace count
60static constexpr uint8_t CRASH_SENTINEL_BITS = 16;
61static constexpr uint8_t CRASH_VERSION_BITS = 8;
62
63static constexpr uint16_t CRASH_SENTINEL_VALUE = 0xDEAD;
64static constexpr uint8_t CRASH_VERSION_VALUE = 1;
65
66static constexpr uint32_t CRASH_SENTINEL = static_cast<uint32_t>(CRASH_SENTINEL_VALUE) << CRASH_SENTINEL_BITS;
67static constexpr uint32_t CRASH_VERSION = static_cast<uint32_t>(CRASH_VERSION_VALUE) << CRASH_VERSION_BITS;
68static constexpr uint32_t CRASH_SENTINEL_MASK = static_cast<uint32_t>(0xFFFF) << CRASH_SENTINEL_BITS;
69static constexpr uint32_t CRASH_VERSION_MASK = static_cast<uint32_t>(0xFF) << CRASH_VERSION_BITS;
70static constexpr uint32_t CRASH_COUNT_MASK = 0xFF;
71
72// Struct layout: 18 RTC blocks (72 bytes):
73// [0] = magic (sentinel | version | count)
74// [1..16] = up to 16 code addresses from stack scanning
75// [17] = epc1 at crash time (to skip duplicates at log time)
76struct RtcCrashData {
77 uint32_t magic;
78 uint32_t backtrace[MAX_BACKTRACE];
79 uint32_t epc1; // Fault PC, used to filter duplicates
80};
81static_assert(sizeof(RtcCrashData) == 72, "RtcCrashData must fit in 18 RTC blocks");
82
83namespace esphome::esp8266 {
84
85static const char *const TAG = "esp8266";
86
87static inline bool is_crash_reason(uint32_t reason) {
88 return reason == REASON_WDT_RST || reason == REASON_EXCEPTION_RST || reason == REASON_SOFT_WDT_RST;
89}
90
91bool crash_handler_has_data() { return is_crash_reason(resetInfo.reason); }
92
93// Xtensa exception cause names for the LX106 core (ESP8266).
94// Only includes causes that can actually occur on the LX106 — it has no MMU,
95// no TLB, no PIF, and no privilege levels, so causes 12-18 and 24-26 are
96// impossible and omitted. The numeric cause is always logged as fallback.
97// Uses if-else with LOG_STR to avoid CSWTCH jump tables (RAM on ESP8266).
98static const LogString *get_exception_cause(uint32_t cause) {
99 if (cause == 0)
100 return LOG_STR("IllegalInst");
101 if (cause == 2)
102 return LOG_STR("InstFetchErr");
103 if (cause == 3)
104 return LOG_STR("LoadStoreErr");
105 if (cause == 4)
106 return LOG_STR("Level1Int");
107 if (cause == 6)
108 return LOG_STR("DivByZero");
109 if (cause == 9)
110 return LOG_STR("Alignment");
111 if (cause == 20)
112 return LOG_STR("InstFetchProhibit");
113 if (cause == 28)
114 return LOG_STR("LoadProhibit");
115 if (cause == 29)
116 return LOG_STR("StoreProhibit");
117 return nullptr;
118}
119
120static const LogString *get_reset_reason(uint32_t reason) {
121 if (reason == REASON_EXCEPTION_RST)
122 return LOG_STR("Exception");
123 if (reason == REASON_SOFT_WDT_RST)
124 return LOG_STR("Soft WDT");
125 return LOG_STR("Unknown");
126}
127
128// Read backtrace from RTC user memory into caller-provided buffer.
129// Returns the number of valid backtrace entries (0 if no data found).
130static uint8_t read_rtc_backtrace(uint32_t *backtrace, size_t max_entries) {
131 RtcCrashData rtc_data;
132 if (!system_rtc_mem_read(RTC_CRASH_BASE, &rtc_data, sizeof(rtc_data)))
133 return 0;
134 uint32_t magic = rtc_data.magic;
135 if ((magic & CRASH_SENTINEL_MASK) != CRASH_SENTINEL || (magic & CRASH_VERSION_MASK) != CRASH_VERSION)
136 return 0;
137 uint8_t raw_count = magic & CRASH_COUNT_MASK;
138 if (raw_count > MAX_BACKTRACE)
139 raw_count = MAX_BACKTRACE;
140 // Skip any that match epc1 (already reported as the fault PC).
141 // Note: we cannot verify CALL instructions at addr-3 on ESP8266 because
142 // reading from IROM causes LoadStoreError due to flash cache conflicts
143 // (the reading code and target can share a direct-mapped cache line).
144 // The linker-symbol IROM bounds already eliminate most false positives.
145 uint8_t out = 0;
146 for (uint8_t i = 0; i < raw_count && out < max_entries; i++) {
147 uint32_t addr = rtc_data.backtrace[i];
148 if (addr != rtc_data.epc1)
149 backtrace[out++] = addr;
150 }
151 return out;
152}
153
154// Intentionally uses separate ESP_LOGE calls per line instead of combining into
155// one multi-line log message. This ensures each address appears as its own line
156// on the serial console, making it possible to see partial output if the device
157// crashes again during boot, and allowing the CLI's process_stacktrace to match
158// and decode each address individually.
160 if (!is_crash_reason(resetInfo.reason))
161 return;
162
163 ESP_LOGE(TAG, "*** CRASH DETECTED ON PREVIOUS BOOT ***");
164 if (resetInfo.reason == REASON_WDT_RST) {
165 // A hardware WDT reset happens entirely in hardware: the postmortem hook
166 // never runs, so rst_info epc1/exccause and the RTC backtrace are
167 // leftovers from an earlier crash. Don't misattribute them (#18596).
168 ESP_LOGE(TAG, " Reason: Hardware WDT (no crash state is recorded for hardware WDT resets)");
169 return;
170 }
171
172 // Read and filter backtrace from RTC into stack-local buffer (no persistent RAM cost).
173 // Both resetInfo and RTC data survive until the next reset, so this can be
174 // called multiple times (logger init + API subscribe) with the same result.
175 uint32_t backtrace[MAX_BACKTRACE];
176 uint8_t bt_count = read_rtc_backtrace(backtrace, MAX_BACKTRACE);
177 // GCC's ROM divide routine triggers IllegalInstruction (exccause=0) at specific
178 // ROM addresses instead of IntegerDivideByZero (exccause=6). Patch to match
179 // the Arduino core's postmortem handler behavior.
180 static constexpr uint32_t EXCCAUSE_ILLEGAL_INSTRUCTION = 0;
181 static constexpr uint32_t EXCCAUSE_INTEGER_DIVIDE_BY_ZERO = 6;
182 static constexpr uint32_t ROM_DIV_ZERO_ADDR_1 = 0x4000dce5;
183 static constexpr uint32_t ROM_DIV_ZERO_ADDR_2 = 0x4000dd3d;
184 uint32_t exccause = resetInfo.exccause;
185 if (exccause == EXCCAUSE_ILLEGAL_INSTRUCTION &&
186 (resetInfo.epc1 == ROM_DIV_ZERO_ADDR_1 || resetInfo.epc1 == ROM_DIV_ZERO_ADDR_2)) {
187 exccause = EXCCAUSE_INTEGER_DIVIDE_BY_ZERO;
188 }
189 const LogString *cause = get_exception_cause(exccause);
190 if (cause != nullptr) {
191 ESP_LOGE(TAG, " Reason: %s - %s (exccause=%" PRIu32 ")", LOG_STR_ARG(get_reset_reason(resetInfo.reason)),
192 LOG_STR_ARG(cause), exccause);
193 } else {
194 ESP_LOGE(TAG, " Reason: %s (exccause=%" PRIu32 ")", LOG_STR_ARG(get_reset_reason(resetInfo.reason)), exccause);
195 }
196 ESP_LOGE(TAG, " PC: 0x%08" PRIX32, resetInfo.epc1);
197 if (resetInfo.reason == REASON_EXCEPTION_RST) {
198 ESP_LOGE(TAG, " EXCVADDR: 0x%08" PRIX32, resetInfo.excvaddr);
199 }
200 for (uint8_t i = 0; i < bt_count; i++) {
201 ESP_LOGE(TAG, " BT%d: 0x%08" PRIX32, i, backtrace[i]);
202 }
203}
204
205} // namespace esphome::esp8266
206
207// --- Custom crash callback ---
208// Overrides the weak custom_crash_callback() from Arduino core's
209// core_esp8266_postmortem.cpp. Called during exception handling before
210// the device restarts. We scan the full stack for code addresses and store
211// them in RTC user memory (which survives software reset).
212extern "C" void IRAM_ATTR custom_crash_callback(struct rst_info *rst_info, uint32_t stack, uint32_t stack_end) {
213 // No zero-init — only magic, epc1, and backtrace[0..count-1] are read.
214 // Saves the IRAM cost of a 72-byte zero-init loop.
215 RtcCrashData data; // NOLINT(cppcoreguidelines-pro-type-member-init)
216 uint8_t count = 0;
217
218 // Stack pointer from the Xtensa exception frame is always 4-byte aligned.
219 auto *scan = (uint32_t *) stack; // NOLINT(performance-no-int-to-ptr)
220 auto *end = (uint32_t *) stack_end; // NOLINT(performance-no-int-to-ptr)
221 uint32_t epc1 = rst_info->epc1;
222
223 for (; scan < end && count < MAX_BACKTRACE; scan++) {
224 uint32_t val = *scan;
225 if (is_code_addr(val)) {
226 uint32_t addr = recover_code_addr(val);
227 // Skip epc1 — already reported as the fault PC
228 if (addr != epc1)
229 data.backtrace[count++] = addr;
230 }
231 }
232
233 data.epc1 = epc1;
234 data.magic = CRASH_SENTINEL | CRASH_VERSION | count;
235
236 system_rtc_mem_write(RTC_CRASH_BASE, &data, sizeof(data));
237}
238
239#endif // USE_ESP8266_CRASH_HANDLER
240#endif // USE_ESP8266
struct rst_info resetInfo
void _irom0_text_end(void)
struct rst_info resetInfo
void IRAM_ATTR custom_crash_callback(struct rst_info *rst_info, uint32_t stack, uint32_t stack_end)
void _irom0_text_start(void)
mopeka_std_values val[3]
bool crash_handler_has_data()
Returns true if the previous boot was a crash (exception, WDT, or soft WDT).
void crash_handler_log()
Log crash data if a crash was detected on previous boot.
static void uint32_t
uint32_t bt_count
uint32_t backtrace[MAX_BACKTRACE]
uint8_t end[39]
Definition sun_gtil2.cpp:17