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