|
| 1 | +#![feature(strict_provenance)] |
| 2 | +use std::{mem, ptr}; |
| 3 | + |
| 4 | +fn t1() { |
| 5 | + // If we are careful, we can exploit data layout... |
| 6 | + // This is a tricky case since we are transmuting a ScalarPair type to a non-ScalarPair type. |
| 7 | + let raw = unsafe { mem::transmute::<&[u8], [*const u8; 2]>(&[42]) }; |
| 8 | + let ptr: *const u8 = unsafe { mem::transmute_copy(&raw) }; |
| 9 | + assert_eq!(unsafe { *ptr }, 42); |
| 10 | +} |
| 11 | + |
| 12 | +#[cfg(target_pointer_width = "64")] |
| 13 | +const PTR_SIZE: usize = 8; |
| 14 | +#[cfg(target_pointer_width = "32")] |
| 15 | +const PTR_SIZE: usize = 4; |
| 16 | + |
| 17 | +fn t2() { |
| 18 | + let bad = unsafe { mem::transmute::<&[u8], [u8; 2 * PTR_SIZE]>(&[1u8]) }; |
| 19 | + let _val = bad[0] + bad[bad.len() - 1]; |
| 20 | +} |
| 21 | + |
| 22 | +fn ptr_integer_array() { |
| 23 | + let r = &mut 42; |
| 24 | + let _i: [usize; 1] = unsafe { mem::transmute(r) }; |
| 25 | + |
| 26 | + let _x: [u8; PTR_SIZE] = unsafe { mem::transmute(&0) }; |
| 27 | +} |
| 28 | + |
| 29 | +fn ptr_in_two_halves() { |
| 30 | + unsafe { |
| 31 | + let ptr = &0 as *const i32; |
| 32 | + let arr = [ptr; 2]; |
| 33 | + // We want to do a scalar read of a pointer at offset PTR_SIZE/2 into this array. But we |
| 34 | + // cannot use a packed struct or `read_unaligned`, as those use the memcpy code path in |
| 35 | + // Miri. So instead we shift the entire array by a bit and then the actual read we want to |
| 36 | + // do is perfectly aligned. |
| 37 | + let mut target_arr = [ptr::null::<i32>(); 3]; |
| 38 | + let target = target_arr.as_mut_ptr().cast::<u8>(); |
| 39 | + target.add(PTR_SIZE / 2).cast::<[*const i32; 2]>().write_unaligned(arr); |
| 40 | + // Now target_arr[1] is a mix of the two `ptr` we had stored in `arr`. |
| 41 | + let strange_ptr = target_arr[1]; |
| 42 | + // Check that the provenance works out. |
| 43 | + assert_eq!(*strange_ptr.with_addr(ptr.addr()), 0); |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +fn main() { |
| 48 | + t1(); |
| 49 | + t2(); |
| 50 | + ptr_integer_array(); |
| 51 | + ptr_in_two_halves(); |
| 52 | +} |
0 commit comments