rust/tests/run-pass/adjacent-allocs.rs
Tavian Barnes b0a463334c intptrcast: Never allocate two objects directly adjecent
When two objects directly follow each other in memory, what is the
provenance of an integer cast to a pointer that points directly between
them?  For a zero-size region, it could point into the end of the first
object, or the start of the second.

We can avoid answering this difficult question by simply never
allocating two objects directly beside each other.  This fixes some of
the false positives from #1866.
2021-12-03 17:00:06 -05:00

22 lines
690 B
Rust

fn main() {
// The slack between allocations is random.
// Loop a few times to hit the zero-slack case.
for _ in 0..1024 {
let n = 0u64;
let ptr: *const u64 = &n;
// Allocate a new stack variable whose lifetime quickly ends.
// If there's a chance that &m == ptr.add(1), then an int-to-ptr cast of
// that value will have ambiguous provenance between n and m.
// See https://github.com/rust-lang/miri/issues/1866#issuecomment-985770125
{
let m = 0u64;
let _ = &m as *const u64;
}
let iptr = ptr as usize;
let zst = (iptr + 8) as *const ();
unsafe { *zst }
}
}