Repository navigation
refactor(stl): move malloc/free hook pointer into a Singleton (#3484) - #3741
Conversation
Last remaining namespace-scope static in allocator.cpp.hpp. The slab registry (the ~1.5 KB .bss table this issue was mainly about) already moved in #3495; this finishes the file. Safe to call from inside Malloc()/Free(): Singleton<T>::instance() placement-news into a static char buffer and never touches the heap, so routing the hook lookup through it cannot recurse back into the allocator. That property is why this is a Singleton and not a lazily-heap-allocated holder. Scope note: gMallocFreeHook sits inside `#if defined(FASTLED_TESTING)`, so it never existed in firmware builds. This change is about removing the last file-scope mutable static from the file, not about flash/RAM savings -- there is no embedded bloat delta to show for it. Co-Authored-By: Claude <[email protected]>
📝 WalkthroughWalkthroughThe allocator test hook storage moves from a namespace-scope pointer to Singleton-backed state. Hook clearing and malloc/free interception paths now access the hook through the new accessor while retaining existing reentrancy and memory-guard behavior. ChangesAllocator hook migration
Estimated code review effort: 2 (Simple) | ~10 minutes Possibly related issues
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@src/fl/stl/allocator.cpp.hpp`:
- Around line 63-76: Make the hook state used by malloc_free_hook() safe for
concurrent first access without routing initialization through the allocator.
Update MallocFreeHookState and/or malloc_free_hook() to use thread-safe one-time
initialization and synchronized hook access, preserving the existing
Singleton-based storage and behavior for Malloc, Free, PSRamAllocate, and
PSRamDeallocate.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: e461d135-3f7c-467c-bc11-1705eaecabfa
📒 Files selected for processing (1)
src/fl/stl/allocator.cpp.hpp
| // Test hook interface pointer. Storage lives inside a Singleton so | ||
| // `--gc-sections` can drop it together with Singleton<T>::instance() when no | ||
| // test installs a hook (FastLED#3484 / #3481). | ||
| // Already inside this file's anonymous namespace. | ||
| // | ||
| // Safe to call from inside Malloc()/Free(): Singleton<T>::instance() | ||
| // placement-news into a static char buffer and never touches the heap, so | ||
| // routing the hook lookup through it cannot recurse back into the allocator. | ||
| struct MallocFreeHookState { | ||
| MallocFreeHook* hook = nullptr; | ||
| }; | ||
| inline MallocFreeHook*& malloc_free_hook() FL_NO_EXCEPT { | ||
| return fl::Singleton<MallocFreeHookState>::instance().hook; | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf 'Files:\n'
git ls-files | rg '(^|/)allocator\.cpp\.hpp$|Singleton|cpp-standards\.md$' || true
printf '\nallocator.cpp.hpp outline:\n'
fd -a 'allocator.cpp.hpp$' . | while read -r f; do
echo "== $f =="
wc -l "$f"
done
printf '\nallocator.cpp.hpp relevant sections:\n'
for f in $(git ls-files | rg '(^|/)allocator\.cpp\.hpp$'); do
echo "== $f lines 1-230 =="
sed -n '1,230p' "$f" | nl -ba | sed -n '1,230p'
done
printf '\nSingleton implementations/usages:\n'
rg -n "class Singleton|struct Singleton|template<.*Singleton|Singleton<|malloc_free_hook|MallocFreeHook" .Repository: FastLED/FastLED
Length of output: 478
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Behavioral probe for the exact Singleton sequence shape if header-only implementation can be inspected.
python3 - <<'PY'
from pathlib import Path
import re
paths = list(Path('.').rglob('*'))
matches = []
for p in Path('.').rglob('*'):
if p.is_file() and p.suffix in {'.h', '.hpp', '.cpp', '.cc', '.cxx'}:
txt = p.read_text(errors='ignore')
if 'Singleton' in txt or 'malloc_free_hook' in txt:
matches.append(str(p))
print('\n'.join(matches[:200]))
for p in Path('.').rglob('*'):
if p.is_file() and p.suffix in {'.h', '.hpp', '.cpp', '.cc', '.cxx'}:
txt = p.read_text(errors='ignore')
if re.search(r'Static.*Singleton|Singleton<.*::instance|static\s+.*ptr|placement(?:-| )new', txt, re.I):
print(f"\n--- {p} ---")
for i, line in enumerate(txt.splitlines(),1):
if any(tok in line for tok in ['Singleton', 'placement-new', 'placement new', 'static T*', 'if (!ptr)']):
print(f"{i}: {line}")
PYRepository: FastLED/FastLED
Length of output: 33747
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== allocator.cpp.hpp lines 1-230 =="
python3 - <<'PY'
from pathlib import Path
p = Path('src/fl/stl/allocator.cpp.hpp')
lines = p.read_text().splitlines()
for i in range(0, min(230, len(lines))):
print(f"{i+1}: {lines[i]}")
PY
echo
echo "== src/fl/stl/singleton.h =="
cat -n src/fl/stl/singleton.h
echo
echo "== allocation call sites involving malloc_free_hook =="
python3 - <<'PY'
from pathlib import Path
p = Path('src/fl/stl/allocator.cpp.hpp')
lines = p.read_text().splitlines()
for i, line in enumerate(lines, 1):
if 'malloc_free_hook()' in line or 'MallocFreeHook' in line or '`#include` "fl/stl/singleton.h"' in line:
print(f"{i}: {line}")
PYRepository: FastLED/FastLED
Length of output: 16212
🏁 Script executed:
#!/bin/bash
set -euo pipefail
python3 - <<'PY'
from pathlib import Path
import re
p = Path('src/fl/stl/allocator.cpp.hpp')
lines = p.read_text().splitlines()
for label, start, end in [('allocator 1-230', 0, 229), ('singleton', 0, 179)]:
file = Path('src/fl/stl/allocator.cpp.hpp') if label.startswith('allocator') else Path('src/fl/stl/singleton.h')
print(f"\n== {file} lines {start+1}-{end+1} ==")
for i in range(start, min(end, len(file.read_text().splitlines()))):
print(f"{i+1}: {file.read_text().splitlines()[i]}")
PY
echo
echo "== C++ memory-order probe concept equivalent =="
python3 - <<'PY'
# Not executing repository code; this models the cited Singleton instanceInner logic shape.
# Thread A and Thread B both see unconfigured static T* ptr == nullptr, each construction
# address resolves to the same static aligned buffer, and neither construction is guarded
# or synchronized across the static assignment.
print("Unsynchronized static ptr write/read can produce observed nullptr in another thread under C++ thread model; construction is not atomic across threads.")
PYRepository: FastLED/FastLED
Length of output: 15104
🏁 Script executed:
#!/bin/bash
set -euo pipefail
python3 - <<'PY'
from pathlib import Path
p = Path('src/fl/stl/allocator.cpp.hpp')
lines = p.read_text().splitlines()
for i in range(0, min(230, len(lines))):
print(f"{i+1}: {lines[i]}")
print("\n== src/fl/stl/singleton.h ==")
q = Path('src/fl/stl/singleton.h')
for i, line in enumerate(q.read_text().splitlines(), 1):
print(f"{i}: {line}")
print("\n== malloc_free_hook call sites ==")
for i, line in enumerate(lines, 1):
if 'malloc_free_hook()' in line or '#' in line or 'MallocFreeHook' in line:
print(f"{i}: {line}")
PYRepository: FastLED/FastLED
Length of output: 16782
Make the hook accessor race-free.
malloc_free_hook() lazily constructs fl::Singleton<MallocFreeHookState> from allocator paths (Malloc, Free, PSRamAllocate, PSRamDeallocate), while Singleton::instance() uses an unsynchronized static T* ptr and non-atomic placement-new sequence. Early concurrent allocation can see uninitialized singleton state or use partially constructed storage; eliminate first-access races here.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/fl/stl/allocator.cpp.hpp` around lines 63 - 76, Make the hook state used
by malloc_free_hook() safe for concurrent first access without routing
initialization through the allocator. Update MallocFreeHookState and/or
malloc_free_hook() to use thread-safe one-time initialization and synchronized
hook access, preserving the existing Singleton-based storage and behavior for
Malloc, Free, PSRamAllocate, and PSRamDeallocate.
Summary
Closes #3484.
Most of that issue was already done. Of the three statics it lists, the slab registry pair (
slab_registry[64]+slab_registry_count— the ~1.5 KB.bsstable the issue was mainly about) moved intofl::Singleton<SlabRegistryState>as part of #3495. This PR finishes the file by migrating the one remaining item,gMallocFreeHook.Why a Singleton specifically
malloc_free_hook()is called from insideMalloc()andFree()themselves, so the holder must not allocate.Singleton<T>::instance()placement-news into a static aligned char buffer and never touches the heap:A lazily heap-allocated holder here would recurse back into the allocator on first use. Verified before making the change; called out in a comment so it isn't "simplified" later.
Scope note — no bloat delta to report
The issue's acceptance criteria ask for
bash bloat esp32devbefore/after confirmation. That is not applicable to this particular static:gMallocFreeHookis inside#if defined(FASTLED_TESTING), so it never existed in firmware builds in the first place. The measurable elision win was the slab table, and that already landed in #3495. Flagging this rather than presenting a no-op diff as a saving.Testing
bash test --cpp --clean— 355/355 passbash test allocator— passes;tests/fl/stl/allocator.cppexercisesSetMallocFreeHookacross several cases, which is the path this PR changesfastled-lint --checker singleton_elision src/fl/stl/allocator.cpp.hpp— cleanbash lint— fully greenRelated finding (not addressed here)
While verifying, I found
singleton_elisionpasses on files that still carry mutable namespace-scope statics — e.g.flexio_driver.cpp.hppstill hassDmaChannel,sDmaComplete,sInitialized,sFlexIOPinand reports clean. So a green checker run does not imply the remaining Tier issues (#3485–#3491) are complete; they need to be verified by reading, not by the linter. Worth knowing before #3492 promotes the checker to hard-fail.🤖 Generated with Claude Code
Summary by CodeRabbit