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