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.
This commit is contained in:
bors 2020-06-20 12:36:25 +00:00
commit 31ad5f6b2b
3 changed files with 29 additions and 1 deletions

View File

@ -0,0 +1,13 @@
// Make sure we find these even with many checks disabled.
// compile-flags: -Zmiri-disable-alignment-check -Zmiri-disable-stacked-borrows -Zmiri-disable-validation
#![feature(raw_ref_macros)]
use std::ptr;
fn main() {
let p = {
let b = Box::new(42);
&*b as *const i32
};
let x = unsafe { ptr::raw_const!(*p) }; //~ ERROR dereferenced after this allocation got freed
panic!("this should never print: {:?}", x);
}

View File

@ -0,0 +1,12 @@
// This should fail even without validation or Stacked Borrows.
// compile-flags: -Zmiri-disable-validation -Zmiri-disable-stacked-borrows
#![feature(raw_ref_macros)]
use std::ptr;
fn main() {
let x = [2u16, 3, 4]; // Make it big enough so we don't get an out-of-bounds error.
let x = &x[0] as *const _ as *const u32;
// This must fail because alignment is violated: the allocation's base is not sufficiently aligned.
// The deref is UB even if we just put the result into a raw pointer.
let _x = unsafe { ptr::raw_const!(*x) }; //~ ERROR memory with alignment 2, but alignment 4 is required
}

View File

@ -1,7 +1,8 @@
#![feature(unsize, coerce_unsized, raw_ref_op)] #![feature(unsize, coerce_unsized, raw_ref_op, raw_ref_macros)]
use std::collections::hash_map::DefaultHasher; use std::collections::hash_map::DefaultHasher;
use std::hash::Hash; use std::hash::Hash;
use std::ptr;
fn test_basic() { fn test_basic() {
#[repr(packed)] #[repr(packed)]
@ -45,7 +46,9 @@ fn test(t: Test2) {
assert_eq!({x.b}, 99); assert_eq!({x.b}, 99);
// but we *can* take a raw pointer! // but we *can* take a raw pointer!
assert_eq!(unsafe { (&raw const x.a).read_unaligned() }, 42); assert_eq!(unsafe { (&raw const x.a).read_unaligned() }, 42);
assert_eq!(unsafe { ptr::raw_const!(x.a).read_unaligned() }, 42);
assert_eq!(unsafe { (&raw const x.b).read_unaligned() }, 99); assert_eq!(unsafe { (&raw const x.b).read_unaligned() }, 99);
assert_eq!(unsafe { ptr::raw_const!(x.b).read_unaligned() }, 99);
x.b = 77; x.b = 77;
assert_eq!({x.b}, 77); assert_eq!({x.b}, 77);