]> git.lizzy.rs Git - rust.git/blob - src/tools/miri/tests/pass/ptr_int_from_exposed.rs
Auto merge of #104915 - weihanglo:update-cargo, r=ehuss
[rust.git] / src / tools / miri / tests / pass / ptr_int_from_exposed.rs
1 //@compile-flags: -Zmiri-permissive-provenance
2 #![feature(strict_provenance)]
3
4 use std::ptr;
5
6 /// Ensure we can expose the address of a pointer that is out-of-bounds
7 fn ptr_roundtrip_out_of_bounds() {
8     let x: i32 = 3;
9     let x_ptr = &x as *const i32;
10
11     let x_usize = x_ptr.wrapping_offset(128).expose_addr();
12
13     let ptr = ptr::from_exposed_addr::<i32>(x_usize).wrapping_offset(-128);
14     assert_eq!(unsafe { *ptr }, 3);
15 }
16
17 /// Ensure that we can move between allocations after casting back to a ptr
18 fn ptr_roundtrip_confusion() {
19     let x: i32 = 0;
20     let y: i32 = 1;
21
22     let x_ptr = &x as *const i32;
23     let y_ptr = &y as *const i32;
24
25     let x_usize = x_ptr.expose_addr();
26     let y_usize = y_ptr.expose_addr();
27
28     let ptr = ptr::from_exposed_addr::<i32>(y_usize);
29     let ptr = ptr.with_addr(x_usize);
30     assert_eq!(unsafe { *ptr }, 0);
31 }
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
44 /// Ensure that we can roundtrip through a pointer with an address of 0
45 fn ptr_roundtrip_null() {
46     let x = &42;
47     let x_ptr = x as *const i32;
48     let x_null_ptr = x_ptr.with_addr(0); // addr 0, but still the provenance of x
49     let null = x_null_ptr.expose_addr();
50     assert_eq!(null, 0);
51
52     let x_null_ptr_copy = ptr::from_exposed_addr::<i32>(null); // just a roundtrip, so has provenance of x (angelically)
53     let x_ptr_copy = x_null_ptr_copy.with_addr(x_ptr.addr()); // addr of x and provenance of x
54     assert_eq!(unsafe { *x_ptr_copy }, 42);
55 }
56
57 fn main() {
58     ptr_roundtrip_out_of_bounds();
59     ptr_roundtrip_confusion();
60     ptr_roundtrip_imperfect();
61     ptr_roundtrip_null();
62 }