]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/memory.rs
Auto merge of #69614 - estebank:ice-age, r=davidtwco
[rust.git] / src / librustc_mir / interpret / memory.rs
1 //! The memory subsystem.
2 //!
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!
8
9 use std::borrow::Cow;
10 use std::collections::VecDeque;
11 use std::ptr;
12
13 use rustc::ty::layout::{Align, HasDataLayout, Size, TargetDataLayout};
14 use rustc::ty::{self, query::TyCtxtAt, Instance, ParamEnv};
15 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
16
17 use rustc_ast::ast::Mutability;
18
19 use super::{
20     AllocId, AllocMap, Allocation, AllocationExtra, CheckInAllocMsg, ErrorHandled, GlobalAlloc,
21     GlobalId, InterpResult, Machine, MayLeak, Pointer, PointerArithmetic, Scalar,
22 };
23
24 #[derive(Debug, PartialEq, Copy, Clone)]
25 pub enum MemoryKind<T> {
26     /// Stack memory. Error if deallocated except during a stack pop.
27     Stack,
28     /// Memory backing vtables. Error if ever deallocated.
29     Vtable,
30     /// Memory allocated by `caller_location` intrinsic. Error if ever deallocated.
31     CallerLocation,
32     /// Additional memory kinds a machine wishes to distinguish from the builtin ones.
33     Machine(T),
34 }
35
36 impl<T: MayLeak> MayLeak for MemoryKind<T> {
37     #[inline]
38     fn may_leak(self) -> bool {
39         match self {
40             MemoryKind::Stack => false,
41             MemoryKind::Vtable => true,
42             MemoryKind::CallerLocation => true,
43             MemoryKind::Machine(k) => k.may_leak(),
44         }
45     }
46 }
47
48 /// Used by `get_size_and_align` to indicate whether the allocation needs to be live.
49 #[derive(Debug, Copy, Clone)]
50 pub enum AllocCheck {
51     /// Allocation must be live and not a function pointer.
52     Dereferenceable,
53     /// Allocations needs to be live, but may be a function pointer.
54     Live,
55     /// Allocation may be dead.
56     MaybeDead,
57 }
58
59 /// The value of a function pointer.
60 #[derive(Debug, Copy, Clone)]
61 pub enum FnVal<'tcx, Other> {
62     Instance(Instance<'tcx>),
63     Other(Other),
64 }
65
66 impl<'tcx, Other> FnVal<'tcx, Other> {
67     pub fn as_instance(self) -> InterpResult<'tcx, Instance<'tcx>> {
68         match self {
69             FnVal::Instance(instance) => Ok(instance),
70             FnVal::Other(_) => {
71                 throw_unsup_format!("'foreign' function pointers are not supported in this context")
72             }
73         }
74     }
75 }
76
77 // `Memory` has to depend on the `Machine` because some of its operations
78 // (e.g., `get`) call a `Machine` hook.
79 pub struct Memory<'mir, 'tcx, M: Machine<'mir, 'tcx>> {
80     /// Allocations local to this instance of the miri engine. The kind
81     /// helps ensure that the same mechanism is used for allocation and
82     /// deallocation. When an allocation is not found here, it is a
83     /// static and looked up in the `tcx` for read access. Some machines may
84     /// have to mutate this map even on a read-only access to a static (because
85     /// they do pointer provenance tracking and the allocations in `tcx` have
86     /// the wrong type), so we let the machine override this type.
87     /// Either way, if the machine allows writing to a static, doing so will
88     /// create a copy of the static allocation here.
89     // FIXME: this should not be public, but interning currently needs access to it
90     pub(super) alloc_map: M::MemoryMap,
91
92     /// Map for "extra" function pointers.
93     extra_fn_ptr_map: FxHashMap<AllocId, M::ExtraFnVal>,
94
95     /// To be able to compare pointers with NULL, and to check alignment for accesses
96     /// to ZSTs (where pointers may dangle), we keep track of the size even for allocations
97     /// that do not exist any more.
98     // FIXME: this should not be public, but interning currently needs access to it
99     pub(super) dead_alloc_map: FxHashMap<AllocId, (Size, Align)>,
100
101     /// Extra data added by the machine.
102     pub extra: M::MemoryExtra,
103
104     /// Lets us implement `HasDataLayout`, which is awfully convenient.
105     pub tcx: TyCtxtAt<'tcx>,
106 }
107
108 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> HasDataLayout for Memory<'mir, 'tcx, M> {
109     #[inline]
110     fn data_layout(&self) -> &TargetDataLayout {
111         &self.tcx.data_layout
112     }
113 }
114
115 // FIXME: Really we shouldn't clone memory, ever. Snapshot machinery should instead
116 // carefully copy only the reachable parts.
117 impl<'mir, 'tcx, M> Clone for Memory<'mir, 'tcx, M>
118 where
119     M: Machine<'mir, 'tcx, PointerTag = (), AllocExtra = ()>,
120     M::MemoryExtra: Copy,
121     M::MemoryMap: AllocMap<AllocId, (MemoryKind<M::MemoryKinds>, Allocation)>,
122 {
123     fn clone(&self) -> Self {
124         Memory {
125             alloc_map: self.alloc_map.clone(),
126             extra_fn_ptr_map: self.extra_fn_ptr_map.clone(),
127             dead_alloc_map: self.dead_alloc_map.clone(),
128             extra: self.extra,
129             tcx: self.tcx,
130         }
131     }
132 }
133
134 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> {
135     pub fn new(tcx: TyCtxtAt<'tcx>, extra: M::MemoryExtra) -> Self {
136         Memory {
137             alloc_map: M::MemoryMap::default(),
138             extra_fn_ptr_map: FxHashMap::default(),
139             dead_alloc_map: FxHashMap::default(),
140             extra,
141             tcx,
142         }
143     }
144
145     /// Call this to turn untagged "global" pointers (obtained via `tcx`) into
146     /// the *canonical* machine pointer to the allocation.  Must never be used
147     /// for any other pointers!
148     ///
149     /// This represents a *direct* access to that memory, as opposed to access
150     /// through a pointer that was created by the program.
151     #[inline]
152     pub fn tag_static_base_pointer(&self, ptr: Pointer) -> Pointer<M::PointerTag> {
153         let id = M::canonical_alloc_id(self, ptr.alloc_id);
154         ptr.with_tag(M::tag_static_base_pointer(&self.extra, id))
155     }
156
157     pub fn create_fn_alloc(
158         &mut self,
159         fn_val: FnVal<'tcx, M::ExtraFnVal>,
160     ) -> Pointer<M::PointerTag> {
161         let id = match fn_val {
162             FnVal::Instance(instance) => self.tcx.alloc_map.lock().create_fn_alloc(instance),
163             FnVal::Other(extra) => {
164                 // FIXME(RalfJung): Should we have a cache here?
165                 let id = self.tcx.alloc_map.lock().reserve();
166                 let old = self.extra_fn_ptr_map.insert(id, extra);
167                 assert!(old.is_none());
168                 id
169             }
170         };
171         self.tag_static_base_pointer(Pointer::from(id))
172     }
173
174     pub fn allocate(
175         &mut self,
176         size: Size,
177         align: Align,
178         kind: MemoryKind<M::MemoryKinds>,
179     ) -> Pointer<M::PointerTag> {
180         let alloc = Allocation::undef(size, align);
181         self.allocate_with(alloc, kind)
182     }
183
184     pub fn allocate_static_bytes(
185         &mut self,
186         bytes: &[u8],
187         kind: MemoryKind<M::MemoryKinds>,
188     ) -> Pointer<M::PointerTag> {
189         let alloc = Allocation::from_byte_aligned_bytes(bytes);
190         self.allocate_with(alloc, kind)
191     }
192
193     pub fn allocate_with(
194         &mut self,
195         alloc: Allocation,
196         kind: MemoryKind<M::MemoryKinds>,
197     ) -> Pointer<M::PointerTag> {
198         let id = self.tcx.alloc_map.lock().reserve();
199         debug_assert_ne!(
200             Some(kind),
201             M::STATIC_KIND.map(MemoryKind::Machine),
202             "dynamically allocating static memory"
203         );
204         let (alloc, tag) = M::init_allocation_extra(&self.extra, id, Cow::Owned(alloc), Some(kind));
205         self.alloc_map.insert(id, (kind, alloc.into_owned()));
206         Pointer::from(id).with_tag(tag)
207     }
208
209     pub fn reallocate(
210         &mut self,
211         ptr: Pointer<M::PointerTag>,
212         old_size_and_align: Option<(Size, Align)>,
213         new_size: Size,
214         new_align: Align,
215         kind: MemoryKind<M::MemoryKinds>,
216     ) -> InterpResult<'tcx, Pointer<M::PointerTag>> {
217         if ptr.offset.bytes() != 0 {
218             throw_unsup!(ReallocateNonBasePtr)
219         }
220
221         // For simplicities' sake, we implement reallocate as "alloc, copy, dealloc".
222         // This happens so rarely, the perf advantage is outweighed by the maintenance cost.
223         let new_ptr = self.allocate(new_size, new_align, kind);
224         let old_size = match old_size_and_align {
225             Some((size, _align)) => size,
226             None => self.get_raw(ptr.alloc_id)?.size,
227         };
228         self.copy(ptr, new_ptr, old_size.min(new_size), /*nonoverlapping*/ true)?;
229         self.deallocate(ptr, old_size_and_align, kind)?;
230
231         Ok(new_ptr)
232     }
233
234     /// Deallocate a local, or do nothing if that local has been made into a static
235     pub fn deallocate_local(&mut self, ptr: Pointer<M::PointerTag>) -> InterpResult<'tcx> {
236         // The allocation might be already removed by static interning.
237         // This can only really happen in the CTFE instance, not in miri.
238         if self.alloc_map.contains_key(&ptr.alloc_id) {
239             self.deallocate(ptr, None, MemoryKind::Stack)
240         } else {
241             Ok(())
242         }
243     }
244
245     pub fn deallocate(
246         &mut self,
247         ptr: Pointer<M::PointerTag>,
248         old_size_and_align: Option<(Size, Align)>,
249         kind: MemoryKind<M::MemoryKinds>,
250     ) -> InterpResult<'tcx> {
251         trace!("deallocating: {}", ptr.alloc_id);
252
253         if ptr.offset.bytes() != 0 {
254             throw_unsup!(DeallocateNonBasePtr)
255         }
256
257         let (alloc_kind, mut alloc) = match self.alloc_map.remove(&ptr.alloc_id) {
258             Some(alloc) => alloc,
259             None => {
260                 // Deallocating static memory -- always an error
261                 return Err(match self.tcx.alloc_map.lock().get(ptr.alloc_id) {
262                     Some(GlobalAlloc::Function(..)) => err_unsup!(DeallocatedWrongMemoryKind(
263                         "function".to_string(),
264                         format!("{:?}", kind),
265                     )),
266                     Some(GlobalAlloc::Static(..)) | Some(GlobalAlloc::Memory(..)) => err_unsup!(
267                         DeallocatedWrongMemoryKind("static".to_string(), format!("{:?}", kind))
268                     ),
269                     None => err_unsup!(DoubleFree),
270                 }
271                 .into());
272             }
273         };
274
275         if alloc_kind != kind {
276             throw_unsup!(DeallocatedWrongMemoryKind(
277                 format!("{:?}", alloc_kind),
278                 format!("{:?}", kind),
279             ))
280         }
281         if let Some((size, align)) = old_size_and_align {
282             if size != alloc.size || align != alloc.align {
283                 let bytes = alloc.size;
284                 throw_unsup!(IncorrectAllocationInformation(size, bytes, align, alloc.align))
285             }
286         }
287
288         // Let the machine take some extra action
289         let size = alloc.size;
290         AllocationExtra::memory_deallocated(&mut alloc, ptr, size)?;
291
292         // Don't forget to remember size and align of this now-dead allocation
293         let old = self.dead_alloc_map.insert(ptr.alloc_id, (alloc.size, alloc.align));
294         if old.is_some() {
295             bug!("Nothing can be deallocated twice");
296         }
297
298         Ok(())
299     }
300
301     /// Check if the given scalar is allowed to do a memory access of given `size`
302     /// and `align`. On success, returns `None` for zero-sized accesses (where
303     /// nothing else is left to do) and a `Pointer` to use for the actual access otherwise.
304     /// Crucially, if the input is a `Pointer`, we will test it for liveness
305     /// *even if* the size is 0.
306     ///
307     /// Everyone accessing memory based on a `Scalar` should use this method to get the
308     /// `Pointer` they need. And even if you already have a `Pointer`, call this method
309     /// to make sure it is sufficiently aligned and not dangling.  Not doing that may
310     /// cause ICEs.
311     ///
312     /// Most of the time you should use `check_mplace_access`, but when you just have a pointer,
313     /// this method is still appropriate.
314     #[inline(always)]
315     pub fn check_ptr_access(
316         &self,
317         sptr: Scalar<M::PointerTag>,
318         size: Size,
319         align: Align,
320     ) -> InterpResult<'tcx, Option<Pointer<M::PointerTag>>> {
321         let align = M::CHECK_ALIGN.then_some(align);
322         self.check_ptr_access_align(sptr, size, align, CheckInAllocMsg::MemoryAccessTest)
323     }
324
325     /// Like `check_ptr_access`, but *definitely* checks alignment when `align`
326     /// is `Some` (overriding `M::CHECK_ALIGN`). Also lets the caller control
327     /// the error message for the out-of-bounds case.
328     pub fn check_ptr_access_align(
329         &self,
330         sptr: Scalar<M::PointerTag>,
331         size: Size,
332         align: Option<Align>,
333         msg: CheckInAllocMsg,
334     ) -> InterpResult<'tcx, Option<Pointer<M::PointerTag>>> {
335         fn check_offset_align(offset: u64, align: Align) -> InterpResult<'static> {
336             if offset % align.bytes() == 0 {
337                 Ok(())
338             } else {
339                 // The biggest power of two through which `offset` is divisible.
340                 let offset_pow2 = 1 << offset.trailing_zeros();
341                 throw_unsup!(AlignmentCheckFailed {
342                     has: Align::from_bytes(offset_pow2).unwrap(),
343                     required: align,
344                 })
345             }
346         }
347
348         // Normalize to a `Pointer` if we definitely need one.
349         let normalized = if size.bytes() == 0 {
350             // Can be an integer, just take what we got.  We do NOT `force_bits` here;
351             // if this is already a `Pointer` we want to do the bounds checks!
352             sptr
353         } else {
354             // A "real" access, we must get a pointer.
355             Scalar::from(self.force_ptr(sptr)?)
356         };
357         Ok(match normalized.to_bits_or_ptr(self.pointer_size(), self) {
358             Ok(bits) => {
359                 let bits = bits as u64; // it's ptr-sized
360                 assert!(size.bytes() == 0);
361                 // Must be non-NULL.
362                 if bits == 0 {
363                     throw_unsup!(InvalidNullPointerUsage)
364                 }
365                 // Must be aligned.
366                 if let Some(align) = align {
367                     check_offset_align(bits, align)?;
368                 }
369                 None
370             }
371             Err(ptr) => {
372                 let (allocation_size, alloc_align) =
373                     self.get_size_and_align(ptr.alloc_id, AllocCheck::Dereferenceable)?;
374                 // Test bounds. This also ensures non-NULL.
375                 // It is sufficient to check this for the end pointer. The addition
376                 // checks for overflow.
377                 let end_ptr = ptr.offset(size, self)?;
378                 end_ptr.check_inbounds_alloc(allocation_size, msg)?;
379                 // Test align. Check this last; if both bounds and alignment are violated
380                 // we want the error to be about the bounds.
381                 if let Some(align) = align {
382                     if alloc_align.bytes() < align.bytes() {
383                         // The allocation itself is not aligned enough.
384                         // FIXME: Alignment check is too strict, depending on the base address that
385                         // got picked we might be aligned even if this check fails.
386                         // We instead have to fall back to converting to an integer and checking
387                         // the "real" alignment.
388                         throw_unsup!(AlignmentCheckFailed { has: alloc_align, required: align });
389                     }
390                     check_offset_align(ptr.offset.bytes(), align)?;
391                 }
392
393                 // We can still be zero-sized in this branch, in which case we have to
394                 // return `None`.
395                 if size.bytes() == 0 { None } else { Some(ptr) }
396             }
397         })
398     }
399
400     /// Test if the pointer might be NULL.
401     pub fn ptr_may_be_null(&self, ptr: Pointer<M::PointerTag>) -> bool {
402         let (size, _align) = self
403             .get_size_and_align(ptr.alloc_id, AllocCheck::MaybeDead)
404             .expect("alloc info with MaybeDead cannot fail");
405         ptr.check_inbounds_alloc(size, CheckInAllocMsg::NullPointerTest).is_err()
406     }
407 }
408
409 /// Allocation accessors
410 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> {
411     /// Helper function to obtain the global (tcx) allocation for a static.
412     /// This attempts to return a reference to an existing allocation if
413     /// one can be found in `tcx`. That, however, is only possible if `tcx` and
414     /// this machine use the same pointer tag, so it is indirected through
415     /// `M::tag_allocation`.
416     ///
417     /// Notice that every static has two `AllocId` that will resolve to the same
418     /// thing here: one maps to `GlobalAlloc::Static`, this is the "lazy" ID,
419     /// and the other one is maps to `GlobalAlloc::Memory`, this is returned by
420     /// `const_eval_raw` and it is the "resolved" ID.
421     /// The resolved ID is never used by the interpreted progrma, it is hidden.
422     /// The `GlobalAlloc::Memory` branch here is still reachable though; when a static
423     /// contains a reference to memory that was created during its evaluation (i.e., not to
424     /// another static), those inner references only exist in "resolved" form.
425     ///
426     /// Assumes `id` is already canonical.
427     fn get_static_alloc(
428         memory_extra: &M::MemoryExtra,
429         tcx: TyCtxtAt<'tcx>,
430         id: AllocId,
431     ) -> InterpResult<'tcx, Cow<'tcx, Allocation<M::PointerTag, M::AllocExtra>>> {
432         let alloc = tcx.alloc_map.lock().get(id);
433         let alloc = match alloc {
434             Some(GlobalAlloc::Memory(mem)) => Cow::Borrowed(mem),
435             Some(GlobalAlloc::Function(..)) => throw_unsup!(DerefFunctionPointer),
436             None => throw_unsup!(DanglingPointerDeref),
437             Some(GlobalAlloc::Static(def_id)) => {
438                 // We got a "lazy" static that has not been computed yet.
439                 if tcx.is_foreign_item(def_id) {
440                     trace!("get_static_alloc: foreign item {:?}", def_id);
441                     throw_unsup!(ReadForeignStatic)
442                 }
443                 trace!("get_static_alloc: Need to compute {:?}", def_id);
444                 let instance = Instance::mono(tcx.tcx, def_id);
445                 let gid = GlobalId { instance, promoted: None };
446                 // use the raw query here to break validation cycles. Later uses of the static
447                 // will call the full query anyway
448                 let raw_const =
449                     tcx.const_eval_raw(ty::ParamEnv::reveal_all().and(gid)).map_err(|err| {
450                         // no need to report anything, the const_eval call takes care of that
451                         // for statics
452                         assert!(tcx.is_static(def_id));
453                         match err {
454                             ErrorHandled::Reported => err_inval!(ReferencedConstant),
455                             ErrorHandled::TooGeneric => err_inval!(TooGeneric),
456                         }
457                     })?;
458                 // Make sure we use the ID of the resolved memory, not the lazy one!
459                 let id = raw_const.alloc_id;
460                 let allocation = tcx.alloc_map.lock().unwrap_memory(id);
461
462                 M::before_access_static(memory_extra, allocation)?;
463                 Cow::Borrowed(allocation)
464             }
465         };
466         // We got tcx memory. Let the machine initialize its "extra" stuff.
467         let (alloc, tag) = M::init_allocation_extra(
468             memory_extra,
469             id, // always use the ID we got as input, not the "hidden" one.
470             alloc,
471             M::STATIC_KIND.map(MemoryKind::Machine),
472         );
473         debug_assert_eq!(tag, M::tag_static_base_pointer(memory_extra, id));
474         Ok(alloc)
475     }
476
477     /// Gives raw access to the `Allocation`, without bounds or alignment checks.
478     /// Use the higher-level, `PlaceTy`- and `OpTy`-based APIs in `InterpCtx` instead!
479     pub fn get_raw(
480         &self,
481         id: AllocId,
482     ) -> InterpResult<'tcx, &Allocation<M::PointerTag, M::AllocExtra>> {
483         let id = M::canonical_alloc_id(self, id);
484         // The error type of the inner closure here is somewhat funny.  We have two
485         // ways of "erroring": An actual error, or because we got a reference from
486         // `get_static_alloc` that we can actually use directly without inserting anything anywhere.
487         // So the error type is `InterpResult<'tcx, &Allocation<M::PointerTag>>`.
488         let a = self.alloc_map.get_or(id, || {
489             let alloc = Self::get_static_alloc(&self.extra, self.tcx, id).map_err(Err)?;
490             match alloc {
491                 Cow::Borrowed(alloc) => {
492                     // We got a ref, cheaply return that as an "error" so that the
493                     // map does not get mutated.
494                     Err(Ok(alloc))
495                 }
496                 Cow::Owned(alloc) => {
497                     // Need to put it into the map and return a ref to that
498                     let kind = M::STATIC_KIND.expect(
499                         "I got an owned allocation that I have to copy but the machine does \
500                             not expect that to happen",
501                     );
502                     Ok((MemoryKind::Machine(kind), alloc))
503                 }
504             }
505         });
506         // Now unpack that funny error type
507         match a {
508             Ok(a) => Ok(&a.1),
509             Err(a) => a,
510         }
511     }
512
513     /// Gives raw mutable access to the `Allocation`, without bounds or alignment checks.
514     /// Use the higher-level, `PlaceTy`- and `OpTy`-based APIs in `InterpCtx` instead!
515     pub fn get_raw_mut(
516         &mut self,
517         id: AllocId,
518     ) -> InterpResult<'tcx, &mut Allocation<M::PointerTag, M::AllocExtra>> {
519         let id = M::canonical_alloc_id(self, id);
520         let tcx = self.tcx;
521         let memory_extra = &self.extra;
522         let a = self.alloc_map.get_mut_or(id, || {
523             // Need to make a copy, even if `get_static_alloc` is able
524             // to give us a cheap reference.
525             let alloc = Self::get_static_alloc(memory_extra, tcx, id)?;
526             if alloc.mutability == Mutability::Not {
527                 throw_unsup!(ModifiedConstantMemory)
528             }
529             match M::STATIC_KIND {
530                 Some(kind) => Ok((MemoryKind::Machine(kind), alloc.into_owned())),
531                 None => throw_unsup!(ModifiedStatic),
532             }
533         });
534         // Unpack the error type manually because type inference doesn't
535         // work otherwise (and we cannot help it because `impl Trait`)
536         match a {
537             Err(e) => Err(e),
538             Ok(a) => {
539                 let a = &mut a.1;
540                 if a.mutability == Mutability::Not {
541                     throw_unsup!(ModifiedConstantMemory)
542                 }
543                 Ok(a)
544             }
545         }
546     }
547
548     /// Obtain the size and alignment of an allocation, even if that allocation has
549     /// been deallocated.
550     ///
551     /// If `liveness` is `AllocCheck::MaybeDead`, this function always returns `Ok`.
552     pub fn get_size_and_align(
553         &self,
554         id: AllocId,
555         liveness: AllocCheck,
556     ) -> InterpResult<'static, (Size, Align)> {
557         let id = M::canonical_alloc_id(self, id);
558         // # Regular allocations
559         // Don't use `self.get_raw` here as that will
560         // a) cause cycles in case `id` refers to a static
561         // b) duplicate a static's allocation in miri
562         if let Some((_, alloc)) = self.alloc_map.get(id) {
563             return Ok((alloc.size, alloc.align));
564         }
565
566         // # Function pointers
567         // (both global from `alloc_map` and local from `extra_fn_ptr_map`)
568         if self.get_fn_alloc(id).is_some() {
569             return if let AllocCheck::Dereferenceable = liveness {
570                 // The caller requested no function pointers.
571                 throw_unsup!(DerefFunctionPointer)
572             } else {
573                 Ok((Size::ZERO, Align::from_bytes(1).unwrap()))
574             };
575         }
576
577         // # Statics
578         // Can't do this in the match argument, we may get cycle errors since the lock would
579         // be held throughout the match.
580         let alloc = self.tcx.alloc_map.lock().get(id);
581         match alloc {
582             Some(GlobalAlloc::Static(did)) => {
583                 // Use size and align of the type.
584                 let ty = self.tcx.type_of(did);
585                 let layout = self.tcx.layout_of(ParamEnv::empty().and(ty)).unwrap();
586                 Ok((layout.size, layout.align.abi))
587             }
588             Some(GlobalAlloc::Memory(alloc)) => {
589                 // Need to duplicate the logic here, because the global allocations have
590                 // different associated types than the interpreter-local ones.
591                 Ok((alloc.size, alloc.align))
592             }
593             Some(GlobalAlloc::Function(_)) => bug!("We already checked function pointers above"),
594             // The rest must be dead.
595             None => {
596                 if let AllocCheck::MaybeDead = liveness {
597                     // Deallocated pointers are allowed, we should be able to find
598                     // them in the map.
599                     Ok(*self.dead_alloc_map.get(&id).expect(
600                         "deallocated pointers should all be recorded in \
601                             `dead_alloc_map`",
602                     ))
603                 } else {
604                     throw_unsup!(DanglingPointerDeref)
605                 }
606             }
607         }
608     }
609
610     /// Assumes `id` is already canonical.
611     fn get_fn_alloc(&self, id: AllocId) -> Option<FnVal<'tcx, M::ExtraFnVal>> {
612         trace!("reading fn ptr: {}", id);
613         if let Some(extra) = self.extra_fn_ptr_map.get(&id) {
614             Some(FnVal::Other(*extra))
615         } else {
616             match self.tcx.alloc_map.lock().get(id) {
617                 Some(GlobalAlloc::Function(instance)) => Some(FnVal::Instance(instance)),
618                 _ => None,
619             }
620         }
621     }
622
623     pub fn get_fn(
624         &self,
625         ptr: Scalar<M::PointerTag>,
626     ) -> InterpResult<'tcx, FnVal<'tcx, M::ExtraFnVal>> {
627         let ptr = self.force_ptr(ptr)?; // We definitely need a pointer value.
628         if ptr.offset.bytes() != 0 {
629             throw_unsup!(InvalidFunctionPointer)
630         }
631         let id = M::canonical_alloc_id(self, ptr.alloc_id);
632         self.get_fn_alloc(id).ok_or_else(|| err_unsup!(ExecuteMemory).into())
633     }
634
635     pub fn mark_immutable(&mut self, id: AllocId) -> InterpResult<'tcx> {
636         self.get_raw_mut(id)?.mutability = Mutability::Not;
637         Ok(())
638     }
639
640     /// Print an allocation and all allocations it points to, recursively.
641     /// This prints directly to stderr, ignoring RUSTC_LOG! It is up to the caller to
642     /// control for this.
643     pub fn dump_alloc(&self, id: AllocId) {
644         self.dump_allocs(vec![id]);
645     }
646
647     fn dump_alloc_helper<Tag, Extra>(
648         &self,
649         allocs_seen: &mut FxHashSet<AllocId>,
650         allocs_to_print: &mut VecDeque<AllocId>,
651         mut msg: String,
652         alloc: &Allocation<Tag, Extra>,
653         extra: String,
654     ) {
655         use std::fmt::Write;
656
657         let prefix_len = msg.len();
658         let mut relocations = vec![];
659
660         for i in 0..alloc.size.bytes() {
661             let i = Size::from_bytes(i);
662             if let Some(&(_, target_id)) = alloc.relocations().get(&i) {
663                 if allocs_seen.insert(target_id) {
664                     allocs_to_print.push_back(target_id);
665                 }
666                 relocations.push((i, target_id));
667             }
668             if alloc.undef_mask().is_range_defined(i, i + Size::from_bytes(1)).is_ok() {
669                 // this `as usize` is fine, since `i` came from a `usize`
670                 let i = i.bytes() as usize;
671
672                 // Checked definedness (and thus range) and relocations. This access also doesn't
673                 // influence interpreter execution but is only for debugging.
674                 let bytes = alloc.inspect_with_undef_and_ptr_outside_interpreter(i..i + 1);
675                 write!(msg, "{:02x} ", bytes[0]).unwrap();
676             } else {
677                 msg.push_str("__ ");
678             }
679         }
680
681         eprintln!(
682             "{}({} bytes, alignment {}){}",
683             msg,
684             alloc.size.bytes(),
685             alloc.align.bytes(),
686             extra
687         );
688
689         if !relocations.is_empty() {
690             msg.clear();
691             write!(msg, "{:1$}", "", prefix_len).unwrap(); // Print spaces.
692             let mut pos = Size::ZERO;
693             let relocation_width = (self.pointer_size().bytes() - 1) * 3;
694             for (i, target_id) in relocations {
695                 // this `as usize` is fine, since we can't print more chars than `usize::MAX`
696                 write!(msg, "{:1$}", "", ((i - pos) * 3).bytes() as usize).unwrap();
697                 let target = format!("({})", target_id);
698                 // this `as usize` is fine, since we can't print more chars than `usize::MAX`
699                 write!(msg, "â””{0:─^1$}┘ ", target, relocation_width as usize).unwrap();
700                 pos = i + self.pointer_size();
701             }
702             eprintln!("{}", msg);
703         }
704     }
705
706     /// Print a list of allocations and all allocations they point to, recursively.
707     /// This prints directly to stderr, ignoring RUSTC_LOG! It is up to the caller to
708     /// control for this.
709     pub fn dump_allocs(&self, mut allocs: Vec<AllocId>) {
710         allocs.sort();
711         allocs.dedup();
712         let mut allocs_to_print = VecDeque::from(allocs);
713         let mut allocs_seen = FxHashSet::default();
714
715         while let Some(id) = allocs_to_print.pop_front() {
716             let msg = format!("Alloc {:<5} ", format!("{}:", id));
717
718             // normal alloc?
719             match self.alloc_map.get_or(id, || Err(())) {
720                 Ok((kind, alloc)) => {
721                     let extra = match kind {
722                         MemoryKind::Stack => " (stack)".to_owned(),
723                         MemoryKind::Vtable => " (vtable)".to_owned(),
724                         MemoryKind::CallerLocation => " (caller_location)".to_owned(),
725                         MemoryKind::Machine(m) => format!(" ({:?})", m),
726                     };
727                     self.dump_alloc_helper(
728                         &mut allocs_seen,
729                         &mut allocs_to_print,
730                         msg,
731                         alloc,
732                         extra,
733                     );
734                 }
735                 Err(()) => {
736                     // static alloc?
737                     match self.tcx.alloc_map.lock().get(id) {
738                         Some(GlobalAlloc::Memory(alloc)) => {
739                             self.dump_alloc_helper(
740                                 &mut allocs_seen,
741                                 &mut allocs_to_print,
742                                 msg,
743                                 alloc,
744                                 " (immutable)".to_owned(),
745                             );
746                         }
747                         Some(GlobalAlloc::Function(func)) => {
748                             eprintln!("{} {}", msg, func);
749                         }
750                         Some(GlobalAlloc::Static(did)) => {
751                             eprintln!("{} {:?}", msg, did);
752                         }
753                         None => {
754                             eprintln!("{} (deallocated)", msg);
755                         }
756                     }
757                 }
758             };
759         }
760     }
761
762     pub fn leak_report(&self) -> usize {
763         let leaks: Vec<_> = self
764             .alloc_map
765             .filter_map_collect(|&id, &(kind, _)| if kind.may_leak() { None } else { Some(id) });
766         let n = leaks.len();
767         if n > 0 {
768             eprintln!("### LEAK REPORT ###");
769             self.dump_allocs(leaks);
770         }
771         n
772     }
773
774     /// This is used by [priroda](https://github.com/oli-obk/priroda)
775     pub fn alloc_map(&self) -> &M::MemoryMap {
776         &self.alloc_map
777     }
778 }
779
780 /// Reading and writing.
781 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> {
782     /// Reads the given number of bytes from memory. Returns them as a slice.
783     ///
784     /// Performs appropriate bounds checks.
785     pub fn read_bytes(&self, ptr: Scalar<M::PointerTag>, size: Size) -> InterpResult<'tcx, &[u8]> {
786         let ptr = match self.check_ptr_access(ptr, size, Align::from_bytes(1).unwrap())? {
787             Some(ptr) => ptr,
788             None => return Ok(&[]), // zero-sized access
789         };
790         self.get_raw(ptr.alloc_id)?.get_bytes(self, ptr, size)
791     }
792
793     /// Reads a 0-terminated sequence of bytes from memory. Returns them as a slice.
794     ///
795     /// Performs appropriate bounds checks.
796     pub fn read_c_str(&self, ptr: Scalar<M::PointerTag>) -> InterpResult<'tcx, &[u8]> {
797         let ptr = self.force_ptr(ptr)?; // We need to read at least 1 byte, so we *need* a ptr.
798         self.get_raw(ptr.alloc_id)?.read_c_str(self, ptr)
799     }
800
801     /// Writes the given stream of bytes into memory.
802     ///
803     /// Performs appropriate bounds checks.
804     pub fn write_bytes(
805         &mut self,
806         ptr: Scalar<M::PointerTag>,
807         src: impl IntoIterator<Item = u8>,
808     ) -> InterpResult<'tcx> {
809         let src = src.into_iter();
810         let size = Size::from_bytes(src.size_hint().0 as u64);
811         // `write_bytes` checks that this lower bound matches the upper bound matches reality.
812         let ptr = match self.check_ptr_access(ptr, size, Align::from_bytes(1).unwrap())? {
813             Some(ptr) => ptr,
814             None => return Ok(()), // zero-sized access
815         };
816         let tcx = self.tcx.tcx;
817         self.get_raw_mut(ptr.alloc_id)?.write_bytes(&tcx, ptr, src)
818     }
819
820     /// Expects the caller to have checked bounds and alignment.
821     pub fn copy(
822         &mut self,
823         src: Pointer<M::PointerTag>,
824         dest: Pointer<M::PointerTag>,
825         size: Size,
826         nonoverlapping: bool,
827     ) -> InterpResult<'tcx> {
828         self.copy_repeatedly(src, dest, size, 1, nonoverlapping)
829     }
830
831     /// Expects the caller to have checked bounds and alignment.
832     pub fn copy_repeatedly(
833         &mut self,
834         src: Pointer<M::PointerTag>,
835         dest: Pointer<M::PointerTag>,
836         size: Size,
837         length: u64,
838         nonoverlapping: bool,
839     ) -> InterpResult<'tcx> {
840         // first copy the relocations to a temporary buffer, because
841         // `get_bytes_mut` will clear the relocations, which is correct,
842         // since we don't want to keep any relocations at the target.
843         // (`get_bytes_with_undef_and_ptr` below checks that there are no
844         // relocations overlapping the edges; those would not be handled correctly).
845         let relocations =
846             self.get_raw(src.alloc_id)?.prepare_relocation_copy(self, src, size, dest, length);
847
848         let tcx = self.tcx.tcx;
849
850         // The bits have to be saved locally before writing to dest in case src and dest overlap.
851         assert_eq!(size.bytes() as usize as u64, size.bytes());
852
853         // This checks relocation edges on the src.
854         let src_bytes =
855             self.get_raw(src.alloc_id)?.get_bytes_with_undef_and_ptr(&tcx, src, size)?.as_ptr();
856         let dest_bytes =
857             self.get_raw_mut(dest.alloc_id)?.get_bytes_mut(&tcx, dest, size * length)?;
858
859         // If `dest_bytes` is empty we just optimize to not run anything for zsts.
860         // See #67539
861         if dest_bytes.is_empty() {
862             return Ok(());
863         }
864
865         let dest_bytes = dest_bytes.as_mut_ptr();
866
867         // Prepare a copy of the undef mask.
868         let compressed = self.get_raw(src.alloc_id)?.compress_undef_range(src, size);
869
870         if compressed.all_bytes_undef() {
871             // Fast path: If all bytes are `undef` then there is nothing to copy. The target range
872             // is marked as undef but we otherwise omit changing the byte representation which may
873             // be arbitrary for undef bytes.
874             // This also avoids writing to the target bytes so that the backing allocation is never
875             // touched if the bytes stay undef for the whole interpreter execution. On contemporary
876             // operating system this can avoid physically allocating the page.
877             let dest_alloc = self.get_raw_mut(dest.alloc_id)?;
878             dest_alloc.mark_definedness(dest, size * length, false);
879             dest_alloc.mark_relocation_range(relocations);
880             return Ok(());
881         }
882
883         // SAFE: The above indexing would have panicked if there weren't at least `size` bytes
884         // behind `src` and `dest`. Also, we use the overlapping-safe `ptr::copy` if `src` and
885         // `dest` could possibly overlap.
886         // The pointers above remain valid even if the `HashMap` table is moved around because they
887         // point into the `Vec` storing the bytes.
888         unsafe {
889             assert_eq!(size.bytes() as usize as u64, size.bytes());
890             if src.alloc_id == dest.alloc_id {
891                 if nonoverlapping {
892                     if (src.offset <= dest.offset && src.offset + size > dest.offset)
893                         || (dest.offset <= src.offset && dest.offset + size > src.offset)
894                     {
895                         throw_ub_format!("copy_nonoverlapping called on overlapping ranges")
896                     }
897                 }
898
899                 for i in 0..length {
900                     ptr::copy(
901                         src_bytes,
902                         dest_bytes.offset((size.bytes() * i) as isize),
903                         size.bytes() as usize,
904                     );
905                 }
906             } else {
907                 for i in 0..length {
908                     ptr::copy_nonoverlapping(
909                         src_bytes,
910                         dest_bytes.offset((size.bytes() * i) as isize),
911                         size.bytes() as usize,
912                     );
913                 }
914             }
915         }
916
917         // now fill in all the data
918         self.get_raw_mut(dest.alloc_id)?.mark_compressed_undef_range(
919             &compressed,
920             dest,
921             size,
922             length,
923         );
924
925         // copy the relocations to the destination
926         self.get_raw_mut(dest.alloc_id)?.mark_relocation_range(relocations);
927
928         Ok(())
929     }
930 }
931
932 /// Machine pointer introspection.
933 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> {
934     pub fn force_ptr(
935         &self,
936         scalar: Scalar<M::PointerTag>,
937     ) -> InterpResult<'tcx, Pointer<M::PointerTag>> {
938         match scalar {
939             Scalar::Ptr(ptr) => Ok(ptr),
940             _ => M::int_to_ptr(&self, scalar.to_machine_usize(self)?),
941         }
942     }
943
944     pub fn force_bits(
945         &self,
946         scalar: Scalar<M::PointerTag>,
947         size: Size,
948     ) -> InterpResult<'tcx, u128> {
949         match scalar.to_bits_or_ptr(size, self) {
950             Ok(bits) => Ok(bits),
951             Err(ptr) => Ok(M::ptr_to_int(&self, ptr)? as u128),
952         }
953     }
954 }