]> git.lizzy.rs Git - rust.git/blob - src/intptrcast.rs
make use of get_alloc_info
[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, FxHashSet};
8 use rustc_span::Span;
9 use rustc_target::abi::{HasDataLayout, Size};
10
11 use crate::*;
12
13 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
14 pub enum ProvenanceMode {
15     /// We support `expose_addr`/`from_exposed_addr` via "wildcard" provenance.
16     /// However, we want on `from_exposed_addr` to alert the user of the precision loss.
17     Default,
18     /// Like `Default`, but without the warning.
19     Permissive,
20     /// We error on `from_exposed_addr`, ensuring no precision loss.
21     Strict,
22 }
23
24 pub type GlobalState = RefCell<GlobalStateInner>;
25
26 #[derive(Clone, Debug)]
27 pub struct GlobalStateInner {
28     /// This is used as a map between the address of each allocation and its `AllocId`.
29     /// It is always sorted
30     int_to_ptr_map: Vec<(u64, AllocId)>,
31     /// The base address for each allocation.  We cannot put that into
32     /// `AllocExtra` because function pointers also have a base address, and
33     /// they do not have an `AllocExtra`.
34     /// This is the inverse of `int_to_ptr_map`.
35     base_addr: FxHashMap<AllocId, u64>,
36     /// Whether an allocation has been exposed or not. This cannot be put
37     /// into `AllocExtra` for the same reason as `base_addr`.
38     exposed: FxHashSet<AllocId>,
39     /// This is used as a memory address when a new pointer is casted to an integer. It
40     /// is always larger than any address that was previously made part of a block.
41     next_base_addr: u64,
42     /// The provenance to use for int2ptr casts
43     provenance_mode: ProvenanceMode,
44 }
45
46 impl GlobalStateInner {
47     pub fn new(config: &MiriConfig) -> Self {
48         GlobalStateInner {
49             int_to_ptr_map: Vec::default(),
50             base_addr: FxHashMap::default(),
51             exposed: FxHashSet::default(),
52             next_base_addr: STACK_ADDR,
53             provenance_mode: config.provenance_mode,
54         }
55     }
56 }
57
58 impl<'mir, 'tcx> GlobalStateInner {
59     // Returns the exposed `AllocId` that corresponds to the specified addr,
60     // or `None` if the addr is out of bounds
61     fn alloc_id_from_addr(ecx: &MiriEvalContext<'mir, 'tcx>, addr: u64) -> Option<AllocId> {
62         let global_state = ecx.machine.intptrcast.borrow();
63         assert!(global_state.provenance_mode != ProvenanceMode::Strict);
64
65         let pos = global_state.int_to_ptr_map.binary_search_by_key(&addr, |(addr, _)| *addr);
66
67         // Determine the in-bounds provenance for this pointer.
68         // (This is only called on an actual access, so in-bounds is the only possible kind of provenance.)
69         let alloc_id = match pos {
70             Ok(pos) => Some(global_state.int_to_ptr_map[pos].1),
71             Err(0) => None,
72             Err(pos) => {
73                 // This is the largest of the adresses smaller than `int`,
74                 // i.e. the greatest lower bound (glb)
75                 let (glb, alloc_id) = global_state.int_to_ptr_map[pos - 1];
76                 // This never overflows because `addr >= glb`
77                 let offset = addr - glb;
78                 // If the offset exceeds the size of the allocation, don't use this `alloc_id`.
79                 let size = ecx.get_alloc_info(alloc_id).0;
80                 if offset <= size.bytes() { Some(alloc_id) } else { None }
81             }
82         }?;
83
84         // We only use this provenance if it has been exposed, *and* is still live.
85         if global_state.exposed.contains(&alloc_id) {
86             let (_size, _align, kind) = ecx.get_alloc_info(alloc_id);
87             match kind {
88                 AllocKind::LiveData | AllocKind::Function => return Some(alloc_id),
89                 AllocKind::Dead => {}
90             }
91         }
92
93         None
94     }
95
96     pub fn expose_ptr(ecx: &mut MiriEvalContext<'mir, 'tcx>, alloc_id: AllocId, sb: SbTag) {
97         let global_state = ecx.machine.intptrcast.get_mut();
98         // In strict mode, we don't need this, so we can save some cycles by not tracking it.
99         if global_state.provenance_mode != ProvenanceMode::Strict {
100             trace!("Exposing allocation id {alloc_id:?}");
101             global_state.exposed.insert(alloc_id);
102             if ecx.machine.stacked_borrows.is_some() {
103                 ecx.expose_tag(alloc_id, sb);
104             }
105         }
106     }
107
108     pub fn ptr_from_addr_transmute(
109         ecx: &MiriEvalContext<'mir, 'tcx>,
110         addr: u64,
111     ) -> Pointer<Option<Tag>> {
112         trace!("Transmuting 0x{:x} to a pointer", addr);
113
114         let provenance = if ecx.machine.allow_ptr_int_transmute {
115             // When we allow transmutes, treat them like casts: generating a wildcard pointer.
116             Some(Tag::Wildcard)
117         } else {
118             // Usually, we consider transmuted pointers to be "invalid" (`None` provenance).
119             None
120         };
121         Pointer::new(provenance, Size::from_bytes(addr))
122     }
123
124     pub fn ptr_from_addr_cast(
125         ecx: &MiriEvalContext<'mir, 'tcx>,
126         addr: u64,
127     ) -> InterpResult<'tcx, Pointer<Option<Tag>>> {
128         trace!("Casting 0x{:x} to a pointer", addr);
129
130         let global_state = ecx.machine.intptrcast.borrow();
131
132         match global_state.provenance_mode {
133             ProvenanceMode::Default => {
134                 // The first time this happens at a particular location, print a warning.
135                 thread_local! {
136                     // `Span` is non-`Send`, so we use a thread-local instead.
137                     static PAST_WARNINGS: RefCell<FxHashSet<Span>> = RefCell::default();
138                 }
139                 PAST_WARNINGS.with_borrow_mut(|past_warnings| {
140                     let first = past_warnings.is_empty();
141                     if past_warnings.insert(ecx.cur_span()) {
142                         // Newly inserted, so first time we see this span.
143                         register_diagnostic(NonHaltingDiagnostic::Int2Ptr { details: first });
144                     }
145                 });
146             }
147             ProvenanceMode::Strict => {
148                 throw_unsup_format!(
149                     "integer-to-pointer casts and `from_exposed_addr` are not supported with `-Zmiri-strict-provenance`; use `with_addr` instead"
150                 )
151             }
152             ProvenanceMode::Permissive => {}
153         }
154
155         // This is how wildcard pointers are born.
156         Ok(Pointer::new(Some(Tag::Wildcard), Size::from_bytes(addr)))
157     }
158
159     fn alloc_base_addr(ecx: &MiriEvalContext<'mir, 'tcx>, alloc_id: AllocId) -> u64 {
160         let mut global_state = ecx.machine.intptrcast.borrow_mut();
161         let global_state = &mut *global_state;
162
163         match global_state.base_addr.entry(alloc_id) {
164             Entry::Occupied(entry) => *entry.get(),
165             Entry::Vacant(entry) => {
166                 // There is nothing wrong with a raw pointer being cast to an integer only after
167                 // it became dangling.  Hence we allow dead allocations.
168                 let (size, align, _kind) = ecx.get_alloc_info(alloc_id);
169
170                 // This allocation does not have a base address yet, pick one.
171                 // Leave some space to the previous allocation, to give it some chance to be less aligned.
172                 let slack = {
173                     let mut rng = ecx.machine.rng.borrow_mut();
174                     // This means that `(global_state.next_base_addr + slack) % 16` is uniformly distributed.
175                     rng.gen_range(0..16)
176                 };
177                 // From next_base_addr + slack, round up to adjust for alignment.
178                 let base_addr = global_state.next_base_addr.checked_add(slack).unwrap();
179                 let base_addr = Self::align_addr(base_addr, align.bytes());
180                 entry.insert(base_addr);
181                 trace!(
182                     "Assigning base address {:#x} to allocation {:?} (size: {}, align: {}, slack: {})",
183                     base_addr,
184                     alloc_id,
185                     size.bytes(),
186                     align.bytes(),
187                     slack,
188                 );
189
190                 // Remember next base address.  Leave a gap of at least 1 to avoid two zero-sized allocations
191                 // having the same base address, and to avoid ambiguous provenance for the address between two
192                 // allocations (also see https://github.com/rust-lang/unsafe-code-guidelines/issues/313).
193                 let size_plus_1 = size.bytes().checked_add(1).unwrap();
194                 global_state.next_base_addr = base_addr.checked_add(size_plus_1).unwrap();
195                 // Given that `next_base_addr` increases in each allocation, pushing the
196                 // corresponding tuple keeps `int_to_ptr_map` sorted
197                 global_state.int_to_ptr_map.push((base_addr, alloc_id));
198
199                 base_addr
200             }
201         }
202     }
203
204     /// Convert a relative (tcx) pointer to an absolute address.
205     pub fn rel_ptr_to_addr(ecx: &MiriEvalContext<'mir, 'tcx>, ptr: Pointer<AllocId>) -> u64 {
206         let (alloc_id, offset) = ptr.into_parts(); // offset is relative (AllocId provenance)
207         let base_addr = GlobalStateInner::alloc_base_addr(ecx, alloc_id);
208
209         // Add offset with the right kind of pointer-overflowing arithmetic.
210         let dl = ecx.data_layout();
211         dl.overflowing_offset(base_addr, offset.bytes()).0
212     }
213
214     /// When a pointer is used for a memory access, this computes where in which allocation the
215     /// access is going.
216     pub fn abs_ptr_to_rel(
217         ecx: &MiriEvalContext<'mir, 'tcx>,
218         ptr: Pointer<Tag>,
219     ) -> Option<(AllocId, Size)> {
220         let (tag, addr) = ptr.into_parts(); // addr is absolute (Tag provenance)
221
222         let alloc_id = if let Tag::Concrete { alloc_id, .. } = tag {
223             alloc_id
224         } else {
225             // A wildcard pointer.
226             GlobalStateInner::alloc_id_from_addr(ecx, addr.bytes())?
227         };
228
229         let base_addr = GlobalStateInner::alloc_base_addr(ecx, alloc_id);
230
231         // Wrapping "addr - base_addr"
232         let dl = ecx.data_layout();
233         let neg_base_addr = (base_addr as i64).wrapping_neg();
234         Some((
235             alloc_id,
236             Size::from_bytes(dl.overflowing_signed_offset(addr.bytes(), neg_base_addr).0),
237         ))
238     }
239
240     /// Shifts `addr` to make it aligned with `align` by rounding `addr` to the smallest multiple
241     /// of `align` that is larger or equal to `addr`
242     fn align_addr(addr: u64, align: u64) -> u64 {
243         match addr % align {
244             0 => addr,
245             rem => addr.checked_add(align).unwrap() - rem,
246         }
247     }
248 }
249
250 #[cfg(test)]
251 mod tests {
252     use super::*;
253
254     #[test]
255     fn test_align_addr() {
256         assert_eq!(GlobalStateInner::align_addr(37, 4), 40);
257         assert_eq!(GlobalStateInner::align_addr(44, 4), 44);
258     }
259 }