]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_const_eval/src/interpret/memory.rs
Rollup merge of #94355 - ouz-a:master, r=oli-bok
[rust.git] / compiler / rustc_const_eval / 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::mir::display_allocation;
19 use rustc_middle::ty::{Instance, ParamEnv, TyCtxt};
20 use rustc_target::abi::{Align, HasDataLayout, Size, TargetDataLayout};
21
22 use super::{
23     alloc_range, AllocId, AllocMap, AllocRange, Allocation, CheckInAllocMsg, GlobalAlloc,
24     InterpResult, Machine, MayLeak, Pointer, PointerArithmetic, Provenance, Scalar,
25     ScalarMaybeUninit,
26 };
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 Some((alloc_kind, mut alloc)) = self.alloc_map.remove(&alloc_id) else {
295             // Deallocating global memory -- always an error
296             return Err(match self.tcx.get_global_alloc(alloc_id) {
297                 Some(GlobalAlloc::Function(..)) => {
298                     err_ub_format!("deallocating {}, which is a function", alloc_id)
299                 }
300                 Some(GlobalAlloc::Static(..) | GlobalAlloc::Memory(..)) => {
301                     err_ub_format!("deallocating {}, which is static memory", alloc_id)
302                 }
303                 None => err_ub!(PointerUseAfterFree(alloc_id)),
304             }
305             .into());
306         };
307
308         if alloc.mutability == Mutability::Not {
309             throw_ub_format!("deallocating immutable allocation {}", alloc_id);
310         }
311         if alloc_kind != kind {
312             throw_ub_format!(
313                 "deallocating {}, which is {} memory, using {} deallocation operation",
314                 alloc_id,
315                 alloc_kind,
316                 kind
317             );
318         }
319         if let Some((size, align)) = old_size_and_align {
320             if size != alloc.size() || align != alloc.align {
321                 throw_ub_format!(
322                     "incorrect layout on deallocation: {} has size {} and alignment {}, but gave size {} and alignment {}",
323                     alloc_id,
324                     alloc.size().bytes(),
325                     alloc.align.bytes(),
326                     size.bytes(),
327                     align.bytes(),
328                 )
329             }
330         }
331
332         // Let the machine take some extra action
333         let size = alloc.size();
334         M::memory_deallocated(
335             &mut self.extra,
336             &mut alloc.extra,
337             ptr.provenance,
338             alloc_range(Size::ZERO, size),
339         )?;
340
341         // Don't forget to remember size and align of this now-dead allocation
342         let old = self.dead_alloc_map.insert(alloc_id, (size, alloc.align));
343         if old.is_some() {
344             bug!("Nothing can be deallocated twice");
345         }
346
347         Ok(())
348     }
349
350     /// Internal helper function to determine the allocation and offset of a pointer (if any).
351     #[inline(always)]
352     fn get_ptr_access(
353         &self,
354         ptr: Pointer<Option<M::PointerTag>>,
355         size: Size,
356         align: Align,
357     ) -> InterpResult<'tcx, Option<(AllocId, Size, Pointer<M::PointerTag>)>> {
358         let align = M::enforce_alignment(&self.extra).then_some(align);
359         self.check_and_deref_ptr(
360             ptr,
361             size,
362             align,
363             CheckInAllocMsg::MemoryAccessTest,
364             |alloc_id, offset, ptr| {
365                 let (size, align) =
366                     self.get_size_and_align(alloc_id, AllocCheck::Dereferenceable)?;
367                 Ok((size, align, (alloc_id, offset, ptr)))
368             },
369         )
370     }
371
372     /// Check if the given pointer points to live memory of given `size` and `align`
373     /// (ignoring `M::enforce_alignment`). The caller can control the error message for the
374     /// out-of-bounds case.
375     #[inline(always)]
376     pub fn check_ptr_access_align(
377         &self,
378         ptr: Pointer<Option<M::PointerTag>>,
379         size: Size,
380         align: Align,
381         msg: CheckInAllocMsg,
382     ) -> InterpResult<'tcx> {
383         self.check_and_deref_ptr(ptr, size, Some(align), msg, |alloc_id, _, _| {
384             let check = match msg {
385                 CheckInAllocMsg::DerefTest | CheckInAllocMsg::MemoryAccessTest => {
386                     AllocCheck::Dereferenceable
387                 }
388                 CheckInAllocMsg::PointerArithmeticTest | CheckInAllocMsg::InboundsTest => {
389                     AllocCheck::Live
390                 }
391             };
392             let (size, align) = self.get_size_and_align(alloc_id, check)?;
393             Ok((size, align, ()))
394         })?;
395         Ok(())
396     }
397
398     /// Low-level helper function to check if a ptr is in-bounds and potentially return a reference
399     /// to the allocation it points to. Supports both shared and mutable references, as the actual
400     /// checking is offloaded to a helper closure. `align` defines whether and which alignment check
401     /// is done. Returns `None` for size 0, and otherwise `Some` of what `alloc_size` returned.
402     fn check_and_deref_ptr<T>(
403         &self,
404         ptr: Pointer<Option<M::PointerTag>>,
405         size: Size,
406         align: Option<Align>,
407         msg: CheckInAllocMsg,
408         alloc_size: impl FnOnce(
409             AllocId,
410             Size,
411             Pointer<M::PointerTag>,
412         ) -> InterpResult<'tcx, (Size, Align, T)>,
413     ) -> InterpResult<'tcx, Option<T>> {
414         fn check_offset_align(offset: u64, align: Align) -> InterpResult<'static> {
415             if offset % align.bytes() == 0 {
416                 Ok(())
417             } else {
418                 // The biggest power of two through which `offset` is divisible.
419                 let offset_pow2 = 1 << offset.trailing_zeros();
420                 throw_ub!(AlignmentCheckFailed {
421                     has: Align::from_bytes(offset_pow2).unwrap(),
422                     required: align,
423                 })
424             }
425         }
426
427         // Extract from the pointer an `Option<AllocId>` and an offset, which is relative to the
428         // allocation or (if that is `None`) an absolute address.
429         let ptr_or_addr = if size.bytes() == 0 {
430             // Let's see what we can do, but don't throw errors if there's nothing there.
431             self.ptr_try_get_alloc(ptr)
432         } else {
433             // A "real" access, we insist on getting an `AllocId`.
434             Ok(self.ptr_get_alloc(ptr)?)
435         };
436         Ok(match ptr_or_addr {
437             Err(addr) => {
438                 // No memory is actually being accessed.
439                 debug_assert!(size.bytes() == 0);
440                 // Must be non-null.
441                 if addr == 0 {
442                     throw_ub!(DanglingIntPointer(0, msg))
443                 }
444                 // Must be aligned.
445                 if let Some(align) = align {
446                     check_offset_align(addr, align)?;
447                 }
448                 None
449             }
450             Ok((alloc_id, offset, ptr)) => {
451                 let (alloc_size, alloc_align, ret_val) = alloc_size(alloc_id, offset, ptr)?;
452                 // Test bounds. This also ensures non-null.
453                 // It is sufficient to check this for the end pointer. Also check for overflow!
454                 if offset.checked_add(size, &self.tcx).map_or(true, |end| end > alloc_size) {
455                     throw_ub!(PointerOutOfBounds {
456                         alloc_id,
457                         alloc_size,
458                         ptr_offset: self.machine_usize_to_isize(offset.bytes()),
459                         ptr_size: size,
460                         msg,
461                     })
462                 }
463                 // Test align. Check this last; if both bounds and alignment are violated
464                 // we want the error to be about the bounds.
465                 if let Some(align) = align {
466                     if M::force_int_for_alignment_check(&self.extra) {
467                         let addr = Scalar::from_pointer(ptr, &self.tcx)
468                             .to_machine_usize(&self.tcx)
469                             .expect("ptr-to-int cast for align check should never fail");
470                         check_offset_align(addr, align)?;
471                     } else {
472                         // Check allocation alignment and offset alignment.
473                         if alloc_align.bytes() < align.bytes() {
474                             throw_ub!(AlignmentCheckFailed { has: alloc_align, required: align });
475                         }
476                         check_offset_align(offset.bytes(), align)?;
477                     }
478                 }
479
480                 // We can still be zero-sized in this branch, in which case we have to
481                 // return `None`.
482                 if size.bytes() == 0 { None } else { Some(ret_val) }
483             }
484         })
485     }
486 }
487
488 /// Allocation accessors
489 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> {
490     /// Helper function to obtain a global (tcx) allocation.
491     /// This attempts to return a reference to an existing allocation if
492     /// one can be found in `tcx`. That, however, is only possible if `tcx` and
493     /// this machine use the same pointer tag, so it is indirected through
494     /// `M::tag_allocation`.
495     fn get_global_alloc(
496         &self,
497         id: AllocId,
498         is_write: bool,
499     ) -> InterpResult<'tcx, Cow<'tcx, Allocation<M::PointerTag, M::AllocExtra>>> {
500         let (alloc, def_id) = match self.tcx.get_global_alloc(id) {
501             Some(GlobalAlloc::Memory(mem)) => {
502                 // Memory of a constant or promoted or anonymous memory referenced by a static.
503                 (mem, None)
504             }
505             Some(GlobalAlloc::Function(..)) => throw_ub!(DerefFunctionPointer(id)),
506             None => throw_ub!(PointerUseAfterFree(id)),
507             Some(GlobalAlloc::Static(def_id)) => {
508                 assert!(self.tcx.is_static(def_id));
509                 assert!(!self.tcx.is_thread_local_static(def_id));
510                 // Notice that every static has two `AllocId` that will resolve to the same
511                 // thing here: one maps to `GlobalAlloc::Static`, this is the "lazy" ID,
512                 // and the other one is maps to `GlobalAlloc::Memory`, this is returned by
513                 // `eval_static_initializer` and it is the "resolved" ID.
514                 // The resolved ID is never used by the interpreted program, it is hidden.
515                 // This is relied upon for soundness of const-patterns; a pointer to the resolved
516                 // ID would "sidestep" the checks that make sure consts do not point to statics!
517                 // The `GlobalAlloc::Memory` branch here is still reachable though; when a static
518                 // contains a reference to memory that was created during its evaluation (i.e., not
519                 // to another static), those inner references only exist in "resolved" form.
520                 if self.tcx.is_foreign_item(def_id) {
521                     throw_unsup!(ReadExternStatic(def_id));
522                 }
523
524                 (self.tcx.eval_static_initializer(def_id)?, Some(def_id))
525             }
526         };
527         M::before_access_global(&self.extra, id, alloc, def_id, is_write)?;
528         let alloc = Cow::Borrowed(alloc);
529         // We got tcx memory. Let the machine initialize its "extra" stuff.
530         let alloc = M::init_allocation_extra(
531             self,
532             id, // always use the ID we got as input, not the "hidden" one.
533             alloc,
534             M::GLOBAL_KIND.map(MemoryKind::Machine),
535         );
536         Ok(alloc)
537     }
538
539     /// Gives raw access to the `Allocation`, without bounds or alignment checks.
540     /// The caller is responsible for calling the access hooks!
541     fn get_raw(
542         &self,
543         id: AllocId,
544     ) -> InterpResult<'tcx, &Allocation<M::PointerTag, M::AllocExtra>> {
545         // The error type of the inner closure here is somewhat funny.  We have two
546         // ways of "erroring": An actual error, or because we got a reference from
547         // `get_global_alloc` that we can actually use directly without inserting anything anywhere.
548         // So the error type is `InterpResult<'tcx, &Allocation<M::PointerTag>>`.
549         let a = self.alloc_map.get_or(id, || {
550             let alloc = self.get_global_alloc(id, /*is_write*/ false).map_err(Err)?;
551             match alloc {
552                 Cow::Borrowed(alloc) => {
553                     // We got a ref, cheaply return that as an "error" so that the
554                     // map does not get mutated.
555                     Err(Ok(alloc))
556                 }
557                 Cow::Owned(alloc) => {
558                     // Need to put it into the map and return a ref to that
559                     let kind = M::GLOBAL_KIND.expect(
560                         "I got a global allocation that I have to copy but the machine does \
561                             not expect that to happen",
562                     );
563                     Ok((MemoryKind::Machine(kind), alloc))
564                 }
565             }
566         });
567         // Now unpack that funny error type
568         match a {
569             Ok(a) => Ok(&a.1),
570             Err(a) => a,
571         }
572     }
573
574     /// "Safe" (bounds and align-checked) allocation access.
575     pub fn get<'a>(
576         &'a self,
577         ptr: Pointer<Option<M::PointerTag>>,
578         size: Size,
579         align: Align,
580     ) -> InterpResult<'tcx, Option<AllocRef<'a, 'tcx, M::PointerTag, M::AllocExtra>>> {
581         let align = M::enforce_alignment(&self.extra).then_some(align);
582         let ptr_and_alloc = self.check_and_deref_ptr(
583             ptr,
584             size,
585             align,
586             CheckInAllocMsg::MemoryAccessTest,
587             |alloc_id, offset, ptr| {
588                 let alloc = self.get_raw(alloc_id)?;
589                 Ok((alloc.size(), alloc.align, (alloc_id, offset, ptr, alloc)))
590             },
591         )?;
592         if let Some((alloc_id, offset, ptr, alloc)) = ptr_and_alloc {
593             let range = alloc_range(offset, size);
594             M::memory_read(&self.extra, &alloc.extra, ptr.provenance, range)?;
595             Ok(Some(AllocRef { alloc, range, tcx: self.tcx, alloc_id }))
596         } else {
597             // Even in this branch we have to be sure that we actually access the allocation, in
598             // order to ensure that `static FOO: Type = FOO;` causes a cycle error instead of
599             // magically pulling *any* ZST value from the ether. However, the `get_raw` above is
600             // always called when `ptr` has an `AllocId`.
601             Ok(None)
602         }
603     }
604
605     /// Return the `extra` field of the given allocation.
606     pub fn get_alloc_extra<'a>(&'a self, id: AllocId) -> InterpResult<'tcx, &'a M::AllocExtra> {
607         Ok(&self.get_raw(id)?.extra)
608     }
609
610     /// Gives raw mutable access to the `Allocation`, without bounds or alignment checks.
611     /// The caller is responsible for calling the access hooks!
612     ///
613     /// Also returns a ptr to `self.extra` so that the caller can use it in parallel with the
614     /// allocation.
615     fn get_raw_mut(
616         &mut self,
617         id: AllocId,
618     ) -> InterpResult<'tcx, (&mut Allocation<M::PointerTag, M::AllocExtra>, &mut M::MemoryExtra)>
619     {
620         // We have "NLL problem case #3" here, which cannot be worked around without loss of
621         // efficiency even for the common case where the key is in the map.
622         // <https://rust-lang.github.io/rfcs/2094-nll.html#problem-case-3-conditional-control-flow-across-functions>
623         // (Cannot use `get_mut_or` since `get_global_alloc` needs `&self`.)
624         if self.alloc_map.get_mut(id).is_none() {
625             // Slow path.
626             // Allocation not found locally, go look global.
627             let alloc = self.get_global_alloc(id, /*is_write*/ true)?;
628             let kind = M::GLOBAL_KIND.expect(
629                 "I got a global allocation that I have to copy but the machine does \
630                     not expect that to happen",
631             );
632             self.alloc_map.insert(id, (MemoryKind::Machine(kind), alloc.into_owned()));
633         }
634
635         let (_kind, alloc) = self.alloc_map.get_mut(id).unwrap();
636         if alloc.mutability == Mutability::Not {
637             throw_ub!(WriteToReadOnly(id))
638         }
639         Ok((alloc, &mut self.extra))
640     }
641
642     /// "Safe" (bounds and align-checked) allocation access.
643     pub fn get_mut<'a>(
644         &'a mut self,
645         ptr: Pointer<Option<M::PointerTag>>,
646         size: Size,
647         align: Align,
648     ) -> InterpResult<'tcx, Option<AllocRefMut<'a, 'tcx, M::PointerTag, M::AllocExtra>>> {
649         let parts = self.get_ptr_access(ptr, size, align)?;
650         if let Some((alloc_id, offset, ptr)) = parts {
651             let tcx = self.tcx;
652             // FIXME: can we somehow avoid looking up the allocation twice here?
653             // We cannot call `get_raw_mut` inside `check_and_deref_ptr` as that would duplicate `&mut self`.
654             let (alloc, extra) = self.get_raw_mut(alloc_id)?;
655             let range = alloc_range(offset, size);
656             M::memory_written(extra, &mut alloc.extra, ptr.provenance, range)?;
657             Ok(Some(AllocRefMut { alloc, range, tcx, alloc_id }))
658         } else {
659             Ok(None)
660         }
661     }
662
663     /// Return the `extra` field of the given allocation.
664     pub fn get_alloc_extra_mut<'a>(
665         &'a mut self,
666         id: AllocId,
667     ) -> InterpResult<'tcx, (&'a mut M::AllocExtra, &'a mut M::MemoryExtra)> {
668         let (alloc, memory_extra) = self.get_raw_mut(id)?;
669         Ok((&mut alloc.extra, memory_extra))
670     }
671
672     /// Obtain the size and alignment of an allocation, even if that allocation has
673     /// been deallocated.
674     ///
675     /// If `liveness` is `AllocCheck::MaybeDead`, this function always returns `Ok`.
676     pub fn get_size_and_align(
677         &self,
678         id: AllocId,
679         liveness: AllocCheck,
680     ) -> InterpResult<'static, (Size, Align)> {
681         // # Regular allocations
682         // Don't use `self.get_raw` here as that will
683         // a) cause cycles in case `id` refers to a static
684         // b) duplicate a global's allocation in miri
685         if let Some((_, alloc)) = self.alloc_map.get(id) {
686             return Ok((alloc.size(), alloc.align));
687         }
688
689         // # Function pointers
690         // (both global from `alloc_map` and local from `extra_fn_ptr_map`)
691         if self.get_fn_alloc(id).is_some() {
692             return if let AllocCheck::Dereferenceable = liveness {
693                 // The caller requested no function pointers.
694                 throw_ub!(DerefFunctionPointer(id))
695             } else {
696                 Ok((Size::ZERO, Align::ONE))
697             };
698         }
699
700         // # Statics
701         // Can't do this in the match argument, we may get cycle errors since the lock would
702         // be held throughout the match.
703         match self.tcx.get_global_alloc(id) {
704             Some(GlobalAlloc::Static(did)) => {
705                 assert!(!self.tcx.is_thread_local_static(did));
706                 // Use size and align of the type.
707                 let ty = self.tcx.type_of(did);
708                 let layout = self.tcx.layout_of(ParamEnv::empty().and(ty)).unwrap();
709                 Ok((layout.size, layout.align.abi))
710             }
711             Some(GlobalAlloc::Memory(alloc)) => {
712                 // Need to duplicate the logic here, because the global allocations have
713                 // different associated types than the interpreter-local ones.
714                 Ok((alloc.size(), alloc.align))
715             }
716             Some(GlobalAlloc::Function(_)) => bug!("We already checked function pointers above"),
717             // The rest must be dead.
718             None => {
719                 if let AllocCheck::MaybeDead = liveness {
720                     // Deallocated pointers are allowed, we should be able to find
721                     // them in the map.
722                     Ok(*self
723                         .dead_alloc_map
724                         .get(&id)
725                         .expect("deallocated pointers should all be recorded in `dead_alloc_map`"))
726                 } else {
727                     throw_ub!(PointerUseAfterFree(id))
728                 }
729             }
730         }
731     }
732
733     fn get_fn_alloc(&self, id: AllocId) -> Option<FnVal<'tcx, M::ExtraFnVal>> {
734         if let Some(extra) = self.extra_fn_ptr_map.get(&id) {
735             Some(FnVal::Other(*extra))
736         } else {
737             match self.tcx.get_global_alloc(id) {
738                 Some(GlobalAlloc::Function(instance)) => Some(FnVal::Instance(instance)),
739                 _ => None,
740             }
741         }
742     }
743
744     pub fn get_fn(
745         &self,
746         ptr: Pointer<Option<M::PointerTag>>,
747     ) -> InterpResult<'tcx, FnVal<'tcx, M::ExtraFnVal>> {
748         trace!("get_fn({:?})", ptr);
749         let (alloc_id, offset, _ptr) = self.ptr_get_alloc(ptr)?;
750         if offset.bytes() != 0 {
751             throw_ub!(InvalidFunctionPointer(Pointer::new(alloc_id, offset)))
752         }
753         self.get_fn_alloc(alloc_id)
754             .ok_or_else(|| err_ub!(InvalidFunctionPointer(Pointer::new(alloc_id, offset))).into())
755     }
756
757     pub fn mark_immutable(&mut self, id: AllocId) -> InterpResult<'tcx> {
758         self.get_raw_mut(id)?.0.mutability = Mutability::Not;
759         Ok(())
760     }
761
762     /// Create a lazy debug printer that prints the given allocation and all allocations it points
763     /// to, recursively.
764     #[must_use]
765     pub fn dump_alloc<'a>(&'a self, id: AllocId) -> DumpAllocs<'a, 'mir, 'tcx, M> {
766         self.dump_allocs(vec![id])
767     }
768
769     /// Create a lazy debug printer for a list of allocations and all allocations they point to,
770     /// recursively.
771     #[must_use]
772     pub fn dump_allocs<'a>(&'a self, mut allocs: Vec<AllocId>) -> DumpAllocs<'a, 'mir, 'tcx, M> {
773         allocs.sort();
774         allocs.dedup();
775         DumpAllocs { mem: self, allocs }
776     }
777
778     /// Print leaked memory. Allocations reachable from `static_roots` or a `Global` allocation
779     /// are not considered leaked. Leaks whose kind `may_leak()` returns true are not reported.
780     pub fn leak_report(&self, static_roots: &[AllocId]) -> usize {
781         // Collect the set of allocations that are *reachable* from `Global` allocations.
782         let reachable = {
783             let mut reachable = FxHashSet::default();
784             let global_kind = M::GLOBAL_KIND.map(MemoryKind::Machine);
785             let mut todo: Vec<_> = self.alloc_map.filter_map_collect(move |&id, &(kind, _)| {
786                 if Some(kind) == global_kind { Some(id) } else { None }
787             });
788             todo.extend(static_roots);
789             while let Some(id) = todo.pop() {
790                 if reachable.insert(id) {
791                     // This is a new allocation, add its relocations to `todo`.
792                     if let Some((_, alloc)) = self.alloc_map.get(id) {
793                         todo.extend(alloc.relocations().values().map(|tag| tag.get_alloc_id()));
794                     }
795                 }
796             }
797             reachable
798         };
799
800         // All allocations that are *not* `reachable` and *not* `may_leak` are considered leaking.
801         let leaks: Vec<_> = self.alloc_map.filter_map_collect(|&id, &(kind, _)| {
802             if kind.may_leak() || reachable.contains(&id) { None } else { Some(id) }
803         });
804         let n = leaks.len();
805         if n > 0 {
806             eprintln!("The following memory was leaked: {:?}", self.dump_allocs(leaks));
807         }
808         n
809     }
810
811     /// This is used by [priroda](https://github.com/oli-obk/priroda)
812     pub fn alloc_map(&self) -> &M::MemoryMap {
813         &self.alloc_map
814     }
815 }
816
817 #[doc(hidden)]
818 /// There's no way to use this directly, it's just a helper struct for the `dump_alloc(s)` methods.
819 pub struct DumpAllocs<'a, 'mir, 'tcx, M: Machine<'mir, 'tcx>> {
820     mem: &'a Memory<'mir, 'tcx, M>,
821     allocs: Vec<AllocId>,
822 }
823
824 impl<'a, 'mir, 'tcx, M: Machine<'mir, 'tcx>> std::fmt::Debug for DumpAllocs<'a, 'mir, 'tcx, M> {
825     fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
826         // Cannot be a closure because it is generic in `Tag`, `Extra`.
827         fn write_allocation_track_relocs<'tcx, Tag: Provenance, Extra>(
828             fmt: &mut std::fmt::Formatter<'_>,
829             tcx: TyCtxt<'tcx>,
830             allocs_to_print: &mut VecDeque<AllocId>,
831             alloc: &Allocation<Tag, Extra>,
832         ) -> std::fmt::Result {
833             for alloc_id in alloc.relocations().values().map(|tag| tag.get_alloc_id()) {
834                 allocs_to_print.push_back(alloc_id);
835             }
836             write!(fmt, "{}", display_allocation(tcx, alloc))
837         }
838
839         let mut allocs_to_print: VecDeque<_> = self.allocs.iter().copied().collect();
840         // `allocs_printed` contains all allocations that we have already printed.
841         let mut allocs_printed = FxHashSet::default();
842
843         while let Some(id) = allocs_to_print.pop_front() {
844             if !allocs_printed.insert(id) {
845                 // Already printed, so skip this.
846                 continue;
847             }
848
849             write!(fmt, "{}", id)?;
850             match self.mem.alloc_map.get(id) {
851                 Some(&(kind, ref alloc)) => {
852                     // normal alloc
853                     write!(fmt, " ({}, ", kind)?;
854                     write_allocation_track_relocs(
855                         &mut *fmt,
856                         self.mem.tcx,
857                         &mut allocs_to_print,
858                         alloc,
859                     )?;
860                 }
861                 None => {
862                     // global alloc
863                     match self.mem.tcx.get_global_alloc(id) {
864                         Some(GlobalAlloc::Memory(alloc)) => {
865                             write!(fmt, " (unchanged global, ")?;
866                             write_allocation_track_relocs(
867                                 &mut *fmt,
868                                 self.mem.tcx,
869                                 &mut allocs_to_print,
870                                 alloc,
871                             )?;
872                         }
873                         Some(GlobalAlloc::Function(func)) => {
874                             write!(fmt, " (fn: {})", func)?;
875                         }
876                         Some(GlobalAlloc::Static(did)) => {
877                             write!(fmt, " (static: {})", self.mem.tcx.def_path_str(did))?;
878                         }
879                         None => {
880                             write!(fmt, " (deallocated)")?;
881                         }
882                     }
883                 }
884             }
885             writeln!(fmt)?;
886         }
887         Ok(())
888     }
889 }
890
891 /// Reading and writing.
892 impl<'tcx, 'a, Tag: Provenance, Extra> AllocRefMut<'a, 'tcx, Tag, Extra> {
893     pub fn write_scalar(
894         &mut self,
895         range: AllocRange,
896         val: ScalarMaybeUninit<Tag>,
897     ) -> InterpResult<'tcx> {
898         Ok(self
899             .alloc
900             .write_scalar(&self.tcx, self.range.subrange(range), val)
901             .map_err(|e| e.to_interp_error(self.alloc_id))?)
902     }
903
904     pub fn write_ptr_sized(
905         &mut self,
906         offset: Size,
907         val: ScalarMaybeUninit<Tag>,
908     ) -> InterpResult<'tcx> {
909         self.write_scalar(alloc_range(offset, self.tcx.data_layout().pointer_size), val)
910     }
911 }
912
913 impl<'tcx, 'a, Tag: Provenance, Extra> AllocRef<'a, 'tcx, Tag, Extra> {
914     pub fn read_scalar(&self, range: AllocRange) -> InterpResult<'tcx, ScalarMaybeUninit<Tag>> {
915         Ok(self
916             .alloc
917             .read_scalar(&self.tcx, self.range.subrange(range))
918             .map_err(|e| e.to_interp_error(self.alloc_id))?)
919     }
920
921     pub fn read_ptr_sized(&self, offset: Size) -> InterpResult<'tcx, ScalarMaybeUninit<Tag>> {
922         self.read_scalar(alloc_range(offset, self.tcx.data_layout().pointer_size))
923     }
924
925     pub fn check_bytes(&self, range: AllocRange, allow_uninit_and_ptr: bool) -> InterpResult<'tcx> {
926         Ok(self
927             .alloc
928             .check_bytes(&self.tcx, self.range.subrange(range), allow_uninit_and_ptr)
929             .map_err(|e| e.to_interp_error(self.alloc_id))?)
930     }
931 }
932
933 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> {
934     /// Reads the given number of bytes from memory. Returns them as a slice.
935     ///
936     /// Performs appropriate bounds checks.
937     pub fn read_bytes(
938         &self,
939         ptr: Pointer<Option<M::PointerTag>>,
940         size: Size,
941     ) -> InterpResult<'tcx, &[u8]> {
942         let Some(alloc_ref) = self.get(ptr, size, Align::ONE)? else {
943             // zero-sized access
944             return Ok(&[]);
945         };
946         // Side-step AllocRef and directly access the underlying bytes more efficiently.
947         // (We are staying inside the bounds here so all is good.)
948         Ok(alloc_ref
949             .alloc
950             .get_bytes(&alloc_ref.tcx, alloc_ref.range)
951             .map_err(|e| e.to_interp_error(alloc_ref.alloc_id))?)
952     }
953
954     /// Writes the given stream of bytes into memory.
955     ///
956     /// Performs appropriate bounds checks.
957     pub fn write_bytes(
958         &mut self,
959         ptr: Pointer<Option<M::PointerTag>>,
960         src: impl IntoIterator<Item = u8>,
961     ) -> InterpResult<'tcx> {
962         let mut src = src.into_iter();
963         let (lower, upper) = src.size_hint();
964         let len = upper.expect("can only write bounded iterators");
965         assert_eq!(lower, len, "can only write iterators with a precise length");
966
967         let size = Size::from_bytes(len);
968         let Some(alloc_ref) = self.get_mut(ptr, size, Align::ONE)? else {
969             // zero-sized access
970             assert_matches!(
971                 src.next(),
972                 None,
973                 "iterator said it was empty but returned an element"
974             );
975             return Ok(());
976         };
977
978         // Side-step AllocRef and directly access the underlying bytes more efficiently.
979         // (We are staying inside the bounds here so all is good.)
980         let alloc_id = alloc_ref.alloc_id;
981         let bytes = alloc_ref
982             .alloc
983             .get_bytes_mut(&alloc_ref.tcx, alloc_ref.range)
984             .map_err(move |e| e.to_interp_error(alloc_id))?;
985         // `zip` would stop when the first iterator ends; we want to definitely
986         // cover all of `bytes`.
987         for dest in bytes {
988             *dest = src.next().expect("iterator was shorter than it said it would be");
989         }
990         assert_matches!(src.next(), None, "iterator was longer than it said it would be");
991         Ok(())
992     }
993
994     pub fn copy(
995         &mut self,
996         src: Pointer<Option<M::PointerTag>>,
997         src_align: Align,
998         dest: Pointer<Option<M::PointerTag>>,
999         dest_align: Align,
1000         size: Size,
1001         nonoverlapping: bool,
1002     ) -> InterpResult<'tcx> {
1003         self.copy_repeatedly(src, src_align, dest, dest_align, size, 1, nonoverlapping)
1004     }
1005
1006     pub fn copy_repeatedly(
1007         &mut self,
1008         src: Pointer<Option<M::PointerTag>>,
1009         src_align: Align,
1010         dest: Pointer<Option<M::PointerTag>>,
1011         dest_align: Align,
1012         size: Size,
1013         num_copies: u64,
1014         nonoverlapping: bool,
1015     ) -> InterpResult<'tcx> {
1016         let tcx = self.tcx;
1017         // We need to do our own bounds-checks.
1018         let src_parts = self.get_ptr_access(src, size, src_align)?;
1019         let dest_parts = self.get_ptr_access(dest, size * num_copies, dest_align)?; // `Size` multiplication
1020
1021         // FIXME: we look up both allocations twice here, once ebfore for the `check_ptr_access`
1022         // and once below to get the underlying `&[mut] Allocation`.
1023
1024         // Source alloc preparations and access hooks.
1025         let Some((src_alloc_id, src_offset, src)) = src_parts else {
1026             // Zero-sized *source*, that means dst is also zero-sized and we have nothing to do.
1027             return Ok(());
1028         };
1029         let src_alloc = self.get_raw(src_alloc_id)?;
1030         let src_range = alloc_range(src_offset, size);
1031         M::memory_read(&self.extra, &src_alloc.extra, src.provenance, src_range)?;
1032         // We need the `dest` ptr for the next operation, so we get it now.
1033         // We already did the source checks and called the hooks so we are good to return early.
1034         let Some((dest_alloc_id, dest_offset, dest)) = dest_parts else {
1035             // Zero-sized *destination*.
1036             return Ok(());
1037         };
1038
1039         // This checks relocation edges on the src, which needs to happen before
1040         // `prepare_relocation_copy`.
1041         let src_bytes = src_alloc
1042             .get_bytes_with_uninit_and_ptr(&tcx, src_range)
1043             .map_err(|e| e.to_interp_error(src_alloc_id))?
1044             .as_ptr(); // raw ptr, so we can also get a ptr to the destination allocation
1045         // first copy the relocations to a temporary buffer, because
1046         // `get_bytes_mut` will clear the relocations, which is correct,
1047         // since we don't want to keep any relocations at the target.
1048         let relocations =
1049             src_alloc.prepare_relocation_copy(self, src_range, dest_offset, num_copies);
1050         // Prepare a copy of the initialization mask.
1051         let compressed = src_alloc.compress_uninit_range(src_range);
1052
1053         // Destination alloc preparations and access hooks.
1054         let (dest_alloc, extra) = self.get_raw_mut(dest_alloc_id)?;
1055         let dest_range = alloc_range(dest_offset, size * num_copies);
1056         M::memory_written(extra, &mut dest_alloc.extra, dest.provenance, dest_range)?;
1057         let dest_bytes = dest_alloc
1058             .get_bytes_mut_ptr(&tcx, dest_range)
1059             .map_err(|e| e.to_interp_error(dest_alloc_id))?
1060             .as_mut_ptr();
1061
1062         if compressed.no_bytes_init() {
1063             // Fast path: If all bytes are `uninit` then there is nothing to copy. The target range
1064             // is marked as uninitialized but we otherwise omit changing the byte representation which may
1065             // be arbitrary for uninitialized bytes.
1066             // This also avoids writing to the target bytes so that the backing allocation is never
1067             // touched if the bytes stay uninitialized for the whole interpreter execution. On contemporary
1068             // operating system this can avoid physically allocating the page.
1069             dest_alloc.mark_init(dest_range, false); // `Size` multiplication
1070             dest_alloc.mark_relocation_range(relocations);
1071             return Ok(());
1072         }
1073
1074         // SAFE: The above indexing would have panicked if there weren't at least `size` bytes
1075         // behind `src` and `dest`. Also, we use the overlapping-safe `ptr::copy` if `src` and
1076         // `dest` could possibly overlap.
1077         // The pointers above remain valid even if the `HashMap` table is moved around because they
1078         // point into the `Vec` storing the bytes.
1079         unsafe {
1080             if src_alloc_id == dest_alloc_id {
1081                 if nonoverlapping {
1082                     // `Size` additions
1083                     if (src_offset <= dest_offset && src_offset + size > dest_offset)
1084                         || (dest_offset <= src_offset && dest_offset + size > src_offset)
1085                     {
1086                         throw_ub_format!("copy_nonoverlapping called on overlapping ranges")
1087                     }
1088                 }
1089
1090                 for i in 0..num_copies {
1091                     ptr::copy(
1092                         src_bytes,
1093                         dest_bytes.add((size * i).bytes_usize()), // `Size` multiplication
1094                         size.bytes_usize(),
1095                     );
1096                 }
1097             } else {
1098                 for i in 0..num_copies {
1099                     ptr::copy_nonoverlapping(
1100                         src_bytes,
1101                         dest_bytes.add((size * i).bytes_usize()), // `Size` multiplication
1102                         size.bytes_usize(),
1103                     );
1104                 }
1105             }
1106         }
1107
1108         // now fill in all the "init" data
1109         dest_alloc.mark_compressed_init_range(
1110             &compressed,
1111             alloc_range(dest_offset, size), // just a single copy (i.e., not full `dest_range`)
1112             num_copies,
1113         );
1114         // copy the relocations to the destination
1115         dest_alloc.mark_relocation_range(relocations);
1116
1117         Ok(())
1118     }
1119 }
1120
1121 /// Machine pointer introspection.
1122 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> {
1123     pub fn scalar_to_ptr(&self, scalar: Scalar<M::PointerTag>) -> Pointer<Option<M::PointerTag>> {
1124         // We use `to_bits_or_ptr_internal` since we are just implementing the method people need to
1125         // call to force getting out a pointer.
1126         match scalar.to_bits_or_ptr_internal(self.pointer_size()) {
1127             Err(ptr) => ptr.into(),
1128             Ok(bits) => {
1129                 let addr = u64::try_from(bits).unwrap();
1130                 let ptr = M::ptr_from_addr(&self, addr);
1131                 if addr == 0 {
1132                     assert!(ptr.provenance.is_none(), "null pointer can never have an AllocId");
1133                 }
1134                 ptr
1135             }
1136         }
1137     }
1138
1139     /// Turning a "maybe pointer" into a proper pointer (and some information
1140     /// about where it points), or an absolute address.
1141     pub fn ptr_try_get_alloc(
1142         &self,
1143         ptr: Pointer<Option<M::PointerTag>>,
1144     ) -> Result<(AllocId, Size, Pointer<M::PointerTag>), u64> {
1145         match ptr.into_pointer_or_addr() {
1146             Ok(ptr) => {
1147                 let (alloc_id, offset) = M::ptr_get_alloc(self, ptr);
1148                 Ok((alloc_id, offset, ptr))
1149             }
1150             Err(addr) => Err(addr.bytes()),
1151         }
1152     }
1153
1154     /// Turning a "maybe pointer" into a proper pointer (and some information about where it points).
1155     #[inline(always)]
1156     pub fn ptr_get_alloc(
1157         &self,
1158         ptr: Pointer<Option<M::PointerTag>>,
1159     ) -> InterpResult<'tcx, (AllocId, Size, Pointer<M::PointerTag>)> {
1160         self.ptr_try_get_alloc(ptr).map_err(|offset| {
1161             err_ub!(DanglingIntPointer(offset, CheckInAllocMsg::InboundsTest)).into()
1162         })
1163     }
1164 }