Skip to content

refactor(stl): move malloc/free hook pointer into a Singleton (#3484) - #3741

Merged
zackees merged 1 commit into
masterfrom
fix/3484-allocator-hook-singleton
Jul 27, 2026
Merged

zackees merged 1 commit into
masterfrom
fix/3484-allocator-hook-singleton

Conversation

@zackees

@zackees zackees commented Jul 27, 2026 •

Copy link
Copy Markdown
Member

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 .bss table the issue was mainly about) moved into fl::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 inside Malloc() and Free() themselves, so the holder must not allocate. Singleton<T>::instance() placement-news into a static aligned char buffer and never touches the heap:

static AlignedStorage storage;
static T* ptr = nullptr;
if (!ptr) { ptr = new (&storage.data) T(); }

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 esp32dev before/after confirmation. That is not applicable to this particular static: gMallocFreeHook is 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 pass
  • bash test allocator — passes; tests/fl/stl/allocator.cpp exercises SetMallocFreeHook across several cases, which is the path this PR changes
  • fastled-lint --checker singleton_elision src/fl/stl/allocator.cpp.hpp — clean
  • bash lint — fully green

Related finding (not addressed here)

While verifying, I found singleton_elision passes on files that still carry mutable namespace-scope statics — e.g. flexio_driver.cpp.hpp still has sDmaChannel, sDmaComplete, sInitialized, sFlexIOPin and 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

  • Bug Fixes
    • Improved memory allocation testing behavior by making allocation and deallocation hooks more reliable.
    • Preserved existing memory safety protections and reentrancy handling while updating hook management.

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]>
@coderabbitai

coderabbitai Bot commented Jul 27, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

The 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.

Changes

Allocator hook migration

Layer / File(s) Summary
Hook state and call-site routing
src/fl/stl/allocator.cpp.hpp
Replaces gMallocFreeHook with Singleton-backed MallocFreeHookState, updates hook clearing, and routes PSRAM, malloc, and free hook calls through malloc_free_hook().

Estimated code review effort: 2 (Simple) | ~10 minutes

Possibly related issues

  • FastLED/FastLED issue 3481: The allocator hook state migration in this PR matches the issue’s described Singleton migration for allocator.cpp.hpp.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the main change: moving the malloc/free hook pointer into a Singleton.
Linked Issues check ✅ Passed The PR routes the remaining gMallocFreeHook state through Singleton as intended, matching the issue's remaining allocator-state migration.
Out of Scope Changes check ✅ Passed The changes stay within allocator state migration and do not introduce unrelated code.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ 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/3484-allocator-hook-singleton

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between ae9ccfb and 1a0311a.

📒 Files selected for processing (1)
  • src/fl/stl/allocator.cpp.hpp

Comment on lines +63 to +76
// 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;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 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}")
PY

Repository: 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}")
PY

Repository: 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.")
PY

Repository: 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}")
PY

Repository: 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.

@zackees
zackees merged commit 4edb418 into master Jul 27, 2026
14 checks passed
@fastled-project-sync fastled-project-sync Bot moved this from Triage to Done in FastLED Tracker Jul 27, 2026
@zackees
zackees deleted the fix/3484-allocator-hook-singleton 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

Development

Successfully merging this pull request may close these issues.

singleton: migrate fl/stl/allocator.cpp.hpp state (Tier 1a)

1 participant