Skip to content

Commit 80a003f

Browse files
committed
Test and implement detecting nested dead allocations
1 parent 2d86ed1 commit 80a003f

File tree

3 files changed

+23
-1
lines changed

3 files changed

+23
-1
lines changed

compiler/rustc_const_eval/src/interpret/validity.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1053,6 +1053,12 @@ impl<'mir, 'tcx> InterpCx<'mir, 'tcx, crate::const_eval::CompileTimeInterpreter<
10531053
path,
10541054
DanglingPtrUseAfterFree { ptr_kind: PointerKind::Ref(Mutability::Not) }
10551055
)
1056+
} else {
1057+
let ptr = Pointer::new(Some(*prov), Size::ZERO);
1058+
let ty = self.tcx.types.unit;
1059+
let layout = self.layout_of(ty).unwrap();
1060+
let op = self.ptr_to_mplace(ptr, layout);
1061+
ref_tracking.track(op, || path.clone())
10561062
}
10571063
}
10581064
}

tests/ui/consts/dangling_raw_ptr.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,11 @@ const BAR: Union = { //~ ERROR it is undefined behavior
1717
Union { ptr: &x }
1818
};
1919

20+
const BAZ: Union = { //~ ERROR it is undefined behavior
21+
let x = 42_u32;
22+
Union { ptr: &(&x as *const u32) as *const *const u32 as _ }
23+
};
24+
2025
fn main() {
2126
let x = FOO;
2227
let x = BAR;

tests/ui/consts/dangling_raw_ptr.stderr

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,17 @@ LL | const BAR: Union = {
2020
HEX_DUMP
2121
}
2222

23-
error: aborting due to 2 previous errors
23+
error[E0080]: it is undefined behavior to use this value
24+
--> $DIR/dangling_raw_ptr.rs:20:1
25+
|
26+
LL | const BAZ: Union = {
27+
| ^^^^^^^^^^^^^^^^ constructing invalid value: encountered a dangling reference (use-after-free)
28+
|
29+
= note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior.
30+
= note: the raw bytes of the constant (size: $SIZE, align: $ALIGN) {
31+
HEX_DUMP
32+
}
33+
34+
error: aborting due to 3 previous errors
2435

2536
For more information about this error, try `rustc --explain E0080`.

0 commit comments

Comments
 (0)