Skip to content

ir: Prevent integer overflow when using word-size bitfields. #742

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

Merged
merged 1 commit into from
Jun 12, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion src/ir/comp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -293,8 +293,21 @@ impl Bitfield {

/// Get the mask value that when &'ed with this bitfield's allocation unit
/// produces this bitfield's value.
///
/// TODO(emilio): This should probably use the target's word size, and what
/// about bitfields that are bigger than that?
pub fn mask(&self) -> usize {
((1usize << self.width()) - 1usize) << self.offset_into_unit()
use std::mem;
use std::usize;

let unoffseted_mask =
if self.width() as usize == mem::size_of::<usize>() * 8 {
usize::MAX
} else {
((1usize << self.width()) - 1usize)
};

unoffseted_mask << self.offset_into_unit()
}

/// Get the bit width of this bitfield.
Expand Down
22 changes: 22 additions & 0 deletions tests/expectations/tests/issue-739-pointer-wide-bitfield.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/* 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)]
pub struct Foo {
pub _bitfield_1: [u64; 4usize],
pub __bindgen_align: [u64; 0usize],
}
#[test]
fn bindgen_test_layout_Foo() {
assert_eq!(::std::mem::size_of::<Foo>() , 32usize , concat ! (
"Size of: " , stringify ! ( Foo ) ));
assert_eq! (::std::mem::align_of::<Foo>() , 8usize , concat ! (
"Alignment of " , stringify ! ( Foo ) ));
}
impl Clone for Foo {
fn clone(&self) -> Self { *self }
}
8 changes: 8 additions & 0 deletions tests/headers/issue-739-pointer-wide-bitfield.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
#define POINTER_WIDTH (sizeof(void*) * 8)

struct Foo {
unsigned long m_bitfield: POINTER_WIDTH;
unsigned long m_bar: POINTER_WIDTH;
unsigned long foo: 1;
unsigned long bar: POINTER_WIDTH;
};