Skip to content

utility: mask: fix bfxw() extracting one bit too many - #2096

Closed
LukeW1999 wants to merge 1 commit into
pyocd:mainfrom
LukeW1999:fix-bfxw-width
Closed

LukeW1999 wants to merge 1 commit into
pyocd:mainfrom
LukeW1999:fix-bfxw-width

Conversation

@LukeW1999

Copy link
Copy Markdown

bfxw(value, lsb, width) built its mask with bitmask((lsb + width, lsb)). bitmask() ranges include both ends, so the mask covered width + 1 bits. For example, bfxw(0x1f0, 4, 4) returned 0x1f instead of 0xf.

This was found by bounded model checking with ESBMC, checking bfxw(v, lsb, w) < 1 << w. Counterexample: v=4294955007 (0xffffcfff), lsb=12, w=2 returns 4. It was confirmed by running the code directly.

The fix uses lsb + width - 1 as the MSB, so bfxw() now agrees with bfx(). A width of 0 selects no bits and returns 0. Nothing in the tree calls bfxw(), so no existing behaviour changes.

Added test/unit/test_mask.py, which compares bfxw() against bfx() for a table of inputs (including width 1, the example above and the counterexample) and checks the result is below 1 << width. Unit tests: 1116 passed, 41 skipped.

Copilot AI balanced review requested due to automatic review settings November 28, 2026 11:20
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
There may be pipelines that require an authorized user to comment /azp run to run.

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

bfxw() built its mask with bitmask((lsb + width, lsb)), but bitmask()
ranges include both ends, so the mask covered width + 1 bits. For
example, bfxw(0x1f0, 4, 4) returned 0x1f instead of 0xf. Use
lsb + width - 1 as the MSB so the result matches bfx(). A width of 0
now selects no bits and returns 0.

Add unit tests comparing bfxw() against bfx().
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