Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BUG: fix incorrect code generation when a struct ends in a bitfield and --explicit-padding is used #2406

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

sw17ch
Copy link

@sw17ch sw17ch commented Feb 9, 2023

A struct ending in a bitfield will have its trailing padding duplicated when --explicit-padding is used. This PR adds a test showing this condition, and performs a small check for whether or not the previous field was a bitfield before emitting trailing padding.

Please Consider

I do not know if my fix is a good fix, it is merely a fix. I wrote this at 1AM, and it may contain errors in judgement consistent with the time of night.

Also, I was able to find this bug because we run the bindgen_test_layout_* test cases in our CI system, and they successfully flagged the difference in size, so thank you for that!

Reproduction

Before this patch, the following header would have incorrect Rust code generated when run with --explicit-padding.

// bindings.h
struct repro {
    short a;
    char bits: 1;
};

First, we look at the output from bindgen without the --explicit-padding flag:

$ bindgen bindings.h
...
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct repro {
    pub a: ::std::os::raw::c_short,
    pub _bitfield_align_1: [u8; 0],
    pub _bitfield_1: __BindgenBitfieldUnit<[u8; 1usize]>,
    pub __bindgen_padding_0: u8,
}
...

Now, we repeat it with --explicit-padding:

$ bindgen --explicit-padding bindings.h
...
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct repro {
    pub a: ::std::os::raw::c_short,
    pub _bitfield_align_1: [u8; 0],
    pub _bitfield_1: __BindgenBitfieldUnit<[u8; 1usize]>,
    pub __bindgen_padding_0: u8,
    pub __bindgen_padding_1: u8,
}
...

Notice that the second invocation has an extra padding field.

@sw17ch
Copy link
Author

sw17ch commented Feb 9, 2023

r? @emilio

I've seen your name around other things with bitfields, so hopefully this is familiar territory for you.

A struct ending in a bitfield will have its trailing padding
duplicated. This change skips adding the trailing padding if the last
field was a bitfield, and thus, already has already been padded.
@sw17ch sw17ch force-pushed the sw17ch/duplicate-padding-with-trailing-bitfield branch from d59c82a to 2aba15d Compare February 9, 2023 10:09
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.

None yet

1 participant