Skip to content

feat(lint): forbid raw pointers into fl:: container storage (#3287) - #3759

Merged
zackees merged 2 commits into
masterfrom
fix/3287-container-data-ptr-lint
Jul 29, 2026
Merged

zackees merged 2 commits into
masterfrom
fix/3287-container-data-ptr-lint

Conversation

@zackees

@zackees zackees commented Jul 29, 2026 •

Copy link
Copy Markdown
Member

Closes #3287.

Adds two checkers for the memory-safety pattern behind #3282 and #3286: treating an fl:: container as a contiguous buffer by taking a raw pointer into its storage. #3282's chunked deque turned &dq[0] into an immediate buffer overrun; #3286 was the same assumption crashing on macOS-arm64.

I measured the tree first, and it changed the design

Pattern Existing sites
.data() / &x[N] on non-contiguous (fl::deque, fl::circular_buffer) 0
&x[N] / &x.front() on contiguous (fl::vector, fl::string, …) 7
.data() on contiguous containers 463 — not flagged, idiomatic and safe

Because the dangerous tier has zero existing sites, it lands as a hard fail immediately, at zero migration cost. The UB class that caused two bugs now cannot come back. That felt worth more than a third warn-only stream nobody reads.

The contiguous tier is warn-only (registered in both lint_core/warn_only.rs and run_all_checkers.py; test_warn_only_checkers_sync.py pins them together). Those 7 are legal today — but brittle to exactly the layout change that bit the deque.

A blanket regex would have been unusable here: 463 legitimate .data() calls. So the checker is same-file type-aware — it records fl:: container declarations by name and kind, and only flags uses it can tie to a container of the relevant kind.

Two traps worth recording

1. The && operator. My first detection pass matched &\s*(\w+)\s*\[, which reads if (annexB[i] == 0 && annexB[i+1] == 0) as address-of — 7 false positives out of 11. The regex crate has no lookaround, so address-of detection is a hand-rolled scanner that rejects & adjacent to another & and disambiguates unary address-of from binary bitwise-AND by the preceding token. flags & a[i] is clean too. Pinned by container_ptr_does_not_match_logical_and_operator.

2. Raw-array shadowing. span<int,3> s(&arr[0], 3) in tests/fl/slice.cpp:367 false-positived because a sibling FL_SUBCASE in the same file declares fl::array<int,4> arr. Name matching is per-file, not scope-aware, so any name also declared as a raw C array anywhere in the file is dropped from the container map — raw arrays are explicitly out of scope for this issue. Pinned by container_ptr_drops_names_shadowed_by_raw_arrays.

Suppression

// fl-lint: container-data-ptr-ok, inline or on the preceding comment line — matching how SingletonElisionChecker handles FL_LINT_ALLOW_GLOBAL.

The 7 warn-tier sites (left for follow-up, not rewritten here)

  • src/fl/asset/asset.cpp.hpp:106 and src/platforms/esp/32/drivers/ble/ble_esp32.cpp.hpp:173 — both resize() an fl::string then write through &s[0] for C-API interop. Genuine buffer-base use; the clearest candidates for either a rewrite or a justified suppression.
  • Three mock accessors returning &vec[size()-1].
  • tests/fl/stl/string_search_b.cpp:915 — FL_CHECK(&ref == &s.at(0)), deliberately asserting element identity; a suppression comment is the right answer.
  • src/fl/channels/adapters/spi_channel_adapter.cpp.hpp:315 — group lookup.

I left these rather than bundling seven behavioral rewrites into a lint PR. Happy to follow up.

Verification

  • 0 hard-fail / 7 warn-only, confirmed from the binary directly and via bash lint
  • bash lint exit 0 · 357/357 C++ tests · warn-only sync test green
  • Rust tests 41/42 — the one failure is the pre-existing 1000-line cap on unity_build.rs (1205 lines), which fails on master too; the new checker file is 494 lines
  • End-to-end probe confirms all eight behaviors: deque.data() / &dq[0] / &dq.front() flagged hard; vector.data() clean; &v[0] warn; raw C array clean; && and bitwise & clean

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added new C++ lint checks to prevent unsafe raw-pointer usage into fl:: containers.
    • Hard-fails are now emitted for non-contiguous container .data() and element-address patterns.
    • Warning-only linting is added for brittle element-address patterns in contiguous containers.
    • Updated the checker set so both checks run and offer safer alternatives (e.g., fl::span, iterator ranges, or explicit copies).
  • Documentation

    • Documented the new “No Raw Pointers Into fl:: Containers” standard and the approved suppression token for C interop.
  • Tests

    • Expanded automated lint test coverage for detection, suppressions, regressions, and third-party exclusions.

Adds two checkers for the memory-safety pattern behind #3282 and #3286:
treating an fl:: container as a contiguous buffer by taking a raw pointer
into its storage. #3282's chunked deque made `&dq[0]` an immediate buffer
overrun; #3286 was the same assumption crashing on macOS-arm64.

Measured the tree before designing, and the result shaped the split:

- `.data()` / address-of-element on NON-contiguous containers
  (fl::deque, fl::circular_buffer): 0 existing sites. So
  ContainerNonContiguousPtrChecker lands as a HARD FAIL immediately, at
  zero migration cost. This is the actual UB class, and it now cannot
  come back.
- address-of-element on CONTIGUOUS containers (fl::vector, fl::string,
  ...): 7 existing sites. Legal today, but brittle to layout changes --
  exactly what bit the deque. ContainerElementAddressChecker is
  warn-only, registered in both lint_core/warn_only.rs and
  run_all_checkers.py (test_warn_only_checkers_sync.py pins them).

`.data()` on a contiguous container is NOT flagged; it is idiomatic and
there are 463 such calls. A blanket regex would have been unusable.

The checker is same-file type-aware: it records fl:: container
declarations by name and kind, then flags uses only for names it can tie
to a non-contiguous (or contiguous, for the warn tier) container. Names
also declared as a raw C array anywhere in the file are dropped, since
raw arrays are out of scope for #3287 -- without that guard,
`span<int,3> s(&arr[0], 3)` in tests/fl/slice.cpp false-positived off an
`fl::array arr` in a sibling subcase.

Address-of detection is a hand-rolled scanner, not a regex: the regex
crate has no lookaround, and a naive `&\s*(\w+)\s*\[` matches the `&&`
operator. `annexB[i] == 0 && annexB[i+1] == 0` produced 7 false
positives out of 11 during development. The scanner rejects `&` adjacent
to another `&` and disambiguates unary address-of from binary bitwise-AND
by the preceding token, so `flags & a[i]` is also clean. Both are pinned
by container_ptr_does_not_match_logical_and_operator.

Suppression: `// fl-lint: container-data-ptr-ok`, inline or on the
preceding comment line, matching how SingletonElisionChecker handles
FL_LINT_ALLOW_GLOBAL.

The 7 warn-tier sites are left for follow-up rather than rewritten here.
Two are genuine C-API interop (`asset.cpp.hpp:106` and
`ble_esp32.cpp.hpp:173` both resize an fl::string then write through
`&s[0]`), three are mock accessors returning `&vec[size()-1]`, one is a
test asserting element identity, and one is a group lookup.

Verified: 0 hard-fail / 7 warn-only from the binary and from `bash lint`;
`bash lint` exit 0; 357/357 C++ tests; 41/42 Rust tests (the one failure
is the pre-existing 1000-line cap on unity_build.rs, which fails on
master too); warn-only sync test green. An end-to-end probe confirms all
eight behaviors: deque data()/[0]/front() flagged hard, vector .data()
clean, vector &v[0] warn, raw array clean, && and bitwise & clean.

Co-Authored-By: Claude <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 29, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Adds two Rust C++ lint checkers for raw pointers into fl:: containers, classifying contiguous and non-contiguous storage, supporting suppressions and file filtering, registering warn-only behavior, documenting the rule, and adding comprehensive tests.

Changes

Container pointer linting

Layer / File(s) Summary
Lint contract and checker wiring
agents/docs/cpp-standards.md, ci/lint_cpp/run_all_checkers.py, ci/lint_cpp_rs/src/checkers/README.md, ci/lint_cpp_rs/src/lib.rs, ci/lint_cpp_rs/src/lint_core/{processor_registry_cli.rs,warn_only.rs}
Documents the new policy and registers contiguous and non-contiguous pointer checkers across the Rust crate, CLI, and warn-only configuration.
Container scanning and classification
ci/lint_cpp_rs/src/checkers/container_ptr.rs, ci/lint_cpp_rs/src/lint_core/regexes.rs
Preprocesses source files, classifies fl:: containers, parses declarations, handles raw-array name ambiguity, and filters supported paths.
Pointer detection and reporting
ci/lint_cpp_rs/src/checkers/container_ptr.rs
Detects .data() and element-address expressions, rejects logical-AND false positives, and emits hard-fail or warn-only violations by container kind.
Checker behavior validation
ci/lint_cpp_rs/src/lint_core/tests.rs
Tests detection, classification, suppression, comments and strings, raw arrays, shadowed names, false positives, and third-party path exclusion.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant SourceFile
  participant ContainerScan
  participant NonContiguousChecker
  participant ElementAddressChecker
  SourceFile->>ContainerScan: preprocess declarations and source lines
  ContainerScan-->>NonContiguousChecker: classified container scan
  ContainerScan-->>ElementAddressChecker: classified container scan
  NonContiguousChecker-->>SourceFile: hard-fail violations
  ElementAddressChecker-->>SourceFile: warn-only violations
Loading

Possibly related issues

Possibly related PRs

🚥 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 matches the PR’s main change: adding a lint rule to forbid raw pointers into fl:: container storage.
Linked Issues check ✅ Passed The changes add, wire, document, and test the new fl:: container raw-pointer lint checks requested in #3287.
Out of Scope Changes check ✅ Passed The modified files all support the lint rule, its wiring, tests, or documentation, with no clear unrelated additions.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ 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/3287-container-data-ptr-lint

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

🧹 Nitpick comments (1)
ci/lint_cpp_rs/src/lint_core/regexes.rs (1)

684-692: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Pointer-array declarations with a hugging * don't match.

\s*[*&]?\s+ requires whitespace after the *, so int *arr[4]; (the common style) isn't recognized as a raw array. That weakens the shadow-name guard in container_ptr.rs and can let an ambiguous name through as a false positive.

♻️ Suggested pattern tweak
-            r"^\s*(?:const\s+|volatile\s+|static\s+|constexpr\s+|unsigned\s+|signed\s+)*([A-Za-z_]\w*(?:::[A-Za-z_]\w*)*)\s*[*&]?\s+([A-Za-z_]\w*)\s*\[[^\]]*\]\s*(?:=|;)",
+            r"^\s*(?:const\s+|volatile\s+|static\s+|constexpr\s+|unsigned\s+|signed\s+)*([A-Za-z_]\w*(?:::[A-Za-z_]\w*)*)(?:\s*[*&]\s*|\s+)([A-Za-z_]\w*)\s*\[[^\]]*\]\s*(?:=|;)",
🤖 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 `@ci/lint_cpp_rs/src/lint_core/regexes.rs` around lines 684 - 692, Update
regex_raw_array_declaration so pointer and reference declarators match both
spaced and hugging styles, including int *arr[4];, without weakening existing
raw-array matches. Preserve the captured type and array-name groups used by the
shadow-name guard in container_ptr.rs.
🤖 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 `@ci/lint_cpp_rs/src/checkers/container_ptr.rs`:
- Around line 311-332: Update the receiver-parsing logic after `member_rest` is
extracted so member-qualified indexing expressions such as `this->mChunks[0]`
and `mState.mQueue[i]` are retained for declaration lookup. When the trailing
member identifier is followed by `[`, re-anchor the candidate on that member
name instead of requiring a `(` call suffix; preserve the existing handling for
method-qualified `at`, `front`, and `back` expressions.

---

Nitpick comments:
In `@ci/lint_cpp_rs/src/lint_core/regexes.rs`:
- Around line 684-692: Update regex_raw_array_declaration so pointer and
reference declarators match both spaced and hugging styles, including int
*arr[4];, without weakening existing raw-array matches. Preserve the captured
type and array-name groups used by the shadow-name guard in container_ptr.rs.
🪄 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: 494a5514-39da-4d49-b596-fb3047b67985

📥 Commits

Reviewing files that changed from the base of the PR and between f980b3b and 2f6829f.

📒 Files selected for processing (9)
  • agents/docs/cpp-standards.md
  • ci/lint_cpp/run_all_checkers.py
  • ci/lint_cpp_rs/src/checkers/README.md
  • ci/lint_cpp_rs/src/checkers/container_ptr.rs
  • ci/lint_cpp_rs/src/lib.rs
  • ci/lint_cpp_rs/src/lint_core/processor_registry_cli.rs
  • ci/lint_cpp_rs/src/lint_core/regexes.rs
  • ci/lint_cpp_rs/src/lint_core/tests.rs
  • ci/lint_cpp_rs/src/lint_core/warn_only.rs

@zackees

zackees commented Jul 29, 2026

Copy link
Copy Markdown
Member Author

Drive-by from another agent session — I'm not taking this PR over, just confirming CodeRabbit's finding is real, since it's easy to read as a nitpick and it isn't.

The gap is at container_ptr.rs:332:

let member = &member_rest[..member_length];
if !member_rest[member_length..].trim_start().starts_with('(') {
    continue;
}

For &this->dq[0], the parsed member is dq and what follows is [, not ( — so it hits continue and the use never reaches the declaration lookup. Same for &obj.dq[0] and &mState.mQueue[i].

Why that matters more than "minor": this PR's own design note says the whole-file declaration scan exists precisely so member containers can be resolved. So the shape the scan was built for is the shape the matcher drops. A checker that silently misses the common case while reporting green is worse than no checker — it's the same failure mode as #3482, where SingletonElisionChecker was registered, listed, and reported zero findings tree-wide for a one-character reason.

Worth adding a regression test alongside the fix, covering all three receiver forms:

fl::deque<int> dq;           // &dq[0]        — already caught
struct S { fl::deque<int> dq; } s;
// &s.dq[0]                  — currently missed
// &this->dq[0]              — currently missed

The third is the one that matters most in real driver code.

Leaving the fix to this PR's author. If it's still open next time I come around I'm happy to pick it up — just say so.

CodeRabbit review catch on #3759, and it was a hole in the HARD-FAIL
tier rather than a cosmetic gap.

find_element_address_uses parsed exactly one identifier after `&`, then
bailed whenever the following token was a `.`/`->` whose member was not
at/front/back. So `&this->mQueue[0]`, `&obj.mQueue[0]` and
`&state.inner.mQueue[2]` never reached the declaration lookup at all.
Members are the common shape for fl::deque FIELDS -- which is precisely
why the checker scans declarations across the whole file -- so the tier
meant to gate the #3282/#3286 UB could miss it.

The scanner now walks the full receiver chain and re-anchors on each
member, treating the LAST identifier before the subscript or accessor as
the container. An accessor call (`.front()`, `.at(...)`) terminates the
chain; a plain member access continues it.

Verified with an end-to-end probe: `&this->mQueue[0]`, `&mQueue[0]`,
`this->mQueue.data()`, `&this->mQueue.front()`, `&obj.mQueue[0]` and
`obj.mQueue.data()` all flag hard; `&this->mVec[0]` flags warn;
`this->mVec.data()`, `&raw[0]`, `&&` and bitwise `&` all stay clean --
7 hits, exactly as expected, up from 3 before the fix.

Tree counts are unchanged: still 0 hard-fail and 7 warn-only, so no
existing deque member misuse was hiding behind the gap and the hard-fail
tier remains safe to land.

Also fixes 4 byte constants that reached the file as literal tabs rather
than `\t` escapes, which broke the build.

Co-Authored-By: Claude <[email protected]>
@zackees

zackees commented Jul 29, 2026

Copy link
Copy Markdown
Member Author

Good catch, and it was worse than "minor" — this was a hole in the hard-fail tier, not just the warn tier.

Confirmed with a probe before fixing. &this->mQueue[0] and &obj.mQueue[0] on an fl::deque member were both silently skipped (3 hits where 7 were expected), while .data() through the same member access was caught — so the gap was specifically in the address-of path. Since members are the common shape for fl::deque fields, the tier meant to gate the #3282/#3286 UB could have missed exactly the case it exists for.

Fixed in d622041. find_element_address_uses now walks the full receiver chain and re-anchors on each member, treating the last identifier before the subscript or accessor as the container. An accessor call (.front(), .at(...)) terminates the chain; a plain member access continues it, so &state.inner.mQueue[2] resolves too.

Verified end-to-end — all 7 expected hits, up from 3:

expression result
&this->mQueue[0], &mQueue[0], this->mQueue.data(), &this->mQueue.front(), &obj.mQueue[0], obj.mQueue.data() hard-fail ✓
&this->mVec[0] warn ✓
this->mVec.data(), &raw[0], a && b[i], flags & a[i] clean ✓

Tree counts are unchanged at 0 hard-fail / 7 warn-only, so no existing deque member misuse was hiding behind the gap and the hard-fail tier is still safe to land.

Regression test added: container_ptr_follows_member_qualified_receivers.

@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 (2)
ci/lint_cpp_rs/src/checkers/container_ptr.rs (2)

293-301: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Trim the historical narrative from the comment.

Lines 298-301 explain a past bug rather than the current code; the PR/commit history already carries that. The first paragraph (Lines 293-296) is sufficient and stays accurate as the code evolves.

🤖 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 `@ci/lint_cpp_rs/src/checkers/container_ptr.rs` around lines 293 - 301, Shorten
the comment above the receiver-chain traversal to retain only the current
behavior described in the first paragraph, and remove the historical explanation
about skipped member-qualified receivers, fl::deque fields, and the hard-fail
tier.

324-382: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Clean up the dead cursor writes and use index += 1.

cursor is never read after the inner loop exits, so the four assignments before each break (Lines 327, 340, 357, 375) are dead, and Line 382 is a manual assign-op. Clippy flags all five; if the workspace builds with -D warnings this fails CI.

If the intent was to skip past the consumed receiver chain, advance index from cursor instead of dropping it.

♻️ Minimal cleanup
             if after < bytes.len() && bytes[after] == b'[' {
                 let form = format!("&{name}[...]");
                 uses.push((name, form));
-                cursor = after;
                 break;
             }
@@
             } else {
-                cursor = after;
                 break;
             };
@@
             if member_end == member_start {
-                cursor = member_end;
                 break;
             }
@@
                     _ => {}
                 }
-                cursor = paren;
                 break;
             }
@@
             cursor = member_start;
         }
-        index = index + 1;
+        index += 1;
🤖 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 `@ci/lint_cpp_rs/src/checkers/container_ptr.rs` around lines 324 - 382, Remove
the dead cursor assignments immediately before each inner-loop break in the
receiver-chain parsing logic, since cursor is not read after the loop exits.
Replace the manual index = index + 1 update with index += 1, while preserving
the existing chain parsing behavior.

Source: Linters/SAST tools

🤖 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 `@ci/lint_cpp_rs/src/checkers/container_ptr.rs`:
- Around line 293-301: Shorten the comment above the receiver-chain traversal to
retain only the current behavior described in the first paragraph, and remove
the historical explanation about skipped member-qualified receivers, fl::deque
fields, and the hard-fail tier.
- Around line 324-382: Remove the dead cursor assignments immediately before
each inner-loop break in the receiver-chain parsing logic, since cursor is not
read after the loop exits. Replace the manual index = index + 1 update with
index += 1, while preserving the existing chain parsing behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 6925ede1-7825-4ccd-a52f-e4fed335e606

📥 Commits

Reviewing files that changed from the base of the PR and between 2f6829f and d622041.

📒 Files selected for processing (2)
  • ci/lint_cpp_rs/src/checkers/container_ptr.rs
  • ci/lint_cpp_rs/src/lint_core/tests.rs

@zackees
zackees merged commit 5dc76fb into master Jul 29, 2026
17 checks passed
@fastled-project-sync fastled-project-sync Bot moved this from Triage to Done in FastLED Tracker Jul 29, 2026
@zackees
zackees deleted the fix/3287-container-data-ptr-lint 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.

cpp-lint: forbid &container[N] / .data() / &container.front() — require fl::span or iterators

1 participant