Skip to content

Commit 0fa166a

Browse files
committed
Detect overflows of non u32 shifts
1 parent 612c280 commit 0fa166a

File tree

3 files changed

+30
-1
lines changed

3 files changed

+30
-1
lines changed

src/librustc_mir/interpret/operator.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -95,9 +95,10 @@ impl<'a, 'mir, 'tcx, M: Machine<'mir, 'tcx>> EvalContext<'a, 'mir, 'tcx, M> {
9595
// These ops can have an RHS with a different numeric type.
9696
if right_kind.is_int() && (bin_op == Shl || bin_op == Shr) {
9797
let signed = left_layout.abi.is_signed();
98+
let mut oflo = (r as u32 as u128) != r;
9899
let mut r = r as u32;
99100
let size = left_layout.size.bits() as u32;
100-
let oflo = r >= size;
101+
oflo |= r >= size;
101102
if oflo {
102103
r %= size;
103104
}
+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// http://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.
10+
11+
enum Foo {
12+
// test that we detect overflows for non-u32 discriminants
13+
X = 1 << ((u32::max_value() as u64) + 1), //~ ERROR E0080
14+
Y = 42,
15+
}
16+
17+
18+
fn main() {
19+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
error[E0080]: could not evaluate enum discriminant
2+
--> $DIR/shift_overflow.rs:13:9
3+
|
4+
LL | X = 1 << ((u32::max_value() as u64) + 1), //~ ERROR E0080
5+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ attempt to shift left with overflow
6+
7+
error: aborting due to previous error
8+
9+
For more information about this error, try `rustc --explain E0080`.

0 commit comments

Comments
 (0)