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