Skip to content

Commit 44e66b6

Browse files
committed
Fix rust-lang#121126: index out of bounds exceeds max value
When indexing an array with an index (u32) that exceeds the maximum value allowed by FieldIdx (default: 0xFFFF_FF00), although the compiler would detect the error, it would also cause a panic, which is a bug. I fixed it by adding a verification before calling the FieldIdx::from_u32(idx) method. This check ensures that if the idx value is greater than the maximum allowed value, it returns Option::None, similar to how other functions handle errors during the call to the project method of type Value.
1 parent 4fd4797 commit 44e66b6

File tree

3 files changed

+31
-2
lines changed

3 files changed

+31
-2
lines changed

compiler/rustc_mir_transform/src/known_panics_lint.rs

+8-2
Original file line numberDiff line numberDiff line change
@@ -101,8 +101,14 @@ impl<'tcx> Value<'tcx> {
101101
}
102102
(PlaceElem::Index(idx), Value::Aggregate { fields, .. }) => {
103103
let idx = prop.get_const(idx.into())?.immediate()?;
104-
let idx = prop.ecx.read_target_usize(idx).ok()?;
105-
fields.get(FieldIdx::from_u32(idx.try_into().ok()?)).unwrap_or(&Value::Uninit)
104+
let idx: u32 = prop.ecx.read_target_usize(idx).ok()?.try_into().ok()?;
105+
106+
let max: u32 = FieldIdx::MAX.index().try_into().ok()?;
107+
if idx > max {
108+
return None;
109+
}
110+
111+
fields.get(FieldIdx::from_u32(idx)).unwrap_or(&Value::Uninit)
106112
}
107113
(
108114
PlaceElem::ConstantIndex { offset, min_length: _, from_end: false },
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
// Regression test for #121126. Compiler was panicking when indexing an array
2+
// with an index that is out of bounds and its value is greater than the max
3+
// value allowed for an index.
4+
5+
//@ build-fail
6+
7+
fn main() {
8+
[0][0xFFFF_FF01];
9+
//~^ ERROR this operation will panic at runtime [unconditional_panic]
10+
}
11+
12+
// NOTE: In order for the test to be valid, the index can take on any value
13+
// between FieldIdx::MAX + 1 (= 0xFFF_FF01) and u32::MAX (= 0xFFF_FFFF)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
error: this operation will panic at runtime
2+
--> $DIR/issue-121126-index-out-of-bounds-exceeds-max-value.rs:8:5
3+
|
4+
LL | [0][0xFFFF_FF01];
5+
| ^^^^^^^^^^^^^^^^ index out of bounds: the length is 1 but the index is 4294967041
6+
|
7+
= note: `#[deny(unconditional_panic)]` on by default
8+
9+
error: aborting due to 1 previous error
10+

0 commit comments

Comments
 (0)