1 //! The memory subsystem.
3 //! Generally, we use `Pointer` to denote memory addresses. However, some operations
4 //! have a "size"-like parameter, and they take `Scalar` for the address because
5 //! if the size is 0, then the pointer can also be a (properly aligned, non-NULL)
6 //! integer. It is crucial that these operations call `check_align` *before*
7 //! short-circuiting the empty case!
10 use std::collections::VecDeque;
11 use std::convert::TryFrom;
15 use rustc_ast::ast::Mutability;
16 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
17 use rustc_middle::ty::{self, Instance, ParamEnv, TyCtxt};
18 use rustc_target::abi::{Align, HasDataLayout, Size, TargetDataLayout};
21 AllocId, AllocMap, Allocation, AllocationExtra, CheckInAllocMsg, GlobalAlloc, GlobalId,
22 InterpResult, Machine, MayLeak, Pointer, PointerArithmetic, Scalar,
24 use crate::util::pretty;
26 #[derive(Debug, PartialEq, Copy, Clone)]
27 pub enum MemoryKind<T> {
28 /// Stack memory. Error if deallocated except during a stack pop.
30 /// Memory backing vtables. Error if ever deallocated.
32 /// Memory allocated by `caller_location` intrinsic. Error if ever deallocated.
34 /// Additional memory kinds a machine wishes to distinguish from the builtin ones.
38 impl<T: MayLeak> MayLeak for MemoryKind<T> {
40 fn may_leak(self) -> bool {
42 MemoryKind::Stack => false,
43 MemoryKind::Vtable => true,
44 MemoryKind::CallerLocation => true,
45 MemoryKind::Machine(k) => k.may_leak(),
50 impl<T: fmt::Display> fmt::Display for MemoryKind<T> {
51 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
53 MemoryKind::Stack => write!(f, "stack variable"),
54 MemoryKind::Vtable => write!(f, "vtable"),
55 MemoryKind::CallerLocation => write!(f, "caller location"),
56 MemoryKind::Machine(m) => write!(f, "{}", m),
61 /// Used by `get_size_and_align` to indicate whether the allocation needs to be live.
62 #[derive(Debug, Copy, Clone)]
64 /// Allocation must be live and not a function pointer.
66 /// Allocations needs to be live, but may be a function pointer.
68 /// Allocation may be dead.
72 /// The value of a function pointer.
73 #[derive(Debug, Copy, Clone)]
74 pub enum FnVal<'tcx, Other> {
75 Instance(Instance<'tcx>),
79 impl<'tcx, Other> FnVal<'tcx, Other> {
80 pub fn as_instance(self) -> InterpResult<'tcx, Instance<'tcx>> {
82 FnVal::Instance(instance) => Ok(instance),
84 throw_unsup_format!("'foreign' function pointers are not supported in this context")
90 // `Memory` has to depend on the `Machine` because some of its operations
91 // (e.g., `get`) call a `Machine` hook.
92 pub struct Memory<'mir, 'tcx, M: Machine<'mir, 'tcx>> {
93 /// Allocations local to this instance of the miri engine. The kind
94 /// helps ensure that the same mechanism is used for allocation and
95 /// deallocation. When an allocation is not found here, it is a
96 /// global and looked up in the `tcx` for read access. Some machines may
97 /// have to mutate this map even on a read-only access to a global (because
98 /// they do pointer provenance tracking and the allocations in `tcx` have
99 /// the wrong type), so we let the machine override this type.
100 /// Either way, if the machine allows writing to a global, doing so will
101 /// create a copy of the global allocation here.
102 // FIXME: this should not be public, but interning currently needs access to it
103 pub(super) alloc_map: M::MemoryMap,
105 /// Map for "extra" function pointers.
106 extra_fn_ptr_map: FxHashMap<AllocId, M::ExtraFnVal>,
108 /// To be able to compare pointers with NULL, and to check alignment for accesses
109 /// to ZSTs (where pointers may dangle), we keep track of the size even for allocations
110 /// that do not exist any more.
111 // FIXME: this should not be public, but interning currently needs access to it
112 pub(super) dead_alloc_map: FxHashMap<AllocId, (Size, Align)>,
114 /// Extra data added by the machine.
115 pub extra: M::MemoryExtra,
117 /// Lets us implement `HasDataLayout`, which is awfully convenient.
118 pub tcx: TyCtxt<'tcx>,
121 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> HasDataLayout for Memory<'mir, 'tcx, M> {
123 fn data_layout(&self) -> &TargetDataLayout {
124 &self.tcx.data_layout
128 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> {
129 pub fn new(tcx: TyCtxt<'tcx>, extra: M::MemoryExtra) -> Self {
131 alloc_map: M::MemoryMap::default(),
132 extra_fn_ptr_map: FxHashMap::default(),
133 dead_alloc_map: FxHashMap::default(),
139 /// Call this to turn untagged "global" pointers (obtained via `tcx`) into
140 /// the *canonical* machine pointer to the allocation. Must never be used
141 /// for any other pointers!
143 /// This represents a *direct* access to that memory, as opposed to access
144 /// through a pointer that was created by the program.
146 pub fn tag_global_base_pointer(&self, ptr: Pointer) -> Pointer<M::PointerTag> {
147 let id = M::canonical_alloc_id(self, ptr.alloc_id);
148 ptr.with_tag(M::tag_global_base_pointer(&self.extra, id))
151 pub fn create_fn_alloc(
153 fn_val: FnVal<'tcx, M::ExtraFnVal>,
154 ) -> Pointer<M::PointerTag> {
155 let id = match fn_val {
156 FnVal::Instance(instance) => self.tcx.create_fn_alloc(instance),
157 FnVal::Other(extra) => {
158 // FIXME(RalfJung): Should we have a cache here?
159 let id = self.tcx.reserve_alloc_id();
160 let old = self.extra_fn_ptr_map.insert(id, extra);
161 assert!(old.is_none());
165 self.tag_global_base_pointer(Pointer::from(id))
172 kind: MemoryKind<M::MemoryKind>,
173 ) -> Pointer<M::PointerTag> {
174 let alloc = Allocation::uninit(size, align);
175 self.allocate_with(alloc, kind)
178 pub fn allocate_bytes(
181 kind: MemoryKind<M::MemoryKind>,
182 ) -> Pointer<M::PointerTag> {
183 let alloc = Allocation::from_byte_aligned_bytes(bytes);
184 self.allocate_with(alloc, kind)
187 pub fn allocate_with(
190 kind: MemoryKind<M::MemoryKind>,
191 ) -> Pointer<M::PointerTag> {
192 let id = self.tcx.reserve_alloc_id();
195 M::GLOBAL_KIND.map(MemoryKind::Machine),
196 "dynamically allocating global memory"
198 let (alloc, tag) = M::init_allocation_extra(&self.extra, id, Cow::Owned(alloc), Some(kind));
199 self.alloc_map.insert(id, (kind, alloc.into_owned()));
200 Pointer::from(id).with_tag(tag)
205 ptr: Pointer<M::PointerTag>,
206 old_size_and_align: Option<(Size, Align)>,
209 kind: MemoryKind<M::MemoryKind>,
210 ) -> InterpResult<'tcx, Pointer<M::PointerTag>> {
211 if ptr.offset.bytes() != 0 {
213 "reallocating {:?} which does not point to the beginning of an object",
218 // For simplicities' sake, we implement reallocate as "alloc, copy, dealloc".
219 // This happens so rarely, the perf advantage is outweighed by the maintenance cost.
220 let new_ptr = self.allocate(new_size, new_align, kind);
221 let old_size = match old_size_and_align {
222 Some((size, _align)) => size,
223 None => self.get_raw(ptr.alloc_id)?.size,
225 self.copy(ptr, new_ptr, old_size.min(new_size), /*nonoverlapping*/ true)?;
226 self.deallocate(ptr, old_size_and_align, kind)?;
231 /// Deallocate a local, or do nothing if that local has been made into a global.
232 pub fn deallocate_local(&mut self, ptr: Pointer<M::PointerTag>) -> InterpResult<'tcx> {
233 // The allocation might be already removed by global interning.
234 // This can only really happen in the CTFE instance, not in miri.
235 if self.alloc_map.contains_key(&ptr.alloc_id) {
236 self.deallocate(ptr, None, MemoryKind::Stack)
244 ptr: Pointer<M::PointerTag>,
245 old_size_and_align: Option<(Size, Align)>,
246 kind: MemoryKind<M::MemoryKind>,
247 ) -> InterpResult<'tcx> {
248 trace!("deallocating: {}", ptr.alloc_id);
250 if ptr.offset.bytes() != 0 {
252 "deallocating {:?} which does not point to the beginning of an object",
257 M::before_deallocation(&mut self.extra, ptr.alloc_id)?;
259 let (alloc_kind, mut alloc) = match self.alloc_map.remove(&ptr.alloc_id) {
260 Some(alloc) => alloc,
262 // Deallocating global memory -- always an error
263 return Err(match self.tcx.get_global_alloc(ptr.alloc_id) {
264 Some(GlobalAlloc::Function(..)) => err_ub_format!("deallocating a function"),
265 Some(GlobalAlloc::Static(..) | GlobalAlloc::Memory(..)) => {
266 err_ub_format!("deallocating static memory")
268 None => err_ub!(PointerUseAfterFree(ptr.alloc_id)),
274 if alloc_kind != kind {
276 "deallocating {} memory using {} deallocation operation",
281 if let Some((size, align)) = old_size_and_align {
282 if size != alloc.size || align != alloc.align {
284 "incorrect layout on deallocation: allocation has size {} and alignment {}, but gave size {} and alignment {}",
293 // Let the machine take some extra action
294 let size = alloc.size;
295 AllocationExtra::memory_deallocated(&mut alloc, ptr, size)?;
297 // Don't forget to remember size and align of this now-dead allocation
298 let old = self.dead_alloc_map.insert(ptr.alloc_id, (alloc.size, alloc.align));
300 bug!("Nothing can be deallocated twice");
306 /// Check if the given scalar is allowed to do a memory access of given `size`
307 /// and `align`. On success, returns `None` for zero-sized accesses (where
308 /// nothing else is left to do) and a `Pointer` to use for the actual access otherwise.
309 /// Crucially, if the input is a `Pointer`, we will test it for liveness
310 /// *even if* the size is 0.
312 /// Everyone accessing memory based on a `Scalar` should use this method to get the
313 /// `Pointer` they need. And even if you already have a `Pointer`, call this method
314 /// to make sure it is sufficiently aligned and not dangling. Not doing that may
317 /// Most of the time you should use `check_mplace_access`, but when you just have a pointer,
318 /// this method is still appropriate.
320 pub fn check_ptr_access(
322 sptr: Scalar<M::PointerTag>,
325 ) -> InterpResult<'tcx, Option<Pointer<M::PointerTag>>> {
326 let align = M::enforce_alignment(&self.extra).then_some(align);
327 self.check_ptr_access_align(sptr, size, align, CheckInAllocMsg::MemoryAccessTest)
330 /// Like `check_ptr_access`, but *definitely* checks alignment when `align`
331 /// is `Some` (overriding `M::enforce_alignment`). Also lets the caller control
332 /// the error message for the out-of-bounds case.
333 pub fn check_ptr_access_align(
335 sptr: Scalar<M::PointerTag>,
337 align: Option<Align>,
338 msg: CheckInAllocMsg,
339 ) -> InterpResult<'tcx, Option<Pointer<M::PointerTag>>> {
340 fn check_offset_align(offset: u64, align: Align) -> InterpResult<'static> {
341 if offset % align.bytes() == 0 {
344 // The biggest power of two through which `offset` is divisible.
345 let offset_pow2 = 1 << offset.trailing_zeros();
346 throw_ub!(AlignmentCheckFailed {
347 has: Align::from_bytes(offset_pow2).unwrap(),
353 // Normalize to a `Pointer` if we definitely need one.
354 let normalized = if size.bytes() == 0 {
355 // Can be an integer, just take what we got. We do NOT `force_bits` here;
356 // if this is already a `Pointer` we want to do the bounds checks!
359 // A "real" access, we must get a pointer.
360 Scalar::from(self.force_ptr(sptr)?)
362 Ok(match normalized.to_bits_or_ptr(self.pointer_size(), self) {
364 let bits = u64::try_from(bits).unwrap(); // it's ptr-sized
365 assert!(size.bytes() == 0);
368 throw_ub!(DanglingIntPointer(0, msg))
371 if let Some(align) = align {
372 check_offset_align(bits, align)?;
377 let (allocation_size, alloc_align) =
378 self.get_size_and_align(ptr.alloc_id, AllocCheck::Dereferenceable)?;
379 // Test bounds. This also ensures non-NULL.
380 // It is sufficient to check this for the end pointer. The addition
381 // checks for overflow.
382 let end_ptr = ptr.offset(size, self)?;
383 if end_ptr.offset > allocation_size {
385 throw_ub!(PointerOutOfBounds { ptr: end_ptr.erase_tag(), msg, allocation_size })
387 // Test align. Check this last; if both bounds and alignment are violated
388 // we want the error to be about the bounds.
389 if let Some(align) = align {
390 if alloc_align.bytes() < align.bytes() {
391 // The allocation itself is not aligned enough.
392 // FIXME: Alignment check is too strict, depending on the base address that
393 // got picked we might be aligned even if this check fails.
394 // We instead have to fall back to converting to an integer and checking
395 // the "real" alignment.
396 throw_ub!(AlignmentCheckFailed { has: alloc_align, required: align });
398 check_offset_align(ptr.offset.bytes(), align)?;
401 // We can still be zero-sized in this branch, in which case we have to
403 if size.bytes() == 0 { None } else { Some(ptr) }
408 /// Test if the pointer might be NULL.
409 pub fn ptr_may_be_null(&self, ptr: Pointer<M::PointerTag>) -> bool {
410 let (size, _align) = self
411 .get_size_and_align(ptr.alloc_id, AllocCheck::MaybeDead)
412 .expect("alloc info with MaybeDead cannot fail");
413 // If the pointer is out-of-bounds, it may be null.
414 // Note that one-past-the-end (offset == size) is still inbounds, and never null.
419 /// Allocation accessors
420 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> {
421 /// Helper function to obtain a global (tcx) allocation.
422 /// This attempts to return a reference to an existing allocation if
423 /// one can be found in `tcx`. That, however, is only possible if `tcx` and
424 /// this machine use the same pointer tag, so it is indirected through
425 /// `M::tag_allocation`.
427 memory_extra: &M::MemoryExtra,
431 ) -> InterpResult<'tcx, Cow<'tcx, Allocation<M::PointerTag, M::AllocExtra>>> {
432 let (alloc, def_id) = match tcx.get_global_alloc(id) {
433 Some(GlobalAlloc::Memory(mem)) => {
434 // Memory of a constant or promoted or anonymous memory referenced by a static.
437 Some(GlobalAlloc::Function(..)) => throw_ub!(DerefFunctionPointer(id)),
438 None => throw_ub!(PointerUseAfterFree(id)),
439 Some(GlobalAlloc::Static(def_id)) => {
440 assert!(!tcx.is_thread_local_static(def_id));
441 // Notice that every static has two `AllocId` that will resolve to the same
442 // thing here: one maps to `GlobalAlloc::Static`, this is the "lazy" ID,
443 // and the other one is maps to `GlobalAlloc::Memory`, this is returned by
444 // `const_eval_raw` and it is the "resolved" ID.
445 // The resolved ID is never used by the interpreted program, it is hidden.
446 // This is relied upon for soundness of const-patterns; a pointer to the resolved
447 // ID would "sidestep" the checks that make sure consts do not point to statics!
448 // The `GlobalAlloc::Memory` branch here is still reachable though; when a static
449 // contains a reference to memory that was created during its evaluation (i.e., not
450 // to another static), those inner references only exist in "resolved" form.
452 // Assumes `id` is already canonical.
453 if tcx.is_foreign_item(def_id) {
454 trace!("get_global_alloc: foreign item {:?}", def_id);
455 throw_unsup!(ReadForeignStatic(def_id))
457 trace!("get_global_alloc: Need to compute {:?}", def_id);
458 let instance = Instance::mono(tcx, def_id);
459 let gid = GlobalId { instance, promoted: None };
460 // Use the raw query here to break validation cycles. Later uses of the static
461 // will call the full query anyway.
463 tcx.const_eval_raw(ty::ParamEnv::reveal_all().and(gid)).map_err(|err| {
464 // no need to report anything, the const_eval call takes care of that
466 assert!(tcx.is_static(def_id));
469 // Make sure we use the ID of the resolved memory, not the lazy one!
470 let id = raw_const.alloc_id;
471 let allocation = tcx.global_alloc(id).unwrap_memory();
473 (allocation, Some(def_id))
476 M::before_access_global(memory_extra, id, alloc, def_id, is_write)?;
477 let alloc = Cow::Borrowed(alloc);
478 // We got tcx memory. Let the machine initialize its "extra" stuff.
479 let (alloc, tag) = M::init_allocation_extra(
481 id, // always use the ID we got as input, not the "hidden" one.
483 M::GLOBAL_KIND.map(MemoryKind::Machine),
485 debug_assert_eq!(tag, M::tag_global_base_pointer(memory_extra, id));
489 /// Gives raw access to the `Allocation`, without bounds or alignment checks.
490 /// Use the higher-level, `PlaceTy`- and `OpTy`-based APIs in `InterpCx` instead!
494 ) -> InterpResult<'tcx, &Allocation<M::PointerTag, M::AllocExtra>> {
495 let id = M::canonical_alloc_id(self, id);
496 // The error type of the inner closure here is somewhat funny. We have two
497 // ways of "erroring": An actual error, or because we got a reference from
498 // `get_global_alloc` that we can actually use directly without inserting anything anywhere.
499 // So the error type is `InterpResult<'tcx, &Allocation<M::PointerTag>>`.
500 let a = self.alloc_map.get_or(id, || {
501 let alloc = Self::get_global_alloc(&self.extra, self.tcx, id, /*is_write*/ false)
504 Cow::Borrowed(alloc) => {
505 // We got a ref, cheaply return that as an "error" so that the
506 // map does not get mutated.
509 Cow::Owned(alloc) => {
510 // Need to put it into the map and return a ref to that
511 let kind = M::GLOBAL_KIND.expect(
512 "I got a global allocation that I have to copy but the machine does \
513 not expect that to happen",
515 Ok((MemoryKind::Machine(kind), alloc))
519 // Now unpack that funny error type
526 /// Gives raw mutable access to the `Allocation`, without bounds or alignment checks.
527 /// Use the higher-level, `PlaceTy`- and `OpTy`-based APIs in `InterpCx` instead!
531 ) -> InterpResult<'tcx, &mut Allocation<M::PointerTag, M::AllocExtra>> {
532 let id = M::canonical_alloc_id(self, id);
534 let memory_extra = &self.extra;
535 let a = self.alloc_map.get_mut_or(id, || {
536 // Need to make a copy, even if `get_global_alloc` is able
537 // to give us a cheap reference.
538 let alloc = Self::get_global_alloc(memory_extra, tcx, id, /*is_write*/ true)?;
539 if alloc.mutability == Mutability::Not {
540 throw_ub!(WriteToReadOnly(id))
542 let kind = M::GLOBAL_KIND.expect(
543 "I got a global allocation that I have to copy but the machine does \
544 not expect that to happen",
546 Ok((MemoryKind::Machine(kind), alloc.into_owned()))
548 // Unpack the error type manually because type inference doesn't
549 // work otherwise (and we cannot help it because `impl Trait`)
554 if a.mutability == Mutability::Not {
555 throw_ub!(WriteToReadOnly(id))
562 /// Obtain the size and alignment of an allocation, even if that allocation has
563 /// been deallocated.
565 /// If `liveness` is `AllocCheck::MaybeDead`, this function always returns `Ok`.
566 pub fn get_size_and_align(
569 liveness: AllocCheck,
570 ) -> InterpResult<'static, (Size, Align)> {
571 let id = M::canonical_alloc_id(self, id);
572 // # Regular allocations
573 // Don't use `self.get_raw` here as that will
574 // a) cause cycles in case `id` refers to a static
575 // b) duplicate a global's allocation in miri
576 if let Some((_, alloc)) = self.alloc_map.get(id) {
577 return Ok((alloc.size, alloc.align));
580 // # Function pointers
581 // (both global from `alloc_map` and local from `extra_fn_ptr_map`)
582 if self.get_fn_alloc(id).is_some() {
583 return if let AllocCheck::Dereferenceable = liveness {
584 // The caller requested no function pointers.
585 throw_ub!(DerefFunctionPointer(id))
587 Ok((Size::ZERO, Align::from_bytes(1).unwrap()))
592 // Can't do this in the match argument, we may get cycle errors since the lock would
593 // be held throughout the match.
594 match self.tcx.get_global_alloc(id) {
595 Some(GlobalAlloc::Static(did)) => {
596 assert!(!self.tcx.is_thread_local_static(did));
597 // Use size and align of the type.
598 let ty = self.tcx.type_of(did);
599 let layout = self.tcx.layout_of(ParamEnv::empty().and(ty)).unwrap();
600 Ok((layout.size, layout.align.abi))
602 Some(GlobalAlloc::Memory(alloc)) => {
603 // Need to duplicate the logic here, because the global allocations have
604 // different associated types than the interpreter-local ones.
605 Ok((alloc.size, alloc.align))
607 Some(GlobalAlloc::Function(_)) => bug!("We already checked function pointers above"),
608 // The rest must be dead.
610 if let AllocCheck::MaybeDead = liveness {
611 // Deallocated pointers are allowed, we should be able to find
616 .expect("deallocated pointers should all be recorded in `dead_alloc_map`"))
618 throw_ub!(PointerUseAfterFree(id))
624 /// Assumes `id` is already canonical.
625 fn get_fn_alloc(&self, id: AllocId) -> Option<FnVal<'tcx, M::ExtraFnVal>> {
626 trace!("reading fn ptr: {}", id);
627 if let Some(extra) = self.extra_fn_ptr_map.get(&id) {
628 Some(FnVal::Other(*extra))
630 match self.tcx.get_global_alloc(id) {
631 Some(GlobalAlloc::Function(instance)) => Some(FnVal::Instance(instance)),
639 ptr: Scalar<M::PointerTag>,
640 ) -> InterpResult<'tcx, FnVal<'tcx, M::ExtraFnVal>> {
641 let ptr = self.force_ptr(ptr)?; // We definitely need a pointer value.
642 if ptr.offset.bytes() != 0 {
643 throw_ub!(InvalidFunctionPointer(ptr.erase_tag()))
645 let id = M::canonical_alloc_id(self, ptr.alloc_id);
646 self.get_fn_alloc(id).ok_or_else(|| err_ub!(InvalidFunctionPointer(ptr.erase_tag())).into())
649 pub fn mark_immutable(&mut self, id: AllocId) -> InterpResult<'tcx> {
650 self.get_raw_mut(id)?.mutability = Mutability::Not;
654 /// Print an allocation and all allocations it points to, recursively.
655 /// This prints directly to stderr, ignoring RUSTC_LOG! It is up to the caller to
656 /// control for this.
657 pub fn dump_alloc(&self, id: AllocId) {
658 self.dump_allocs(vec![id]);
661 /// Print a list of allocations and all allocations they point to, recursively.
662 /// This prints directly to stderr, ignoring RUSTC_LOG! It is up to the caller to
663 /// control for this.
664 pub fn dump_allocs(&self, mut allocs: Vec<AllocId>) {
665 // Cannot be a closure because it is generic in `Tag`, `Extra`.
666 fn write_allocation_track_relocs<'tcx, Tag: Copy + fmt::Debug, Extra>(
668 allocs_to_print: &mut VecDeque<AllocId>,
669 alloc: &Allocation<Tag, Extra>,
671 for &(_, target_id) in alloc.relocations().values() {
672 allocs_to_print.push_back(target_id);
674 pretty::write_allocation(tcx, alloc, &mut std::io::stderr()).unwrap();
679 let mut allocs_to_print = VecDeque::from(allocs);
680 // `allocs_printed` contains all allocations that we have already printed.
681 let mut allocs_printed = FxHashSet::default();
683 while let Some(id) = allocs_to_print.pop_front() {
684 if !allocs_printed.insert(id) {
685 // Already printed, so skip this.
690 match self.alloc_map.get(id) {
691 Some(&(kind, ref alloc)) => {
693 eprint!(" ({}, ", kind);
694 write_allocation_track_relocs(self.tcx, &mut allocs_to_print, alloc);
698 match self.tcx.get_global_alloc(id) {
699 Some(GlobalAlloc::Memory(alloc)) => {
700 eprint!(" (unchanged global, ");
701 write_allocation_track_relocs(self.tcx, &mut allocs_to_print, alloc);
703 Some(GlobalAlloc::Function(func)) => {
704 eprint!(" (fn: {})", func);
706 Some(GlobalAlloc::Static(did)) => {
707 eprint!(" (static: {})", self.tcx.def_path_str(did));
710 eprint!(" (deallocated)");
719 /// Print leaked memory. Allocations reachable from `static_roots` or a `Global` allocation
720 /// are not considered leaked. Leaks whose kind `may_leak()` returns true are not reported.
721 pub fn leak_report(&self, static_roots: &[AllocId]) -> usize {
722 // Collect the set of allocations that are *reachable* from `Global` allocations.
724 let mut reachable = FxHashSet::default();
725 let global_kind = M::GLOBAL_KIND.map(MemoryKind::Machine);
726 let mut todo: Vec<_> = self.alloc_map.filter_map_collect(move |&id, &(kind, _)| {
727 if Some(kind) == global_kind { Some(id) } else { None }
729 todo.extend(static_roots);
730 while let Some(id) = todo.pop() {
731 if reachable.insert(id) {
732 // This is a new allocation, add its relocations to `todo`.
733 if let Some((_, alloc)) = self.alloc_map.get(id) {
734 todo.extend(alloc.relocations().values().map(|&(_, target_id)| target_id));
741 // All allocations that are *not* `reachable` and *not* `may_leak` are considered leaking.
742 let leaks: Vec<_> = self.alloc_map.filter_map_collect(|&id, &(kind, _)| {
743 if kind.may_leak() || reachable.contains(&id) { None } else { Some(id) }
747 eprintln!("The following memory was leaked:");
748 self.dump_allocs(leaks);
753 /// This is used by [priroda](https://github.com/oli-obk/priroda)
754 pub fn alloc_map(&self) -> &M::MemoryMap {
759 /// Reading and writing.
760 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> {
761 /// Reads the given number of bytes from memory. Returns them as a slice.
763 /// Performs appropriate bounds checks.
764 pub fn read_bytes(&self, ptr: Scalar<M::PointerTag>, size: Size) -> InterpResult<'tcx, &[u8]> {
765 let ptr = match self.check_ptr_access(ptr, size, Align::from_bytes(1).unwrap())? {
767 None => return Ok(&[]), // zero-sized access
769 self.get_raw(ptr.alloc_id)?.get_bytes(self, ptr, size)
772 /// Reads a 0-terminated sequence of bytes from memory. Returns them as a slice.
774 /// Performs appropriate bounds checks.
775 pub fn read_c_str(&self, ptr: Scalar<M::PointerTag>) -> InterpResult<'tcx, &[u8]> {
776 let ptr = self.force_ptr(ptr)?; // We need to read at least 1 byte, so we *need* a ptr.
777 self.get_raw(ptr.alloc_id)?.read_c_str(self, ptr)
780 /// Reads a 0x0000-terminated u16-sequence from memory. Returns them as a Vec<u16>.
781 /// Terminator 0x0000 is not included in the returned Vec<u16>.
783 /// Performs appropriate bounds checks.
784 pub fn read_wide_str(&self, ptr: Scalar<M::PointerTag>) -> InterpResult<'tcx, Vec<u16>> {
785 let size_2bytes = Size::from_bytes(2);
786 let align_2bytes = Align::from_bytes(2).unwrap();
787 // We need to read at least 2 bytes, so we *need* a ptr.
788 let mut ptr = self.force_ptr(ptr)?;
789 let allocation = self.get_raw(ptr.alloc_id)?;
790 let mut u16_seq = Vec::new();
794 .check_ptr_access(ptr.into(), size_2bytes, align_2bytes)?
795 .expect("cannot be a ZST");
796 let single_u16 = allocation.read_scalar(self, ptr, size_2bytes)?.to_u16()?;
797 if single_u16 != 0x0000 {
798 u16_seq.push(single_u16);
799 ptr = ptr.offset(size_2bytes, self)?;
807 /// Writes the given stream of bytes into memory.
809 /// Performs appropriate bounds checks.
812 ptr: Scalar<M::PointerTag>,
813 src: impl IntoIterator<Item = u8>,
814 ) -> InterpResult<'tcx> {
815 let mut src = src.into_iter();
816 let size = Size::from_bytes(src.size_hint().0);
817 // `write_bytes` checks that this lower bound `size` matches the upper bound and reality.
818 let ptr = match self.check_ptr_access(ptr, size, Align::from_bytes(1).unwrap())? {
822 src.next().expect_none("iterator said it was empty but returned an element");
827 self.get_raw_mut(ptr.alloc_id)?.write_bytes(&tcx, ptr, src)
830 /// Writes the given stream of u16s into memory.
832 /// Performs appropriate bounds checks.
835 ptr: Scalar<M::PointerTag>,
836 src: impl IntoIterator<Item = u16>,
837 ) -> InterpResult<'tcx> {
838 let mut src = src.into_iter();
839 let (lower, upper) = src.size_hint();
840 let len = upper.expect("can only write bounded iterators");
841 assert_eq!(lower, len, "can only write iterators with a precise length");
843 let size = Size::from_bytes(lower);
844 let ptr = match self.check_ptr_access(ptr, size, Align::from_bytes(2).unwrap())? {
848 src.next().expect_none("iterator said it was empty but returned an element");
853 let allocation = self.get_raw_mut(ptr.alloc_id)?;
856 let val = Scalar::from_u16(
857 src.next().expect("iterator was shorter than it said it would be"),
859 let offset_ptr = ptr.offset(Size::from_bytes(idx) * 2, &tcx)?; // `Size` multiplication
860 allocation.write_scalar(&tcx, offset_ptr, val.into(), Size::from_bytes(2))?;
862 src.next().expect_none("iterator was longer than it said it would be");
866 /// Expects the caller to have checked bounds and alignment.
869 src: Pointer<M::PointerTag>,
870 dest: Pointer<M::PointerTag>,
872 nonoverlapping: bool,
873 ) -> InterpResult<'tcx> {
874 self.copy_repeatedly(src, dest, size, 1, nonoverlapping)
877 /// Expects the caller to have checked bounds and alignment.
878 pub fn copy_repeatedly(
880 src: Pointer<M::PointerTag>,
881 dest: Pointer<M::PointerTag>,
884 nonoverlapping: bool,
885 ) -> InterpResult<'tcx> {
886 // first copy the relocations to a temporary buffer, because
887 // `get_bytes_mut` will clear the relocations, which is correct,
888 // since we don't want to keep any relocations at the target.
889 // (`get_bytes_with_undef_and_ptr` below checks that there are no
890 // relocations overlapping the edges; those would not be handled correctly).
892 self.get_raw(src.alloc_id)?.prepare_relocation_copy(self, src, size, dest, length);
896 // This checks relocation edges on the src.
898 self.get_raw(src.alloc_id)?.get_bytes_with_undef_and_ptr(&tcx, src, size)?.as_ptr();
900 self.get_raw_mut(dest.alloc_id)?.get_bytes_mut(&tcx, dest, size * length)?; // `Size` multiplication
902 // If `dest_bytes` is empty we just optimize to not run anything for zsts.
904 if dest_bytes.is_empty() {
908 let dest_bytes = dest_bytes.as_mut_ptr();
910 // Prepare a copy of the initialization mask.
911 let compressed = self.get_raw(src.alloc_id)?.compress_undef_range(src, size);
913 if compressed.no_bytes_init() {
914 // Fast path: If all bytes are `uninit` then there is nothing to copy. The target range
915 // is marked as unititialized but we otherwise omit changing the byte representation which may
916 // be arbitrary for uninitialized bytes.
917 // This also avoids writing to the target bytes so that the backing allocation is never
918 // touched if the bytes stay uninitialized for the whole interpreter execution. On contemporary
919 // operating system this can avoid physically allocating the page.
920 let dest_alloc = self.get_raw_mut(dest.alloc_id)?;
921 dest_alloc.mark_init(dest, size * length, false); // `Size` multiplication
922 dest_alloc.mark_relocation_range(relocations);
926 // SAFE: The above indexing would have panicked if there weren't at least `size` bytes
927 // behind `src` and `dest`. Also, we use the overlapping-safe `ptr::copy` if `src` and
928 // `dest` could possibly overlap.
929 // The pointers above remain valid even if the `HashMap` table is moved around because they
930 // point into the `Vec` storing the bytes.
932 if src.alloc_id == dest.alloc_id {
935 if (src.offset <= dest.offset && src.offset + size > dest.offset)
936 || (dest.offset <= src.offset && dest.offset + size > src.offset)
938 throw_ub_format!("copy_nonoverlapping called on overlapping ranges")
945 dest_bytes.add((size * i).bytes_usize()), // `Size` multiplication
951 ptr::copy_nonoverlapping(
953 dest_bytes.add((size * i).bytes_usize()), // `Size` multiplication
960 // now fill in all the data
961 self.get_raw_mut(dest.alloc_id)?.mark_compressed_init_range(
968 // copy the relocations to the destination
969 self.get_raw_mut(dest.alloc_id)?.mark_relocation_range(relocations);
975 /// Machine pointer introspection.
976 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> {
979 scalar: Scalar<M::PointerTag>,
980 ) -> InterpResult<'tcx, Pointer<M::PointerTag>> {
982 Scalar::Ptr(ptr) => Ok(ptr),
983 _ => M::int_to_ptr(&self, scalar.to_machine_usize(self)?),
989 scalar: Scalar<M::PointerTag>,
991 ) -> InterpResult<'tcx, u128> {
992 match scalar.to_bits_or_ptr(size, self) {
993 Ok(bits) => Ok(bits),
994 Err(ptr) => Ok(M::ptr_to_int(&self, ptr)?.into()),