rust-lang / rust-lang/rust-bindgen

Deriving default for a struct with a rustified enum member that isn't representable by 0 generates undefined behavior

Open
#2,974 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Rust
Stars
5.3k
Forks
829
Avg merge
1d 1h
Merged PRs (30d)
15

Description

// header.h
enum E { A = 1, B, C };

struct S {
	enum E e;
};

bindgen invocation:

bindgen header.h --rustified-enum '.*' --with-derive-default 

bindgen output:

/* automatically generated by rust-bindgen 0.70.1 */

#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub enum E {
    A = 1,
    B = 2,
    C = 3,
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct S {
    pub e: E,
}
#[allow(clippy::unnecessary_operation, clippy::identity_op)]
const _: () = {
    ["Size of S"][::std::mem::size_of::<S>() - 4usize];
    ["Alignment of S"][::std::mem::align_of::<S>() - 4usize];
    ["Offset of field: S::e"][::std::mem::offset_of!(S, e) - 0usize];
};
impl Default for S {
    fn default() -> Self {
        let mut s = ::std::mem::MaybeUninit::<Self>::uninit();
        unsafe {
            ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1);
            s.assume_init()
        }
    }
}

This implementation of Default is UB, since it generates an E with an invalid tag.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by running the bindgen invocation against header.h and compare the generated Default implementation for S with the rustified enum E. Trace the code-generation path responsible for --with-derive-default and inspect existing regression tests. Done means the generated default cannot construct E with an invalid tag and the reproducer is covered by a test.

Written by the indexing model from the issue text.

Assessment

Tech stack
c, rust
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.