Skip to content

Commit 3842ea6

Browse files
committed
miri: fix overflow detection for unsigned pointer offset
1 parent 16beabe commit 3842ea6

File tree

3 files changed

+30
-1
lines changed

3 files changed

+30
-1
lines changed

compiler/rustc_const_eval/src/interpret/operator.rs

+8-1
Original file line numberDiff line numberDiff line change
@@ -303,8 +303,10 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
303303
let pointee_layout = self.layout_of(pointee_ty)?;
304304
assert!(pointee_layout.abi.is_sized());
305305

306-
// We cannot overflow i64 as a type's size must be <= isize::MAX.
306+
// The size always fits in `i64` as it can be at most `isize::MAX`.
307307
let pointee_size = i64::try_from(pointee_layout.size.bytes()).unwrap();
308+
// This uses the same type as `right`, which can be `isize` or `usize`.
309+
// `pointee_size` is guaranteed to fit into both types.
308310
let pointee_size = ImmTy::from_int(pointee_size, right.layout);
309311
// Multiply element size and element count.
310312
let (val, overflowed) = self
@@ -316,6 +318,11 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
316318
}
317319

318320
let offset_bytes = val.to_target_isize(self)?;
321+
if !right.layout.abi.is_signed() && offset_bytes < 0 {
322+
// We were supposed to do an unsigned offset but the result is negative -- this
323+
// can only mean that the cast wrapped around.
324+
throw_ub!(PointerArithOverflow)
325+
}
319326
let offset_ptr = self.ptr_offset_inbounds(ptr, offset_bytes)?;
320327
Ok(ImmTy::from_scalar(Scalar::from_maybe_pointer(offset_ptr, self), left.layout))
321328
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
fn main() {
2+
let x = &[0i32; 2];
3+
let x = x.as_ptr().wrapping_add(1);
4+
// If the `!0` is interpreted as `isize`, it is just `-1` and hence harmless.
5+
// However, this is unsigned arithmetic, so really this is `usize::MAX` and hence UB.
6+
unsafe { x.byte_add(!0).read() }; //~ERROR: does not fit in an `isize`
7+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
error: Undefined Behavior: overflowing pointer arithmetic: the total offset in bytes does not fit in an `isize`
2+
--> $DIR/ptr_offset_unsigned_overflow.rs:LL:CC
3+
|
4+
LL | unsafe { x.byte_add(!0).read() };
5+
| ^^^^^^^^^^^^^^ overflowing pointer arithmetic: the total offset in bytes does not fit in an `isize`
6+
|
7+
= help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior
8+
= help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information
9+
= note: BACKTRACE:
10+
= note: inside `main` at $DIR/ptr_offset_unsigned_overflow.rs:LL:CC
11+
12+
note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace
13+
14+
error: aborting due to 1 previous error
15+

0 commit comments

Comments
 (0)