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