]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir/src/interpret/memory.rs
Re-use std::sealed::Sealed in os/linux/process.
[rust.git] / compiler / rustc_mir / src / 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::assert_matches::assert_matches;
10 use std::borrow::Cow;
11 use std::collections::VecDeque;
12 use std::convert::TryFrom;
13 use std::fmt;
14 use std::ptr;
15
16 use rustc_ast::Mutability;
17 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
18 use rustc_middle::ty::{Instance, ParamEnv, TyCtxt};
19 use rustc_target::abi::{Align, HasDataLayout, Size, TargetDataLayout};
20
21 use super::{
22     alloc_range, AllocId, AllocMap, AllocRange, Allocation, CheckInAllocMsg, GlobalAlloc,
23     InterpResult, Machine, MayLeak, Pointer, PointerArithmetic, Provenance, Scalar,
24     ScalarMaybeUninit,
25 };
26 use crate::util::pretty;
27
28 #[derive(Debug, PartialEq, Copy, Clone)]
29 pub enum MemoryKind<T> {
30     /// Stack memory. Error if deallocated except during a stack pop.
31     Stack,
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::CallerLocation => true,
44             MemoryKind::Machine(k) => k.may_leak(),
45         }
46     }
47 }
48
49 impl<T: fmt::Display> fmt::Display for MemoryKind<T> {
50     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51         match self {
52             MemoryKind::Stack => write!(f, "stack variable"),
53             MemoryKind::CallerLocation => write!(f, "caller location"),
54             MemoryKind::Machine(m) => write!(f, "{}", m),
55         }
56     }
57 }
58
59 /// Used by `get_size_and_align` to indicate whether the allocation needs to be live.
60 #[derive(Debug, Copy, Clone)]
61 pub enum AllocCheck {
62     /// Allocation must be live and not a function pointer.
63     Dereferenceable,
64     /// Allocations needs to be live, but may be a function pointer.
65     Live,
66     /// Allocation may be dead.
67     MaybeDead,
68 }
69
70 /// The value of a function pointer.
71 #[derive(Debug, Copy, Clone)]
72 pub enum FnVal<'tcx, Other> {
73     Instance(Instance<'tcx>),
74     Other(Other),
75 }
76
77 impl<'tcx, Other> FnVal<'tcx, Other> {
78     pub fn as_instance(self) -> InterpResult<'tcx, Instance<'tcx>> {
79         match self {
80             FnVal::Instance(instance) => Ok(instance),
81             FnVal::Other(_) => {
82                 throw_unsup_format!("'foreign' function pointers are not supported in this context")
83             }
84         }
85     }
86 }
87
88 // `Memory` has to depend on the `Machine` because some of its operations
89 // (e.g., `get`) call a `Machine` hook.
90 pub struct Memory<'mir, 'tcx, M: Machine<'mir, 'tcx>> {
91     /// Allocations local to this instance of the miri engine. The kind
92     /// helps ensure that the same mechanism is used for allocation and
93     /// deallocation. When an allocation is not found here, it is a
94     /// global and looked up in the `tcx` for read access. Some machines may
95     /// have to mutate this map even on a read-only access to a global (because
96     /// they do pointer provenance tracking and the allocations in `tcx` have
97     /// the wrong type), so we let the machine override this type.
98     /// Either way, if the machine allows writing to a global, doing so will
99     /// create a copy of the global allocation here.
100     // FIXME: this should not be public, but interning currently needs access to it
101     pub(super) alloc_map: M::MemoryMap,
102
103     /// Map for "extra" function pointers.
104     extra_fn_ptr_map: FxHashMap<AllocId, M::ExtraFnVal>,
105
106     /// To be able to compare pointers with null, and to check alignment for accesses
107     /// to ZSTs (where pointers may dangle), we keep track of the size even for allocations
108     /// that do not exist any more.
109     // FIXME: this should not be public, but interning currently needs access to it
110     pub(super) dead_alloc_map: FxHashMap<AllocId, (Size, Align)>,
111
112     /// Extra data added by the machine.
113     pub extra: M::MemoryExtra,
114
115     /// Lets us implement `HasDataLayout`, which is awfully convenient.
116     pub tcx: TyCtxt<'tcx>,
117 }
118
119 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> HasDataLayout for Memory<'mir, 'tcx, M> {
120     #[inline]
121     fn data_layout(&self) -> &TargetDataLayout {
122         &self.tcx.data_layout
123     }
124 }
125
126 /// A reference to some allocation that was already bounds-checked for the given region
127 /// and had the on-access machine hooks run.
128 #[derive(Copy, Clone)]
129 pub struct AllocRef<'a, 'tcx, Tag, Extra> {
130     alloc: &'a Allocation<Tag, Extra>,
131     range: AllocRange,
132     tcx: TyCtxt<'tcx>,
133     alloc_id: AllocId,
134 }
135 /// A reference to some allocation that was already bounds-checked for the given region
136 /// and had the on-access machine hooks run.
137 pub struct AllocRefMut<'a, 'tcx, Tag, Extra> {
138     alloc: &'a mut Allocation<Tag, Extra>,
139     range: AllocRange,
140     tcx: TyCtxt<'tcx>,
141     alloc_id: AllocId,
142 }
143
144 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> {
145     pub fn new(tcx: TyCtxt<'tcx>, extra: M::MemoryExtra) -> Self {
146         Memory {
147             alloc_map: M::MemoryMap::default(),
148             extra_fn_ptr_map: FxHashMap::default(),
149             dead_alloc_map: FxHashMap::default(),
150             extra,
151             tcx,
152         }
153     }
154
155     /// Call this to turn untagged "global" pointers (obtained via `tcx`) into
156     /// the machine pointer to the allocation.  Must never be used
157     /// for any other pointers, nor for TLS statics.
158     ///
159     /// Using the resulting pointer represents a *direct* access to that memory
160     /// (e.g. by directly using a `static`),
161     /// as opposed to access through a pointer that was created by the program.
162     ///
163     /// This function can fail only if `ptr` points to an `extern static`.
164     #[inline]
165     pub fn global_base_pointer(
166         &self,
167         ptr: Pointer<AllocId>,
168     ) -> InterpResult<'tcx, Pointer<M::PointerTag>> {
169         // We know `offset` is relative to the allocation, so we can use `into_parts`.
170         let (alloc_id, offset) = ptr.into_parts();
171         // We need to handle `extern static`.
172         match self.tcx.get_global_alloc(alloc_id) {
173             Some(GlobalAlloc::Static(def_id)) if self.tcx.is_thread_local_static(def_id) => {
174                 bug!("global memory cannot point to thread-local static")
175             }
176             Some(GlobalAlloc::Static(def_id)) if self.tcx.is_foreign_item(def_id) => {
177                 return M::extern_static_base_pointer(self, def_id);
178             }
179             _ => {}
180         }
181         // And we need to get the tag.
182         Ok(M::tag_alloc_base_pointer(self, Pointer::new(alloc_id, offset)))
183     }
184
185     pub fn create_fn_alloc(
186         &mut self,
187         fn_val: FnVal<'tcx, M::ExtraFnVal>,
188     ) -> Pointer<M::PointerTag> {
189         let id = match fn_val {
190             FnVal::Instance(instance) => self.tcx.create_fn_alloc(instance),
191             FnVal::Other(extra) => {
192                 // FIXME(RalfJung): Should we have a cache here?
193                 let id = self.tcx.reserve_alloc_id();
194                 let old = self.extra_fn_ptr_map.insert(id, extra);
195                 assert!(old.is_none());
196                 id
197             }
198         };
199         // Functions are global allocations, so make sure we get the right base pointer.
200         // We know this is not an `extern static` so this cannot fail.
201         self.global_base_pointer(Pointer::from(id)).unwrap()
202     }
203
204     pub fn allocate(
205         &mut self,
206         size: Size,
207         align: Align,
208         kind: MemoryKind<M::MemoryKind>,
209     ) -> InterpResult<'static, Pointer<M::PointerTag>> {
210         let alloc = Allocation::uninit(size, align, M::PANIC_ON_ALLOC_FAIL)?;
211         Ok(self.allocate_with(alloc, kind))
212     }
213
214     pub fn allocate_bytes(
215         &mut self,
216         bytes: &[u8],
217         align: Align,
218         kind: MemoryKind<M::MemoryKind>,
219         mutability: Mutability,
220     ) -> Pointer<M::PointerTag> {
221         let alloc = Allocation::from_bytes(bytes, align, mutability);
222         self.allocate_with(alloc, kind)
223     }
224
225     pub fn allocate_with(
226         &mut self,
227         alloc: Allocation,
228         kind: MemoryKind<M::MemoryKind>,
229     ) -> Pointer<M::PointerTag> {
230         let id = self.tcx.reserve_alloc_id();
231         debug_assert_ne!(
232             Some(kind),
233             M::GLOBAL_KIND.map(MemoryKind::Machine),
234             "dynamically allocating global memory"
235         );
236         let alloc = M::init_allocation_extra(self, id, Cow::Owned(alloc), Some(kind));
237         self.alloc_map.insert(id, (kind, alloc.into_owned()));
238         M::tag_alloc_base_pointer(self, Pointer::from(id))
239     }
240
241     pub fn reallocate(
242         &mut self,
243         ptr: Pointer<Option<M::PointerTag>>,
244         old_size_and_align: Option<(Size, Align)>,
245         new_size: Size,
246         new_align: Align,
247         kind: MemoryKind<M::MemoryKind>,
248     ) -> InterpResult<'tcx, Pointer<M::PointerTag>> {
249         let (alloc_id, offset, ptr) = self.ptr_get_alloc(ptr)?;
250         if offset.bytes() != 0 {
251             throw_ub_format!(
252                 "reallocating {:?} which does not point to the beginning of an object",
253                 ptr
254             );
255         }
256
257         // For simplicities' sake, we implement reallocate as "alloc, copy, dealloc".
258         // This happens so rarely, the perf advantage is outweighed by the maintenance cost.
259         let new_ptr = self.allocate(new_size, new_align, kind)?;
260         let old_size = match old_size_and_align {
261             Some((size, _align)) => size,
262             None => self.get_raw(alloc_id)?.size(),
263         };
264         // This will also call the access hooks.
265         self.copy(
266             ptr.into(),
267             Align::ONE,
268             new_ptr.into(),
269             Align::ONE,
270             old_size.min(new_size),
271             /*nonoverlapping*/ true,
272         )?;
273         self.deallocate(ptr.into(), old_size_and_align, kind)?;
274
275         Ok(new_ptr)
276     }
277
278     pub fn deallocate(
279         &mut self,
280         ptr: Pointer<Option<M::PointerTag>>,
281         old_size_and_align: Option<(Size, Align)>,
282         kind: MemoryKind<M::MemoryKind>,
283     ) -> InterpResult<'tcx> {
284         let (alloc_id, offset, ptr) = self.ptr_get_alloc(ptr)?;
285         trace!("deallocating: {}", alloc_id);
286
287         if offset.bytes() != 0 {
288             throw_ub_format!(
289                 "deallocating {:?} which does not point to the beginning of an object",
290                 ptr
291             );
292         }
293
294         let (alloc_kind, mut alloc) = match self.alloc_map.remove(&alloc_id) {
295             Some(alloc) => alloc,
296             None => {
297                 // Deallocating global memory -- always an error
298                 return Err(match self.tcx.get_global_alloc(alloc_id) {
299                     Some(GlobalAlloc::Function(..)) => {
300                         err_ub_format!("deallocating {}, which is a function", alloc_id)
301                     }
302                     Some(GlobalAlloc::Static(..) | GlobalAlloc::Memory(..)) => {
303                         err_ub_format!("deallocating {}, which is static memory", alloc_id)
304                     }
305                     None => err_ub!(PointerUseAfterFree(alloc_id)),
306                 }
307                 .into());
308             }
309         };
310
311         if alloc.mutability == Mutability::Not {
312             throw_ub_format!("deallocating immutable allocation {}", alloc_id);
313         }
314         if alloc_kind != kind {
315             throw_ub_format!(
316                 "deallocating {}, which is {} memory, using {} deallocation operation",
317                 alloc_id,
318                 alloc_kind,
319                 kind
320             );
321         }
322         if let Some((size, align)) = old_size_and_align {
323             if size != alloc.size() || align != alloc.align {
324                 throw_ub_format!(
325                     "incorrect layout on deallocation: {} has size {} and alignment {}, but gave size {} and alignment {}",
326                     alloc_id,
327                     alloc.size().bytes(),
328                     alloc.align.bytes(),
329                     size.bytes(),
330                     align.bytes(),
331                 )
332             }
333         }
334
335         // Let the machine take some extra action
336         let size = alloc.size();
337         M::memory_deallocated(
338             &mut self.extra,
339             &mut alloc.extra,
340             ptr.provenance,
341             alloc_range(Size::ZERO, size),
342         )?;
343
344         // Don't forget to remember size and align of this now-dead allocation
345         let old = self.dead_alloc_map.insert(alloc_id, (size, alloc.align));
346         if old.is_some() {
347             bug!("Nothing can be deallocated twice");
348         }
349
350         Ok(())
351     }
352
353     /// Internal helper function to determine the allocation and offset of a pointer (if any).
354     #[inline(always)]
355     fn get_ptr_access(
356         &self,
357         ptr: Pointer<Option<M::PointerTag>>,
358         size: Size,
359         align: Align,
360     ) -> InterpResult<'tcx, Option<(AllocId, Size, Pointer<M::PointerTag>)>> {
361         let align = M::enforce_alignment(&self.extra).then_some(align);
362         self.check_and_deref_ptr(
363             ptr,
364             size,
365             align,
366             CheckInAllocMsg::MemoryAccessTest,
367             |alloc_id, offset, ptr| {
368                 let (size, align) =
369                     self.get_size_and_align(alloc_id, AllocCheck::Dereferenceable)?;
370                 Ok((size, align, (alloc_id, offset, ptr)))
371             },
372         )
373     }
374
375     /// Check if the given pointer points to live memory of given `size` and `align`
376     /// (ignoring `M::enforce_alignment`). The caller can control the error message for the
377     /// out-of-bounds case.
378     #[inline(always)]
379     pub fn check_ptr_access_align(
380         &self,
381         ptr: Pointer<Option<M::PointerTag>>,
382         size: Size,
383         align: Align,
384         msg: CheckInAllocMsg,
385     ) -> InterpResult<'tcx> {
386         self.check_and_deref_ptr(ptr, size, Some(align), msg, |alloc_id, _, _| {
387             let check = match msg {
388                 CheckInAllocMsg::DerefTest | CheckInAllocMsg::MemoryAccessTest => {
389                     AllocCheck::Dereferenceable
390                 }
391                 CheckInAllocMsg::PointerArithmeticTest | CheckInAllocMsg::InboundsTest => {
392                     AllocCheck::Live
393                 }
394             };
395             let (size, align) = self.get_size_and_align(alloc_id, check)?;
396             Ok((size, align, ()))
397         })?;
398         Ok(())
399     }
400
401     /// Low-level helper function to check if a ptr is in-bounds and potentially return a reference
402     /// to the allocation it points to. Supports both shared and mutable references, as the actual
403     /// checking is offloaded to a helper closure. `align` defines whether and which alignment check
404     /// is done. Returns `None` for size 0, and otherwise `Some` of what `alloc_size` returned.
405     fn check_and_deref_ptr<T>(
406         &self,
407         ptr: Pointer<Option<M::PointerTag>>,
408         size: Size,
409         align: Option<Align>,
410         msg: CheckInAllocMsg,
411         alloc_size: impl FnOnce(
412             AllocId,
413             Size,
414             Pointer<M::PointerTag>,
415         ) -> InterpResult<'tcx, (Size, Align, T)>,
416     ) -> InterpResult<'tcx, Option<T>> {
417         fn check_offset_align(offset: u64, align: Align) -> InterpResult<'static> {
418             if offset % align.bytes() == 0 {
419                 Ok(())
420             } else {
421                 // The biggest power of two through which `offset` is divisible.
422                 let offset_pow2 = 1 << offset.trailing_zeros();
423                 throw_ub!(AlignmentCheckFailed {
424                     has: Align::from_bytes(offset_pow2).unwrap(),
425                     required: align,
426                 })
427             }
428         }
429
430         // Extract from the pointer an `Option<AllocId>` and an offset, which is relative to the
431         // allocation or (if that is `None`) an absolute address.
432         let ptr_or_addr = if size.bytes() == 0 {
433             // Let's see what we can do, but don't throw errors if there's nothing there.
434             self.ptr_try_get_alloc(ptr)
435         } else {
436             // A "real" access, we insist on getting an `AllocId`.
437             Ok(self.ptr_get_alloc(ptr)?)
438         };
439         Ok(match ptr_or_addr {
440             Err(addr) => {
441                 // No memory is actually being accessed.
442                 debug_assert!(size.bytes() == 0);
443                 // Must be non-null.
444                 if addr == 0 {
445                     throw_ub!(DanglingIntPointer(0, msg))
446                 }
447                 // Must be aligned.
448                 if let Some(align) = align {
449                     check_offset_align(addr, align)?;
450                 }
451                 None
452             }
453             Ok((alloc_id, offset, ptr)) => {
454                 let (alloc_size, alloc_align, ret_val) = alloc_size(alloc_id, offset, ptr)?;
455                 // Test bounds. This also ensures non-null.
456                 // It is sufficient to check this for the end pointer. Also check for overflow!
457                 if offset.checked_add(size, &self.tcx).map_or(true, |end| end > alloc_size) {
458                     throw_ub!(PointerOutOfBounds {
459                         alloc_id,
460                         alloc_size,
461                         ptr_offset: self.machine_usize_to_isize(offset.bytes()),
462                         ptr_size: size,
463                         msg,
464                     })
465                 }
466                 // Test align. Check this last; if both bounds and alignment are violated
467                 // we want the error to be about the bounds.
468                 if let Some(align) = align {
469                     if M::force_int_for_alignment_check(&self.extra) {
470                         let addr = Scalar::from_pointer(ptr, &self.tcx)
471                             .to_machine_usize(&self.tcx)
472                             .expect("ptr-to-int cast for align check should never fail");
473                         check_offset_align(addr, align)?;
474                     } else {
475                         // Check allocation alignment and offset alignment.
476                         if alloc_align.bytes() < align.bytes() {
477                             throw_ub!(AlignmentCheckFailed { has: alloc_align, required: align });
478                         }
479                         check_offset_align(offset.bytes(), align)?;
480                     }
481                 }
482
483                 // We can still be zero-sized in this branch, in which case we have to
484                 // return `None`.
485                 if size.bytes() == 0 { None } else { Some(ret_val) }
486             }
487         })
488     }
489
490     /// Test if the pointer might be null.
491     pub fn ptr_may_be_null(&self, ptr: Pointer<Option<M::PointerTag>>) -> bool {
492         match self.ptr_try_get_alloc(ptr) {
493             Ok((alloc_id, offset, _)) => {
494                 let (size, _align) = self
495                     .get_size_and_align(alloc_id, AllocCheck::MaybeDead)
496                     .expect("alloc info with MaybeDead cannot fail");
497                 // If the pointer is out-of-bounds, it may be null.
498                 // Note that one-past-the-end (offset == size) is still inbounds, and never null.
499                 offset > size
500             }
501             Err(offset) => offset == 0,
502         }
503     }
504 }
505
506 /// Allocation accessors
507 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> {
508     /// Helper function to obtain a global (tcx) allocation.
509     /// This attempts to return a reference to an existing allocation if
510     /// one can be found in `tcx`. That, however, is only possible if `tcx` and
511     /// this machine use the same pointer tag, so it is indirected through
512     /// `M::tag_allocation`.
513     fn get_global_alloc(
514         &self,
515         id: AllocId,
516         is_write: bool,
517     ) -> InterpResult<'tcx, Cow<'tcx, Allocation<M::PointerTag, M::AllocExtra>>> {
518         let (alloc, def_id) = match self.tcx.get_global_alloc(id) {
519             Some(GlobalAlloc::Memory(mem)) => {
520                 // Memory of a constant or promoted or anonymous memory referenced by a static.
521                 (mem, None)
522             }
523             Some(GlobalAlloc::Function(..)) => throw_ub!(DerefFunctionPointer(id)),
524             None => throw_ub!(PointerUseAfterFree(id)),
525             Some(GlobalAlloc::Static(def_id)) => {
526                 assert!(self.tcx.is_static(def_id));
527                 assert!(!self.tcx.is_thread_local_static(def_id));
528                 // Notice that every static has two `AllocId` that will resolve to the same
529                 // thing here: one maps to `GlobalAlloc::Static`, this is the "lazy" ID,
530                 // and the other one is maps to `GlobalAlloc::Memory`, this is returned by
531                 // `eval_static_initializer` and it is the "resolved" ID.
532                 // The resolved ID is never used by the interpreted program, it is hidden.
533                 // This is relied upon for soundness of const-patterns; a pointer to the resolved
534                 // ID would "sidestep" the checks that make sure consts do not point to statics!
535                 // The `GlobalAlloc::Memory` branch here is still reachable though; when a static
536                 // contains a reference to memory that was created during its evaluation (i.e., not
537                 // to another static), those inner references only exist in "resolved" form.
538                 if self.tcx.is_foreign_item(def_id) {
539                     throw_unsup!(ReadExternStatic(def_id));
540                 }
541
542                 (self.tcx.eval_static_initializer(def_id)?, Some(def_id))
543             }
544         };
545         M::before_access_global(&self.extra, id, alloc, def_id, is_write)?;
546         let alloc = Cow::Borrowed(alloc);
547         // We got tcx memory. Let the machine initialize its "extra" stuff.
548         let alloc = M::init_allocation_extra(
549             self,
550             id, // always use the ID we got as input, not the "hidden" one.
551             alloc,
552             M::GLOBAL_KIND.map(MemoryKind::Machine),
553         );
554         Ok(alloc)
555     }
556
557     /// Gives raw access to the `Allocation`, without bounds or alignment checks.
558     /// The caller is responsible for calling the access hooks!
559     fn get_raw(
560         &self,
561         id: AllocId,
562     ) -> InterpResult<'tcx, &Allocation<M::PointerTag, M::AllocExtra>> {
563         // The error type of the inner closure here is somewhat funny.  We have two
564         // ways of "erroring": An actual error, or because we got a reference from
565         // `get_global_alloc` that we can actually use directly without inserting anything anywhere.
566         // So the error type is `InterpResult<'tcx, &Allocation<M::PointerTag>>`.
567         let a = self.alloc_map.get_or(id, || {
568             let alloc = self.get_global_alloc(id, /*is_write*/ false).map_err(Err)?;
569             match alloc {
570                 Cow::Borrowed(alloc) => {
571                     // We got a ref, cheaply return that as an "error" so that the
572                     // map does not get mutated.
573                     Err(Ok(alloc))
574                 }
575                 Cow::Owned(alloc) => {
576                     // Need to put it into the map and return a ref to that
577                     let kind = M::GLOBAL_KIND.expect(
578                         "I got a global allocation that I have to copy but the machine does \
579                             not expect that to happen",
580                     );
581                     Ok((MemoryKind::Machine(kind), alloc))
582                 }
583             }
584         });
585         // Now unpack that funny error type
586         match a {
587             Ok(a) => Ok(&a.1),
588             Err(a) => a,
589         }
590     }
591
592     /// "Safe" (bounds and align-checked) allocation access.
593     pub fn get<'a>(
594         &'a self,
595         ptr: Pointer<Option<M::PointerTag>>,
596         size: Size,
597         align: Align,
598     ) -> InterpResult<'tcx, Option<AllocRef<'a, 'tcx, M::PointerTag, M::AllocExtra>>> {
599         let align = M::enforce_alignment(&self.extra).then_some(align);
600         let ptr_and_alloc = self.check_and_deref_ptr(
601             ptr,
602             size,
603             align,
604             CheckInAllocMsg::MemoryAccessTest,
605             |alloc_id, offset, ptr| {
606                 let alloc = self.get_raw(alloc_id)?;
607                 Ok((alloc.size(), alloc.align, (alloc_id, offset, ptr, alloc)))
608             },
609         )?;
610         if let Some((alloc_id, offset, ptr, alloc)) = ptr_and_alloc {
611             let range = alloc_range(offset, size);
612             M::memory_read(&self.extra, &alloc.extra, ptr.provenance, range)?;
613             Ok(Some(AllocRef { alloc, range, tcx: self.tcx, alloc_id }))
614         } else {
615             // Even in this branch we have to be sure that we actually access the allocation, in
616             // order to ensure that `static FOO: Type = FOO;` causes a cycle error instead of
617             // magically pulling *any* ZST value from the ether. However, the `get_raw` above is
618             // always called when `ptr` has an `AllocId`.
619             Ok(None)
620         }
621     }
622
623     /// Return the `extra` field of the given allocation.
624     pub fn get_alloc_extra<'a>(&'a self, id: AllocId) -> InterpResult<'tcx, &'a M::AllocExtra> {
625         Ok(&self.get_raw(id)?.extra)
626     }
627
628     /// Gives raw mutable access to the `Allocation`, without bounds or alignment checks.
629     /// The caller is responsible for calling the access hooks!
630     ///
631     /// Also returns a ptr to `self.extra` so that the caller can use it in parallel with the
632     /// allocation.
633     fn get_raw_mut(
634         &mut self,
635         id: AllocId,
636     ) -> InterpResult<'tcx, (&mut Allocation<M::PointerTag, M::AllocExtra>, &mut M::MemoryExtra)>
637     {
638         // We have "NLL problem case #3" here, which cannot be worked around without loss of
639         // efficiency even for the common case where the key is in the map.
640         // <https://rust-lang.github.io/rfcs/2094-nll.html#problem-case-3-conditional-control-flow-across-functions>
641         // (Cannot use `get_mut_or` since `get_global_alloc` needs `&self`.)
642         if self.alloc_map.get_mut(id).is_none() {
643             // Slow path.
644             // Allocation not found locally, go look global.
645             let alloc = self.get_global_alloc(id, /*is_write*/ true)?;
646             let kind = M::GLOBAL_KIND.expect(
647                 "I got a global allocation that I have to copy but the machine does \
648                     not expect that to happen",
649             );
650             self.alloc_map.insert(id, (MemoryKind::Machine(kind), alloc.into_owned()));
651         }
652
653         let (_kind, alloc) = self.alloc_map.get_mut(id).unwrap();
654         if alloc.mutability == Mutability::Not {
655             throw_ub!(WriteToReadOnly(id))
656         }
657         Ok((alloc, &mut self.extra))
658     }
659
660     /// "Safe" (bounds and align-checked) allocation access.
661     pub fn get_mut<'a>(
662         &'a mut self,
663         ptr: Pointer<Option<M::PointerTag>>,
664         size: Size,
665         align: Align,
666     ) -> InterpResult<'tcx, Option<AllocRefMut<'a, 'tcx, M::PointerTag, M::AllocExtra>>> {
667         let parts = self.get_ptr_access(ptr, size, align)?;
668         if let Some((alloc_id, offset, ptr)) = parts {
669             let tcx = self.tcx;
670             // FIXME: can we somehow avoid looking up the allocation twice here?
671             // We cannot call `get_raw_mut` inside `check_and_deref_ptr` as that would duplicate `&mut self`.
672             let (alloc, extra) = self.get_raw_mut(alloc_id)?;
673             let range = alloc_range(offset, size);
674             M::memory_written(extra, &mut alloc.extra, ptr.provenance, range)?;
675             Ok(Some(AllocRefMut { alloc, range, tcx, alloc_id }))
676         } else {
677             Ok(None)
678         }
679     }
680
681     /// Return the `extra` field of the given allocation.
682     pub fn get_alloc_extra_mut<'a>(
683         &'a mut self,
684         id: AllocId,
685     ) -> InterpResult<'tcx, (&'a mut M::AllocExtra, &'a mut M::MemoryExtra)> {
686         let (alloc, memory_extra) = self.get_raw_mut(id)?;
687         Ok((&mut alloc.extra, memory_extra))
688     }
689
690     /// Obtain the size and alignment of an allocation, even if that allocation has
691     /// been deallocated.
692     ///
693     /// If `liveness` is `AllocCheck::MaybeDead`, this function always returns `Ok`.
694     pub fn get_size_and_align(
695         &self,
696         id: AllocId,
697         liveness: AllocCheck,
698     ) -> InterpResult<'static, (Size, Align)> {
699         // # Regular allocations
700         // Don't use `self.get_raw` here as that will
701         // a) cause cycles in case `id` refers to a static
702         // b) duplicate a global's allocation in miri
703         if let Some((_, alloc)) = self.alloc_map.get(id) {
704             return Ok((alloc.size(), alloc.align));
705         }
706
707         // # Function pointers
708         // (both global from `alloc_map` and local from `extra_fn_ptr_map`)
709         if self.get_fn_alloc(id).is_some() {
710             return if let AllocCheck::Dereferenceable = liveness {
711                 // The caller requested no function pointers.
712                 throw_ub!(DerefFunctionPointer(id))
713             } else {
714                 Ok((Size::ZERO, Align::ONE))
715             };
716         }
717
718         // # Statics
719         // Can't do this in the match argument, we may get cycle errors since the lock would
720         // be held throughout the match.
721         match self.tcx.get_global_alloc(id) {
722             Some(GlobalAlloc::Static(did)) => {
723                 assert!(!self.tcx.is_thread_local_static(did));
724                 // Use size and align of the type.
725                 let ty = self.tcx.type_of(did);
726                 let layout = self.tcx.layout_of(ParamEnv::empty().and(ty)).unwrap();
727                 Ok((layout.size, layout.align.abi))
728             }
729             Some(GlobalAlloc::Memory(alloc)) => {
730                 // Need to duplicate the logic here, because the global allocations have
731                 // different associated types than the interpreter-local ones.
732                 Ok((alloc.size(), alloc.align))
733             }
734             Some(GlobalAlloc::Function(_)) => bug!("We already checked function pointers above"),
735             // The rest must be dead.
736             None => {
737                 if let AllocCheck::MaybeDead = liveness {
738                     // Deallocated pointers are allowed, we should be able to find
739                     // them in the map.
740                     Ok(*self
741                         .dead_alloc_map
742                         .get(&id)
743                         .expect("deallocated pointers should all be recorded in `dead_alloc_map`"))
744                 } else {
745                     throw_ub!(PointerUseAfterFree(id))
746                 }
747             }
748         }
749     }
750
751     fn get_fn_alloc(&self, id: AllocId) -> Option<FnVal<'tcx, M::ExtraFnVal>> {
752         if let Some(extra) = self.extra_fn_ptr_map.get(&id) {
753             Some(FnVal::Other(*extra))
754         } else {
755             match self.tcx.get_global_alloc(id) {
756                 Some(GlobalAlloc::Function(instance)) => Some(FnVal::Instance(instance)),
757                 _ => None,
758             }
759         }
760     }
761
762     pub fn get_fn(
763         &self,
764         ptr: Pointer<Option<M::PointerTag>>,
765     ) -> InterpResult<'tcx, FnVal<'tcx, M::ExtraFnVal>> {
766         trace!("get_fn({:?})", ptr);
767         let (alloc_id, offset, _ptr) = self.ptr_get_alloc(ptr)?;
768         if offset.bytes() != 0 {
769             throw_ub!(InvalidFunctionPointer(Pointer::new(alloc_id, offset)))
770         }
771         self.get_fn_alloc(alloc_id)
772             .ok_or_else(|| err_ub!(InvalidFunctionPointer(Pointer::new(alloc_id, offset))).into())
773     }
774
775     pub fn mark_immutable(&mut self, id: AllocId) -> InterpResult<'tcx> {
776         self.get_raw_mut(id)?.0.mutability = Mutability::Not;
777         Ok(())
778     }
779
780     /// Create a lazy debug printer that prints the given allocation and all allocations it points
781     /// to, recursively.
782     #[must_use]
783     pub fn dump_alloc<'a>(&'a self, id: AllocId) -> DumpAllocs<'a, 'mir, 'tcx, M> {
784         self.dump_allocs(vec![id])
785     }
786
787     /// Create a lazy debug printer for a list of allocations and all allocations they point to,
788     /// recursively.
789     #[must_use]
790     pub fn dump_allocs<'a>(&'a self, mut allocs: Vec<AllocId>) -> DumpAllocs<'a, 'mir, 'tcx, M> {
791         allocs.sort();
792         allocs.dedup();
793         DumpAllocs { mem: self, allocs }
794     }
795
796     /// Print leaked memory. Allocations reachable from `static_roots` or a `Global` allocation
797     /// are not considered leaked. Leaks whose kind `may_leak()` returns true are not reported.
798     pub fn leak_report(&self, static_roots: &[AllocId]) -> usize {
799         // Collect the set of allocations that are *reachable* from `Global` allocations.
800         let reachable = {
801             let mut reachable = FxHashSet::default();
802             let global_kind = M::GLOBAL_KIND.map(MemoryKind::Machine);
803             let mut todo: Vec<_> = self.alloc_map.filter_map_collect(move |&id, &(kind, _)| {
804                 if Some(kind) == global_kind { Some(id) } else { None }
805             });
806             todo.extend(static_roots);
807             while let Some(id) = todo.pop() {
808                 if reachable.insert(id) {
809                     // This is a new allocation, add its relocations to `todo`.
810                     if let Some((_, alloc)) = self.alloc_map.get(id) {
811                         todo.extend(alloc.relocations().values().map(|tag| tag.get_alloc_id()));
812                     }
813                 }
814             }
815             reachable
816         };
817
818         // All allocations that are *not* `reachable` and *not* `may_leak` are considered leaking.
819         let leaks: Vec<_> = self.alloc_map.filter_map_collect(|&id, &(kind, _)| {
820             if kind.may_leak() || reachable.contains(&id) { None } else { Some(id) }
821         });
822         let n = leaks.len();
823         if n > 0 {
824             eprintln!("The following memory was leaked: {:?}", self.dump_allocs(leaks));
825         }
826         n
827     }
828
829     /// This is used by [priroda](https://github.com/oli-obk/priroda)
830     pub fn alloc_map(&self) -> &M::MemoryMap {
831         &self.alloc_map
832     }
833 }
834
835 #[doc(hidden)]
836 /// There's no way to use this directly, it's just a helper struct for the `dump_alloc(s)` methods.
837 pub struct DumpAllocs<'a, 'mir, 'tcx, M: Machine<'mir, 'tcx>> {
838     mem: &'a Memory<'mir, 'tcx, M>,
839     allocs: Vec<AllocId>,
840 }
841
842 impl<'a, 'mir, 'tcx, M: Machine<'mir, 'tcx>> std::fmt::Debug for DumpAllocs<'a, 'mir, 'tcx, M> {
843     fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
844         // Cannot be a closure because it is generic in `Tag`, `Extra`.
845         fn write_allocation_track_relocs<'tcx, Tag: Provenance, Extra>(
846             fmt: &mut std::fmt::Formatter<'_>,
847             tcx: TyCtxt<'tcx>,
848             allocs_to_print: &mut VecDeque<AllocId>,
849             alloc: &Allocation<Tag, Extra>,
850         ) -> std::fmt::Result {
851             for alloc_id in alloc.relocations().values().map(|tag| tag.get_alloc_id()) {
852                 allocs_to_print.push_back(alloc_id);
853             }
854             write!(fmt, "{}", pretty::display_allocation(tcx, alloc))
855         }
856
857         let mut allocs_to_print: VecDeque<_> = self.allocs.iter().copied().collect();
858         // `allocs_printed` contains all allocations that we have already printed.
859         let mut allocs_printed = FxHashSet::default();
860
861         while let Some(id) = allocs_to_print.pop_front() {
862             if !allocs_printed.insert(id) {
863                 // Already printed, so skip this.
864                 continue;
865             }
866
867             write!(fmt, "{}", id)?;
868             match self.mem.alloc_map.get(id) {
869                 Some(&(kind, ref alloc)) => {
870                     // normal alloc
871                     write!(fmt, " ({}, ", kind)?;
872                     write_allocation_track_relocs(
873                         &mut *fmt,
874                         self.mem.tcx,
875                         &mut allocs_to_print,
876                         alloc,
877                     )?;
878                 }
879                 None => {
880                     // global alloc
881                     match self.mem.tcx.get_global_alloc(id) {
882                         Some(GlobalAlloc::Memory(alloc)) => {
883                             write!(fmt, " (unchanged global, ")?;
884                             write_allocation_track_relocs(
885                                 &mut *fmt,
886                                 self.mem.tcx,
887                                 &mut allocs_to_print,
888                                 alloc,
889                             )?;
890                         }
891                         Some(GlobalAlloc::Function(func)) => {
892                             write!(fmt, " (fn: {})", func)?;
893                         }
894                         Some(GlobalAlloc::Static(did)) => {
895                             write!(fmt, " (static: {})", self.mem.tcx.def_path_str(did))?;
896                         }
897                         None => {
898                             write!(fmt, " (deallocated)")?;
899                         }
900                     }
901                 }
902             }
903             writeln!(fmt)?;
904         }
905         Ok(())
906     }
907 }
908
909 /// Reading and writing.
910 impl<'tcx, 'a, Tag: Copy, Extra> AllocRefMut<'a, 'tcx, Tag, Extra> {
911     pub fn write_scalar(
912         &mut self,
913         range: AllocRange,
914         val: ScalarMaybeUninit<Tag>,
915     ) -> InterpResult<'tcx> {
916         Ok(self
917             .alloc
918             .write_scalar(&self.tcx, self.range.subrange(range), val)
919             .map_err(|e| e.to_interp_error(self.alloc_id))?)
920     }
921
922     pub fn write_ptr_sized(
923         &mut self,
924         offset: Size,
925         val: ScalarMaybeUninit<Tag>,
926     ) -> InterpResult<'tcx> {
927         self.write_scalar(alloc_range(offset, self.tcx.data_layout().pointer_size), val)
928     }
929 }
930
931 impl<'tcx, 'a, Tag: Copy, Extra> AllocRef<'a, 'tcx, Tag, Extra> {
932     pub fn read_scalar(&self, range: AllocRange) -> InterpResult<'tcx, ScalarMaybeUninit<Tag>> {
933         Ok(self
934             .alloc
935             .read_scalar(&self.tcx, self.range.subrange(range))
936             .map_err(|e| e.to_interp_error(self.alloc_id))?)
937     }
938
939     pub fn read_ptr_sized(&self, offset: Size) -> InterpResult<'tcx, ScalarMaybeUninit<Tag>> {
940         self.read_scalar(alloc_range(offset, self.tcx.data_layout().pointer_size))
941     }
942
943     pub fn check_bytes(&self, range: AllocRange, allow_uninit_and_ptr: bool) -> InterpResult<'tcx> {
944         Ok(self
945             .alloc
946             .check_bytes(&self.tcx, self.range.subrange(range), allow_uninit_and_ptr)
947             .map_err(|e| e.to_interp_error(self.alloc_id))?)
948     }
949 }
950
951 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> {
952     /// Reads the given number of bytes from memory. Returns them as a slice.
953     ///
954     /// Performs appropriate bounds checks.
955     pub fn read_bytes(
956         &self,
957         ptr: Pointer<Option<M::PointerTag>>,
958         size: Size,
959     ) -> InterpResult<'tcx, &[u8]> {
960         let alloc_ref = match self.get(ptr, size, Align::ONE)? {
961             Some(a) => a,
962             None => return Ok(&[]), // zero-sized access
963         };
964         // Side-step AllocRef and directly access the underlying bytes more efficiently.
965         // (We are staying inside the bounds here so all is good.)
966         Ok(alloc_ref
967             .alloc
968             .get_bytes(&alloc_ref.tcx, alloc_ref.range)
969             .map_err(|e| e.to_interp_error(alloc_ref.alloc_id))?)
970     }
971
972     /// Writes the given stream of bytes into memory.
973     ///
974     /// Performs appropriate bounds checks.
975     pub fn write_bytes(
976         &mut self,
977         ptr: Pointer<Option<M::PointerTag>>,
978         src: impl IntoIterator<Item = u8>,
979     ) -> InterpResult<'tcx> {
980         let mut src = src.into_iter();
981         let (lower, upper) = src.size_hint();
982         let len = upper.expect("can only write bounded iterators");
983         assert_eq!(lower, len, "can only write iterators with a precise length");
984
985         let size = Size::from_bytes(len);
986         let alloc_ref = match self.get_mut(ptr, size, Align::ONE)? {
987             Some(alloc_ref) => alloc_ref,
988             None => {
989                 // zero-sized access
990                 assert_matches!(
991                     src.next(),
992                     None,
993                     "iterator said it was empty but returned an element"
994                 );
995                 return Ok(());
996             }
997         };
998
999         // Side-step AllocRef and directly access the underlying bytes more efficiently.
1000         // (We are staying inside the bounds here so all is good.)
1001         let bytes = alloc_ref.alloc.get_bytes_mut(&alloc_ref.tcx, alloc_ref.range);
1002         // `zip` would stop when the first iterator ends; we want to definitely
1003         // cover all of `bytes`.
1004         for dest in bytes {
1005             *dest = src.next().expect("iterator was shorter than it said it would be");
1006         }
1007         assert_matches!(src.next(), None, "iterator was longer than it said it would be");
1008         Ok(())
1009     }
1010
1011     pub fn copy(
1012         &mut self,
1013         src: Pointer<Option<M::PointerTag>>,
1014         src_align: Align,
1015         dest: Pointer<Option<M::PointerTag>>,
1016         dest_align: Align,
1017         size: Size,
1018         nonoverlapping: bool,
1019     ) -> InterpResult<'tcx> {
1020         self.copy_repeatedly(src, src_align, dest, dest_align, size, 1, nonoverlapping)
1021     }
1022
1023     pub fn copy_repeatedly(
1024         &mut self,
1025         src: Pointer<Option<M::PointerTag>>,
1026         src_align: Align,
1027         dest: Pointer<Option<M::PointerTag>>,
1028         dest_align: Align,
1029         size: Size,
1030         num_copies: u64,
1031         nonoverlapping: bool,
1032     ) -> InterpResult<'tcx> {
1033         let tcx = self.tcx;
1034         // We need to do our own bounds-checks.
1035         let src_parts = self.get_ptr_access(src, size, src_align)?;
1036         let dest_parts = self.get_ptr_access(dest, size * num_copies, dest_align)?; // `Size` multiplication
1037
1038         // FIXME: we look up both allocations twice here, once ebfore for the `check_ptr_access`
1039         // and once below to get the underlying `&[mut] Allocation`.
1040
1041         // Source alloc preparations and access hooks.
1042         let (src_alloc_id, src_offset, src) = match src_parts {
1043             None => return Ok(()), // Zero-sized *source*, that means dst is also zero-sized and we have nothing to do.
1044             Some(src_ptr) => src_ptr,
1045         };
1046         let src_alloc = self.get_raw(src_alloc_id)?;
1047         let src_range = alloc_range(src_offset, size);
1048         M::memory_read(&self.extra, &src_alloc.extra, src.provenance, src_range)?;
1049         // We need the `dest` ptr for the next operation, so we get it now.
1050         // We already did the source checks and called the hooks so we are good to return early.
1051         let (dest_alloc_id, dest_offset, dest) = match dest_parts {
1052             None => return Ok(()), // Zero-sized *destiantion*.
1053             Some(dest_ptr) => dest_ptr,
1054         };
1055
1056         // first copy the relocations to a temporary buffer, because
1057         // `get_bytes_mut` will clear the relocations, which is correct,
1058         // since we don't want to keep any relocations at the target.
1059         // (`get_bytes_with_uninit_and_ptr` below checks that there are no
1060         // relocations overlapping the edges; those would not be handled correctly).
1061         let relocations =
1062             src_alloc.prepare_relocation_copy(self, src_range, dest_offset, num_copies);
1063         // Prepare a copy of the initialization mask.
1064         let compressed = src_alloc.compress_uninit_range(src_range);
1065         // This checks relocation edges on the src.
1066         let src_bytes = src_alloc
1067             .get_bytes_with_uninit_and_ptr(&tcx, src_range)
1068             .map_err(|e| e.to_interp_error(src_alloc_id))?
1069             .as_ptr(); // raw ptr, so we can also get a ptr to the destination allocation
1070
1071         // Destination alloc preparations and access hooks.
1072         let (dest_alloc, extra) = self.get_raw_mut(dest_alloc_id)?;
1073         let dest_range = alloc_range(dest_offset, size * num_copies);
1074         M::memory_written(extra, &mut dest_alloc.extra, dest.provenance, dest_range)?;
1075         let dest_bytes = dest_alloc.get_bytes_mut_ptr(&tcx, dest_range).as_mut_ptr();
1076
1077         if compressed.no_bytes_init() {
1078             // Fast path: If all bytes are `uninit` then there is nothing to copy. The target range
1079             // is marked as uninitialized but we otherwise omit changing the byte representation which may
1080             // be arbitrary for uninitialized bytes.
1081             // This also avoids writing to the target bytes so that the backing allocation is never
1082             // touched if the bytes stay uninitialized for the whole interpreter execution. On contemporary
1083             // operating system this can avoid physically allocating the page.
1084             dest_alloc.mark_init(dest_range, false); // `Size` multiplication
1085             dest_alloc.mark_relocation_range(relocations);
1086             return Ok(());
1087         }
1088
1089         // SAFE: The above indexing would have panicked if there weren't at least `size` bytes
1090         // behind `src` and `dest`. Also, we use the overlapping-safe `ptr::copy` if `src` and
1091         // `dest` could possibly overlap.
1092         // The pointers above remain valid even if the `HashMap` table is moved around because they
1093         // point into the `Vec` storing the bytes.
1094         unsafe {
1095             if src_alloc_id == dest_alloc_id {
1096                 if nonoverlapping {
1097                     // `Size` additions
1098                     if (src_offset <= dest_offset && src_offset + size > dest_offset)
1099                         || (dest_offset <= src_offset && dest_offset + size > src_offset)
1100                     {
1101                         throw_ub_format!("copy_nonoverlapping called on overlapping ranges")
1102                     }
1103                 }
1104
1105                 for i in 0..num_copies {
1106                     ptr::copy(
1107                         src_bytes,
1108                         dest_bytes.add((size * i).bytes_usize()), // `Size` multiplication
1109                         size.bytes_usize(),
1110                     );
1111                 }
1112             } else {
1113                 for i in 0..num_copies {
1114                     ptr::copy_nonoverlapping(
1115                         src_bytes,
1116                         dest_bytes.add((size * i).bytes_usize()), // `Size` multiplication
1117                         size.bytes_usize(),
1118                     );
1119                 }
1120             }
1121         }
1122
1123         // now fill in all the "init" data
1124         dest_alloc.mark_compressed_init_range(
1125             &compressed,
1126             alloc_range(dest_offset, size), // just a single copy (i.e., not full `dest_range`)
1127             num_copies,
1128         );
1129         // copy the relocations to the destination
1130         dest_alloc.mark_relocation_range(relocations);
1131
1132         Ok(())
1133     }
1134 }
1135
1136 /// Machine pointer introspection.
1137 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> {
1138     pub fn scalar_to_ptr(&self, scalar: Scalar<M::PointerTag>) -> Pointer<Option<M::PointerTag>> {
1139         // We use `to_bits_or_ptr_internal` since we are just implementing the method people need to
1140         // call to force getting out a pointer.
1141         match scalar.to_bits_or_ptr_internal(self.pointer_size()) {
1142             Err(ptr) => ptr.into(),
1143             Ok(bits) => {
1144                 let addr = u64::try_from(bits).unwrap();
1145                 let ptr = M::ptr_from_addr(&self, addr);
1146                 if addr == 0 {
1147                     assert!(ptr.provenance.is_none(), "null pointer can never have an AllocId");
1148                 }
1149                 ptr
1150             }
1151         }
1152     }
1153
1154     /// Turning a "maybe pointer" into a proper pointer (and some information
1155     /// about where it points), or an absolute address.
1156     pub fn ptr_try_get_alloc(
1157         &self,
1158         ptr: Pointer<Option<M::PointerTag>>,
1159     ) -> Result<(AllocId, Size, Pointer<M::PointerTag>), u64> {
1160         match ptr.into_pointer_or_addr() {
1161             Ok(ptr) => {
1162                 let (alloc_id, offset) = M::ptr_get_alloc(self, ptr);
1163                 Ok((alloc_id, offset, ptr))
1164             }
1165             Err(addr) => Err(addr.bytes()),
1166         }
1167     }
1168
1169     /// Turning a "maybe pointer" into a proper pointer (and some information about where it points).
1170     #[inline(always)]
1171     pub fn ptr_get_alloc(
1172         &self,
1173         ptr: Pointer<Option<M::PointerTag>>,
1174     ) -> InterpResult<'tcx, (AllocId, Size, Pointer<M::PointerTag>)> {
1175         self.ptr_try_get_alloc(ptr).map_err(|offset| {
1176             err_ub!(DanglingIntPointer(offset, CheckInAllocMsg::InboundsTest)).into()
1177         })
1178     }
1179 }