Skip to content

Commit 31ad5f6

Browse files
committed
Auto merge of #1454 - RalfJung:test-raw-ptr, r=RalfJung
Test raw_ptr macro Make sure it can create pointers to packed fields, but *cannot* deref dangling or unaligned (raw) pointers.
2 parents 5961977 + 8d1d572 commit 31ad5f6

File tree

3 files changed

+29
-1
lines changed

3 files changed

+29
-1
lines changed
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
// Make sure we find these even with many checks disabled.
2+
// compile-flags: -Zmiri-disable-alignment-check -Zmiri-disable-stacked-borrows -Zmiri-disable-validation
3+
#![feature(raw_ref_macros)]
4+
use std::ptr;
5+
6+
fn main() {
7+
let p = {
8+
let b = Box::new(42);
9+
&*b as *const i32
10+
};
11+
let x = unsafe { ptr::raw_const!(*p) }; //~ ERROR dereferenced after this allocation got freed
12+
panic!("this should never print: {:?}", x);
13+
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
// This should fail even without validation or Stacked Borrows.
2+
// compile-flags: -Zmiri-disable-validation -Zmiri-disable-stacked-borrows
3+
#![feature(raw_ref_macros)]
4+
use std::ptr;
5+
6+
fn main() {
7+
let x = [2u16, 3, 4]; // Make it big enough so we don't get an out-of-bounds error.
8+
let x = &x[0] as *const _ as *const u32;
9+
// This must fail because alignment is violated: the allocation's base is not sufficiently aligned.
10+
// The deref is UB even if we just put the result into a raw pointer.
11+
let _x = unsafe { ptr::raw_const!(*x) }; //~ ERROR memory with alignment 2, but alignment 4 is required
12+
}

tests/run-pass/packed_struct.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
1-
#![feature(unsize, coerce_unsized, raw_ref_op)]
1+
#![feature(unsize, coerce_unsized, raw_ref_op, raw_ref_macros)]
22

33
use std::collections::hash_map::DefaultHasher;
44
use std::hash::Hash;
5+
use std::ptr;
56

67
fn test_basic() {
78
#[repr(packed)]
@@ -45,7 +46,9 @@ fn test_basic() {
4546
assert_eq!({x.b}, 99);
4647
// but we *can* take a raw pointer!
4748
assert_eq!(unsafe { (&raw const x.a).read_unaligned() }, 42);
49+
assert_eq!(unsafe { ptr::raw_const!(x.a).read_unaligned() }, 42);
4850
assert_eq!(unsafe { (&raw const x.b).read_unaligned() }, 99);
51+
assert_eq!(unsafe { ptr::raw_const!(x.b).read_unaligned() }, 99);
4952

5053
x.b = 77;
5154
assert_eq!({x.b}, 77);

0 commit comments

Comments
 (0)