]> git.lizzy.rs Git - rust.git/blob - src/tools/miri/tests/pass/adjacent-allocs.rs
Auto merge of #104915 - weihanglo:update-cargo, r=ehuss
[rust.git] / src / tools / miri / tests / pass / adjacent-allocs.rs
1 //@compile-flags: -Zmiri-permissive-provenance
2
3 fn ensure_allocs_can_be_adjacent() {
4     for _ in 0..512 {
5         let n = 0u64;
6         let ptr: *const u64 = &n;
7         let ptr2 = {
8             let m = 0u64;
9             &m as *const u64
10         };
11         if ptr.wrapping_add(1) == ptr2 {
12             return;
13         }
14     }
15     panic!("never saw adjacent stack variables?");
16 }
17
18 fn test1() {
19     // The slack between allocations is random.
20     // Loop a few times to hit the zero-slack case.
21     for _ in 0..512 {
22         let n = 0u64;
23         let ptr: *const u64 = &n;
24
25         // Allocate a new stack variable whose lifetime quickly ends.
26         // If there's a chance that &m == ptr.add(1), then an int-to-ptr cast of
27         // that value will have ambiguous provenance between n and m.
28         // See https://github.com/rust-lang/miri/issues/1866#issuecomment-985770125
29         {
30             let m = 0u64;
31             let _ = &m as *const u64;
32         }
33
34         let iptr = ptr as usize;
35         let zst = (iptr + 8) as *const ();
36         // This is a ZST ptr just at the end of `n`, so it should be valid to deref.
37         unsafe { *zst }
38     }
39 }
40
41 fn test2() {
42     fn foo() -> u64 {
43         0
44     }
45
46     for _ in 0..512 {
47         let n = 0u64;
48         let ptr: *const u64 = &n;
49         foo();
50         let iptr = ptr as usize;
51         unsafe {
52             let start = &*std::ptr::slice_from_raw_parts(iptr as *const (), 1);
53             let end = &*std::ptr::slice_from_raw_parts((iptr + 8) as *const (), 1);
54             assert_eq!(start.len(), end.len());
55         }
56     }
57 }
58
59 fn main() {
60     ensure_allocs_can_be_adjacent();
61     test1();
62     test2();
63 }