Skip to content

fix(stl): make_shared must not construct on null under OOM (#3588 root cause) - #3603

Merged
zackees merged 1 commit into
masterfrom
fix/3588-make-shared-oom-null-construct
Jul 5, 2026
Merged

zackees merged 1 commit into
masterfrom
fix/3588-make-shared-oom-null-construct

Conversation

@zackees

@zackees zackees commented Jul 5, 2026 •

Copy link
Copy Markdown
Member

Root cause of #3588 (found by reproducing with NO WiFi)

Leaking heap down to the ~23 KB an active SoftAP leaves reproduces the crash with WiFi off — proving WiFi was incidental (it only consumed heap).

fl::make_shared<T>() did new InlinedControlBlock<T>(). That class's custom operator new returns null under OOM, but the new-expression still ran the constructor on the null pointer (writing through ~address 0), and the if (control == nullptr) guard was dead code (it ran after the null construction). Under low heap, every make_shared<json_value> in the RPC response path corrupted a neighbouring shared_ptr control block — detonating later as the wild-pointer refcount decrement in remove_shared_ref() from the issue. Host ASAN never sees it (the host never fails the allocation).

Fixes

  • shared_ptr.h — make_shared allocates the control block, null-checks it, then placement-constructs. This is the corruption fix.
  • flat_map.h — operator[] no longer dereferences end() after a failed OOM insert (that returned a ref one past the buffer); returns a discardable SingletonShared sink instead.
  • json.h — guard methods that deref mValue right after a make_shared that can now return empty under OOM.

Why OOM happened at all

  • FASTLED_STR_INLINED_SIZE 64 → 32. Every fl::string carried a 64-byte inline buffer, and since json_value's variant is sized to fl::string, every json value (even an int/bool) paid for it. Halving it freed ~11 KB baseline heap on the bench (34 KB free after SoftAP vs ~23 KB).

Verified

500 help calls at a forced ~23 KB heap (no WiFi) — no crash; 200 help under active SoftAP — no crash. Host 349/349 (fixed two tests that hard-coded position-50 assuming a ≥40-byte inline buffer). Lint clean.

Large responses building under concurrent traffic can still exhaust memory — a separate response-size problem being addressed by async streaming in a follow-up.

Fixes #3588.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes

    • Improved safety when memory is tight by preventing invalid string, map, and JSON operations from dereferencing unavailable storage.
    • flat_map now safely handles failed inserts without returning corrupted references.
    • json now gracefully skips or returns empty values when automatic container creation cannot allocate memory.
    • make_shared now more reliably returns an empty result when allocation fails.
  • Tests

    • Updated string search coverage to use inline-buffer-relative positions, keeping checks valid with the new default string size.

…r OOM (#3588 root cause)

ROOT CAUSE of #3588, found by reproducing the crash with NO WiFi at all —
just by leaking heap down to the ~23 KB an active SoftAP leaves:

  fl::make_shared<T>() did `auto* control = new InlinedControlBlock<T>()`.
  InlinedControlBlock's custom operator new returns null under OOM, but
  the new-expression still ran the constructor on that null pointer
  (writing through address 0 / a small offset from it), and the
  subsequent `if (control == nullptr)` guard was DEAD CODE — it ran only
  after the null construction had already corrupted memory. Under low
  free heap every make_shared<json_value> in the JSON-RPC response path
  faulted, and the stray writes corrupted neighbouring shared_ptr control
  blocks — detonating later as the wild-pointer refcount decrement in
  ControlBlockBase::remove_shared_ref() reported on the issue. WiFi was
  purely incidental: it only consumed heap to reach the low-heap regime
  (verified — the crash reproduces identically with WiFi off once heap is
  leaked to the same level, and host ASAN never sees it because the host
  never fails the allocation).

Fixes, smallest-blast-radius first:
- shared_ptr.h: make_shared now allocates the control block's raw memory
  explicitly, null-checks it, and only then placement-constructs. No
  reliance on new-expression null semantics. THIS is the corruption fix.
- flat_map.h: operator[] no longer dereferences end() after a failed
  (OOM) insert — that returned a reference one past the buffer and the
  caller's write corrupted the adjacent block. It now returns a
  discardable SingletonShared sink (cross-DLL safe), so a failed insert
  is a graceful no-op.
- json.h: guard the handful of methods that dereference mValue right
  after a make_shared that can now legitimately return empty under OOM.

Root memory reduction (why OOM happened at all):
- FASTLED_STR_INLINED_SIZE 64 -> 32. Every fl::string carried a 64-byte
  inline buffer, and because fl::json_value's variant is sized to its
  largest alternative (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. Halving the inline buffer freed ~11 KB of baseline
  heap on the AutoResearch bench (34 KB free after SoftAP vs ~23 KB
  before) and lets typical responses build without exhausting the heap.

Verified: 500 `help` calls at a forced ~23 KB free heap (no WiFi) with no
crash; 200 `help` calls under an active SoftAP with no crash. Host
349/349 (two string-search tests had hard-coded position-50 assumptions
that assumed a >=40-byte inline buffer; made them inline-size-relative).
Lint clean.

Note: large responses (e.g. help with ~200 methods, runSingleTest under
concurrent WiFi traffic) can still exhaust memory during construction —
that is a separate response-size problem addressed by async streaming in
a follow-up, not heap corruption.

Co-Authored-By: Claude Fable 5 <[email protected]>
@fastled-project-sync fastled-project-sync Bot moved this to Triage in FastLED Tracker Jul 5, 2026
@zackees
zackees merged commit 4c6414e into master Jul 5, 2026
10 of 11 checks passed
@coderabbitai

coderabbitai Bot commented Jul 5, 2026 •

Copy link
Copy Markdown

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: fc3ef4d6-8214-49e5-8194-9e8adca747bc

📥 Commits

Reviewing files that changed from the base of the PR and between fbeb889 and e8ce4a5.

📒 Files selected for processing (6)
  • src/fl/stl/flat_map.h
  • src/fl/stl/json.h
  • src/fl/stl/shared_ptr.h
  • src/fl/stl/string.h
  • tests/fl/stl/string_search_a.cpp
  • tests/fl/stl/string_search_b.cpp

📝 Walkthrough

Walkthrough

This PR hardens allocation-failure paths across fl::make_shared, fl::json, and fl::flat_map, preventing null-pointer dereference and heap corruption when allocations fail under memory pressure. Additionally, the default fl::string inline buffer size is reduced from 64 to 32, with corresponding test adjustments for heap-string boundary positions.

Changes

Allocation-failure hardening

Layer / File(s) Summary
make_shared allocation/construction split
src/fl/stl/shared_ptr.h
Separates raw memory allocation from object construction, null-checking allocated memory before placement-new to avoid constructing on a null pointer.
json null mValue guards
src/fl/stl/json.h
Adds null checks for mValue after make_shared calls in the vector-float constructor/assignment, operator[] overloads, set, and push_back, returning early or a null json instead of dereferencing.
flat_map operator[] insertion-failure fallback
src/fl/stl/flat_map.h
Includes fl/stl/singleton.h; when mData.insert fails, returns a process-lifetime SingletonShared sink reference instead of asserting and calling find on a potentially invalid entry.
Reduced default string inline size and heap-boundary tests
src/fl/stl/string.h, tests/fl/stl/string_search_a.cpp, tests/fl/stl/string_search_b.cpp
Changes default FASTLED_STR_INLINED_SIZE from 64 to 32; updates heap-string search tests to compute expected match positions relative to FASTLED_STR_INLINED_SIZE instead of fixed offsets.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant flat_map as "fl::flat_map"
    participant Vector as "mData (vector)"
    participant Singleton as "SingletonShared"

    Caller->>flat_map: operator[](key)
    flat_map->>Vector: insert(key, Value())
    alt insert succeeds
        Vector-->>flat_map: success
        flat_map->>Vector: find(key)
        flat_map-->>Caller: reference to inserted value
    else insert fails (OOM)
        Vector-->>flat_map: failure
        flat_map->>Singleton: get shared sink instance
        Singleton-->>flat_map: sink reference
        flat_map->>Singleton: assign Value()
        flat_map-->>Caller: reference to sink (write dropped)
    end
Loading
sequenceDiagram
    participant Caller
    participant json as "fl::json"
    participant MakeShared as "fl::make_shared"

    Caller->>json: set(key, value) / push_back(value) / operator[]
    json->>MakeShared: make_shared<json_value>(...)
    alt allocation succeeds
        MakeShared-->>json: valid shared_ptr
        json->>json: mutate mValue (array/object)
        json-->>Caller: updated json / reference
    else allocation fails (OOM)
        MakeShared-->>json: null shared_ptr
        json->>json: detect null mValue
        json-->>Caller: no-op return / json(nullptr)
    end
Loading

Estimated code review effort: 3 (Moderate) | ~25 minutes

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/3588-make-shared-oom-null-construct

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@fastled-project-sync fastled-project-sync Bot moved this from Triage to Done in FastLED Tracker Jul 5, 2026
eelstretching pushed a commit to eelstretching/FastLED-pico that referenced this pull request Jul 11, 2026
…r OOM (FastLED#3588 root cause) (FastLED#3603)

ROOT CAUSE of FastLED#3588, found by reproducing the crash with NO WiFi at all —
just by leaking heap down to the ~23 KB an active SoftAP leaves:

  fl::make_shared<T>() did `auto* control = new InlinedControlBlock<T>()`.
  InlinedControlBlock's custom operator new returns null under OOM, but
  the new-expression still ran the constructor on that null pointer
  (writing through address 0 / a small offset from it), and the
  subsequent `if (control == nullptr)` guard was DEAD CODE — it ran only
  after the null construction had already corrupted memory. Under low
  free heap every make_shared<json_value> in the JSON-RPC response path
  faulted, and the stray writes corrupted neighbouring shared_ptr control
  blocks — detonating later as the wild-pointer refcount decrement in
  ControlBlockBase::remove_shared_ref() reported on the issue. WiFi was
  purely incidental: it only consumed heap to reach the low-heap regime
  (verified — the crash reproduces identically with WiFi off once heap is
  leaked to the same level, and host ASAN never sees it because the host
  never fails the allocation).

Fixes, smallest-blast-radius first:
- shared_ptr.h: make_shared now allocates the control block's raw memory
  explicitly, null-checks it, and only then placement-constructs. No
  reliance on new-expression null semantics. THIS is the corruption fix.
- flat_map.h: operator[] no longer dereferences end() after a failed
  (OOM) insert — that returned a reference one past the buffer and the
  caller's write corrupted the adjacent block. It now returns a
  discardable SingletonShared sink (cross-DLL safe), so a failed insert
  is a graceful no-op.
- json.h: guard the handful of methods that dereference mValue right
  after a make_shared that can now legitimately return empty under OOM.

Root memory reduction (why OOM happened at all):
- FASTLED_STR_INLINED_SIZE 64 -> 32. Every fl::string carried a 64-byte
  inline buffer, and because fl::json_value's variant is sized to its
  largest alternative (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. Halving the inline buffer freed ~11 KB of baseline
  heap on the AutoResearch bench (34 KB free after SoftAP vs ~23 KB
  before) and lets typical responses build without exhausting the heap.

Verified: 500 `help` calls at a forced ~23 KB free heap (no WiFi) with no
crash; 200 `help` calls under an active SoftAP with no crash. Host
349/349 (two string-search tests had hard-coded position-50 assumptions
that assumed a >=40-byte inline buffer; made them inline-size-relative).
Lint clean.

Note: large responses (e.g. help with ~200 methods, runSingleTest under
concurrent WiFi traffic) can still exhaust memory during construction —
that is a separate response-size problem addressed by async streaming in
a follow-up, not heap corruption.

Co-authored-by: Claude Fable 5 <[email protected]>
@zackees
zackees deleted the fix/3588-make-shared-oom-null-construct branch August 21, 2026 19:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

1 participant