Skip to content

PixelUtil: setRangeRGB writes out of bounds when range.start exceeds numPixels() - #13

Merged
aphelps-claude-bot merged 2 commits into
mainfrom
pixelutil-setrange-oob
Aug 18, 2026
Merged

aphelps-claude-bot merged 2 commits into
mainfrom
pixelutil-setrange-oob

Conversation

@aphelps-claude-bot

@aphelps-claude-bot aphelps-claude-bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Collaborator

What / why

PixelUtil::setRangeRGB clamped only the end of a range. A start past the end of the strip made numPixels() - range.start wrap, and fill_solid walked off the array from leds + start. Measured on the host with the exact expression, for a 10-pixel strip and start = 200:

build clamped length writes
default (uint8_t) 66 leds[200..265]
-DBIG_PIXELS (uint16_t) 65346 leds[200..65545]

The second case is ~196 KB of CRGB writes on a part with 2 KB of SRAM. This is reachable today with no protocol change: PIXEL_ADDR_TYPE is uint8_t by default, and the one caller (HMTLPrograms.cpp:670, program_color) casts the wire payload straight in — a single malformed or stale PROGRAM_COLOR frame on the RS485 bus triggers it. On AVR (16-bit int) start + length in uint16_t can also wrap modulo 65536 and skip the clamp entirely, so the fix computes the available span once, in a width that cannot wrap, and never forms the sum.

New semantics of setRangeRGB (documented in PixelUtil/README.md):

  • length == 0 still means the whole strip, now checked on the input rather than produced by accident of the clamp arithmetic (load-bearing: HMTLprotocol.py zero-fills unspecified program bytes, so a colour program sent with just an RGB triple arrives as {0, 0}).
  • start >= numPixels() draws nothing, with a DEBUG1 line only (not DEBUG_ERR_STATE — this is a per-frame path; a repeating malformed stream must not pin the module in an error state).
  • An over-long range clamps to the end of the strip.

Bounds policy made explicit (decided 2026-08-05): getColor() returns 0 and setDistinct() no-ops out of range; the three setPixelRGB(uint16_t led, …) overloads deliberately stay unchecked and fast (they are the inner loop of every effect on the ATMega328) and now carry a comment saying the asymmetry with the checked setPixelRGB(PRGB*) is deliberate.

⚠️ Behaviour change

For start == numPixels() exactly, the old code was not undefined — it clamped to length = 0 and fell into "fill the whole strip" via setAllRGB. The fix turns that into a no-op. That is intended, but it is visible on a real module: a sender that has been using an out-of-range start as an accidental "all pixels" command goes dark. The new behaviour is asserted in the host test.

Test harness

ArduinoLibs/test/ did not compile PixelUtil at all — the only thing that looked like coverage was HMTL's native suite, which tests a hand-written stub with different (safe) behaviour. This PR adds:

  • test/shim/FastLED.h — host shim (CRGB pinned to 3 bytes / alignment 1 by static_assert, fill_solid, the FastLED singleton with all three addLeds<…> template shapes, chipset tags, colour-order enumerators visible at header-parse time for the order=RGB default argument).
  • map() added to test/shim/Arduino.h (PixelUtil's colour helpers call it).
  • test/pixelutil_test.cpp, built twice (pixelutil_test, pixelutil_test_big) via explicit Makefile targets so -DBIG_PIXELS reaches PixelUtil.cpp too; PixelUtil.cpp stays out of the shared $(SOURCES) so rs485_receive_test is not relinked against it.
  • leds is private, so corruption is caught by interposing global operator new[]/delete[] with a sentinel-filled 384 KiB trailing pad sized to the whole reachable overrun — this bug skips over a conventional guard band entirely (measured against the buggy code: PAD=512 intact, PAD=1024 caught).

Test results

make -C ArduinoLibs/test (note: make -C ArduinoLibs test is a documented no-op — use the path form):

-- rs485_receive_test --      55 checks, 0 failures   ALL TESTS PASSED
-- pixelutil_test --          PIXEL_ADDR_TYPE width: 1 byte(s)                PASS: 51 checks, 0 failures
-- pixelutil_test_big --      PIXEL_ADDR_TYPE width: 2 byte(s) (BIG_PIXELS)  PASS: 55 checks, 0 failures

Super-repo make test STRICT=1: OK — all submodule host tests passed (WLED, bridge, ArduinoLibs incl. both new binaries, esp-now-router).

Negative control (mandatory per plan): setRangeRGB temporarily reverted to the buggy implementation; both widths went red by the sentinel check — a clean sentinels_intact() == false assertion, exit 1, no crash, no garbage:

default:      FAIL: start=200,len=5: sentinels intact (buggy code corrupts them) (line 182)  … 14 failures, exit=1
-DBIG_PIXELS: FAIL: start=200,len=5: sentinels intact (buggy code corrupts them) (line 182)
              FAIL: start=1000,len=5: sentinels intact (line 194)                            … 15 failures, exit=1

The buggy build also failed the start == num no-flood assertions, pinning the behaviour change above. Fix restored afterwards; suite green.

Not run: pio run -e ampworks in WLED — PixelUtil is not on the WLED build path, so that build is a regression formality with no coverage of this change (and it was blocked in this environment).

Companion PR: aphelps/HMTL aligns the native-suite stub's setRangeRGB with this implementation. Conceptually depends on this PR, but mergeable independently.

🤖 Generated with Claude Code

https://claude.ai/code/session_015KSu1SeP42JExkGvrWGd2u

…nds policy is now explicit

setRangeRGB clamped only the END of a range: a start past the end of the
strip made `numPixels() - range.start` wrap, and fill_solid walked off the
array from `leds + start`. Measured for a 10-pixel strip and start = 200:

  | build                   | clamped length | writes           |
  |-------------------------|----------------|------------------|
  | default (uint8_t)       | 66             | leds[200..265]   |
  | -DBIG_PIXELS (uint16_t) | 65346          | leds[200..65545] |

The second is ~196 KB of CRGB writes on a part with 2 KB of SRAM. And on
AVR (16-bit int) `start + length` in uint16_t can itself wrap modulo 65536,
skipping the clamp entirely — so the rewrite computes the available span
once, in a width that cannot wrap, and never forms the sum:

  - length == 0 still means the WHOLE strip, but is now checked on the
    input rather than produced by accident of the clamp arithmetic
    (HMTLprotocol.py zero-fills unspecified program bytes, so a colour
    program sent with just an RGB triple arrives as {0, 0})
  - start >= numPixels() now draws nothing, with a DEBUG1 line (not
    DEBUG_ERR_STATE — this is a per-frame path, and a repeating malformed
    stream would otherwise pin the module in an error state)
  - an over-long range clamps to the end of the strip

BEHAVIOUR CHANGE: start == numPixels() exactly used to clamp to length = 0
and fall into "fill the whole strip". Now it is a no-op. A sender that was
using an out-of-range start as an accidental "all pixels" goes dark.

The same file was inconsistent about bounds, so the policy is now explicit
(and written down in the README): getColor() and setDistinct() gain bounds
checks; the three setPixelRGB(uint16_t led, ...) overloads deliberately
stay unchecked and fast — they are the inner loop of every effect on the
ATMega328 — and now say so in a comment.

The test harness gains its first PixelUtil coverage: a FastLED shim (the
real one bit-bangs MCU registers and is unbuildable on a host), map() in
the Arduino shim, and pixelutil_test built TWICE — default and -DBIG_PIXELS
— since the two widths wrap to different lengths and only the second is
catastrophic. `leds` is private, so corruption is caught by interposing
global operator new[] with a sentinel-filled 384 KiB trailing pad sized to
the whole reachable overrun (a conventional guard band sits inside the gap
the write skips over and survives untouched; measured: PAD=512 intact,
PAD=1024 caught). Negative control verified: with the old implementation
both widths fail by the sentinel check, exit 1, no crash.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_015KSu1SeP42JExkGvrWGd2u

@aphelps-claude-bot aphelps-claude-bot left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Reviewed the full stack (this PR plus aphelps/HMTL#8); built and ran the suite locally: rs485_receive_test 55/0, pixelutil_test 50/0, pixelutil_test_big 52/0. The fix itself is correct at both PIXEL_ADDR_TYPE widths and the sentinel-pad sizing rationale holds. Cross-PR/top-level findings:

  • Record the negative control in the PR description. The Test Plan's mandatory control (revert setRangeRGB, confirm both widths go red via the sentinels_intact() assertion, not a crash) is by nature invisible in this diff. Please paste its output (exit codes plus the failing CHECK lines for both widths) into the PR description so the ArduinoLibs#11 failure mode — a suite that exits 0 while testing nothing — is ruled out on the record.
  • Call out the visible behaviour change. start == numPixels() previously clamped to length 0 and fell into the whole-strip flood via setAllRGB; it is now a no-op. The test asserts this deliberately, but per the plan's Testing Required section the PR description should state it: a sender that used an out-of-range start as an accidental "all pixels" command goes dark after this merge.
  • HMTL#8 looks correct, no changes requested there (noted here since this review posts to the ArduinoLibs PR): the stub now mirrors the real three-branch shape, and its new zero-baseline assertions are deterministic because the stub's _leds is value-initialized (new CRGB[n]()).

Comment thread test/pixelutil_test.cpp Resolved
Comment thread test/pixelutil_test.cpp Resolved
Comment thread test/pixelutil_test.cpp Resolved
- operator new[] interposition now aborts on a second tracked allocation
  instead of silently overwriting g_raw/g_user (which would leak the first
  block and later free() an interior pointer)
- add the AVR clamp-skip shape {start=65535, length=2} to the BIG_PIXELS
  block, pinning the second overflow path the rewrite closes
- add the exact boundary prgb.pixel == num to the setPixelRGB(PRGB*) case,
  pinning the < vs <= bounds check

Counts: pixelutil_test 50 -> 51, pixelutil_test_big 52 -> 55.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015KSu1SeP42JExkGvrWGd2u

@aphelps-claude-bot aphelps-claude-bot left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

⏳ Testing Tasks — human confirmation required before merge

Thanks for the approval. Holding the merge on one unchecked ## Testing Required item, and I want to be straight that it may well be a no-op — but ticking it is a hardware judgement, not mine to make.

The item: "Bench check only if the unchecked-setter policy changes."

Why it looks inapplicable. The recorded decision (plan Notes, 2026-08-05) was that the three setPixelRGB(uint16_t led, …) overloads stay unchecked and fast — only getColor() and setDistinct() gained bounds checks. So the item's own precondition is not met.

The one real behaviour change it flags, independent of that condition: for start == numPixels() exactly, the old code was not undefined — it clamped and flooded the whole strip. The fix makes it a no-op. A sender that had been using an out-of-range start as an accidental "all pixels" command would go dark. That case is asserted in the host suite, but only you know whether anything on the bus was relying on it.

If nothing was, /ack-tested on this PR and the bot merges the stack.

Everything else is verified at the approved heads (ArduinoLibs 73d9e1d, HMTL e0ea310):

make -C ArduinoLibs/test
  rs485_receive_test   55 checks, 0 failures
  pixelutil_test       PIXEL_ADDR_TYPE 1 byte   PASS: 51 checks, 0 failures
  pixelutil_test_big   PIXEL_ADDR_TYPE 2 bytes  PASS: 55 checks, 0 failures

make test STRICT=1     OK — all submodule host tests passed
HMTL pio test -e native   58 test cases: 58 succeeded (incl. test_pixelutil)
pio run -e ampworks    SUCCESS, 49.30s (formality — PixelUtil is not on the WLED build path)

Negative control, reverting setRangeRGB to the pre-fix implementation in a scratch worktree:

pixelutil_test       FAIL: 51 checks, 14 failures
pixelutil_test_big   FAIL: 55 checks, 16 failures

Red by the sentinel check under both widths — every failure is a sentinels intact assertion, exit=1, no segfault. That distinction was the point: a crash would have meant an undersized guard pad and would not have counted as proof.

@aphelps

aphelps commented Aug 18, 2026

Copy link
Copy Markdown
Owner

/ack-tested

@aphelps-claude-bot
aphelps-claude-bot merged commit 9194ddf into main Aug 18, 2026
@aphelps-claude-bot
aphelps-claude-bot deleted the pixelutil-setrange-oob branch August 18, 2026 07:14
aphelps-claude-bot added a commit to aphelps/WLED_dev that referenced this pull request Aug 22, 2026
aphelps/ArduinoLibs#13 stops setRangeRGB writing out of bounds when
range.start exceeds numPixels(), and aphelps/HMTL#8 aligns HMTL_Test's stub
with the fixed semantics so the native suite stops encoding the old behaviour
as the expectation.

Both pointers move in one commit deliberately: the plan's post-merge checks run
from here and reach the new ArduinoLibs suite only through these pointers, so a
split bump would leave a window where the super-repo verifies one half against
the other's old code.

Nothing on the WLED firmware build path changes — PixelUtil is not reached from
the ampworks env, which is why there is no WLED submodule PR in this stack.

Verified on this combination before opening:
  make -C ArduinoLibs/test  — 51 checks (uint8_t) + 55 checks (BIG_PIXELS), 0 failures
  make test STRICT=1        — all submodule host tests, sweep across four ABIs
                              x both pixel widths, 460/460 perturbations red as required


Claude-Session: https://claude.ai/code/session_013HqzdRdTRnreSvevaQGQSJ

Co-authored-by: aphelps-claude-bot <[email protected]>
Co-authored-by: Claude Opus 5 (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

None yet

Development

Successfully merging this pull request may close these issues.

2 participants