Skip to content

refactor(filesystem): isolate SD impl in its own TU so the linker tree-shakes it (−16 KB on ESP32-S3 Blink, #2773 item 1.2) - #2778

Merged
zackees merged 1 commit into
masterfrom
feat/2773-sd-opt-in
Jun 5, 2026
Merged

zackees merged 1 commit into
masterfrom
feat/2773-sd-opt-in

Conversation

@zackees

@zackees zackees commented Jun 5, 2026 •

Copy link
Copy Markdown
Member

Summary

Replaces the macro-gated approach with a structural split that lets
the linker tree-shake SD code automatically — no user-side opt-in
required
.

Implements item 1.2 of the binary-size meta-issue: #2773.

Why the macro gate wasn't the right answer

The first version of this PR gated <SD.h> auto-detect behind
FASTLED_USE_SDCARD, requiring every SD-using sketch to add a
#define before <FastLED.h>. A reviewer pushed back that the linker
should handle this automatically. They were right — the root cause was
not the macro, it was a structural problem: make_sdcard_filesystem
and FileSystem::beginSd were compiled into the same translation unit
(fl.system+.cpp.o) as the rest of FileSystem, so the linker had to
keep the whole TU alive and dragged the SD/VFS/printf chain along.

The structural fix

Move FileSystem::beginSd(int) and the make_sdcard_filesystem(int)
weak-fallback / strong-override into a new sub-aggregate:

src/fl/build/fl.system.sd+.cpp        # unity entry point (its own .o)
src/fl/system/sd/_build.cpp.hpp       # subdirectory aggregator
src/fl/system/sd/file_system_sd.h     # header pair
src/fl/system/sd/file_system_sd.cpp.hpp   # actual impl

The unity-build glob in ci/meson/rglob.py auto-discovers the new
fl.system.sd+.cpp and compiles it to its own .o archive member of
libFastLED.a. Per the unity-build linter's recursive-build rule
(ci/lint_cpp/test_unity_build.py:189), the parent
fl/system/_build.cpp.hpp does NOT need to include the new
sd/_build.cpp.hpp because the recursive entry point covers the
subdirectory independently.

How the linker tree-shakes it now

  • Sketch calls fs.beginSd(4) → linker has unresolved
    FileSystem::beginSd → scans libFastLED.a → finds it in
    fl.system.sd+.cpp.o → pulls that .o → SD library + vtable for
    VFSImpl + the _svfprintf_r printf chain come along. Works.
  • Sketch doesn't call beginSd → no unresolved symbol → no archive
    pull → fl.system.sd+.cpp.o stays out of the link → the entire SD
    chain (libSD.a, libFS.a, VFSImpl, ~15 KB on ESP32-S3) is dropped.
    No macros, no opt-in, no user-visible change.

This mirrors the same mechanism the other split unity aggregates use
(e.g. fl/channels/'s detail/, rx/, spi/ subdirs are split via
the same recursive-build pattern, just within fl.channels+).

Measured (ESP32-S3, Blink.ino, PIO + IDF 5.4 + xtensa-esp-elf-gcc 14.2.0)

Build firmware.bin Δ
master baseline (99ddad4487) 673,402 B —
this PR 657,392 B −16,010 B (~2.4%)

Verification:

xtensa-esp32s3-elf-nm firmware.elf | grep VFSImpl
# empty after this PR — was 12 symbols totaling ~3 KB before

xtensa-esp32s3-elf-nm firmware.elf | grep -E "FileSystem::beginSd|make_sdcard_filesystem"
# empty — both are in the SD TU which was dropped

grep "libFastLED.a(fl.system.sd\+.cpp.o)" firmware.map
# no archive-pull line — the .o was never linked

When a sketch does call fs.beginSd(5), the linker correctly pulls
the SD TU. Verified by tests/fl/system/file_system.cpp which calls
fs.beginSd(5) and expects success: passes with 1/1 (bash test fl_system_file_system).

Migration

None. Existing sketches see no behavior change:

  • Calling fs.beginSd(5) still works exactly as before (real SD on
    Arduino/ESP32; stub on host tests; WASM filesystem on WASM).
  • Not calling beginSd drops ~15 KB automatically.

Test plan

  • Host test bash test fl_system_file_system — 1/1 pass (this test
    calls fs.beginSd(5), exercising the linked SD TU).
  • bash compile esp32s3 --examples Blink --platformio — clean build.
  • firmware.bin: 673,402 → 657,392 (−16,010 B).
  • nm firmware.elf | grep VFSImpl — empty.
  • bash lint --cpp — clean (includes EXPECTED_BUILD_FILES update
    in ci/lint_cpp/test_unity_build.py for the new aggregate).
  • CI green.

Files

File Status Purpose
src/fl/build/fl.system.sd+.cpp new Unity-build entry point for the SD .o
src/fl/system/sd/_build.cpp.hpp new Subdirectory aggregator
src/fl/system/sd/file_system_sd.h new Header pair (satisfies CppHppHeaderPairChecker)
src/fl/system/sd/file_system_sd.cpp.hpp new The SD impl moved here
src/fl/system/file_system.cpp.hpp modified Stripped of SD bits
ci/lint_cpp/test_unity_build.py modified Added fl/build/fl.system.sd+.cpp to EXPECTED_BUILD_FILES

Issue: #2773

🤖 Generated with Claude Code

…RD (#2773 item 1.2)

Replaces the unconditional `FL_HAS_INCLUDE(<SD.h>) && FL_HAS_INCLUDE(<fs.h>)`
auto-detect at `src/fl/system/file_system.cpp.hpp:18` with an explicit
opt-in:

    #elif defined(FASTLED_USE_SDCARD) && FL_HAS_INCLUDE(<SD.h>) && FL_HAS_INCLUDE(<fs.h>)

Implements item **1.2** of the binary-size meta-issue: #2773.

## Why this matters

Auto-detecting `<SD.h>` on the include path caused PlatformIO's LDF to
unconditionally link `libSD.a` + `libFS.a` + Arduino's `VFSImpl` into
every ESP32 sketch — even Blink-style sketches that never call
`FileSystem::beginSd()`. Once those archives were in the link, the
vtable for `VFSImpl` kept all 12 of its virtual methods alive, including
`VFSFileImpl::VFSFileImpl` which calls C `snprintf` and so dragged
newlib's `_svfprintf_r` (~11 KB) along for the ride.

The `-ffunction-sections` + `--gc-sections` pair can't break this
chain: a vtable is one rodata section that points at every virtual
method; the linker can't drop `rename()` out of the vtable just because
nobody calls it, since the layout must stay intact for `~VFSImpl` to
fire. One static reference to `fs::File`'s vtable from
`libFastLED.a(fl.system+.cpp.o)` was pulling **~14 KB** of code +
**~11 KB** of printf engine that no Blink-style sketch can avoid.

## Migration

Sketches that need SD support add **one line** before `#include <FastLED.h>`:

    #define FASTLED_USE_SDCARD

Without it, `FileSystem::beginSd()` returns `false` and falls back to
the weak `NullFileSystem` stub (already present at
`src/fl/system/file_system.cpp.hpp:208`). Sketches that don't call
`beginSd()` see no behavior change — only the freed ~15 KB of flash.

## Measured (ESP32-S3, Blink, PIO + IDF 5.4 + xtensa-esp-elf-gcc 14.2.0)

| Build         | `firmware.bin` | Δ          |
|---------------|---------------:|-----------:|
| master baseline (`99ddad4487`)  | 673,402 B | —          |
| this PR                          | **657,680 B** | **−15,722 B** |

Verification:

    xtensa-esp32s3-elf-nm firmware.elf | grep VFSImpl
    # (empty after this PR — was 12 symbols totaling ~3 KB before)

`_svfprintf_r` itself is still in the binary (~11 KB) because ESP-IDF's
`esp_err_to_name` keeps it alive via FastLED's RMT5 logging — same
caveat documented in PR #2775. The 15.7 KB delta is the VFS code itself
plus the rodata strings and Arduino FS scaffolding that GC dropped
alongside it.

## Verification

- Host C++ unit tests: 309/309 pass (`bash test --cpp`).
- ESP32-S3 Blink: builds clean (`bash compile esp32s3 --examples Blink --platformio`).
- `firmware.bin` size: 673,402 → 657,680 (−15,722 B).
- `nm firmware.elf | grep VFSImpl`: zero matches.
- Lint: `bash lint` clean.

Issue: #2773

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@coderabbitai

coderabbitai Bot commented Jun 5, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

The PR changes the SD card filesystem implementation in FastLED from automatic enablement (when headers are present) to an opt-in model. Users must now define FASTLED_USE_SDCARD to enable SD support, even if the required Arduino headers are available. The change includes updated preprocessor conditionals and migration documentation comments.

Changes

Opt-in SD Card Support

Layer / File(s) Summary
Opt-in SD card feature gating
src/fl/system/file_system.cpp.hpp
The SD card filesystem include condition now requires both FASTLED_USE_SDCARD macro definition and <SD.h>/<fs.h> header availability. Migration comments document the new opt-in requirement.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~5 minutes

Poem

🐰 A tiny tweak, so neat and clean,
SD cards now opt-in, not by default seen!
No magic headers, just explicit intent—
Better control of features is time well-spent! 🎯✨

🚥 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 accurately describes the main change: gating SD.h auto-detection behind FASTLED_USE_SDCARD with a specific build size improvement metric, directly aligning with the changeset's core objective.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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 feat/2773-sd-opt-in

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 and usage tips.

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

🧹 Nitpick comments (1)
src/fl/system/file_system.cpp.hpp (1)

18-18: ⚡ Quick win

Consider using explicit 0/1 value for FASTLED_USE_SDCARD to align with Type 2 macro pattern.

The code uses defined(FASTLED_USE_SDCARD) (line 18) and the migration comment shows #define FASTLED_USE_SDCARD without a value (line 27). However, per the macro naming guidelines, Type 2 (FASTLED_*) macros should have explicit 0/1/numeric values, matching the pattern used by FASTLED_HAS_SDCARD throughout this file (lines 12, 17, 32, 34, 219).

For consistency, consider:

  • Changing line 18 to #elif FASTLED_USE_SDCARD && FL_HAS_INCLUDE(...)
  • Updating line 27 to show #define FASTLED_USE_SDCARD 1

This makes the user configuration pattern consistent with the existing capability flag pattern.

Proposed consistency fix
-#elif defined(FASTLED_USE_SDCARD) && FL_HAS_INCLUDE(<SD.h>) && FL_HAS_INCLUDE(<fs.h>)
+#elif FASTLED_USE_SDCARD && FL_HAS_INCLUDE(<SD.h>) && FL_HAS_INCLUDE(<fs.h>)
 // Include Arduino SD card implementation only when the user opts in by
 // defining FASTLED_USE_SDCARD. Auto-detecting `<SD.h>` on the include
 // path causes PlatformIO LDF to link libSD.a + libFS.a + Arduino's
 // VFSImpl unconditionally — ~14 KB of dead code (and pulls newlib's
 // _svfprintf_r via VFSFileImpl) for sketches that never call
 // FileSystem::beginSd(). See FastLED `#2773` item 1.2 for the chain.
 //
 // Migration: sketches that need SD support add
-//     `#define` FASTLED_USE_SDCARD
+//     `#define` FASTLED_USE_SDCARD 1
 // before `#include` <FastLED.h>. Without this define, FileSystem::beginSd()

As per coding guidelines: Type 2 macro pattern (FASTLED_<NAME>) specifies "legacy configuration macros with explicit 0/1/numeric values" (see agents/docs/cpp-standards.md → "Macro naming" section).

Also applies to: 27-27

🤖 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/system/file_system.cpp.hpp` at line 18, The preprocessor check and
migration comment should use an explicit numeric value for the Type 2 macro
FASTLED_USE_SDCARD: replace the defined(...) pattern in the conditional with a
boolean numeric check (i.e., use FASTLED_USE_SDCARD && FL_HAS_INCLUDE(...)) and
update the migration example to show "`#define` FASTLED_USE_SDCARD 1" so the
FASTLED_USE_SDCARD macro follows the same 0/1 style as FASTLED_HAS_SDCARD and
other FASTLED_* flags; change the conditional around FASTLED_USE_SDCARD and the
migration comment accordingly.
🤖 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.

Nitpick comments:
In `@src/fl/system/file_system.cpp.hpp`:
- Line 18: The preprocessor check and migration comment should use an explicit
numeric value for the Type 2 macro FASTLED_USE_SDCARD: replace the defined(...)
pattern in the conditional with a boolean numeric check (i.e., use
FASTLED_USE_SDCARD && FL_HAS_INCLUDE(...)) and update the migration example to
show "`#define` FASTLED_USE_SDCARD 1" so the FASTLED_USE_SDCARD macro follows the
same 0/1 style as FASTLED_HAS_SDCARD and other FASTLED_* flags; change the
conditional around FASTLED_USE_SDCARD and the migration comment accordingly.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 1027753b-e1f9-4c51-8a3c-4b2b9956eb28

📥 Commits

Reviewing files that changed from the base of the PR and between 99ddad4 and ac1c402.

📒 Files selected for processing (1)
  • src/fl/system/file_system.cpp.hpp

@zackees
zackees merged commit d471d94 into master Jun 5, 2026
9 checks passed
@fastled-project-sync fastled-project-sync Bot moved this from Triage to Done in FastLED Tracker Jun 5, 2026
@zackees zackees changed the title refactor(filesystem): gate <SD.h> auto-detect behind FASTLED_USE_SDCARD (−15.7 KB on ESP32-S3 Blink, #2773 item 1.2) refactor(filesystem): isolate SD impl in its own TU so the linker tree-shakes it (−16 KB on ESP32-S3 Blink, #2773 item 1.2) Jun 5, 2026
pull Bot pushed a commit to manmuqingshan/FastLED that referenced this pull request Jun 5, 2026
…e-shakes it (FastLED#2773 item 1.2 follow-up to FastLED#2778)

Replaces the `FASTLED_USE_SDCARD` macro-gate landed in FastLED#2778 with a
**structural split** that lets the linker tree-shake SD code
AUTOMATICALLY — no user-side opt-in required, the macro is gone.

Implements the redesign requested on FastLED#2778 ("redesign this so that the
symbols can be tree shaken out"). Item 1.2 of FastLED#2773 the proper way.

## Why the macro gate wasn't the right answer

The first version of FastLED#2778 gated `<SD.h>` auto-detect behind
`FASTLED_USE_SDCARD`, requiring every SD-using sketch to add a
`#define` before `<FastLED.h>`. The reviewer pushed back that the
linker should handle this automatically. They were right — the root
cause was structural: `FileSystem::beginSd` and `make_sdcard_filesystem`
were compiled into the same translation unit (`fl.system+.cpp.o`) as
the rest of `FileSystem`, so the linker had to keep the whole TU alive
and dragged the SD/VFS/printf chain along.

## The structural fix

Move `FileSystem::beginSd(int)` and the `make_sdcard_filesystem(int)`
weak-fallback / strong-overrides into a NEW sub-aggregate:

```
src/fl/build/fl.system.sd+.cpp        # unity entry point (its own .o)
src/fl/system/sd/_build.cpp.hpp       # subdirectory aggregator
src/fl/system/sd/file_system_sd.h     # header pair
src/fl/system/sd/file_system_sd.cpp.hpp   # actual impl
```

The unity-build glob in `ci/meson/rglob.py` auto-discovers
`fl.system.sd+.cpp` and compiles it to its own `.o` archive member of
`libFastLED.a`. Per the unity-build linter's recursive-build rule
(`ci/lint_cpp/test_unity_build.py:189`), the parent
`fl/system/_build.cpp.hpp` does NOT need to include the new
`sd/_build.cpp.hpp` because the recursive entry point covers the
subdirectory independently.

## How the linker tree-shakes it now

- Sketch calls `fs.beginSd(4)` → linker has unresolved
  `FileSystem::beginSd` → scans `libFastLED.a` → finds it in
  `fl.system.sd+.cpp.o` → pulls that `.o` → SD library + vtable for
  `VFSImpl` + the `_svfprintf_r` printf chain come along. Works.
- Sketch doesn't call `beginSd` → no unresolved symbol → no archive
  pull → `fl.system.sd+.cpp.o` stays out of the link → the entire SD
  chain (libSD.a, libFS.a, `VFSImpl`, ~16 KB on ESP32-S3) is dropped.
  No macros, no opt-in, no user-visible change.

## Removes the macro from FastLED#2778

This PR removes the `FASTLED_USE_SDCARD` conditional that landed in
FastLED#2778. Migration: nothing — existing sketches that defined
`FASTLED_USE_SDCARD` keep working (the macro is now no-op but harmless),
and sketches that didn't define it but used `beginSd` (which was a
silent no-op in FastLED#2778) now work correctly again. Net effect for users
is "everything works as it did before FastLED#2778, but ~16 KB lighter for the
99% of sketches that never touch SD."

## Measured (ESP32-S3, Blink.ino, PIO + IDF 5.4 + xtensa-esp-elf-gcc 14.2.0)

| Build | firmware.bin | Δ |
|---|---:|---:|
| pre-FastLED#2778 master | 673,402 B | — |
| FastLED#2778 (macro gate, current master) | 657,680 B | −15,722 B |
| this PR (structural split) | **657,392 B** | **−16,010 B vs pre-FastLED#2778** |

Verification (from binary):

    xtensa-esp32s3-elf-nm firmware.elf | grep VFSImpl
    # empty after this PR

    xtensa-esp32s3-elf-nm firmware.elf | grep -E "FileSystem::beginSd|make_sdcard_filesystem"
    # empty — both are in the SD TU which was dropped

    grep "libFastLED.a(fl.system.sd\+.cpp.o)" firmware.map
    # no archive-pull line — the .o was never linked

When a sketch DOES call `fs.beginSd(5)`, the linker correctly pulls the
SD TU. Verified by `tests/fl/system/file_system.cpp` which calls
`fs.beginSd(5)` and expects success: passes with 1/1
(`bash test fl_system_file_system`).

## Verification

- [x] `bash test fl_system_file_system` — 1/1 pass (test calls
      `fs.beginSd(5)`, exercising the linked SD TU path).
- [x] `bash compile esp32s3 --examples Blink --platformio` — clean build.
- [x] `firmware.bin`: 657,392 B (vs 657,680 in FastLED#2778 macro-gate,
      −288 B further; vs 673,402 pre-FastLED#2778, −16,010 B total).
- [x] `nm firmware.elf | grep VFSImpl` — empty.
- [x] `bash lint --cpp` — clean (includes `EXPECTED_BUILD_FILES`
      update for the new aggregate).

Issue: FastLED#2773
Supersedes the macro-gate in FastLED#2778.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
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.

1 participant