Repository navigation
feat(lint): forbid raw pointers into fl:: container storage (#3287) - #3759
Conversation
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]>
📝 WalkthroughWalkthroughAdds two Rust C++ lint checkers for raw pointers into ChangesContainer pointer linting
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
Possibly related issues
Possibly related PRs
🚥 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
🧹 Nitpick comments (1)
ci/lint_cpp_rs/src/lint_core/regexes.rs (1)
684-692: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winPointer-array declarations with a hugging
*don't match.
\s*[*&]?\s+requires whitespace after the*, soint *arr[4];(the common style) isn't recognized as a raw array. That weakens the shadow-name guard incontainer_ptr.rsand 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
📒 Files selected for processing (9)
agents/docs/cpp-standards.mdci/lint_cpp/run_all_checkers.pyci/lint_cpp_rs/src/checkers/README.mdci/lint_cpp_rs/src/checkers/container_ptr.rsci/lint_cpp_rs/src/lib.rsci/lint_cpp_rs/src/lint_core/processor_registry_cli.rsci/lint_cpp_rs/src/lint_core/regexes.rsci/lint_cpp_rs/src/lint_core/tests.rsci/lint_cpp_rs/src/lint_core/warn_only.rs
|
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 let member = &member_rest[..member_length];
if !member_rest[member_length..].trim_start().starts_with('(') {
continue;
}For 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 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 missedThe 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]>
|
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. Fixed in d622041. Verified end-to-end — all 7 expected hits, up from 3:
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: |
There was a problem hiding this comment.
🧹 Nitpick comments (2)
ci/lint_cpp_rs/src/checkers/container_ptr.rs (2)
293-301: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueTrim 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 winClean up the dead
cursorwrites and useindex += 1.
cursoris never read after the inner loop exits, so the four assignments before eachbreak(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 warningsthis fails CI.If the intent was to skip past the consumed receiver chain, advance
indexfromcursorinstead 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
📒 Files selected for processing (2)
ci/lint_cpp_rs/src/checkers/container_ptr.rsci/lint_cpp_rs/src/lint_core/tests.rs
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
.data()/&x[N]on non-contiguous (fl::deque,fl::circular_buffer)&x[N]/&x.front()on contiguous (fl::vector,fl::string, …).data()on contiguous containersBecause 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.rsandrun_all_checkers.py;test_warn_only_checkers_sync.pypins 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 recordsfl::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 readsif (annexB[i] == 0 && annexB[i+1] == 0)as address-of — 7 false positives out of 11. Theregexcrate 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 bycontainer_ptr_does_not_match_logical_and_operator.2. Raw-array shadowing.
span<int,3> s(&arr[0], 3)intests/fl/slice.cpp:367false-positived because a siblingFL_SUBCASEin the same file declaresfl::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 bycontainer_ptr_drops_names_shadowed_by_raw_arrays.Suppression
// fl-lint: container-data-ptr-ok, inline or on the preceding comment line — matching howSingletonElisionCheckerhandlesFL_LINT_ALLOW_GLOBAL.The 7 warn-tier sites (left for follow-up, not rewritten here)
src/fl/asset/asset.cpp.hpp:106andsrc/platforms/esp/32/drivers/ble/ble_esp32.cpp.hpp:173— bothresize()anfl::stringthen write through&s[0]for C-API interop. Genuine buffer-base use; the clearest candidates for either a rewrite or a justified suppression.&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
bash lintbash lintexit 0 · 357/357 C++ tests · warn-only sync test greenunity_build.rs(1205 lines), which fails on master too; the new checker file is 494 linesdeque.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
fl::containers..data()and element-address patterns.fl::span, iterator ranges, or explicit copies).Documentation
fl::Containers” standard and the approved suppression token for C interop.Tests