|
1 | 1 | // compile-flags: -Zmiri-permissive-provenance -Zmiri-disable-stacked-borrows
|
2 | 2 | #![feature(strict_provenance)]
|
3 | 3 |
|
| 4 | +use std::ptr; |
| 5 | + |
| 6 | +/// Ensure we can expose the address of a pointer that is out-of-bounds |
4 | 7 | fn ptr_roundtrip_out_of_bounds() {
|
5 | 8 | let x: i32 = 3;
|
6 | 9 | let x_ptr = &x as *const i32;
|
7 | 10 |
|
8 |
| - let x_usize = x_ptr.wrapping_offset(128) as usize; |
| 11 | + let x_usize = x_ptr.wrapping_offset(128).expose_addr(); |
9 | 12 |
|
10 |
| - let ptr = (x_usize as *const i32).wrapping_offset(-128); |
| 13 | + let ptr = ptr::from_exposed_addr::<i32>(x_usize).wrapping_offset(-128); |
11 | 14 | assert_eq!(unsafe { *ptr }, 3);
|
12 | 15 | }
|
13 | 16 |
|
14 |
| -fn ptr_roundtrip_out_of_bounds_with_addr() { |
| 17 | +/// Ensure that we can move between allocations using when casting |
| 18 | +fn ptr_roundtrip_confusion() { |
15 | 19 | let x: i32 = 0;
|
16 | 20 | let y: i32 = 1;
|
17 | 21 |
|
18 |
| - let x_ptr = &x as *const _; |
19 |
| - let y_ptr = &y as *const _; |
| 22 | + let x_ptr = &x as *const i32; |
| 23 | + let y_ptr = &y as *const i32; |
20 | 24 |
|
21 |
| - let x_usize = x_ptr as usize; |
22 |
| - let y_usize = y_ptr as usize; |
| 25 | + let x_usize = x_ptr.expose_addr(); |
| 26 | + let y_usize = y_ptr.expose_addr(); |
23 | 27 |
|
24 |
| - let ptr = y_usize as *const i32; |
| 28 | + let ptr = ptr::from_exposed_addr::<i32>(y_usize); |
25 | 29 | let ptr = ptr.with_addr(x_usize);
|
26 | 30 | assert_eq!(unsafe { *ptr }, 0);
|
27 | 31 | }
|
28 | 32 |
|
| 33 | +/// Ensure we can cast back a different integer than the one we got when exposing. |
| 34 | +fn ptr_roundtrip_imperfect() { |
| 35 | + let x: u8 = 3; |
| 36 | + let x_ptr = &x as *const u8; |
| 37 | + |
| 38 | + let x_usize = x_ptr.expose_addr() + 128; |
| 39 | + |
| 40 | + let ptr = ptr::from_exposed_addr::<u8>(x_usize).wrapping_offset(-128); |
| 41 | + assert_eq!(unsafe { *ptr }, 3); |
| 42 | +} |
| 43 | + |
29 | 44 | fn main() {
|
30 | 45 | ptr_roundtrip_out_of_bounds();
|
31 |
| - ptr_roundtrip_out_of_bounds_with_addr(); |
| 46 | + ptr_roundtrip_confusion(); |
| 47 | + ptr_roundtrip_imperfect(); |
32 | 48 | }
|
0 commit comments