diff --git a/docs/features/feature-catalog.md b/docs/features/feature-catalog.md index f37a8a5..202428d 100644 --- a/docs/features/feature-catalog.md +++ b/docs/features/feature-catalog.md @@ -82,6 +82,7 @@ Check `git log -- src/Version.hpp` for the real bump history before tagging a ne | F-067 | Specific `playback.play` / `playback.stop` ACK messages (busy, invalid params, not found, load failed, bells disabled, overload…) instead of a generic "Playback command failed"; `url` no longer sticky | v2.3.0 | Stable | | F-068 | `loading` playback state while a melody downloads (MQTT `status/playback`), cancellable by `playback.stop`; `playback_failed` event on `control/reports` when an ACKed play never starts | v2.3.0 | Stable | | F-069 | RF remote disabled on Vesper Standard builds (`HAS_RF=0`) — no fielded unit has a receiver; `rf.*` now only on agnus | v2.3.0 | Stable | +| F-070 | Richer crash reports — coredump backtrace + ELF SHA, abort() reason string, and last pre-crash heap/uptime snapshot in `boot_report` and the SD boot log | v2.3.0 | Stable | --- @@ -1358,3 +1359,66 @@ build. Agnus keeps RF. `status/playback` `source: "rf"` can therefore only appea Verified: `pio run -e vesper-std-v1` builds clean. Subsystem: `variants/vesper-std.hpp` + +--- + +### F-070 — Richer crash reports: backtrace, abort reason, pre-crash snapshot + +**Why.** Crashes kept arriving on the console as `task async_tcp, PC 0x40083ed5, cause 29, vaddr 0x0`. +That PC is `panic_abort()` (IDF `panic.c:408`), which *deliberately* writes to address 0 to halt the +chip, so every `abort()` looks identical no matter what caused it (see F-055's note on this). The +actual reason, and the call chain that led to it, were only ever on the serial port. + +**What's added.** + +1. **Backtrace + ELF SHA from the coredump** (`Telemetry::captureCrashReport()`). The coredump summary + already carried `exc_bt_info` (up to 16 PCs) and the crashing app's ELF SHA-256 prefix; they're now + read and reported. For an `abort()` the first 2–4 frames are the abort machinery (`panic_abort`, + `esp_system_abort`, `abort`, `std::terminate`…); the frames after that are the real call site. + Also logged at boot in the same `0x… 0x…` format as the serial panic output, ready for `addr2line`. +2. **Abort reason string** (`src/Telemetry/CrashBreadcrumbs.cpp`). `platformio.ini` links with + `-Wl,--wrap=esp_system_abort`, so every abort path in this SDK (`abort()`, `assert`, `configASSERT`, + the FreeRTOS stack-overflow hook, stack-smashing protection) passes through + `__wrap_esp_system_abort()` first. It copies the message (≤159 chars) into `RTC_NOINIT` memory and + hands off to the real function. Typical values: `abort() was called at PC 0x400d1234 on core 0` + (that PC is `abort()`'s caller; decode it), `assert failed: tcp_update_rcv_ann_wnd tcp.c:951 (...)`, + `***ERROR*** A stack overflow in task async_tcp has been detected.` The wrapper is IRAM-only, copies + bytes by hand, and takes no locks, since it can run with the heap lock held or the cache disabled. +3. **Pre-crash snapshot.** TelemetryTask writes `millis()`, free heap, largest free block and the + boot's minimum-ever free heap into the same RTC block every second, regardless of the OTA pause + flag. Enough to tell "heap exhaustion again" (F-055) apart from a genuine bug. + +RTC memory survives panic/watchdog/software resets but not power-on or brownout; magic words guard +against garbage. `CrashBreadcrumbs::consume()` runs once in `Telemetry::begin()` and clears the block; +the result is kept only when `isFaultReset()`, so a clean reboot/OTA never reports the previous boot's +snapshot. + +**Where it shows up.** MQTT `boot_report` (`system/info`) and each SD boot-log entry +(`telemetry.get_boot_history`), same shape in both, built by `Telemetry::writeCrashJson()` / +`writePreCrashJson()`: + +```json +"crash": { + "task": "async_tcp", "pc": 1074282197, "exc_cause": 29, "exc_vaddr": 0, + "backtrace": [1074282194, 1074340312, 1074348122, 1074606712], + "backtrace_corrupted": false, + "elf_sha256": "3f9a1c0be7d2a441" +}, +"pre_crash": { + "uptime_ms": 5412000, "free_heap": 21480, "largest_block": 9716, "min_free_heap": 18112, + "abort_msg": "abort() was called at PC 0x400d8a3f on core 0" +} +``` + +All new `crash` keys are additive. `pre_crash` is independent of `crash`: it can appear without a +coredump (e.g. a task-watchdog reset whose dump failed), and `abort_msg` is omitted when the reset +wasn't an abort (a real hardware exception, a watchdog). + +**Decoding.** `elf_sha256` is the first 16 hex chars of the SHA-256 of the crashing build's +`firmware.elf`. Keep each release's `.elf`: `xtensa-esp32-elf-addr2line -pfiaC -e firmware.elf `. + +Verified: `pio run -e vesper-std-v1`, `-e agnus-v1` and `-e bespoke-rs485-v1` build clean; `objdump` +confirms `abort()` now calls `__wrap_esp_system_abort` (IRAM) and the breadcrumb block lives in RTC slow +memory (`0x5000xxxx`). Not yet exercised with a deliberate crash on hardware. + +Subsystem: `src/Telemetry/CrashBreadcrumbs.hpp`, `src/Telemetry/CrashBreadcrumbs.cpp`, `src/Telemetry/Telemetry.hpp`, `src/Telemetry/Telemetry.cpp`, `src/Communication/CommunicationRouter/CommunicationRouter.cpp`, `platformio.ini` diff --git a/docs/reference/mqtt-events.md b/docs/reference/mqtt-events.md index fc783aa..5c15377 100644 --- a/docs/reference/mqtt-events.md +++ b/docs/reference/mqtt-events.md @@ -284,12 +284,23 @@ Published once, the first time MQTT connects after boot (guarded, not repeated o "reset_reason": "PANIC", "is_fault": true, "free_heap": 187234, - "crash": { "task": "TelemetryTask", "pc": 1074111832, "exc_cause": 1, "exc_vaddr": 0 } + "crash": { + "task": "async_tcp", "pc": 1074282197, "exc_cause": 29, "exc_vaddr": 0, + "backtrace": [1074282194, 1074340312, 1074348122, 1074606712], + "backtrace_corrupted": false, + "elf_sha256": "3f9a1c0be7d2a441" + }, + "pre_crash": { + "uptime_ms": 5412000, "free_heap": 21480, "largest_block": 9716, "min_free_heap": 18112, + "abort_msg": "abort() was called at PC 0x400d8a3f on core 0" + } } } ``` -`crash` is present only when a coredump was found for the crash that caused this boot — omitted on a clean/expected reset or a fault reset with no coredump (e.g. brownout). A fault-class reset additionally publishes a `system/alerts` WARNING (see above) — `system/info`'s `boot_report` is published unconditionally, fault or not. +`crash` is present only when a coredump was found for the crash that caused this boot — omitted on a clean/expected reset or a fault reset with no coredump (e.g. brownout). `backtrace` (up to 16 PCs, decimal) and `elf_sha256` (first 16 hex chars of the crashing build's ELF SHA-256) identify the call chain; decode with `addr2line` against that exact `.elf`. + +`pre_crash` (F-070) is present only on a fault reset where RTC memory survived (not power-on/brownout): the last once-per-second heap/uptime snapshot before the reset, plus `abort_msg` when the reset came from `abort()`/`assert`/a stack-overflow check. For those resets `pc`/`exc_cause 29`/`exc_vaddr 0` are the abort mechanism itself; `abort_msg` and the later `backtrace` frames are the real cause. A fault-class reset additionally publishes a `system/alerts` WARNING (see above) — `system/info`'s `boot_report` is published unconditionally, fault or not. --- diff --git a/platformio.ini b/platformio.ini index 46b7313..4f8dd74 100644 --- a/platformio.ini +++ b/platformio.ini @@ -61,6 +61,9 @@ build_flags_common = -std=gnu++14 -DCORE_DEBUG_LEVEL=0 -DCONFIG_ASYNC_TCP_RUNNING_CORE=0 + ; F-070: route every abort()/assert/stack-overflow through our wrapper so the + ; reason string survives the reboot (src/Telemetry/CrashBreadcrumbs.cpp) + -Wl,--wrap=esp_system_abort ; ─────────────────────────────────────────────────────────────────────────────── ; VESPER Standard v1 — Kincony KC868-A6 (ESP32-D0WD-V3, 4MB Flash) diff --git a/src/Communication/CommunicationRouter/CommunicationRouter.cpp b/src/Communication/CommunicationRouter/CommunicationRouter.cpp index 8599dc6..4116fad 100644 --- a/src/Communication/CommunicationRouter/CommunicationRouter.cpp +++ b/src/Communication/CommunicationRouter/CommunicationRouter.cpp @@ -583,12 +583,9 @@ void CommunicationRouter::reportBootOnce() { payload["free_heap"] = (uint32_t)ESP.getFreeHeap(); const CrashReport& crash = _telemetry->getCrashReport(); - if (crash.available) { - JsonObject crashObj = payload["crash"].to(); - crashObj["task"] = crash.taskName; - crashObj["pc"] = crash.pc; - crashObj["exc_cause"] = crash.excCause; - crashObj["exc_vaddr"] = crash.excVaddr; + if (crash.available) _telemetry->writeCrashJson(payload["crash"].to()); + if (_telemetry->getPreCrashSnapshot().available) { + _telemetry->writePreCrashJson(payload["pre_crash"].to()); } publishInfo("boot_report", payload); diff --git a/src/Telemetry/CrashBreadcrumbs.cpp b/src/Telemetry/CrashBreadcrumbs.cpp new file mode 100644 index 0000000..5ca00d8 --- /dev/null +++ b/src/Telemetry/CrashBreadcrumbs.cpp @@ -0,0 +1,73 @@ +#include "CrashBreadcrumbs.hpp" + +#include +#include +#include +#include + +namespace { + constexpr uint32_t SNAPSHOT_MAGIC = 0x56534E50; // "VSNP" + constexpr uint32_t ABORT_MAGIC = 0x56414252; // "VABR" + + struct RtcBreadcrumbs { + uint32_t snapshotMagic; + uint32_t uptimeMs; + uint32_t freeHeap; + uint32_t largestBlock; + uint32_t minFreeHeap; + uint32_t abortMagic; + char abortMsg[sizeof(PreCrashSnapshot::abortMsg)]; + }; + + // Not zeroed on boot — that's the point. Validated by the magic words. + RTC_NOINIT_ATTR RtcBreadcrumbs s_rtc; +} + +// Link-time wrapper: every esp_system_abort() call in the SDK (abort, assert, +// stack-overflow hook) lands here first. Runs in whatever context aborted — +// possibly with the heap lock held or the flash cache disabled — so it only +// copies bytes into RTC memory: no allocation, no locks, no libc, IRAM only. +extern "C" void __real_esp_system_abort(const char* details) __attribute__((noreturn)); + +extern "C" void IRAM_ATTR __attribute__((noreturn)) __wrap_esp_system_abort(const char* details) { + size_t i = 0; + if (details) { + for (; i < sizeof(s_rtc.abortMsg) - 1 && details[i] != '\0'; i++) { + s_rtc.abortMsg[i] = details[i]; + } + } + s_rtc.abortMsg[i] = '\0'; + s_rtc.abortMagic = ABORT_MAGIC; + __real_esp_system_abort(details); +} + +namespace CrashBreadcrumbs { + +void updateSnapshot() { + s_rtc.uptimeMs = millis(); + s_rtc.freeHeap = heap_caps_get_free_size(MALLOC_CAP_8BIT); + s_rtc.largestBlock = heap_caps_get_largest_free_block(MALLOC_CAP_8BIT); + s_rtc.minFreeHeap = heap_caps_get_minimum_free_size(MALLOC_CAP_8BIT); + s_rtc.snapshotMagic = SNAPSHOT_MAGIC; +} + +PreCrashSnapshot consume() { + PreCrashSnapshot out; + if (s_rtc.snapshotMagic == SNAPSHOT_MAGIC) { + out.available = true; + out.uptimeMs = s_rtc.uptimeMs; + out.freeHeap = s_rtc.freeHeap; + out.largestBlock = s_rtc.largestBlock; + out.minFreeHeap = s_rtc.minFreeHeap; + } + if (s_rtc.abortMagic == ABORT_MAGIC) { + out.available = true; + memcpy(out.abortMsg, s_rtc.abortMsg, sizeof(out.abortMsg)); + out.abortMsg[sizeof(out.abortMsg) - 1] = '\0'; + } + s_rtc.snapshotMagic = 0; + s_rtc.abortMagic = 0; + return out; +} + +} diff --git a/src/Telemetry/CrashBreadcrumbs.hpp b/src/Telemetry/CrashBreadcrumbs.hpp new file mode 100644 index 0000000..5b67394 --- /dev/null +++ b/src/Telemetry/CrashBreadcrumbs.hpp @@ -0,0 +1,43 @@ +#pragma once +#include +#include + +// ════════════════════════════════════════════════════════════════════════════ +// CRASH BREADCRUMBS — context that survives a panic reboot (F-070) +// ════════════════════════════════════════════════════════════════════════════ +// The coredump summary (see Telemetry::captureCrashReport) only knows the CPU +// state at the moment the chip went down. For an abort() — unhandled C++ +// exception, failed assert, FreeRTOS stack-overflow check — that state is +// panic_abort()'s own deliberate write to address 0, so PC/cause/vaddr say +// nothing about *why* (see F-055). Two things fill that gap, both kept in +// RTC_NOINIT memory, which survives software/panic/watchdog resets but NOT +// power-on or brownout: +// +// 1. The abort reason string — captured by wrapping esp_system_abort() at +// link time (-Wl,--wrap=esp_system_abort in platformio.ini). Every abort +// path in this SDK funnels through it: abort() ("abort() was called at PC +// 0x... on core N" — that PC is abort()'s caller), assert ("assert failed: +// func file:line (expr)"), and the FreeRTOS stack-overflow hook. +// 2. A heap/uptime snapshot refreshed every second by TelemetryTask — the +// last known state right before the reset (fragmentation killed us once). +// +// Both are consumed once at boot and cleared, so they're reported exactly once. + +struct PreCrashSnapshot { + bool available = false; + uint32_t uptimeMs = 0; // millis() at the last snapshot before the reset + uint32_t freeHeap = 0; // free heap at that snapshot + uint32_t largestBlock = 0; // largest allocatable block at that snapshot + uint32_t minFreeHeap = 0; // lowest free heap ever seen during that boot + char abortMsg[160] = {0}; // empty unless the reset came from esp_system_abort() +}; + +namespace CrashBreadcrumbs { + // Refresh the heap/uptime snapshot. Cheap; called from TelemetryTask every 1s. + void updateSnapshot(); + + // Read whatever the previous boot left behind, then clear it. Call once, + // early in boot, and only trust the result on a fault-class reset — RTC + // memory is garbage after a power-on, which the magic check guards against. + PreCrashSnapshot consume(); +} diff --git a/src/Telemetry/Telemetry.cpp b/src/Telemetry/Telemetry.cpp index f45a15c..d16705d 100644 Binary files a/src/Telemetry/Telemetry.cpp and b/src/Telemetry/Telemetry.cpp differ diff --git a/src/Telemetry/Telemetry.hpp b/src/Telemetry/Telemetry.hpp index 296e020..f77d89c 100644 --- a/src/Telemetry/Telemetry.hpp +++ b/src/Telemetry/Telemetry.hpp @@ -66,6 +66,7 @@ // panic handler automatically on every crash (already enabled in this project's SDK // build; no custom panic hook needed). See CrashReport below. #include +#include "CrashBreadcrumbs.hpp" // Most recent crash's coredump summary, captured once at begin() and erased from // flash immediately after reading so it's reported exactly once. Empty/zeroed @@ -77,6 +78,13 @@ struct CrashReport { uint32_t pc = 0; // Program counter at exception uint32_t excCause = 0; // Xtensa exception cause code uint32_t excVaddr = 0; // Faulting virtual address + // F-070: backtrace of the faulting task (decode with addr2line against the + // ELF whose SHA matches elfSha). For an abort() the first frames are the + // abort machinery; the real call site follows. + uint32_t backtrace[16] = {0}; + uint8_t backtraceDepth = 0; + bool backtraceCorrupted = false; + char elfSha[APP_ELF_SHA256_SZ] = {0}; // first 16 hex chars of the crashing app's ELF SHA-256 }; // Maximum number of boot log entries retained on SD (rotating) @@ -154,6 +162,10 @@ private: // Most recent crash's coredump summary, if any — read once at begin(). CrashReport crashReport; + // Abort reason + last heap/uptime snapshot from before a fault reset, if + // the previous boot left them in RTC memory (F-070). See CrashBreadcrumbs.hpp. + PreCrashSnapshot preCrash; + // Diagnostics — CPU temperature sampled locally every 15s, reduced to // min/max/avg between 5-minute batch reports. See RunningStats above for // why only temperature needs local sampling (stack high-water and the @@ -235,6 +247,12 @@ public: // if one was captured. available == false when the last reset wasn't a crash, // or no coredump was found for one that was. const CrashReport& getCrashReport() const { return crashReport; } + const PreCrashSnapshot& getPreCrashSnapshot() const { return preCrash; } + + // Serialize the above into the shared JSON shape used by the MQTT + // boot_report and the SD boot log. Callers check .available first. + void writeCrashJson(JsonObject out) const; + void writePreCrashJson(JsonObject out) const; // Reset reason (captured once at begin(), before anything else can crash again) esp_reset_reason_t getResetReason() const { return resetReason; }