Skip to content

Fix shift-overflow in const-generic bitfield accessors#3374

Merged
emilio merged 3 commits into
rust-lang:mainfrom
dimbleby:bit-width
May 16, 2026
Merged

Fix shift-overflow in const-generic bitfield accessors#3374
emilio merged 3 commits into
rust-lang:mainfrom
dimbleby:bit-width

Conversation

@dimbleby
Copy link
Copy Markdown
Contributor

When BIT_WIDTH equals the native word size (e.g. a 64-bit field on a 64-bit target), (1usize << BIT_WIDTH) - 1 shifted by the full width of usize, panicking in debug builds and producing a wrong mask in release. Affected get_const, set_const, raw_get_const and raw_set_const.

Guard the value mask with BIT_WIDTH < usize::BITS and compute the runtime set. Add a regression test exercising width = 64.

`cargo clippy -- -D warnings` was failing on stable with a
collapsible_match lint in ObjCInterface::from_ty: a nested `if` inside
a `CXCursor_ObjCClassRef` match arm should be expressed as a match
guard. Collapse it as suggested. No behaviour change.

Co-authored-by: Copilot <[email protected]>
When BIT_WIDTH equals the native word size (e.g. a 64-bit field on a
64-bit target), `(1usize << BIT_WIDTH) - 1` shifted by the full width
of usize, panicking in debug builds and producing a wrong mask in
release. Affected `get_const`, `set_const`, `raw_get_const` and
`raw_set_const`.

Guard the value mask with `BIT_WIDTH < usize::BITS` and compute
the runtime `set`. Add a regression test exercising width = 64.

Co-authored-by: Copilot <[email protected]>
The upper-bound check in get/set/raw_get/raw_set and their const-generic
siblings used floor division: `(bit_offset + bit_width) / 8 <= len`.
The byte-loop touches indices up to
`start_byte + bytes_needed - 1 = ceil((bit_offset + bit_width) / 8) - 1`,
so the correct check is `(bit_offset + bit_width + 7) / 8 <= len`.

Codegen never produces values that would fail the tighter assert, so
this is a hardening of the safety check rather than a runtime fix.
Regenerate the matching expectations.

Co-authored-by: Copilot <[email protected]>
Comment thread bindgen/ir/objc.rs
@emilio emilio added this pull request to the merge queue May 16, 2026
Merged via the queue into rust-lang:main with commit 5b1b56d May 16, 2026
51 checks passed
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