Skip to content

Commit

Permalink
Avoid divide-by-zero when checking if a field will merge with bitfields
Browse files Browse the repository at this point in the history
  • Loading branch information
fitzgen committed Nov 1, 2017
1 parent ddb680b commit 8592f36
Show file tree
Hide file tree
Showing 3 changed files with 72 additions and 2 deletions.
7 changes: 5 additions & 2 deletions src/codegen/struct_layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -335,9 +335,12 @@ impl<'a> StructLayoutTracker<'a> {
new_field_layout
);

// Avoid divide-by-zero errors if align is 0.
let align = cmp::max(1, layout.align);

if self.last_field_was_bitfield &&
new_field_layout.align <= layout.size % layout.align &&
new_field_layout.size <= layout.size % layout.align
new_field_layout.align <= layout.size % align &&
new_field_layout.size <= layout.size % align
{
// The new field will be coalesced into some of the remaining bits.
//
Expand Down
45 changes: 45 additions & 0 deletions tests/expectations/tests/divide-by-zero-in-struct-layout.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/* automatically generated by rust-bindgen */


#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)]


#[repr(C)]
#[derive(Debug, Default, Copy, Clone)]
pub struct WithBitfield {
pub _bitfield_1: [u8; 0usize],
pub __bindgen_padding_0: u32,
pub a: ::std::os::raw::c_uint,
}
impl WithBitfield {
#[inline]
pub fn new_bitfield_1() -> u8 {
0
}
}
#[repr(C, packed)]
#[derive(Debug, Default, Copy, Clone)]
pub struct WithBitfieldAndAttrPacked {
pub _bitfield_1: [u8; 0usize],
pub a: ::std::os::raw::c_uint,
pub __bindgen_padding_0: u8,
}
impl WithBitfieldAndAttrPacked {
#[inline]
pub fn new_bitfield_1() -> u8 {
0
}
}
#[repr(C, packed)]
#[derive(Debug, Default, Copy, Clone)]
pub struct WithBitfieldAndPacked {
pub _bitfield_1: [u8; 0usize],
pub a: ::std::os::raw::c_uint,
pub __bindgen_padding_0: u8,
}
impl WithBitfieldAndPacked {
#[inline]
pub fn new_bitfield_1() -> u8 {
0
}
}
22 changes: 22 additions & 0 deletions tests/headers/divide-by-zero-in-struct-layout.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// bindgen-flags: --no-layout-tests
//
// Unfortunately, we aren't translating the second and third structs correctly
// yet. But we definitely shouldn't divide-by-zero when we see it...
//
// Once we fix #981 we should remove the `--no-layout-tests`.

struct WithBitfield {
unsigned : 7;
unsigned a;
};

struct WithBitfieldAndAttrPacked {
unsigned : 7;
unsigned a;
} __attribute__((packed));

#pragma pack(1)
struct WithBitfieldAndPacked {
unsigned : 7;
unsigned a;
};

0 comments on commit 8592f36

Please sign in to comment.