Skip to content

Commit 8592f36

Browse files
committed
Avoid divide-by-zero when checking if a field will merge with bitfields
1 parent ddb680b commit 8592f36

File tree

3 files changed

+72
-2
lines changed

3 files changed

+72
-2
lines changed

src/codegen/struct_layout.rs

+5-2
Original file line numberDiff line numberDiff line change
@@ -335,9 +335,12 @@ impl<'a> StructLayoutTracker<'a> {
335335
new_field_layout
336336
);
337337

338+
// Avoid divide-by-zero errors if align is 0.
339+
let align = cmp::max(1, layout.align);
340+
338341
if self.last_field_was_bitfield &&
339-
new_field_layout.align <= layout.size % layout.align &&
340-
new_field_layout.size <= layout.size % layout.align
342+
new_field_layout.align <= layout.size % align &&
343+
new_field_layout.size <= layout.size % align
341344
{
342345
// The new field will be coalesced into some of the remaining bits.
343346
//
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/* automatically generated by rust-bindgen */
2+
3+
4+
#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)]
5+
6+
7+
#[repr(C)]
8+
#[derive(Debug, Default, Copy, Clone)]
9+
pub struct WithBitfield {
10+
pub _bitfield_1: [u8; 0usize],
11+
pub __bindgen_padding_0: u32,
12+
pub a: ::std::os::raw::c_uint,
13+
}
14+
impl WithBitfield {
15+
#[inline]
16+
pub fn new_bitfield_1() -> u8 {
17+
0
18+
}
19+
}
20+
#[repr(C, packed)]
21+
#[derive(Debug, Default, Copy, Clone)]
22+
pub struct WithBitfieldAndAttrPacked {
23+
pub _bitfield_1: [u8; 0usize],
24+
pub a: ::std::os::raw::c_uint,
25+
pub __bindgen_padding_0: u8,
26+
}
27+
impl WithBitfieldAndAttrPacked {
28+
#[inline]
29+
pub fn new_bitfield_1() -> u8 {
30+
0
31+
}
32+
}
33+
#[repr(C, packed)]
34+
#[derive(Debug, Default, Copy, Clone)]
35+
pub struct WithBitfieldAndPacked {
36+
pub _bitfield_1: [u8; 0usize],
37+
pub a: ::std::os::raw::c_uint,
38+
pub __bindgen_padding_0: u8,
39+
}
40+
impl WithBitfieldAndPacked {
41+
#[inline]
42+
pub fn new_bitfield_1() -> u8 {
43+
0
44+
}
45+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
// bindgen-flags: --no-layout-tests
2+
//
3+
// Unfortunately, we aren't translating the second and third structs correctly
4+
// yet. But we definitely shouldn't divide-by-zero when we see it...
5+
//
6+
// Once we fix #981 we should remove the `--no-layout-tests`.
7+
8+
struct WithBitfield {
9+
unsigned : 7;
10+
unsigned a;
11+
};
12+
13+
struct WithBitfieldAndAttrPacked {
14+
unsigned : 7;
15+
unsigned a;
16+
} __attribute__((packed));
17+
18+
#pragma pack(1)
19+
struct WithBitfieldAndPacked {
20+
unsigned : 7;
21+
unsigned a;
22+
};

0 commit comments

Comments
 (0)