]> git.lizzy.rs Git - rust.git/blob - src/intptrcast.rs
Auto merge of #2029 - RalfJung:simd-bitmask, r=RalfJung
[rust.git] / src / intptrcast.rs
1 use std::cell::RefCell;
2 use std::collections::hash_map::Entry;
3
4 use log::trace;
5 use rand::Rng;
6
7 use rustc_data_structures::fx::FxHashMap;
8 use rustc_target::abi::{HasDataLayout, Size};
9
10 use crate::*;
11
12 pub type MemoryExtra = RefCell<GlobalState>;
13
14 #[derive(Clone, Debug)]
15 pub struct GlobalState {
16     /// This is used as a map between the address of each allocation and its `AllocId`.
17     /// It is always sorted
18     pub int_to_ptr_map: Vec<(u64, AllocId)>,
19     /// The base address for each allocation.  We cannot put that into
20     /// `AllocExtra` because function pointers also have a base address, and
21     /// they do not have an `AllocExtra`.
22     /// This is the inverse of `int_to_ptr_map`.
23     pub base_addr: FxHashMap<AllocId, u64>,
24     /// This is used as a memory address when a new pointer is casted to an integer. It
25     /// is always larger than any address that was previously made part of a block.
26     pub next_base_addr: u64,
27 }
28
29 impl Default for GlobalState {
30     fn default() -> Self {
31         GlobalState {
32             int_to_ptr_map: Vec::default(),
33             base_addr: FxHashMap::default(),
34             next_base_addr: STACK_ADDR,
35         }
36     }
37 }
38
39 impl<'mir, 'tcx> GlobalState {
40     pub fn ptr_from_addr(
41         addr: u64,
42         memory: &Memory<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
43     ) -> Pointer<Option<Tag>> {
44         trace!("Casting 0x{:x} to a pointer", addr);
45         let global_state = memory.extra.intptrcast.borrow();
46         let pos = global_state.int_to_ptr_map.binary_search_by_key(&addr, |(addr, _)| *addr);
47
48         let alloc_id = match pos {
49             Ok(pos) => Some(global_state.int_to_ptr_map[pos].1),
50             Err(0) => None,
51             Err(pos) => {
52                 // This is the largest of the adresses smaller than `int`,
53                 // i.e. the greatest lower bound (glb)
54                 let (glb, alloc_id) = global_state.int_to_ptr_map[pos - 1];
55                 // This never overflows because `addr >= glb`
56                 let offset = addr - glb;
57                 // If the offset exceeds the size of the allocation, don't use this `alloc_id`.
58                 if offset
59                     <= memory.get_size_and_align(alloc_id, AllocCheck::MaybeDead).unwrap().0.bytes()
60                 {
61                     Some(alloc_id)
62                 } else {
63                     None
64                 }
65             }
66         };
67         // Pointers created from integers are untagged.
68         Pointer::new(
69             alloc_id.map(|alloc_id| Tag { alloc_id, sb: SbTag::Untagged }),
70             Size::from_bytes(addr),
71         )
72     }
73
74     fn alloc_base_addr(
75         memory: &Memory<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
76         alloc_id: AllocId,
77     ) -> u64 {
78         let mut global_state = memory.extra.intptrcast.borrow_mut();
79         let global_state = &mut *global_state;
80
81         match global_state.base_addr.entry(alloc_id) {
82             Entry::Occupied(entry) => *entry.get(),
83             Entry::Vacant(entry) => {
84                 // There is nothing wrong with a raw pointer being cast to an integer only after
85                 // it became dangling.  Hence `MaybeDead`.
86                 let (size, align) =
87                     memory.get_size_and_align(alloc_id, AllocCheck::MaybeDead).unwrap();
88
89                 // This allocation does not have a base address yet, pick one.
90                 // Leave some space to the previous allocation, to give it some chance to be less aligned.
91                 let slack = {
92                     let mut rng = memory.extra.rng.borrow_mut();
93                     // This means that `(global_state.next_base_addr + slack) % 16` is uniformly distributed.
94                     rng.gen_range(0..16)
95                 };
96                 // From next_base_addr + slack, round up to adjust for alignment.
97                 let base_addr = global_state.next_base_addr.checked_add(slack).unwrap();
98                 let base_addr = Self::align_addr(base_addr, align.bytes());
99                 entry.insert(base_addr);
100                 trace!(
101                     "Assigning base address {:#x} to allocation {:?} (size: {}, align: {}, slack: {})",
102                     base_addr,
103                     alloc_id,
104                     size.bytes(),
105                     align.bytes(),
106                     slack,
107                 );
108
109                 // Remember next base address.  Leave a gap of at least 1 to avoid two zero-sized allocations
110                 // having the same base address, and to avoid ambiguous provenance for the address between two
111                 // allocations (also see https://github.com/rust-lang/unsafe-code-guidelines/issues/313).
112                 let size_plus_1 = size.bytes().checked_add(1).unwrap();
113                 global_state.next_base_addr = base_addr.checked_add(size_plus_1).unwrap();
114                 // Given that `next_base_addr` increases in each allocation, pushing the
115                 // corresponding tuple keeps `int_to_ptr_map` sorted
116                 global_state.int_to_ptr_map.push((base_addr, alloc_id));
117
118                 base_addr
119             }
120         }
121     }
122
123     /// Convert a relative (tcx) pointer to an absolute address.
124     pub fn rel_ptr_to_addr(
125         memory: &Memory<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
126         ptr: Pointer<AllocId>,
127     ) -> u64 {
128         let (alloc_id, offset) = ptr.into_parts(); // offset is relative
129         let base_addr = GlobalState::alloc_base_addr(memory, alloc_id);
130
131         // Add offset with the right kind of pointer-overflowing arithmetic.
132         let dl = memory.data_layout();
133         dl.overflowing_offset(base_addr, offset.bytes()).0
134     }
135
136     pub fn abs_ptr_to_rel(
137         memory: &Memory<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
138         ptr: Pointer<Tag>,
139     ) -> Size {
140         let (tag, addr) = ptr.into_parts(); // addr is absolute
141         let base_addr = GlobalState::alloc_base_addr(memory, tag.alloc_id);
142
143         // Wrapping "addr - base_addr"
144         let dl = memory.data_layout();
145         let neg_base_addr = (base_addr as i64).wrapping_neg();
146         Size::from_bytes(dl.overflowing_signed_offset(addr.bytes(), neg_base_addr).0)
147     }
148
149     /// Shifts `addr` to make it aligned with `align` by rounding `addr` to the smallest multiple
150     /// of `align` that is larger or equal to `addr`
151     fn align_addr(addr: u64, align: u64) -> u64 {
152         match addr % align {
153             0 => addr,
154             rem => addr.checked_add(align).unwrap() - rem,
155         }
156     }
157 }
158
159 #[cfg(test)]
160 mod tests {
161     use super::*;
162
163     #[test]
164     fn test_align_addr() {
165         assert_eq!(GlobalState::align_addr(37, 4), 40);
166         assert_eq!(GlobalState::align_addr(44, 4), 44);
167     }
168 }