miri/alloc_addresses/
mod.rs

1//! This module is responsible for managing the absolute addresses that allocations are located at,
2//! and for casting between pointers and integers based on those addresses.
3
4mod reuse_pool;
5
6use std::cell::RefCell;
7use std::cmp::max;
8
9use rand::Rng;
10use rustc_abi::{Align, Size};
11use rustc_data_structures::fx::{FxHashMap, FxHashSet};
12
13use self::reuse_pool::ReusePool;
14use crate::concurrency::VClock;
15use crate::*;
16
17#[derive(Copy, Clone, Debug, PartialEq, Eq)]
18pub enum ProvenanceMode {
19    /// We support `expose_provenance`/`with_exposed_provenance` via "wildcard" provenance.
20    /// However, we warn on `with_exposed_provenance` to alert the user of the precision loss.
21    Default,
22    /// Like `Default`, but without the warning.
23    Permissive,
24    /// We error on `with_exposed_provenance`, ensuring no precision loss.
25    Strict,
26}
27
28pub type GlobalState = RefCell<GlobalStateInner>;
29
30#[derive(Debug)]
31pub struct GlobalStateInner {
32    /// This is used as a map between the address of each allocation and its `AllocId`. It is always
33    /// sorted by address. We cannot use a `HashMap` since we can be given an address that is offset
34    /// from the base address, and we need to find the `AllocId` it belongs to. This is not the
35    /// *full* inverse of `base_addr`; dead allocations have been removed.
36    int_to_ptr_map: Vec<(u64, AllocId)>,
37    /// The base address for each allocation.  We cannot put that into
38    /// `AllocExtra` because function pointers also have a base address, and
39    /// they do not have an `AllocExtra`.
40    /// This is the inverse of `int_to_ptr_map`.
41    base_addr: FxHashMap<AllocId, u64>,
42    /// Temporarily store prepared memory space for global allocations the first time their memory
43    /// address is required. This is used to ensure that the memory is allocated before Miri assigns
44    /// it an internal address, which is important for matching the internal address to the machine
45    /// address so FFI can read from pointers.
46    prepared_alloc_bytes: FxHashMap<AllocId, MiriAllocBytes>,
47    /// A pool of addresses we can reuse for future allocations.
48    reuse: ReusePool,
49    /// Whether an allocation has been exposed or not. This cannot be put
50    /// into `AllocExtra` for the same reason as `base_addr`.
51    exposed: FxHashSet<AllocId>,
52    /// This is used as a memory address when a new pointer is casted to an integer. It
53    /// is always larger than any address that was previously made part of a block.
54    next_base_addr: u64,
55    /// The provenance to use for int2ptr casts
56    provenance_mode: ProvenanceMode,
57}
58
59impl VisitProvenance for GlobalStateInner {
60    fn visit_provenance(&self, _visit: &mut VisitWith<'_>) {
61        let GlobalStateInner {
62            int_to_ptr_map: _,
63            base_addr: _,
64            prepared_alloc_bytes: _,
65            reuse: _,
66            exposed: _,
67            next_base_addr: _,
68            provenance_mode: _,
69        } = self;
70        // Though base_addr, int_to_ptr_map, and exposed contain AllocIds, we do not want to visit them.
71        // int_to_ptr_map and exposed must contain only live allocations, and those
72        // are never garbage collected.
73        // base_addr is only relevant if we have a pointer to an AllocId and need to look up its
74        // base address; so if an AllocId is not reachable from somewhere else we can remove it
75        // here.
76    }
77}
78
79impl GlobalStateInner {
80    pub fn new(config: &MiriConfig, stack_addr: u64) -> Self {
81        GlobalStateInner {
82            int_to_ptr_map: Vec::default(),
83            base_addr: FxHashMap::default(),
84            prepared_alloc_bytes: FxHashMap::default(),
85            reuse: ReusePool::new(config),
86            exposed: FxHashSet::default(),
87            next_base_addr: stack_addr,
88            provenance_mode: config.provenance_mode,
89        }
90    }
91
92    pub fn remove_unreachable_allocs(&mut self, allocs: &LiveAllocs<'_, '_>) {
93        // `exposed` and `int_to_ptr_map` are cleared immediately when an allocation
94        // is freed, so `base_addr` is the only one we have to clean up based on the GC.
95        self.base_addr.retain(|id, _| allocs.is_live(*id));
96    }
97}
98
99/// Shifts `addr` to make it aligned with `align` by rounding `addr` to the smallest multiple
100/// of `align` that is larger or equal to `addr`
101fn align_addr(addr: u64, align: u64) -> u64 {
102    match addr % align {
103        0 => addr,
104        rem => addr.strict_add(align) - rem,
105    }
106}
107
108impl<'tcx> EvalContextExtPriv<'tcx> for crate::MiriInterpCx<'tcx> {}
109trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> {
110    // Returns the exposed `AllocId` that corresponds to the specified addr,
111    // or `None` if the addr is out of bounds
112    fn alloc_id_from_addr(&self, addr: u64, size: i64) -> Option<AllocId> {
113        let this = self.eval_context_ref();
114        let global_state = this.machine.alloc_addresses.borrow();
115        assert!(global_state.provenance_mode != ProvenanceMode::Strict);
116
117        // We always search the allocation to the right of this address. So if the size is structly
118        // negative, we have to search for `addr-1` instead.
119        let addr = if size >= 0 { addr } else { addr.saturating_sub(1) };
120        let pos = global_state.int_to_ptr_map.binary_search_by_key(&addr, |(addr, _)| *addr);
121
122        // Determine the in-bounds provenance for this pointer.
123        let alloc_id = match pos {
124            Ok(pos) => Some(global_state.int_to_ptr_map[pos].1),
125            Err(0) => None,
126            Err(pos) => {
127                // This is the largest of the addresses smaller than `int`,
128                // i.e. the greatest lower bound (glb)
129                let (glb, alloc_id) = global_state.int_to_ptr_map[pos - 1];
130                // This never overflows because `addr >= glb`
131                let offset = addr - glb;
132                // We require this to be strict in-bounds of the allocation. This arm is only
133                // entered for addresses that are not the base address, so even zero-sized
134                // allocations will get recognized at their base address -- but all other
135                // allocations will *not* be recognized at their "end" address.
136                let size = this.get_alloc_info(alloc_id).size;
137                if offset < size.bytes() { Some(alloc_id) } else { None }
138            }
139        }?;
140
141        // We only use this provenance if it has been exposed.
142        if global_state.exposed.contains(&alloc_id) {
143            // This must still be live, since we remove allocations from `int_to_ptr_map` when they get freed.
144            debug_assert!(this.is_alloc_live(alloc_id));
145            Some(alloc_id)
146        } else {
147            None
148        }
149    }
150
151    fn addr_from_alloc_id_uncached(
152        &self,
153        global_state: &mut GlobalStateInner,
154        alloc_id: AllocId,
155        memory_kind: MemoryKind,
156    ) -> InterpResult<'tcx, u64> {
157        let this = self.eval_context_ref();
158        let mut rng = this.machine.rng.borrow_mut();
159        let info = this.get_alloc_info(alloc_id);
160        // This is either called immediately after allocation (and then cached), or when
161        // adjusting `tcx` pointers (which never get freed). So assert that we are looking
162        // at a live allocation. This also ensures that we never re-assign an address to an
163        // allocation that previously had an address, but then was freed and the address
164        // information was removed.
165        assert!(!matches!(info.kind, AllocKind::Dead));
166
167        // This allocation does not have a base address yet, pick or reuse one.
168        if this.machine.native_lib.is_some() {
169            // In native lib mode, we use the "real" address of the bytes for this allocation.
170            // This ensures the interpreted program and native code have the same view of memory.
171            let base_ptr = match info.kind {
172                AllocKind::LiveData => {
173                    if this.tcx.try_get_global_alloc(alloc_id).is_some() {
174                        // For new global allocations, we always pre-allocate the memory to be able use the machine address directly.
175                        let prepared_bytes = MiriAllocBytes::zeroed(info.size, info.align)
176                            .unwrap_or_else(|| {
177                                panic!("Miri ran out of memory: cannot create allocation of {size:?} bytes", size = info.size)
178                            });
179                        let ptr = prepared_bytes.as_ptr();
180                        // Store prepared allocation space to be picked up for use later.
181                        global_state
182                            .prepared_alloc_bytes
183                            .try_insert(alloc_id, prepared_bytes)
184                            .unwrap();
185                        ptr
186                    } else {
187                        this.get_alloc_bytes_unchecked_raw(alloc_id)?
188                    }
189                }
190                AllocKind::Function | AllocKind::VTable => {
191                    // Allocate some dummy memory to get a unique address for this function/vtable.
192                    let alloc_bytes =
193                        MiriAllocBytes::from_bytes(&[0u8; 1], Align::from_bytes(1).unwrap());
194                    let ptr = alloc_bytes.as_ptr();
195                    // Leak the underlying memory to ensure it remains unique.
196                    std::mem::forget(alloc_bytes);
197                    ptr
198                }
199                AllocKind::Dead => unreachable!(),
200            };
201            // We don't have to expose this pointer yet, we do that in `prepare_for_native_call`.
202            return interp_ok(base_ptr.addr().try_into().unwrap());
203        }
204        // We are not in native lib mode, so we control the addresses ourselves.
205        if let Some((reuse_addr, clock)) = global_state.reuse.take_addr(
206            &mut *rng,
207            info.size,
208            info.align,
209            memory_kind,
210            this.active_thread(),
211        ) {
212            if let Some(clock) = clock {
213                this.acquire_clock(&clock);
214            }
215            interp_ok(reuse_addr)
216        } else {
217            // We have to pick a fresh address.
218            // Leave some space to the previous allocation, to give it some chance to be less aligned.
219            // We ensure that `(global_state.next_base_addr + slack) % 16` is uniformly distributed.
220            let slack = rng.random_range(0..16);
221            // From next_base_addr + slack, round up to adjust for alignment.
222            let base_addr = global_state
223                .next_base_addr
224                .checked_add(slack)
225                .ok_or_else(|| err_exhaust!(AddressSpaceFull))?;
226            let base_addr = align_addr(base_addr, info.align.bytes());
227
228            // Remember next base address.  If this allocation is zero-sized, leave a gap of at
229            // least 1 to avoid two allocations having the same base address. (The logic in
230            // `alloc_id_from_addr` assumes unique addresses, and different function/vtable pointers
231            // need to be distinguishable!)
232            global_state.next_base_addr = base_addr
233                .checked_add(max(info.size.bytes(), 1))
234                .ok_or_else(|| err_exhaust!(AddressSpaceFull))?;
235            // Even if `Size` didn't overflow, we might still have filled up the address space.
236            if global_state.next_base_addr > this.target_usize_max() {
237                throw_exhaust!(AddressSpaceFull);
238            }
239
240            interp_ok(base_addr)
241        }
242    }
243
244    fn addr_from_alloc_id(
245        &self,
246        alloc_id: AllocId,
247        memory_kind: MemoryKind,
248    ) -> InterpResult<'tcx, u64> {
249        let this = self.eval_context_ref();
250        let mut global_state = this.machine.alloc_addresses.borrow_mut();
251        let global_state = &mut *global_state;
252
253        match global_state.base_addr.get(&alloc_id) {
254            Some(&addr) => interp_ok(addr),
255            None => {
256                // First time we're looking for the absolute address of this allocation.
257                let base_addr =
258                    self.addr_from_alloc_id_uncached(global_state, alloc_id, memory_kind)?;
259                trace!("Assigning base address {:#x} to allocation {:?}", base_addr, alloc_id);
260
261                // Store address in cache.
262                global_state.base_addr.try_insert(alloc_id, base_addr).unwrap();
263
264                // Also maintain the opposite mapping in `int_to_ptr_map`, ensuring we keep it sorted.
265                // We have a fast-path for the common case that this address is bigger than all previous ones.
266                let pos = if global_state
267                    .int_to_ptr_map
268                    .last()
269                    .is_some_and(|(last_addr, _)| *last_addr < base_addr)
270                {
271                    global_state.int_to_ptr_map.len()
272                } else {
273                    global_state
274                        .int_to_ptr_map
275                        .binary_search_by_key(&base_addr, |(addr, _)| *addr)
276                        .unwrap_err()
277                };
278                global_state.int_to_ptr_map.insert(pos, (base_addr, alloc_id));
279
280                interp_ok(base_addr)
281            }
282        }
283    }
284}
285
286impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
287pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
288    fn expose_provenance(&self, provenance: Provenance) -> InterpResult<'tcx> {
289        let this = self.eval_context_ref();
290        let mut global_state = this.machine.alloc_addresses.borrow_mut();
291
292        let (alloc_id, tag) = match provenance {
293            Provenance::Concrete { alloc_id, tag } => (alloc_id, tag),
294            Provenance::Wildcard => {
295                // No need to do anything for wildcard pointers as
296                // their provenances have already been previously exposed.
297                return interp_ok(());
298            }
299        };
300
301        // In strict mode, we don't need this, so we can save some cycles by not tracking it.
302        if global_state.provenance_mode == ProvenanceMode::Strict {
303            return interp_ok(());
304        }
305        // Exposing a dead alloc is a no-op, because it's not possible to get a dead allocation
306        // via int2ptr.
307        if !this.is_alloc_live(alloc_id) {
308            return interp_ok(());
309        }
310        trace!("Exposing allocation id {alloc_id:?}");
311        global_state.exposed.insert(alloc_id);
312        // Release the global state before we call `expose_tag`, which may call `get_alloc_info_extra`,
313        // which may need access to the global state.
314        drop(global_state);
315        if this.machine.borrow_tracker.is_some() {
316            this.expose_tag(alloc_id, tag)?;
317        }
318        interp_ok(())
319    }
320
321    fn ptr_from_addr_cast(&self, addr: u64) -> InterpResult<'tcx, Pointer> {
322        trace!("Casting {:#x} to a pointer", addr);
323
324        let this = self.eval_context_ref();
325        let global_state = this.machine.alloc_addresses.borrow();
326
327        // Potentially emit a warning.
328        match global_state.provenance_mode {
329            ProvenanceMode::Default => {
330                // The first time this happens at a particular location, print a warning.
331                let mut int2ptr_warned = this.machine.int2ptr_warned.borrow_mut();
332                let first = int2ptr_warned.is_empty();
333                if int2ptr_warned.insert(this.cur_span()) {
334                    // Newly inserted, so first time we see this span.
335                    this.emit_diagnostic(NonHaltingDiagnostic::Int2Ptr { details: first });
336                }
337            }
338            ProvenanceMode::Strict => {
339                throw_machine_stop!(TerminationInfo::Int2PtrWithStrictProvenance);
340            }
341            ProvenanceMode::Permissive => {}
342        }
343
344        // We do *not* look up the `AllocId` here! This is a `ptr as usize` cast, and it is
345        // completely legal to do a cast and then `wrapping_offset` to another allocation and only
346        // *then* do a memory access. So the allocation that the pointer happens to point to on a
347        // cast is fairly irrelevant. Instead we generate this as a "wildcard" pointer, such that
348        // *every time the pointer is used*, we do an `AllocId` lookup to find the (exposed)
349        // allocation it might be referencing.
350        interp_ok(Pointer::new(Some(Provenance::Wildcard), Size::from_bytes(addr)))
351    }
352
353    /// Convert a relative (tcx) pointer to a Miri pointer.
354    fn adjust_alloc_root_pointer(
355        &self,
356        ptr: interpret::Pointer<CtfeProvenance>,
357        tag: BorTag,
358        kind: MemoryKind,
359    ) -> InterpResult<'tcx, interpret::Pointer<Provenance>> {
360        let this = self.eval_context_ref();
361
362        let (prov, offset) = ptr.into_parts(); // offset is relative (AllocId provenance)
363        let alloc_id = prov.alloc_id();
364
365        // Get a pointer to the beginning of this allocation.
366        let base_addr = this.addr_from_alloc_id(alloc_id, kind)?;
367        let base_ptr = interpret::Pointer::new(
368            Provenance::Concrete { alloc_id, tag },
369            Size::from_bytes(base_addr),
370        );
371        // Add offset with the right kind of pointer-overflowing arithmetic.
372        interp_ok(base_ptr.wrapping_offset(offset, this))
373    }
374
375    // This returns some prepared `MiriAllocBytes`, either because `addr_from_alloc_id` reserved
376    // memory space in the past, or by doing the pre-allocation right upon being called.
377    fn get_global_alloc_bytes(
378        &self,
379        id: AllocId,
380        bytes: &[u8],
381        align: Align,
382    ) -> InterpResult<'tcx, MiriAllocBytes> {
383        let this = self.eval_context_ref();
384        if this.machine.native_lib.is_some() {
385            // In native lib mode, MiriAllocBytes for global allocations are handled via `prepared_alloc_bytes`.
386            // This additional call ensures that some `MiriAllocBytes` are always prepared, just in case
387            // this function gets called before the first time `addr_from_alloc_id` gets called.
388            this.addr_from_alloc_id(id, MiriMemoryKind::Global.into())?;
389            // The memory we need here will have already been allocated during an earlier call to
390            // `addr_from_alloc_id` for this allocation. So don't create a new `MiriAllocBytes` here, instead
391            // fetch the previously prepared bytes from `prepared_alloc_bytes`.
392            let mut global_state = this.machine.alloc_addresses.borrow_mut();
393            let mut prepared_alloc_bytes = global_state
394                .prepared_alloc_bytes
395                .remove(&id)
396                .unwrap_or_else(|| panic!("alloc bytes for {id:?} have not been prepared"));
397            // Sanity-check that the prepared allocation has the right size and alignment.
398            assert!(prepared_alloc_bytes.as_ptr().is_aligned_to(align.bytes_usize()));
399            assert_eq!(prepared_alloc_bytes.len(), bytes.len());
400            // Copy allocation contents into prepared memory.
401            prepared_alloc_bytes.copy_from_slice(bytes);
402            interp_ok(prepared_alloc_bytes)
403        } else {
404            interp_ok(MiriAllocBytes::from_bytes(std::borrow::Cow::Borrowed(bytes), align))
405        }
406    }
407
408    /// When a pointer is used for a memory access, this computes where in which allocation the
409    /// access is going.
410    fn ptr_get_alloc(
411        &self,
412        ptr: interpret::Pointer<Provenance>,
413        size: i64,
414    ) -> Option<(AllocId, Size)> {
415        let this = self.eval_context_ref();
416
417        let (tag, addr) = ptr.into_parts(); // addr is absolute (Tag provenance)
418
419        let alloc_id = if let Provenance::Concrete { alloc_id, .. } = tag {
420            alloc_id
421        } else {
422            // A wildcard pointer.
423            this.alloc_id_from_addr(addr.bytes(), size)?
424        };
425
426        // This cannot fail: since we already have a pointer with that provenance, adjust_alloc_root_pointer
427        // must have been called in the past, so we can just look up the address in the map.
428        let base_addr = *this.machine.alloc_addresses.borrow().base_addr.get(&alloc_id).unwrap();
429
430        // Wrapping "addr - base_addr"
431        let rel_offset = this.truncate_to_target_usize(addr.bytes().wrapping_sub(base_addr));
432        Some((alloc_id, Size::from_bytes(rel_offset)))
433    }
434
435    /// Prepare all exposed memory for a native call.
436    /// This overapproximates the modifications which external code might make to memory:
437    /// We set all reachable allocations as initialized, mark all reachable provenances as exposed
438    /// and overwrite them with `Provenance::WILDCARD`.
439    fn prepare_exposed_for_native_call(&mut self) -> InterpResult<'tcx> {
440        let this = self.eval_context_mut();
441        // We need to make a deep copy of this list, but it's fine; it also serves as scratch space
442        // for the search within `prepare_for_native_call`.
443        let exposed: Vec<AllocId> =
444            this.machine.alloc_addresses.get_mut().exposed.iter().copied().collect();
445        this.prepare_for_native_call(exposed)
446    }
447}
448
449impl<'tcx> MiriMachine<'tcx> {
450    pub fn free_alloc_id(&mut self, dead_id: AllocId, size: Size, align: Align, kind: MemoryKind) {
451        let global_state = self.alloc_addresses.get_mut();
452        let rng = self.rng.get_mut();
453
454        // We can *not* remove this from `base_addr`, since the interpreter design requires that we
455        // be able to retrieve an AllocId + offset for any memory access *before* we check if the
456        // access is valid. Specifically, `ptr_get_alloc` is called on each attempt at a memory
457        // access to determine the allocation ID and offset -- and there can still be pointers with
458        // `dead_id` that one can attempt to use for a memory access. `ptr_get_alloc` may return
459        // `None` only if the pointer truly has no provenance (this ensures consistent error
460        // messages).
461        // However, we *can* remove it from `int_to_ptr_map`, since any wildcard pointers that exist
462        // can no longer actually be accessing that address. This ensures `alloc_id_from_addr` never
463        // returns a dead allocation.
464        // To avoid a linear scan we first look up the address in `base_addr`, and then find it in
465        // `int_to_ptr_map`.
466        let addr = *global_state.base_addr.get(&dead_id).unwrap();
467        let pos =
468            global_state.int_to_ptr_map.binary_search_by_key(&addr, |(addr, _)| *addr).unwrap();
469        let removed = global_state.int_to_ptr_map.remove(pos);
470        assert_eq!(removed, (addr, dead_id)); // double-check that we removed the right thing
471        // We can also remove it from `exposed`, since this allocation can anyway not be returned by
472        // `alloc_id_from_addr` any more.
473        global_state.exposed.remove(&dead_id);
474        // Also remember this address for future reuse.
475        let thread = self.threads.active_thread();
476        global_state.reuse.add_addr(rng, addr, size, align, kind, thread, || {
477            if let Some(data_race) = &self.data_race {
478                data_race.release_clock(&self.threads, |clock| clock.clone())
479            } else {
480                VClock::default()
481            }
482        })
483    }
484}
485
486#[cfg(test)]
487mod tests {
488    use super::*;
489
490    #[test]
491    fn test_align_addr() {
492        assert_eq!(align_addr(37, 4), 40);
493        assert_eq!(align_addr(44, 4), 44);
494    }
495}