Skip to content

Classic ESP32: heap corruption crash (LoadProhibited, garbage pointer) when AutoResearch HTTP server + client traffic runs alongside RPC response building #3588

Closed

Description

@zackees

Found during the #3576 Phase 7 WROOM I2S lane-count robustness sweep (dual-device bench: WROOM COM11 server, C6 COM9 client).

Repro (deterministic within the sweep timing, 2/2 runs)

  1. WROOM: startNetServer (SoftAP + asio HTTP server).
  2. C6: wifiConnect to the AP, then a tight runNetClientTest loop (HTTP GETs against the WROOM).
  3. WROOM: runSingleTest {driver:I2S, laneSizes:[10]} fired immediately after traffic starts.

→ WROOM panics building the response JSON:

Guru Meditation Error: Core 1 panic'ed (LoadProhibited)
PC 0x4011275e  EXCCAUSE 0x1c  EXCVADDR 0xcf012704
fl::detail::ControlBlockBase::remove_shared_ref()
fl::shared_ptr<fl::json_value>::reset()
fl::json::set(fl::string const&, fl::json const&)
fl::json::set(fl::string const&, long long)
AutoResearchRemoteControl::runSingleTestImpl(...)

EXCVADDR is a garbage pointer (0xcf012704), not null — this is NOT the known OOM/null-alloc family (#3569 forensics): a json_value control block was corrupted while the main task built the test response. Identical backtrace address-for-address across runs (deterministic heap layout).

Discriminators

  • Same test with AP-only (wifiAp, no HTTP server, no traffic): I2S 1/2/4/8/16 lanes all pass byte-exact. WiFi RF/coexistence is NOT the problem.
  • Same full scenario but with a 2 s settle between traffic start and the test: passed once (timing-sensitive).
  • After the crash+reboot the remaining sweep entries pass (WiFi gone).

Suspects (network stack, per program policy: fix in the stack)

  • asio HTTP server task stack overflow under concurrent accept/request while the main loop is blocked in runSingleTest (lwip backlog grows) — overflow corrupting adjacent heap.
  • Or a thread-safety hole between the HTTP server's connection handling (its own task / lwip callbacks) and main-task fl:: allocations.

Suggested first steps: uxTaskGetStackHighWaterMark on the server task under the repro; heap poisoning (CONFIG_HEAP_POISONING_COMPREHENSIVE) build to catch the corrupter red-handed.

Repro scripts archived in the bench scratchpad (sweep_with_wifi.py, repro_crash.py — WROOM+C6 orchestration over COM11/COM9).

Refs #3576.

🤖 Generated with Claude Code

Activity

  1. zackees commented on Jul 2, 2026

    @zackees
    MemberAuthor

    Investigation update — hardening landed (PR #3589), root cause still open. Full forensic record:

    Established facts (bench, WROOM COM11 + C6 COM9)

    1. AP-only + LED tests (1–16 lanes): stable across many runs.
    2. HTTP server up, zero requests: stable (3× 8-lane, heap intact at 21 KB free).
    3. Server + concurrent client requests during a test: crash within one request, reproducible 6/6 sweeps. Main task dies with LoadProhibited / StoreProhibited / LoadStoreAlignment at garbage EXCVADDRs (0xcf012704, 0xb3b04204, 0x00020003) inside json::set → shared_ptr<json_value>::reset → remove_shared_ref while building the RPC response. heap_caps_check_integrity_all = intact right before the test.
    4. Handler CONTENT is irrelevant: fl::json handlers, string-only handlers, and gutted Response::ok("x") handlers all crash (an earlier "gutted = stable" reading was a false negative — the device had silently rebooted).
    5. The C6 client was ALSO crashing (tick-hook WDT panic_abort — single-core starvation in blocking esp_http_client_perform), fixed in fix(stl/net): OOM + concurrency hardening from the #3588 crash hunt #3589; the WROOM crash persists with the stabilized client.
    6. Host-side reproduction attempt (tests/fl/stl/json_cross_thread.cpp, 3 threads × 2000+ iterations of the same workload shapes): ASAN-clean — the corruption needs ESP32-specific machinery.

    Ruled out

    Remaining suspects / next steps

    • fl::string COW (shared_ptr<StringHolder> heap storage) mutation semantics under cross-task copies.
    • ESP32-specific allocator path: DefaultAlloc tries heap_caps_malloc(MALLOC_CAP_SPIRAM) first on every fl::vector allocation (returns null on PSRAM-less WROOM — worth checking for side effects/TLB behavior, and it doubles allocator traffic).
    • Architectural fix worth considering regardless: marshal esp_http_server route-handler execution onto the main loop (FreeRTOS queue + response semaphore, like the POSIX impl's executor pumping) so no fl:: object work ever runs off the main task. Turns the whole bug class off.
    • On-target: heap poisoning needs an IDF rebuild (Arduino prebuilt libs can't flip CONFIG_HEAP_POISONING_*); a pioarduino IDF-source build of AutoResearch would let comprehensive poisoning catch the corrupter red-handed.

    Repro harness: sweep_with_wifi.py (bench scratchpad) crashes the WROOM within the first 1–2 tests, 6/6 runs.

  2. zackees commented on Jul 2, 2026

    @zackees
    MemberAuthor

    Elimination complete at the fl-software layer (PR #3597 merged). The esp_http_server route handlers are now fully marshaled onto the main task (no fl:: object ever constructed/mutated off the main task; busy loop → clean 5xx) — verified serving over the air — and the corruption still reproduces identically. Combined elimination table now:

    What remains: corruption of main-task fl::json internals within ~1 pattern whenever HTTP requests are being serviced by the IDF/lwip stack concurrently with an LED test, on classic ESP32, with every observable register/stack/heap metric healthy. The remaining candidates live below our layer (lwip/WiFi internals interacting with the RMT RX ISR timing, or newlib/heap internals under this interleave).

    Next concrete step (documented for pickup): build AutoResearch against IDF source (pioarduino IDF-build, not prebuilt arduino libs) with CONFIG_HEAP_POISONING_COMPREHENSIVE=y + CONFIG_FREERTOS_WATCHPOINT_END_OF_STACK=y; the poisoning check will name the corrupter on first touch. The repro (sweep_with_wifi.py) fires within the first 1–2 patterns, 9/9 runs this session.

  3. zackees commented on Jul 2, 2026

    @zackees
    MemberAuthor

    Heap-poisoning run complete + host replicas clean (PR #3598 merged). Refined signature:

    1. Built and ran the repro on the new esp32dev_heapdbg board (IDF libs rebuilt from source with CONFIG_HEAP_POISONING_COMPREHENSIVE). The crash reproduces — without any poisoning canary firing first. The corrupting write lands INSIDE a live allocation (block-interior), which comprehensive poisoning cannot see. Decoded poisoned-build backtrace pins the faulting op: the ATOMIC refcount decrement (__atomic_s32c1i_fetch_sub_4) dereferencing a garbage control-block pointer (EXCVADDR 0x23d54bfb) inside json::set(key, const char*) during response assembly.
    2. Host replicas are exhausted and ASAN-clean: exact response-assembly choreography ×200 with fragmentation churn (json_response_assembly.cpp), cross-thread workloads, trait-classification checks (json_pair_traits.cpp — pair is non-trivial, real move/destroy ops).
    3. Timing note: the garbage slot is released within MICROSECONDS of the response object's construction (single-threaded assembly window, no executor pumping between sets) — so the stomp happens either inside the set/insert machinery on-device (host says the machinery is clean) or from an ISR during those microsecond windows.

    Prepared next experiment for pickup (all assets ready): hardware watchpoint on the response map slot. Plan: temp fl::json::debugSlotAddr(key) accessor (5-liner, was prototyped this session), esp_cpu_set_watchpoint(0, slot, 8, WATCHPOINT_TRIGGER_ON_WO) armed between response.set calls and disarmed inside them (slots move on map growth; heap-free poison writes would false-positive during grows). A hit during the armed µs-windows names an ISR writer with a full panic backtrace. Boards/tooling: esp32dev_heapdbg for poisoning, sweep_with_wifi.py repro (fires in ≤2 patterns, 100% this session).

  4. zackees commented on Jul 2, 2026

    @zackees
    MemberAuthor

    Watchpoint round executed (single-slot watch on "success"): no hit; crash unchanged with a garbage control-block pointer in a DIFFERENT (unidentified) map slot. With ~30 response keys + 4×15 pattern keys and 2 hardware watchpoints, slot-picking via serial RPC is a losing game. This investigation now requires interactive JTAG (OpenOCD breakpoint on the response object's map storage at creation + hardware access trace), or an Espressif-side review. Everything else is exhausted and documented above: heap poisoning (interior-write, no canary), full software-theory elimination (marshaling/slab/OOM/stacks/ISR-allocs/traits), host ASAN replicas clean, exact decoded fault (atomic refcount decrement on garbage pointer inside json::set during response assembly, single-threaded µs window). Handoff assets merged: esp32dev_heapdbg board, sweep repro, edgeProbe suite, g_rmtrx telemetry, json regression tests.

  5. zackees commented on Jul 5, 2026

    @zackees
    MemberAuthor

    Signature sharpened dramatically this session (PRs #3599, #3597, #3589 merged). The corruption is now pinned to a single deterministic byte, which rewrites the earlier "garbage control block" description:

    • Under comprehensive heap poisoning the assert is CORRUPT HEAP: Bad tail at 0x3ffeb9ef. Expected 0xbaad5678 got 0xbaad5600 — i.e. exactly one byte was zeroed (0x78 → 0x00) at a fixed address, every run. 0x3ffeb9ef is the first byte of an IDF block's 4-byte tail canary, so this is a single-byte write one byte past the end of a heap block — a classic off-by-one, not a wild pointer.
    • The realloc that trips the assert (StringHolder::grow ← basic_string::append ← formatJsonResponse) is the detector, not the culprit — IDF only validates the canary on the next heap op touching that block. The stray write happened earlier.
    • A CPU store-watchpoint on that exact address did NOT fire before the corruption — even armed on both cores via esp_ipc_call_blocking. Proof-of-arm sentinel confirmed the arming path executed. Two implications: either the write is a DMA/bus-master store (Xtensa debug watchpoints don't observe peripheral DMA — WiFi, I2S, or RMT-RX are the active DMA masters), or the corrupter block is a non-StringHolder allocation whose live instance fell outside the arming window.

    Fixes shipped that did NOT cure it (but are real bugs): main-task handler marshaling (#3597), heap-ownership handshake for the marshaled request item — was writing through a freed stack frame on timeout (#3599), RMT-RX accumulation-copy underflow guard (#3599), OOM/slab/atomic hardening (#3589).

    Next concrete step (needs hardware I don't have on this bench): JTAG/OpenOCD with a hardware data watchpoint at 0x3ffeb9ef that catches DMA (not just CPU) writes, OR a heap-allocation-tracing build to identify the owner of the block ending at 0x3ffeb9ee and instrument that allocation's producer. If the write is DMA, the descriptor length of whichever engine (WiFi/I2S/RMT-RX) overruns by one byte is the fix site.

  6. zackees commented on Jul 5, 2026

    @zackees
    MemberAuthor

    Root-cause investigation — major narrowing (this session)

    Two prior beliefs were wrong and are corrected below; the corruptor is now tightly localized.

    Trigger: WiFi AP merely active — NOT HTTP, NOT a client, NOT RX traffic

    Systematic isolation on the WROOM bench (each 3×):

    • Full repro (AP + associated C6 + HTTP flood) → crashes. ✅ (known)
    • AP + associated C6 + zero HTTP requests → still crashes.
    • AP up + no client associated at all → still crashes.
    • No WiFi at all (same LED sweep + JSON-RPC over serial, thousands of iterations) → never crashes. ✅ (known)

    So the corruptor is not esp_http_server/request handling (that theory drove #3597 marshaling, which did not cure it) — it is simply the WiFi stack being active concurrently with the main task doing JSON response building. This also explains why marshaling handlers onto the main task (#3597), the SlabAllocator mutex (#3589), OOM hardening (#3589), and the fl::strncpy fix (#3602) all failed to cure it — none touch the WiFi path.

    Fault: atomic refcount decrement on a garbage control-block pointer

    Deterministic across runs — decoded backtrace:

    ControlBlockBase::remove_shared_ref()          // --shared_count : __atomic_fetch_sub_4  faults
     ← shared_ptr<json_value>::reset()
     ← fl::json::set(key, const json&)
     ← fl::json::set(key, const char*)              // destroying the stack-local temporary json
     ← runSingleTestImpl(...)
    

    The crash alternates between LoadProhibited and LoadStoreAlignment at that atomic sub — i.e. the shared_ptr's control-block pointer is garbage (an unaligned/wild value), so decrementing shared_count through it faults. The specific shared_ptr is the one backing the temporary json created inside json::set while assembling the response.

    The corrupting bytes are data-dependent, heap-derived garbage — NOT a fixed address

    Layout-shift experiment (leak a 4 KB block at boot so all later allocations move):

    • The crash site is unchanged (same PC, same code path) but the garbage control-block pointer value changes run-to-run (0x96ddab24, 0xcf8065fa, …) and with the heap shift.
    • Under CONFIG_HEAP_POISONING_COMPREHENSIVE the same event shows as Bad tail at 0x3ffeb9ef with only the first canary byte hit — i.e. the poison catch is just the leading byte of a larger, varying, data-dependent overwrite.

    So this is not a fixed-address dangling write and not a single constant null byte — it is variable heap content written over the memory backing a json_value control block.

    Why it is external to FastLED's JSON code

    Host ASAN is clean on the exact json::set / response-assembly choreography (tests/fl/stl/json_response_assembly.cpp, 200× with fragmentation churn). ASAN detects use-after-free and 1-byte heap overflows; if the corruption originated inside fl::json / fl::shared_ptr / the SlabAllocator logic, that test would fail. It does not. The corruption only appears on-device with WiFi active.

    Conclusion (cause)

    The most-supported cause is an errant write originating in the ESP-IDF WiFi stack (present whenever the AP is active, independent of application traffic) that lands in heap memory occupied by FastLED's fl::json control-block allocations, overwriting a shared_ptr control-block pointer with variable heap/DMA content. FastLED's JSON logic is provably correct in isolation; it is the collateral victim because its allocations neighbor the WiFi-touched region. FastLED-level mitigations (marshaling, allocator mutex, OOM/strncpy hardening) reduce the surface but cannot fix a write that originates below FastLED.

    Next step to name the exact writer (needs hardware)

    A JTAG data watchpoint on the victim control-block address that catches bus-master/DMA writes (a CPU-only store watchpoint on classic ESP32 did not fire, consistent with a DMA or cross-context write). Failing hardware access, an ESP-IDF WiFi issue should be filed with this reproduction (WiFi AP active + concurrent main-task heap churn → adjacent-heap corruption on classic ESP32 / ESP32-S3). Reproduction assets: esp32dev_heapdbg board, sweep_ap_only.py (AP up, no client — fires within ~1–2 patterns).

  7. moved this from Triage to Done in FastLED Trackeron Jul 5, 2026
  8. zackees commented on Jul 5, 2026

    @zackees
    MemberAuthor

    Root cause FOUND and FIXED — it was FastLED, not the WiFi stack (correcting my earlier comment)

    My earlier "the ESP-IDF WiFi stack writes into FastLED's heap" conclusion was wrong. A second-opinion pass (skeptical of blaming WiFi) proved the corruptor is entirely FastLED-side, and WiFi was purely incidental.

    Proof it isn't WiFi: the crash reproduces with WiFi completely off — just by leaking heap down to the ~23 KB an active SoftAP leaves (after setup ran healthy, matching WiFi's post-setup timing). Same remove_shared_ref wild-pointer signature. Host ASAN never catches it because the host never actually fails the allocation.

    The bug (fl::make_shared):

    auto* control = new detail::InlinedControlBlock<T>();  // custom operator new returns null under OOM
    if (control == nullptr) { return {}; }                 // DEAD CODE — runs AFTER the null ctor

    InlinedControlBlock's operator new returns null under OOM, but the new-expression still ran the constructor on the null pointer (writing through ~address 0), corrupting a neighbouring shared_ptr control block — which detonated later as the garbage-pointer refcount decrement in remove_shared_ref() reported here. Fixed by allocating the raw memory, null-checking it, then placement-constructing (#3603).

    Why the heap was exhausted in the first place (the deeper question): FASTLED_STR_INLINED_SIZE was 64, so every fl::string carried a 64-byte inline buffer — and because json_value's variant is sized to its largest member (fl::string), every json value (even an int or bool) paid for it. A single RPC response with a few hundred values consumed tens of KB. Reducing it to 32 freed ~11 KB of baseline heap on the bench (34 KB free after SoftAP vs ~23 KB before). Also fixed: flat_map::operator[] wrote one-past-the-buffer on a failed OOM insert (now returns a sink), and several fl::json methods dereferenced mValue after a make_shared that can now return empty.

    Verified: 500 help calls at a forced ~23 KB heap (no WiFi) and 200 under an active SoftAP — no crash. The heap corruption is resolved.

    Merged: #3602 (strncpy hardening), #3603 (root-cause fix + memory reduction — Fixes #3588), #3604 (JsonStreamWriter, a streaming serializer that emits any-size response through a fixed buffer — the mechanism to return very large responses like help with ~200 methods without an N-sized allocation; wiring it into the RPC transport is a tracked follow-up).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions