Repository navigation
Fix union bitfield storage and layout - #3531
Conversation
| @@ -0,0 +1,3 @@ | |||
| // bindgen-flags: --raw-line '#![cfg(target_env = "msvc")]' -- --target=x86_64-pc-windows-msvc | |||
There was a problem hiding this comment.
So we're not running these on msvc at all right now...
There was a problem hiding this comment.
Right, CI compares the MSVC-targeted output against the snapshot, but doesn't compile its layout assertions. I've kept this fixture for MSVC-specific codegen coverage.
| @@ -0,0 +1,11 @@ | |||
| // bindgen-flags: --bindgen-wrapper-union 'WithBindgenWrapper' --no-copy 'NonCopyType' --raw-line '#![cfg(target_env = "msvc")]' -- --target=x86_64-pc-windows-msvc | |||
There was a problem hiding this comment.
Why do we need to restrict these / run these in msvc? I guess it doesn't hurt to test the MSVC layout?
There was a problem hiding this comment.
Agreed, the restriction wasn't necessary. Removed the forced MSVC target and cfg, and regenerated the expectation. The separate MSVC layout fixture remains.
|
|
||
| // Bitfields can occupy fewer bytes than their C allocation unit. Union | ||
| // members overlap, so this field must cover the full size, not the gap. | ||
| Some(self.padding_field(Layout::new(layout.size, 1))) |
There was a problem hiding this comment.
I guess we're relying on the alignment being correct already, seems fine.
There was a problem hiding this comment.
Correct, alignment is handled by the existing requires_explicit_align path. The padding field only ensures sufficient storage.
|
@emilio FYI automatic merge was canceled (unrelated CI job error) |
Upstream: c799f9e73b9041d43033dfffcaeeec1c1ba6b444 Source: rust-lang/rust-bindgen#3531
Fixes #3184.
Overlapping union bitfields can produce undersized storage when a narrower member follows a wider one. Native unions can also be smaller than their C layout when bitfields occupy fewer bytes than their allocation unit.
This is not MSVC-specific: on the GNU ABI, alignment can preserve the correct union size while bitfield accessors still fail because the underlying storage is too small.
This also surfaced in a real-world project using native Windows structures from PHNT (x64/MSVC, generated size vs. C size):
Track the maximum bitfield extent and add a full-size, byte-aligned padding member where needed, preserving Clang-provided offsets and existing alignment handling.
Regression tests cover #3184, varying bit widths, packed layouts, and C/Rust accessor and by-value ABI round trips.