Skip to content

Commit 72667b5

Browse files
committed
Auto merge of #1346 - RalfJung:dyn-layout-test, r=RalfJung
Test that we enforce dynamic layout properties (not just static ones of sized prefix)
2 parents 216e686 + 0345ee4 commit 72667b5

File tree

3 files changed

+34
-1
lines changed

3 files changed

+34
-1
lines changed
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
// should find the bug even without these, but gets masked by optimizations
2+
// compile-flags: -Zmiri-disable-validation -Zmiri-disable-stacked-borrows -Zmir-opt-level=0
3+
4+
struct SliceWithHead(u8, [u8]);
5+
6+
fn main() {
7+
let buf = [0u32; 1];
8+
// We craft a wide pointer `*const SliceWithHead` such that the unsized tail is only partially allocated.
9+
// That should be UB, as the reference is not fully dereferencable.
10+
let ptr: *const SliceWithHead = unsafe { std::mem::transmute((&buf, 4usize)) };
11+
// Re-borrow that. This should be UB.
12+
let _ptr = unsafe { &*ptr }; //~ ERROR pointer must be in-bounds at offset 5
13+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// should find the bug even without these, but gets masked by optimizations
2+
// compile-flags: -Zmiri-disable-validation -Zmiri-disable-stacked-borrows -Zmir-opt-level=0
3+
4+
#[repr(align(256))]
5+
#[derive(Debug)]
6+
struct MuchAlign;
7+
8+
fn main() {
9+
let buf = [0u32; 256];
10+
// `buf` is sufficiently aligned for `layout.align` on a `dyn Debug`, but not
11+
// for the actual alignment required by `MuchAlign`.
12+
// We craft a wide reference `&dyn Debug` with the vtable for `MuchAlign`. That should be UB,
13+
// as the reference is not aligned to its dynamic alignment requirements.
14+
let mut ptr = &MuchAlign as &dyn std::fmt::Debug;
15+
// Overwrite the data part of `ptr` so it points to `buf`.
16+
unsafe { (&mut ptr as *mut _ as *mut *const u8).write(&buf as *const _ as *const u8); }
17+
// Re-borrow that. This should be UB.
18+
let _ptr = &*ptr; //~ ERROR accessing memory with alignment 4, but alignment 256 is required
19+
}

tests/compile-fail/validity/nonzero.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
// compile-flags: -Zmir-opt-level=1
1+
// gets masked by optimizations
2+
// compile-flags: -Zmir-opt-level=0
23
#![feature(rustc_attrs)]
34
#![allow(unused_attributes)]
45

0 commit comments

Comments
 (0)