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    fn addr_from_alloc_id_uncached(
111        &self,
112        global_state: &mut GlobalStateInner,
113        alloc_id: AllocId,
114        memory_kind: MemoryKind,
115    ) -> InterpResult<'tcx, u64> {
116        let this = self.eval_context_ref();
117        let info = this.get_alloc_info(alloc_id);
118
119        // Miri's address assignment leaks state across thread boundaries, which is incompatible
120        // with GenMC execution. So we instead let GenMC assign addresses to allocations.
121        if let Some(genmc_ctx) = this.machine.data_race.as_genmc_ref() {
122            let addr = genmc_ctx.handle_alloc(&this.machine, info.size, info.align, memory_kind)?;
123            return interp_ok(addr);
124        }
125
126        let mut rng = this.machine.rng.borrow_mut();
127        // This is either called immediately after allocation (and then cached), or when
128        // adjusting `tcx` pointers (which never get freed). So assert that we are looking
129        // at a live allocation. This also ensures that we never re-assign an address to an
130        // allocation that previously had an address, but then was freed and the address
131        // information was removed.
132        assert!(!matches!(info.kind, AllocKind::Dead));
133
134        // This allocation does not have a base address yet, pick or reuse one.
135        if this.machine.native_lib.is_some() {
136            // In native lib mode, we use the "real" address of the bytes for this allocation.
137            // This ensures the interpreted program and native code have the same view of memory.
138            let base_ptr = match info.kind {
139                AllocKind::LiveData => {
140                    if memory_kind == MiriMemoryKind::Global.into() {
141                        // For new global allocations, we always pre-allocate the memory to be able use the machine address directly.
142                        let prepared_bytes = MiriAllocBytes::zeroed(info.size, info.align)
143                            .unwrap_or_else(|| {
144                                panic!("Miri ran out of memory: cannot create allocation of {size:?} bytes", size = info.size)
145                            });
146                        let ptr = prepared_bytes.as_ptr();
147                        // Store prepared allocation to be picked up for use later.
148                        global_state
149                            .prepared_alloc_bytes
150                            .try_insert(alloc_id, prepared_bytes)
151                            .unwrap();
152                        ptr
153                    } else {
154                        // Non-global allocations are already in memory at this point so
155                        // we can just get a pointer to where their data is stored.
156                        this.get_alloc_bytes_unchecked_raw(alloc_id)?
157                    }
158                }
159                AllocKind::Function | AllocKind::VTable => {
160                    // Allocate some dummy memory to get a unique address for this function/vtable.
161                    let alloc_bytes =
162                        MiriAllocBytes::from_bytes(&[0u8; 1], Align::from_bytes(1).unwrap());
163                    let ptr = alloc_bytes.as_ptr();
164                    // Leak the underlying memory to ensure it remains unique.
165                    std::mem::forget(alloc_bytes);
166                    ptr
167                }
168                AllocKind::Dead => unreachable!(),
169            };
170            // We don't have to expose this pointer yet, we do that in `prepare_for_native_call`.
171            return interp_ok(base_ptr.addr().try_into().unwrap());
172        }
173        // We are not in native lib mode, so we control the addresses ourselves.
174        if let Some((reuse_addr, clock)) = global_state.reuse.take_addr(
175            &mut *rng,
176            info.size,
177            info.align,
178            memory_kind,
179            this.active_thread(),
180        ) {
181            if let Some(clock) = clock {
182                this.acquire_clock(&clock);
183            }
184            interp_ok(reuse_addr)
185        } else {
186            // We have to pick a fresh address.
187            // Leave some space to the previous allocation, to give it some chance to be less aligned.
188            // We ensure that `(global_state.next_base_addr + slack) % 16` is uniformly distributed.
189            let slack = rng.random_range(0..16);
190            // From next_base_addr + slack, round up to adjust for alignment.
191            let base_addr = global_state
192                .next_base_addr
193                .checked_add(slack)
194                .ok_or_else(|| err_exhaust!(AddressSpaceFull))?;
195            let base_addr = align_addr(base_addr, info.align.bytes());
196
197            // Remember next base address.  If this allocation is zero-sized, leave a gap of at
198            // least 1 to avoid two allocations having the same base address. (The logic in
199            // `alloc_id_from_addr` assumes unique addresses, and different function/vtable pointers
200            // need to be distinguishable!)
201            global_state.next_base_addr = base_addr
202                .checked_add(max(info.size.bytes(), 1))
203                .ok_or_else(|| err_exhaust!(AddressSpaceFull))?;
204            // Even if `Size` didn't overflow, we might still have filled up the address space.
205            if global_state.next_base_addr > this.target_usize_max() {
206                throw_exhaust!(AddressSpaceFull);
207            }
208            // If we filled up more than half the address space, start aggressively reusing
209            // addresses to avoid running out.
210            if global_state.next_base_addr > u64::try_from(this.target_isize_max()).unwrap() {
211                global_state.reuse.address_space_shortage();
212            }
213
214            interp_ok(base_addr)
215        }
216    }
217}
218
219impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
220pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
221    // Returns the `AllocId` that corresponds to the specified addr,
222    // or `None` if the addr is out of bounds.
223    // Setting `only_exposed_allocations` selects whether only exposed allocations are considered.
224    fn alloc_id_from_addr(
225        &self,
226        addr: u64,
227        size: i64,
228        only_exposed_allocations: bool,
229    ) -> Option<AllocId> {
230        let this = self.eval_context_ref();
231        let global_state = this.machine.alloc_addresses.borrow();
232        assert!(global_state.provenance_mode != ProvenanceMode::Strict);
233
234        // We always search the allocation to the right of this address. So if the size is strictly
235        // negative, we have to search for `addr-1` instead.
236        let addr = if size >= 0 { addr } else { addr.saturating_sub(1) };
237        let pos = global_state.int_to_ptr_map.binary_search_by_key(&addr, |(addr, _)| *addr);
238
239        // Determine the in-bounds provenance for this pointer.
240        let alloc_id = match pos {
241            Ok(pos) => Some(global_state.int_to_ptr_map[pos].1),
242            Err(0) => None,
243            Err(pos) => {
244                // This is the largest of the addresses smaller than `int`,
245                // i.e. the greatest lower bound (glb)
246                let (glb, alloc_id) = global_state.int_to_ptr_map[pos - 1];
247                // This never overflows because `addr >= glb`
248                let offset = addr - glb;
249                // We require this to be strict in-bounds of the allocation. This arm is only
250                // entered for addresses that are not the base address, so even zero-sized
251                // allocations will get recognized at their base address -- but all other
252                // allocations will *not* be recognized at their "end" address.
253                let size = this.get_alloc_info(alloc_id).size;
254                if offset < size.bytes() { Some(alloc_id) } else { None }
255            }
256        }?;
257
258        // We only use this provenance if it has been exposed, or if the caller requested also non-exposed allocations
259        if !only_exposed_allocations || global_state.exposed.contains(&alloc_id) {
260            // This must still be live, since we remove allocations from `int_to_ptr_map` when they get freed.
261            debug_assert!(this.is_alloc_live(alloc_id));
262            Some(alloc_id)
263        } else {
264            None
265        }
266    }
267
268    /// Returns the base address of an allocation, or an error if no base address could be found
269    ///
270    /// # Panics
271    /// If `memory_kind = None` and the `alloc_id` is not cached, meaning that the first call to this function per `alloc_id` must get the `memory_kind`.
272    fn addr_from_alloc_id(
273        &self,
274        alloc_id: AllocId,
275        memory_kind: Option<MemoryKind>,
276    ) -> InterpResult<'tcx, u64> {
277        let this = self.eval_context_ref();
278        let mut global_state = this.machine.alloc_addresses.borrow_mut();
279        let global_state = &mut *global_state;
280
281        match global_state.base_addr.get(&alloc_id) {
282            Some(&addr) => interp_ok(addr),
283            None => {
284                // First time we're looking for the absolute address of this allocation.
285                let memory_kind =
286                    memory_kind.expect("memory_kind is required since alloc_id is not cached");
287                let base_addr =
288                    this.addr_from_alloc_id_uncached(global_state, alloc_id, memory_kind)?;
289                trace!("Assigning base address {:#x} to allocation {:?}", base_addr, alloc_id);
290
291                // Store address in cache.
292                global_state.base_addr.try_insert(alloc_id, base_addr).unwrap();
293
294                // Also maintain the opposite mapping in `int_to_ptr_map`, ensuring we keep it sorted.
295                // We have a fast-path for the common case that this address is bigger than all previous ones.
296                let pos = if global_state
297                    .int_to_ptr_map
298                    .last()
299                    .is_some_and(|(last_addr, _)| *last_addr < base_addr)
300                {
301                    global_state.int_to_ptr_map.len()
302                } else {
303                    global_state
304                        .int_to_ptr_map
305                        .binary_search_by_key(&base_addr, |(addr, _)| *addr)
306                        .unwrap_err()
307                };
308                global_state.int_to_ptr_map.insert(pos, (base_addr, alloc_id));
309
310                interp_ok(base_addr)
311            }
312        }
313    }
314
315    fn expose_provenance(&self, provenance: Provenance) -> InterpResult<'tcx> {
316        let this = self.eval_context_ref();
317        let mut global_state = this.machine.alloc_addresses.borrow_mut();
318
319        let (alloc_id, tag) = match provenance {
320            Provenance::Concrete { alloc_id, tag } => (alloc_id, tag),
321            Provenance::Wildcard => {
322                // No need to do anything for wildcard pointers as
323                // their provenances have already been previously exposed.
324                return interp_ok(());
325            }
326        };
327
328        // In strict mode, we don't need this, so we can save some cycles by not tracking it.
329        if global_state.provenance_mode == ProvenanceMode::Strict {
330            return interp_ok(());
331        }
332        // Exposing a dead alloc is a no-op, because it's not possible to get a dead allocation
333        // via int2ptr.
334        if !this.is_alloc_live(alloc_id) {
335            return interp_ok(());
336        }
337        trace!("Exposing allocation id {alloc_id:?}");
338        global_state.exposed.insert(alloc_id);
339        // Release the global state before we call `expose_tag`, which may call `get_alloc_info_extra`,
340        // which may need access to the global state.
341        drop(global_state);
342        if this.machine.borrow_tracker.is_some() {
343            this.expose_tag(alloc_id, tag)?;
344        }
345        interp_ok(())
346    }
347
348    fn ptr_from_addr_cast(&self, addr: u64) -> InterpResult<'tcx, Pointer> {
349        trace!("Casting {:#x} to a pointer", addr);
350
351        let this = self.eval_context_ref();
352        let global_state = this.machine.alloc_addresses.borrow();
353
354        // Potentially emit a warning.
355        match global_state.provenance_mode {
356            ProvenanceMode::Default => {
357                // The first time this happens at a particular location, print a warning.
358                let mut int2ptr_warned = this.machine.int2ptr_warned.borrow_mut();
359                let first = int2ptr_warned.is_empty();
360                if int2ptr_warned.insert(this.cur_span()) {
361                    // Newly inserted, so first time we see this span.
362                    this.emit_diagnostic(NonHaltingDiagnostic::Int2Ptr { details: first });
363                }
364            }
365            ProvenanceMode::Strict => {
366                throw_machine_stop!(TerminationInfo::Int2PtrWithStrictProvenance);
367            }
368            ProvenanceMode::Permissive => {}
369        }
370
371        // We do *not* look up the `AllocId` here! This is a `ptr as usize` cast, and it is
372        // completely legal to do a cast and then `wrapping_offset` to another allocation and only
373        // *then* do a memory access. So the allocation that the pointer happens to point to on a
374        // cast is fairly irrelevant. Instead we generate this as a "wildcard" pointer, such that
375        // *every time the pointer is used*, we do an `AllocId` lookup to find the (exposed)
376        // allocation it might be referencing.
377        interp_ok(Pointer::new(Some(Provenance::Wildcard), Size::from_bytes(addr)))
378    }
379
380    /// Convert a relative (tcx) pointer to a Miri pointer.
381    fn adjust_alloc_root_pointer(
382        &self,
383        ptr: interpret::Pointer<CtfeProvenance>,
384        tag: BorTag,
385        kind: MemoryKind,
386    ) -> InterpResult<'tcx, interpret::Pointer<Provenance>> {
387        let this = self.eval_context_ref();
388
389        let (prov, offset) = ptr.into_parts(); // offset is relative (AllocId provenance)
390        let alloc_id = prov.alloc_id();
391
392        // Get a pointer to the beginning of this allocation.
393        let base_addr = this.addr_from_alloc_id(alloc_id, Some(kind))?;
394        let base_ptr = interpret::Pointer::new(
395            Provenance::Concrete { alloc_id, tag },
396            Size::from_bytes(base_addr),
397        );
398        // Add offset with the right kind of pointer-overflowing arithmetic.
399        interp_ok(base_ptr.wrapping_offset(offset, this))
400    }
401
402    // This returns some prepared `MiriAllocBytes`, either because `addr_from_alloc_id` reserved
403    // memory space in the past, or by doing the pre-allocation right upon being called.
404    fn get_global_alloc_bytes(
405        &self,
406        id: AllocId,
407        bytes: &[u8],
408        align: Align,
409    ) -> InterpResult<'tcx, MiriAllocBytes> {
410        let this = self.eval_context_ref();
411        assert!(this.tcx.try_get_global_alloc(id).is_some());
412        if this.machine.native_lib.is_some() {
413            // In native lib mode, MiriAllocBytes for global allocations are handled via `prepared_alloc_bytes`.
414            // This additional call ensures that some `MiriAllocBytes` are always prepared, just in case
415            // this function gets called before the first time `addr_from_alloc_id` gets called.
416            this.addr_from_alloc_id(id, Some(MiriMemoryKind::Global.into()))?;
417            // The memory we need here will have already been allocated during an earlier call to
418            // `addr_from_alloc_id` for this allocation. So don't create a new `MiriAllocBytes` here, instead
419            // fetch the previously prepared bytes from `prepared_alloc_bytes`.
420            let mut global_state = this.machine.alloc_addresses.borrow_mut();
421            let mut prepared_alloc_bytes = global_state
422                .prepared_alloc_bytes
423                .remove(&id)
424                .unwrap_or_else(|| panic!("alloc bytes for {id:?} have not been prepared"));
425            // Sanity-check that the prepared allocation has the right size and alignment.
426            assert!(prepared_alloc_bytes.as_ptr().is_aligned_to(align.bytes_usize()));
427            assert_eq!(prepared_alloc_bytes.len(), bytes.len());
428            // Copy allocation contents into prepared memory.
429            prepared_alloc_bytes.copy_from_slice(bytes);
430            interp_ok(prepared_alloc_bytes)
431        } else {
432            interp_ok(MiriAllocBytes::from_bytes(std::borrow::Cow::Borrowed(bytes), align))
433        }
434    }
435
436    /// When a pointer is used for a memory access, this computes where in which allocation the
437    /// access is going.
438    fn ptr_get_alloc(
439        &self,
440        ptr: interpret::Pointer<Provenance>,
441        size: i64,
442    ) -> Option<(AllocId, Size)> {
443        let this = self.eval_context_ref();
444
445        let (tag, addr) = ptr.into_parts(); // addr is absolute (Tag provenance)
446
447        let alloc_id = if let Provenance::Concrete { alloc_id, .. } = tag {
448            alloc_id
449        } else {
450            // A wildcard pointer.
451            let only_exposed_allocations = true;
452            this.alloc_id_from_addr(addr.bytes(), size, only_exposed_allocations)?
453        };
454
455        // This cannot fail: since we already have a pointer with that provenance, adjust_alloc_root_pointer
456        // must have been called in the past, so we can just look up the address in the map.
457        let base_addr = *this.machine.alloc_addresses.borrow().base_addr.get(&alloc_id).unwrap();
458
459        // Wrapping "addr - base_addr"
460        let rel_offset = this.truncate_to_target_usize(addr.bytes().wrapping_sub(base_addr));
461        Some((alloc_id, Size::from_bytes(rel_offset)))
462    }
463
464    /// Prepare all exposed memory for a native call.
465    /// This overapproximates the modifications which external code might make to memory:
466    /// We set all reachable allocations as initialized, mark all reachable provenances as exposed
467    /// and overwrite them with `Provenance::WILDCARD`.
468    fn prepare_exposed_for_native_call(&mut self) -> InterpResult<'tcx> {
469        let this = self.eval_context_mut();
470        // We need to make a deep copy of this list, but it's fine; it also serves as scratch space
471        // for the search within `prepare_for_native_call`.
472        let exposed: Vec<AllocId> =
473            this.machine.alloc_addresses.get_mut().exposed.iter().copied().collect();
474        this.prepare_for_native_call(exposed)
475    }
476}
477
478impl<'tcx> MiriMachine<'tcx> {
479    pub fn free_alloc_id(&mut self, dead_id: AllocId, size: Size, align: Align, kind: MemoryKind) {
480        let global_state = self.alloc_addresses.get_mut();
481        let rng = self.rng.get_mut();
482
483        // We can *not* remove this from `base_addr`, since the interpreter design requires that we
484        // be able to retrieve an AllocId + offset for any memory access *before* we check if the
485        // access is valid. Specifically, `ptr_get_alloc` is called on each attempt at a memory
486        // access to determine the allocation ID and offset -- and there can still be pointers with
487        // `dead_id` that one can attempt to use for a memory access. `ptr_get_alloc` may return
488        // `None` only if the pointer truly has no provenance (this ensures consistent error
489        // messages).
490        // However, we *can* remove it from `int_to_ptr_map`, since any wildcard pointers that exist
491        // can no longer actually be accessing that address. This ensures `alloc_id_from_addr` never
492        // returns a dead allocation.
493        // To avoid a linear scan we first look up the address in `base_addr`, and then find it in
494        // `int_to_ptr_map`.
495        let addr = *global_state.base_addr.get(&dead_id).unwrap();
496        let pos =
497            global_state.int_to_ptr_map.binary_search_by_key(&addr, |(addr, _)| *addr).unwrap();
498        let removed = global_state.int_to_ptr_map.remove(pos);
499        assert_eq!(removed, (addr, dead_id)); // double-check that we removed the right thing
500        // We can also remove it from `exposed`, since this allocation can anyway not be returned by
501        // `alloc_id_from_addr` any more.
502        global_state.exposed.remove(&dead_id);
503        // Also remember this address for future reuse.
504        let thread = self.threads.active_thread();
505        global_state.reuse.add_addr(rng, addr, size, align, kind, thread, || {
506            if let Some(data_race) = self.data_race.as_vclocks_ref() {
507                data_race.release_clock(&self.threads, |clock| clock.clone())
508            } else {
509                VClock::default()
510            }
511        })
512    }
513}
514
515#[cfg(test)]
516mod tests {
517    use super::*;
518
519    #[test]
520    fn test_align_addr() {
521        assert_eq!(align_addr(37, 4), 40);
522        assert_eq!(align_addr(44, 4), 44);
523    }
524}