Skip to content

Autogenerated tests contains UB: reference to packed field is unaligned #2053

@Apostoln

Description

@Apostoln

Input C/C++ Header

struct Foo {
    unsigned int a;
} __attribute__((__packed__));

Bindgen Invocation

bindgen::Builder::default()
        .header("wrapper.h")
        .generate()
        .unwrap();

Actual Results

cargo +nightly test --no-run emits a warning which causes UB and will be considered as error in the future rust releases

warning: reference to packed field is unaligned
   |
21 |         unsafe { &(*(::std::ptr::null::<Foo>())).a as *const _ as usize },
   |                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
   = note: `#[warn(unaligned_references)]` on by default
   = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
   = note: for more information, see issue #82523 <https://github.com/rust-lang/rust/issues/82523>
   = note: fields of packed structs are not properly aligned, and creating a misaligned reference is undefined behavior (even if that reference is never dereferenced)

Expected Results

No warnings, errors, and UB.
We can use the workaround mentioned in #82523 rust-lang/rust#82523 to avoid UB.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions