Skip to main content

rustc_const_eval/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
9use std::borrow::{Borrow, Cow};
10use std::cell::Cell;
11use std::collections::VecDeque;
12use std::{assert_matches, fmt, ptr};
13
14use rustc_abi::{Align, HasDataLayout, Size};
15use rustc_ast::Mutability;
16use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
17use rustc_middle::mir::display_allocation;
18use rustc_middle::ty::{self, Instance, Ty, TyCtxt};
19use rustc_span::bug;
20use tracing::{debug, instrument, trace};
21
22use super::{
23    AllocBytes, AllocId, AllocInit, AllocMap, AllocRange, Allocation, CheckAlignMsg,
24    CheckInAllocMsg, CtfeProvenance, GlobalAlloc, InterpCx, InterpResult, MPlaceTy, Machine,
25    MayLeak, Misalignment, Pointer, PointerArithmetic, Provenance, Scalar, alloc_range, err_ub,
26    err_ub_format, interp_ok, throw_ub, throw_ub_format, throw_unsup, throw_unsup_format,
27};
28use crate::const_eval::ConstEvalErrKind;
29
30#[derive(#[automatically_derived]
impl<T: ::core::fmt::Debug> ::core::fmt::Debug for MemoryKind<T> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            MemoryKind::Stack =>
                ::core::fmt::Formatter::write_str(f, "Stack"),
            MemoryKind::CallerLocation =>
                ::core::fmt::Formatter::write_str(f, "CallerLocation"),
            MemoryKind::Machine(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Machine", &__self_0),
        }
    }
}Debug, #[automatically_derived]
impl<T: ::core::cmp::PartialEq> ::core::marker::StructuralPartialEq for
    MemoryKind<T> {
}
#[automatically_derived]
impl<T: ::core::cmp::PartialEq> ::core::cmp::PartialEq for MemoryKind<T> {
    #[inline]
    fn eq(&self, other: &MemoryKind<T>) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (MemoryKind::Machine(__self_0), MemoryKind::Machine(__arg1_0))
                    => __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq, #[automatically_derived]
impl<T: ::core::marker::Copy> ::core::marker::Copy for MemoryKind<T> { }Copy, #[automatically_derived]
impl<T: ::core::clone::Clone> ::core::clone::Clone for MemoryKind<T> {
    #[inline]
    fn clone(&self) -> MemoryKind<T> {
        match self {
            MemoryKind::Stack => MemoryKind::Stack,
            MemoryKind::CallerLocation => MemoryKind::CallerLocation,
            MemoryKind::Machine(__self_0) =>
                MemoryKind::Machine(::core::clone::Clone::clone(__self_0)),
        }
    }
}Clone)]
31pub enum MemoryKind<T> {
32    /// Stack memory. Error if deallocated except during a stack pop.
33    Stack,
34    /// Memory allocated by `caller_location` intrinsic. Error if ever deallocated.
35    CallerLocation,
36    /// Additional memory kinds a machine wishes to distinguish from the builtin ones.
37    Machine(T),
38}
39
40impl<T: MayLeak> MayLeak for MemoryKind<T> {
41    #[inline]
42    fn may_leak(self) -> bool {
43        match self {
44            MemoryKind::Stack => false,
45            MemoryKind::CallerLocation => true,
46            MemoryKind::Machine(k) => k.may_leak(),
47        }
48    }
49}
50
51impl<T: fmt::Display> fmt::Display for MemoryKind<T> {
52    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
53        match self {
54            MemoryKind::Stack => f.write_fmt(format_args!("stack variable"))write!(f, "stack variable"),
55            MemoryKind::CallerLocation => f.write_fmt(format_args!("caller location"))write!(f, "caller location"),
56            MemoryKind::Machine(m) => f.write_fmt(format_args!("{0}", m))write!(f, "{m}"),
57        }
58    }
59}
60
61/// The return value of `get_alloc_info` indicates the "kind" of the allocation.
62#[derive(#[automatically_derived]
impl ::core::marker::Copy for AllocKind { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for AllocKind { }
#[automatically_derived]
impl ::core::clone::Clone for AllocKind {
    #[inline]
    fn clone(&self) -> AllocKind { *self }
}Clone, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for AllocKind { }
#[automatically_derived]
impl ::core::cmp::PartialEq for AllocKind {
    #[inline]
    fn eq(&self, other: &AllocKind) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::fmt::Debug for AllocKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                AllocKind::LiveData => "LiveData",
                AllocKind::Function => "Function",
                AllocKind::VaList => "VaList",
                AllocKind::VTable => "VTable",
                AllocKind::TypeId => "TypeId",
                AllocKind::Dead => "Dead",
            })
    }
}Debug)]
63pub enum AllocKind {
64    /// A regular live data allocation.
65    LiveData,
66    /// A function allocation (that fn ptrs point to).
67    Function,
68    /// A variable argument list allocation (used by c-variadic functions).
69    VaList,
70    /// A vtable allocation.
71    VTable,
72    /// A TypeId allocation.
73    TypeId,
74    /// A dead allocation.
75    Dead,
76}
77
78/// Metadata about an `AllocId`.
79#[derive(#[automatically_derived]
impl ::core::marker::Copy for AllocInfo { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for AllocInfo { }
#[automatically_derived]
impl ::core::clone::Clone for AllocInfo {
    #[inline]
    fn clone(&self) -> AllocInfo {
        let _: ::core::clone::AssertParamIsClone<Size>;
        let _: ::core::clone::AssertParamIsClone<Align>;
        let _: ::core::clone::AssertParamIsClone<AllocKind>;
        let _: ::core::clone::AssertParamIsClone<Mutability>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for AllocInfo { }
#[automatically_derived]
impl ::core::cmp::PartialEq for AllocInfo {
    #[inline]
    fn eq(&self, other: &AllocInfo) -> bool {
        self.size == other.size && self.align == other.align &&
                self.kind == other.kind && self.mutbl == other.mutbl
    }
}PartialEq, #[automatically_derived]
impl ::core::fmt::Debug for AllocInfo {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field4_finish(f, "AllocInfo",
            "size", &self.size, "align", &self.align, "kind", &self.kind,
            "mutbl", &&self.mutbl)
    }
}Debug)]
80pub struct AllocInfo {
81    pub size: Size,
82    pub align: Align,
83    pub kind: AllocKind,
84    pub mutbl: Mutability,
85}
86
87impl AllocInfo {
88    fn new(size: Size, align: Align, kind: AllocKind, mutbl: Mutability) -> Self {
89        Self { size, align, kind, mutbl }
90    }
91}
92
93/// The value of a function pointer.
94#[derive(#[automatically_derived]
impl<'tcx, Other: ::core::fmt::Debug> ::core::fmt::Debug for
    FnVal<'tcx, Other> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            FnVal::Instance(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Instance", &__self_0),
            FnVal::Other(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Other",
                    &__self_0),
        }
    }
}Debug, #[automatically_derived]
impl<'tcx, Other: ::core::marker::Copy> ::core::marker::Copy for
    FnVal<'tcx, Other> {
}Copy, #[automatically_derived]
impl<'tcx, Other: ::core::clone::Clone> ::core::clone::Clone for
    FnVal<'tcx, Other> {
    #[inline]
    fn clone(&self) -> FnVal<'tcx, Other> {
        match self {
            FnVal::Instance(__self_0) =>
                FnVal::Instance(::core::clone::Clone::clone(__self_0)),
            FnVal::Other(__self_0) =>
                FnVal::Other(::core::clone::Clone::clone(__self_0)),
        }
    }
}Clone)]
95pub enum FnVal<'tcx, Other> {
96    Instance(Instance<'tcx>),
97    Other(Other),
98}
99
100impl<'tcx, Other> FnVal<'tcx, Other> {
101    pub fn as_instance(self) -> InterpResult<'tcx, Instance<'tcx>> {
102        match self {
103            FnVal::Instance(instance) => interp_ok(instance),
104            FnVal::Other(_) => {
105                do yeet ::rustc_middle::mir::interpret::InterpErrorKind::Unsupported(::rustc_middle::mir::interpret::UnsupportedOpInfo::Unsupported(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("\'foreign\' function pointers are not supported in this context"))
                })))throw_unsup_format!("'foreign' function pointers are not supported in this context")
106            }
107        }
108    }
109}
110
111// `Memory` has to depend on the `Machine` because some of its operations
112// (e.g., `get`) call a `Machine` hook.
113pub struct Memory<'tcx, M: Machine<'tcx>> {
114    /// Allocations local to this instance of the interpreter. The kind
115    /// helps ensure that the same mechanism is used for allocation and
116    /// deallocation. When an allocation is not found here, it is a
117    /// global and looked up in the `tcx` for read access. Some machines may
118    /// have to mutate this map even on a read-only access to a global (because
119    /// they do pointer provenance tracking and the allocations in `tcx` have
120    /// the wrong type), so we let the machine override this type.
121    /// Either way, if the machine allows writing to a global, doing so will
122    /// create a copy of the global allocation here.
123    // FIXME: this should not be public, but interning currently needs access to it
124    pub(super) alloc_map: M::MemoryMap,
125
126    /// Map for "extra" function pointers.
127    extra_fn_ptr_map: FxIndexMap<AllocId, M::ExtraFnVal>,
128
129    /// Map storing variable argument lists.
130    va_list_map: FxIndexMap<AllocId, VecDeque<MPlaceTy<'tcx, M::Provenance>>>,
131
132    /// To be able to compare pointers with null, and to check alignment for accesses
133    /// to ZSTs (where pointers may dangle), we keep track of the size even for allocations
134    /// that do not exist any more.
135    // FIXME: this should not be public, but interning currently needs access to it
136    pub(super) dead_alloc_map: FxIndexMap<AllocId, (Size, Align)>,
137
138    /// This stores whether we are currently doing reads/writes that aren't "real".
139    /// Those accesses do not trigger the machine's hooks.
140    /// Needless to say, this must only be set with great care!
141    ghost_mode: Cell<bool>,
142}
143
144/// A reference to some allocation that was already bounds-checked for the given region
145/// and had the on-access machine hooks run.
146#[derive(#[automatically_derived]
impl<'a, 'tcx, Prov: ::core::marker::Copy + Provenance,
    Extra: ::core::marker::Copy, Bytes: ::core::marker::Copy + AllocBytes>
    ::core::marker::Copy for AllocRef<'a, 'tcx, Prov, Extra, Bytes> {
}Copy, #[automatically_derived]
impl<'a, 'tcx, Prov: ::core::clone::Clone + Provenance,
    Extra: ::core::clone::Clone, Bytes: ::core::clone::Clone + AllocBytes>
    ::core::clone::Clone for AllocRef<'a, 'tcx, Prov, Extra, Bytes> {
    #[inline]
    fn clone(&self) -> AllocRef<'a, 'tcx, Prov, Extra, Bytes> {
        AllocRef {
            alloc: ::core::clone::Clone::clone(&self.alloc),
            range: ::core::clone::Clone::clone(&self.range),
            tcx: ::core::clone::Clone::clone(&self.tcx),
            alloc_id: ::core::clone::Clone::clone(&self.alloc_id),
        }
    }
}Clone)]
147pub struct AllocRef<'a, 'tcx, Prov: Provenance, Extra, Bytes: AllocBytes = Box<[u8]>> {
148    alloc: &'a Allocation<Prov, Extra, Bytes>,
149    range: AllocRange,
150    tcx: TyCtxt<'tcx>,
151    alloc_id: AllocId,
152}
153/// A reference to some allocation that was already bounds-checked for the given region
154/// and had the on-access machine hooks run.
155pub struct AllocRefMut<'a, 'tcx, Prov: Provenance, Extra, Bytes: AllocBytes = Box<[u8]>> {
156    alloc: &'a mut Allocation<Prov, Extra, Bytes>,
157    range: AllocRange,
158    tcx: TyCtxt<'tcx>,
159    alloc_id: AllocId,
160}
161
162impl<'tcx, M: Machine<'tcx>> Memory<'tcx, M> {
163    pub fn new() -> Self {
164        Memory {
165            alloc_map: M::MemoryMap::default(),
166            extra_fn_ptr_map: FxIndexMap::default(),
167            va_list_map: FxIndexMap::default(),
168            dead_alloc_map: FxIndexMap::default(),
169            ghost_mode: Cell::new(false),
170        }
171    }
172
173    /// This is used by [priroda](https://github.com/oli-obk/priroda)
174    pub fn alloc_map(&self) -> &M::MemoryMap {
175        &self.alloc_map
176    }
177}
178
179impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
180    /// Call this to turn untagged "global" pointers (obtained via `tcx`) into
181    /// the machine pointer to the allocation. Must never be used
182    /// for any other pointers, nor for TLS statics.
183    ///
184    /// Using the resulting pointer represents a *direct* access to that memory
185    /// (e.g. by directly using a `static`),
186    /// as opposed to access through a pointer that was created by the program.
187    ///
188    /// This function can fail only if `ptr` points to an `extern static`.
189    #[inline]
190    pub fn global_root_pointer(
191        &self,
192        ptr: Pointer<CtfeProvenance>,
193    ) -> InterpResult<'tcx, Pointer<M::Provenance>> {
194        let alloc_id = ptr.provenance.alloc_id();
195        // We need to handle `extern static`.
196        match self.tcx.try_get_global_alloc(alloc_id) {
197            Some(GlobalAlloc::Static(def_id)) if self.tcx.is_thread_local_static(def_id) => {
198                // Thread-local statics do not have a constant address. They *must* be accessed via
199                // `ThreadLocalRef`; we can never have a pointer to them as a regular constant value.
200                bug_impl(None,
    format_args!("global memory cannot point to thread-local static"),
    Location::caller())bug!("global memory cannot point to thread-local static")
201            }
202            Some(GlobalAlloc::Static(def_id)) if self.tcx.is_foreign_item(def_id) => {
203                return M::extern_static_pointer(self, def_id);
204            }
205            None => {
206                let is_fn_ptr = self.memory.extra_fn_ptr_map.contains_key(&alloc_id);
207                let is_va_list = self.memory.va_list_map.contains_key(&alloc_id);
208                if !(is_fn_ptr || is_va_list) {
    {
        ::core::panicking::panic_fmt(format_args!("{0:?} is neither global, va_list nor a function pointer",
                alloc_id));
    }
};assert!(
209                    is_fn_ptr || is_va_list,
210                    "{alloc_id:?} is neither global, va_list nor a function pointer"
211                );
212            }
213            _ => {}
214        }
215        // And we need to get the provenance.
216        M::adjust_alloc_root_pointer(self, ptr, M::GLOBAL_KIND.map(MemoryKind::Machine))
217    }
218
219    pub fn fn_ptr(&mut self, fn_val: FnVal<'tcx, M::ExtraFnVal>) -> Pointer<M::Provenance> {
220        let id = match fn_val {
221            FnVal::Instance(instance) => {
222                let salt = M::get_global_alloc_salt(self, Some(instance));
223                self.tcx.reserve_and_set_fn_alloc(instance, salt)
224            }
225            FnVal::Other(extra) => {
226                // FIXME(RalfJung): Should we have a cache here?
227                let id = self.tcx.reserve_alloc_id();
228                let old = self.memory.extra_fn_ptr_map.insert(id, extra);
229                if !old.is_none() {
    ::core::panicking::panic("assertion failed: old.is_none()")
};assert!(old.is_none());
230                id
231            }
232        };
233        // Functions are global allocations, so make sure we get the right root pointer.
234        // We know this is not an `extern static` so this cannot fail.
235        self.global_root_pointer(Pointer::from(id)).unwrap()
236    }
237
238    /// Insert a new variable argument list in the global map of variable argument lists.
239    pub fn va_list_ptr(
240        &mut self,
241        varargs: VecDeque<MPlaceTy<'tcx, M::Provenance>>,
242    ) -> Pointer<M::Provenance> {
243        let id = self.tcx.reserve_alloc_id();
244        let old = self.memory.va_list_map.insert(id, varargs);
245        if !old.is_none() {
    ::core::panicking::panic("assertion failed: old.is_none()")
};assert!(old.is_none());
246        // Variable argument lists are global allocations, so make sure we get the right root
247        // pointer. We know this is not an `extern static` so this cannot fail.
248        self.global_root_pointer(Pointer::from(id)).unwrap()
249    }
250
251    pub fn allocate_ptr(
252        &mut self,
253        size: Size,
254        align: Align,
255        kind: MemoryKind<M::MemoryKind>,
256        init: AllocInit,
257    ) -> InterpResult<'tcx, Pointer<M::Provenance>> {
258        let params = self.machine.get_default_alloc_params();
259        let alloc = if M::PANIC_ON_ALLOC_FAIL {
260            Allocation::new(size, align, init, params)
261        } else {
262            Allocation::try_new(size, align, init, params)?
263        };
264        self.insert_allocation(alloc, kind)
265    }
266
267    pub fn allocate_bytes_ptr(
268        &mut self,
269        bytes: &[u8],
270        align: Align,
271        kind: MemoryKind<M::MemoryKind>,
272        mutability: Mutability,
273    ) -> InterpResult<'tcx, Pointer<M::Provenance>> {
274        let params = self.machine.get_default_alloc_params();
275        let alloc = Allocation::from_bytes(bytes, align, mutability, params);
276        self.insert_allocation(alloc, kind)
277    }
278
279    pub fn insert_allocation(
280        &mut self,
281        alloc: Allocation<M::Provenance, (), M::Bytes>,
282        kind: MemoryKind<M::MemoryKind>,
283    ) -> InterpResult<'tcx, Pointer<M::Provenance>> {
284        if !(alloc.size() <= self.max_size_of_val()) {
    ::core::panicking::panic("assertion failed: alloc.size() <= self.max_size_of_val()")
};assert!(alloc.size() <= self.max_size_of_val());
285        let id = self.tcx.reserve_alloc_id();
286        if true {
    {
        match (&(Some(kind)), &(M::GLOBAL_KIND.map(MemoryKind::Machine))) {
            (left_val, right_val) => {
                if *left_val == *right_val {
                    let kind = ::core::panicking::AssertKind::Ne;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val,
                        ::core::option::Option::Some(format_args!("dynamically allocating global memory")));
                }
            }
        }
    };
};debug_assert_ne!(
287            Some(kind),
288            M::GLOBAL_KIND.map(MemoryKind::Machine),
289            "dynamically allocating global memory"
290        );
291        // This cannot be merged with the `adjust_global_allocation` code path
292        // since here we have an allocation that already uses `M::Bytes`.
293        let extra = M::init_local_allocation(self, id, kind, alloc.size(), alloc.align)?;
294        let alloc = alloc.with_extra(extra);
295        self.memory.alloc_map.insert(id, (kind, alloc));
296        M::adjust_alloc_root_pointer(self, Pointer::from(id), Some(kind))
297    }
298
299    /// If this grows the allocation, `init_growth` determines
300    /// whether the additional space will be initialized.
301    pub fn reallocate_ptr(
302        &mut self,
303        ptr: Pointer<Option<M::Provenance>>,
304        old_size_and_align: Option<(Size, Align)>,
305        new_size: Size,
306        new_align: Align,
307        kind: MemoryKind<M::MemoryKind>,
308        init_growth: AllocInit,
309    ) -> InterpResult<'tcx, Pointer<M::Provenance>> {
310        let (alloc_id, offset, _prov) = self.ptr_get_alloc_id(ptr, 0)?;
311        if offset.bytes() != 0 {
312            do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Ub(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("reallocating {0} which does not point to the beginning of an object",
                            ptr))
                })));throw_ub_format!(
313                "reallocating {ptr} which does not point to the beginning of an object"
314            );
315        }
316
317        // For simplicities' sake, we implement reallocate as "alloc, copy, dealloc".
318        // This happens so rarely, the perf advantage is outweighed by the maintenance cost.
319        // If requested, we zero-init the entire allocation, to ensure that a growing
320        // allocation has its new bytes properly set. For the part that is copied,
321        // `mem_copy` below will de-initialize things as necessary.
322        let new_ptr = self.allocate_ptr(new_size, new_align, kind, init_growth)?;
323        let old_size = match old_size_and_align {
324            Some((size, _align)) => size,
325            None => self.get_alloc_raw(alloc_id)?.size(),
326        };
327        // This will also call the access hooks.
328        self.mem_copy(ptr, new_ptr.into(), old_size.min(new_size), /*nonoverlapping*/ true)?;
329        self.deallocate_ptr(ptr, old_size_and_align, kind)?;
330
331        interp_ok(new_ptr)
332    }
333
334    /// Mark the `const_allocate`d allocation `ptr` points to as immutable so we can intern it.
335    pub fn make_const_heap_ptr_global(
336        &mut self,
337        ptr: Pointer<Option<CtfeProvenance>>,
338    ) -> InterpResult<'tcx>
339    where
340        M: Machine<'tcx, MemoryKind = crate::const_eval::MemoryKind, Provenance = CtfeProvenance>,
341    {
342        let (alloc_id, offset, _) = self.ptr_get_alloc_id(ptr, 0)?;
343        if offset.bytes() != 0 {
344            return Err(ConstEvalErrKind::ConstMakeGlobalWithOffset(ptr)).into();
345        }
346
347        if self.tcx.try_get_global_alloc(alloc_id).is_some() {
348            // This points to something outside the current interpreter.
349            return Err(ConstEvalErrKind::ConstMakeGlobalPtrIsNonHeap(ptr)).into();
350        }
351
352        // If we can't find it in `alloc_map` it must be dangling (because we don't use
353        // `extra_fn_ptr_map` in const-eval).
354        let (kind, alloc) = self
355            .memory
356            .alloc_map
357            .get_mut_or(alloc_id, || Err(ConstEvalErrKind::ConstMakeGlobalWithDanglingPtr(ptr)))?;
358
359        // Ensure this is actually a *heap* allocation, and record it as made-global.
360        match kind {
361            MemoryKind::Stack | MemoryKind::CallerLocation => {
362                return Err(ConstEvalErrKind::ConstMakeGlobalPtrIsNonHeap(ptr)).into();
363            }
364            MemoryKind::Machine(crate::const_eval::MemoryKind::Heap { was_made_global }) => {
365                if *was_made_global {
366                    return Err(ConstEvalErrKind::ConstMakeGlobalPtrAlreadyMadeGlobal(alloc_id))
367                        .into();
368                }
369                *was_made_global = true;
370            }
371        }
372
373        // Prevent further mutation, this is now an immutable global.
374        alloc.mutability = Mutability::Not;
375
376        interp_ok(())
377    }
378
379    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("deallocate_ptr",
                                    "rustc_const_eval::interpret::memory",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_const_eval/src/interpret/memory.rs"),
                                    ::tracing_core::__macro_support::Option::Some(379u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::memory"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("ptr")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("ptr");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("old_size_and_align")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("old_size_and_align");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("kind")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("kind");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ptr)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&old_size_and_align)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&kind)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: InterpResult<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let (alloc_id, offset, prov) = self.ptr_get_alloc_id(ptr, 0)?;
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_const_eval/src/interpret/memory.rs:387",
                                    "rustc_const_eval::interpret::memory",
                                    ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_const_eval/src/interpret/memory.rs"),
                                    ::tracing_core::__macro_support::Option::Some(387u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::memory"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::TRACE <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::TRACE <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("deallocating: {0}",
                                                                alloc_id) as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            if offset.bytes() != 0 {
                do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Ub(::alloc::__export::must_use({
                                    ::alloc::fmt::format(format_args!("deallocating {0} which does not point to the beginning of an object",
                                            ptr))
                                })));
            }
            let Some((alloc_kind, mut alloc)) =
                self.memory.alloc_map.remove(&alloc_id) else {
                    return Err(match self.tcx.try_get_global_alloc(alloc_id) {
                                    Some(GlobalAlloc::Function { .. }) => {
                                        ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Ub(::alloc::__export::must_use({
                                                        ::alloc::fmt::format(format_args!("deallocating {0}, which is a function",
                                                                alloc_id))
                                                    })))
                                    }
                                    Some(GlobalAlloc::VTable(..)) => {
                                        ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Ub(::alloc::__export::must_use({
                                                        ::alloc::fmt::format(format_args!("deallocating {0}, which is a vtable",
                                                                alloc_id))
                                                    })))
                                    }
                                    Some(GlobalAlloc::TypeId { .. }) => {
                                        ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Ub(::alloc::__export::must_use({
                                                        ::alloc::fmt::format(format_args!("deallocating {0}, which is a type id",
                                                                alloc_id))
                                                    })))
                                    }
                                    Some(GlobalAlloc::Static(..) | GlobalAlloc::Memory(..)) => {
                                        ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Ub(::alloc::__export::must_use({
                                                        ::alloc::fmt::format(format_args!("deallocating {0}, which is static memory",
                                                                alloc_id))
                                                    })))
                                    }
                                    None =>
                                        ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::PointerUseAfterFree(alloc_id,
                                                CheckInAllocMsg::MemoryAccess)),
                                }).into();
                };
            if alloc.mutability.is_not() {
                do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Ub(::alloc::__export::must_use({
                                    ::alloc::fmt::format(format_args!("deallocating immutable allocation {0}",
                                            alloc_id))
                                })));
            }
            if alloc_kind != kind {
                do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Ub(::alloc::__export::must_use({
                                    ::alloc::fmt::format(format_args!("deallocating {0}, which is {1} memory, using {2} deallocation operation",
                                            alloc_id, alloc_kind, kind))
                                })));
            }
            if let Some((size, align)) = old_size_and_align {
                if size != alloc.size() || align != alloc.align {
                    do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Ub(::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("incorrect layout on deallocation: {4} has size {0} and alignment {1}, but gave size {2} and alignment {3}",
                                                alloc.size().bytes(), alloc.align.bytes(), size.bytes(),
                                                align.bytes(), alloc_id))
                                    })))
                }
            }
            let size = alloc.size();
            M::before_memory_deallocation(self.tcx, &mut self.machine,
                    &mut alloc.extra, ptr, (alloc_id, prov), size, alloc.align,
                    kind)?;
            let old =
                self.memory.dead_alloc_map.insert(alloc_id,
                    (size, alloc.align));
            if old.is_some() {
                bug_impl(None,
                    format_args!("Nothing can be deallocated twice"),
                    Location::caller());
            }
            interp_ok(())
        }
    }
}#[instrument(skip(self), level = "debug")]
380    pub fn deallocate_ptr(
381        &mut self,
382        ptr: Pointer<Option<M::Provenance>>,
383        old_size_and_align: Option<(Size, Align)>,
384        kind: MemoryKind<M::MemoryKind>,
385    ) -> InterpResult<'tcx> {
386        let (alloc_id, offset, prov) = self.ptr_get_alloc_id(ptr, 0)?;
387        trace!("deallocating: {alloc_id}");
388
389        if offset.bytes() != 0 {
390            throw_ub_format!(
391                "deallocating {ptr} which does not point to the beginning of an object"
392            );
393        }
394
395        let Some((alloc_kind, mut alloc)) = self.memory.alloc_map.remove(&alloc_id) else {
396            // Deallocating global memory -- always an error
397            return Err(match self.tcx.try_get_global_alloc(alloc_id) {
398                Some(GlobalAlloc::Function { .. }) => {
399                    err_ub_format!("deallocating {alloc_id}, which is a function")
400                }
401                Some(GlobalAlloc::VTable(..)) => {
402                    err_ub_format!("deallocating {alloc_id}, which is a vtable")
403                }
404                Some(GlobalAlloc::TypeId { .. }) => {
405                    err_ub_format!("deallocating {alloc_id}, which is a type id")
406                }
407                Some(GlobalAlloc::Static(..) | GlobalAlloc::Memory(..)) => {
408                    err_ub_format!("deallocating {alloc_id}, which is static memory")
409                }
410                None => err_ub!(PointerUseAfterFree(alloc_id, CheckInAllocMsg::MemoryAccess)),
411            })
412            .into();
413        };
414
415        if alloc.mutability.is_not() {
416            throw_ub_format!("deallocating immutable allocation {alloc_id}");
417        }
418        if alloc_kind != kind {
419            throw_ub_format!(
420                "deallocating {alloc_id}, which is {alloc_kind} memory, using {kind} deallocation operation",
421            );
422        }
423        if let Some((size, align)) = old_size_and_align {
424            if size != alloc.size() || align != alloc.align {
425                throw_ub_format!(
426                    "incorrect layout on deallocation: {alloc_id} has size {size} and alignment {align}, but gave size {size_found} and alignment {align_found}",
427                    size = alloc.size().bytes(),
428                    align = alloc.align.bytes(),
429                    size_found = size.bytes(),
430                    align_found = align.bytes(),
431                )
432            }
433        }
434
435        // Let the machine take some extra action
436        let size = alloc.size();
437        M::before_memory_deallocation(
438            self.tcx,
439            &mut self.machine,
440            &mut alloc.extra,
441            ptr,
442            (alloc_id, prov),
443            size,
444            alloc.align,
445            kind,
446        )?;
447
448        // Don't forget to remember size and align of this now-dead allocation
449        let old = self.memory.dead_alloc_map.insert(alloc_id, (size, alloc.align));
450        if old.is_some() {
451            bug!("Nothing can be deallocated twice");
452        }
453
454        interp_ok(())
455    }
456
457    /// Internal helper function to determine the allocation and offset of a pointer (if any).
458    #[inline(always)]
459    fn get_ptr_access(
460        &self,
461        ptr: Pointer<Option<M::Provenance>>,
462        size: Size,
463    ) -> InterpResult<'tcx, Option<(AllocId, Size, M::ProvenanceExtra)>> {
464        let size = i64::try_from(size.bytes()).unwrap(); // it would be an error to even ask for more than isize::MAX bytes
465        Self::check_and_deref_ptr(
466            self,
467            ptr,
468            size,
469            CheckInAllocMsg::MemoryAccess,
470            |this, alloc_id, offset, prov| {
471                let (size, align) =
472                    this.get_live_alloc_size_and_align(alloc_id, CheckInAllocMsg::MemoryAccess)?;
473                interp_ok((size, align, (alloc_id, offset, prov)))
474            },
475        )
476    }
477
478    /// Check if the given pointer points to live memory of the given `size`.
479    /// The caller can control the error message for the out-of-bounds case.
480    #[inline(always)]
481    pub fn check_ptr_access(
482        &self,
483        ptr: Pointer<Option<M::Provenance>>,
484        size: Size,
485        msg: CheckInAllocMsg,
486    ) -> InterpResult<'tcx> {
487        let size = i64::try_from(size.bytes()).unwrap(); // it would be an error to even ask for more than isize::MAX bytes
488        Self::check_and_deref_ptr(self, ptr, size, msg, |this, alloc_id, _, _| {
489            let (size, align) = this.get_live_alloc_size_and_align(alloc_id, msg)?;
490            interp_ok((size, align, ()))
491        })?;
492        interp_ok(())
493    }
494
495    /// Check whether the given pointer points to live memory for a signed amount of bytes.
496    /// A negative amounts means that the given range of memory to the left of the pointer
497    /// needs to be dereferenceable.
498    pub fn check_ptr_access_signed(
499        &self,
500        ptr: Pointer<Option<M::Provenance>>,
501        size: i64,
502        msg: CheckInAllocMsg,
503    ) -> InterpResult<'tcx> {
504        Self::check_and_deref_ptr(self, ptr, size, msg, |this, alloc_id, _, _| {
505            let (size, align) = this.get_live_alloc_size_and_align(alloc_id, msg)?;
506            interp_ok((size, align, ()))
507        })?;
508        interp_ok(())
509    }
510
511    /// Low-level helper function to check if a ptr is in-bounds and potentially return a reference
512    /// to the allocation it points to. Supports both shared and mutable references, as the actual
513    /// checking is offloaded to a helper closure. Supports signed sizes for checks "to the left" of
514    /// a pointer.
515    ///
516    /// `alloc_size` will only get called for non-zero-sized accesses.
517    ///
518    /// Returns `None` if and only if the size is 0.
519    fn check_and_deref_ptr<T, R: Borrow<Self>>(
520        this: R,
521        ptr: Pointer<Option<M::Provenance>>,
522        size: i64,
523        msg: CheckInAllocMsg,
524        alloc_size: impl FnOnce(
525            R,
526            AllocId,
527            Size,
528            M::ProvenanceExtra,
529        ) -> InterpResult<'tcx, (Size, Align, T)>,
530    ) -> InterpResult<'tcx, Option<T>> {
531        // Everything is okay with size 0.
532        if size == 0 {
533            return interp_ok(None);
534        }
535
536        interp_ok(match this.borrow().ptr_try_get_alloc_id(ptr, size) {
537            Err(addr) => {
538                // We couldn't get a proper allocation.
539                do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::DanglingIntPointer {
            addr,
            inbounds_size: size,
            msg,
        });throw_ub!(DanglingIntPointer { addr, inbounds_size: size, msg });
540            }
541            Ok((alloc_id, offset, prov)) => {
542                let tcx = this.borrow().tcx;
543                let (alloc_size, _alloc_align, ret_val) = alloc_size(this, alloc_id, offset, prov)?;
544                let offset = offset.bytes();
545                // Compute absolute begin and end of the range.
546                let (begin, end) = if size >= 0 {
547                    (Some(offset), offset.checked_add(size as u64))
548                } else {
549                    (offset.checked_sub(size.unsigned_abs()), Some(offset))
550                };
551                // Ensure both are within bounds.
552                let in_bounds = begin.is_some() && end.is_some_and(|e| e <= alloc_size.bytes());
553                if !in_bounds {
554                    do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::PointerOutOfBounds {
            alloc_id,
            alloc_size,
            ptr_offset: tcx.sign_extend_to_target_isize(offset),
            inbounds_size: size,
            msg,
        })throw_ub!(PointerOutOfBounds {
555                        alloc_id,
556                        alloc_size,
557                        ptr_offset: tcx.sign_extend_to_target_isize(offset),
558                        inbounds_size: size,
559                        msg,
560                    })
561                }
562
563                Some(ret_val)
564            }
565        })
566    }
567
568    pub(super) fn check_misalign(
569        &self,
570        misaligned: Option<Misalignment>,
571        msg: CheckAlignMsg,
572    ) -> InterpResult<'tcx> {
573        if let Some(misaligned) = misaligned {
574            do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::AlignmentCheckFailed(misaligned,
            msg))throw_ub!(AlignmentCheckFailed(misaligned, msg))
575        }
576        interp_ok(())
577    }
578
579    pub(super) fn is_ptr_misaligned(
580        &self,
581        ptr: Pointer<Option<M::Provenance>>,
582        align: Align,
583    ) -> Option<Misalignment> {
584        if !M::enforce_alignment(self) || align.bytes() == 1 {
585            return None;
586        }
587
588        #[inline]
589        fn is_offset_misaligned(offset: u64, align: Align) -> Option<Misalignment> {
590            if offset.is_multiple_of(align.bytes()) {
591                None
592            } else {
593                // The biggest power of two through which `offset` is divisible.
594                let offset_pow2 = 1 << offset.trailing_zeros();
595                Some(Misalignment { has: Align::from_bytes(offset_pow2).unwrap(), required: align })
596            }
597        }
598
599        match self.ptr_try_get_alloc_id(ptr, 0) {
600            Err(addr) => is_offset_misaligned(addr, align),
601            Ok((alloc_id, offset, _prov)) => {
602                let alloc_info = self.get_alloc_info(alloc_id);
603                if let Some(misalign) = M::alignment_check(
604                    self,
605                    alloc_id,
606                    alloc_info.align,
607                    alloc_info.kind,
608                    offset,
609                    align,
610                ) {
611                    Some(misalign)
612                } else if M::Provenance::OFFSET_IS_ADDR {
613                    is_offset_misaligned(ptr.addr().bytes(), align)
614                } else {
615                    // Check allocation alignment and offset alignment.
616                    if alloc_info.align.bytes() < align.bytes() {
617                        Some(Misalignment { has: alloc_info.align, required: align })
618                    } else {
619                        is_offset_misaligned(offset.bytes(), align)
620                    }
621                }
622            }
623        }
624    }
625
626    /// Checks a pointer for misalignment.
627    ///
628    /// The error assumes this is checking the pointer used directly for an access.
629    pub fn check_ptr_align(
630        &self,
631        ptr: Pointer<Option<M::Provenance>>,
632        align: Align,
633    ) -> InterpResult<'tcx> {
634        self.check_misalign(self.is_ptr_misaligned(ptr, align), CheckAlignMsg::AccessedPtr)
635    }
636}
637
638impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
639    /// This function is used by Miri's provenance GC to remove unreachable entries from the dead_alloc_map.
640    pub fn remove_unreachable_allocs(&mut self, reachable_allocs: &FxHashSet<AllocId>) {
641        // Unlike all the other GC helpers where we check if an `AllocId` is found in the interpreter or
642        // is live, here all the IDs in the map are for dead allocations so we don't
643        // need to check for liveness.
644        self.memory.dead_alloc_map.retain(|id, _| reachable_allocs.contains(id));
645    }
646}
647
648/// Allocation accessors
649impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
650    /// Helper function to obtain a global (tcx) allocation.
651    /// This attempts to return a reference to an existing allocation if
652    /// one can be found in `tcx`. That, however, is only possible if `tcx` and
653    /// this machine use the same pointer provenance, so it is indirected through
654    /// `M::adjust_allocation`.
655    fn get_global_alloc(
656        &self,
657        id: AllocId,
658        is_write: bool,
659    ) -> InterpResult<'tcx, Cow<'tcx, Allocation<M::Provenance, M::AllocExtra, M::Bytes>>> {
660        let (alloc, def_id) = match self.tcx.try_get_global_alloc(id) {
661            Some(GlobalAlloc::Memory(mem)) => {
662                // Memory of a constant or promoted or anonymous memory referenced by a static.
663                (mem, None)
664            }
665            Some(GlobalAlloc::Function { .. }) => do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::DerefFunctionPointer(id))throw_ub!(DerefFunctionPointer(id)),
666            Some(GlobalAlloc::VTable(..)) => do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::DerefVTablePointer(id))throw_ub!(DerefVTablePointer(id)),
667            Some(GlobalAlloc::TypeId { .. }) => do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::DerefTypeIdPointer(id))throw_ub!(DerefTypeIdPointer(id)),
668            None => do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::PointerUseAfterFree(id,
            CheckInAllocMsg::MemoryAccess))throw_ub!(PointerUseAfterFree(id, CheckInAllocMsg::MemoryAccess)),
669            Some(GlobalAlloc::Static(def_id)) => {
670                if !self.tcx.is_static(def_id) {
    ::core::panicking::panic("assertion failed: self.tcx.is_static(def_id)")
};assert!(self.tcx.is_static(def_id));
671                // Thread-local statics do not have a constant address. They *must* be accessed via
672                // `ThreadLocalRef`; we can never have a pointer to them as a regular constant value.
673                if !!self.tcx.is_thread_local_static(def_id) {
    ::core::panicking::panic("assertion failed: !self.tcx.is_thread_local_static(def_id)")
};assert!(!self.tcx.is_thread_local_static(def_id));
674                // Notice that every static has two `AllocId` that will resolve to the same
675                // thing here: one maps to `GlobalAlloc::Static`, this is the "lazy" ID,
676                // and the other one is maps to `GlobalAlloc::Memory`, this is returned by
677                // `eval_static_initializer` and it is the "resolved" ID.
678                // The resolved ID is never used by the interpreted program, it is hidden.
679                // This is relied upon for soundness of const-patterns; a pointer to the resolved
680                // ID would "sidestep" the checks that make sure consts do not point to statics!
681                // The `GlobalAlloc::Memory` branch here is still reachable though; when a static
682                // contains a reference to memory that was created during its evaluation (i.e., not
683                // to another static), those inner references only exist in "resolved" form.
684                if self.tcx.is_foreign_item(def_id) {
685                    // This is unreachable in Miri, but can happen in CTFE where we actually *do* support
686                    // referencing arbitrary (declared) extern statics.
687                    do yeet ::rustc_middle::mir::interpret::InterpErrorKind::Unsupported(::rustc_middle::mir::interpret::UnsupportedOpInfo::ExternStatic(def_id));throw_unsup!(ExternStatic(def_id));
688                }
689
690                // We don't give a span -- statics don't need that, they cannot be generic or associated.
691                let val = self.ctfe_query(|tcx| tcx.eval_static_initializer(def_id))?;
692                (val, Some(def_id))
693            }
694        };
695        M::before_access_global(self.tcx, &self.machine, id, alloc, def_id, is_write)?;
696        // We got tcx memory. Let the machine initialize its "extra" stuff.
697        M::adjust_global_allocation(
698            self,
699            id, // always use the ID we got as input, not the "hidden" one.
700            alloc.inner(),
701        )
702    }
703
704    /// Gives raw access to the `Allocation`, without bounds or alignment checks.
705    /// The caller is responsible for calling the access hooks!
706    ///
707    /// You almost certainly want to use `get_ptr_alloc`/`get_ptr_alloc_mut` instead.
708    pub fn get_alloc_raw(
709        &self,
710        id: AllocId,
711    ) -> InterpResult<'tcx, &Allocation<M::Provenance, M::AllocExtra, M::Bytes>> {
712        // The error type of the inner closure here is somewhat funny. We have two
713        // ways of "erroring": An actual error, or because we got a reference from
714        // `get_global_alloc` that we can actually use directly without inserting anything anywhere.
715        // So the error type is `InterpResult<'tcx, &Allocation<M::Provenance>>`.
716        let a = self.memory.alloc_map.get_or(id, || {
717            // We have to funnel the `InterpErrorInfo` through a `Result` to match the `get_or` API,
718            // so we use `report_err` for that.
719            let alloc = self.get_global_alloc(id, /*is_write*/ false).report_err().map_err(Err)?;
720            match alloc {
721                Cow::Borrowed(alloc) => {
722                    // We got a ref, cheaply return that as an "error" so that the
723                    // map does not get mutated.
724                    Err(Ok(alloc))
725                }
726                Cow::Owned(alloc) => {
727                    // Need to put it into the map and return a ref to that
728                    let kind = M::GLOBAL_KIND.expect(
729                        "I got a global allocation that I have to copy but the machine does \
730                            not expect that to happen",
731                    );
732                    Ok((MemoryKind::Machine(kind), alloc))
733                }
734            }
735        });
736        // Now unpack that funny error type
737        match a {
738            Ok(a) => interp_ok(&a.1),
739            Err(a) => a.into(),
740        }
741    }
742
743    /// Gives raw, immutable access to the `Allocation` address, without bounds or alignment checks.
744    /// The caller is responsible for calling the access hooks!
745    pub fn get_alloc_bytes_unchecked_raw(&self, id: AllocId) -> InterpResult<'tcx, *const u8> {
746        let alloc = self.get_alloc_raw(id)?;
747        interp_ok(alloc.get_bytes_unchecked_raw())
748    }
749
750    /// Bounds-checked *but not align-checked* allocation access.
751    pub fn get_ptr_alloc<'a>(
752        &'a self,
753        ptr: Pointer<Option<M::Provenance>>,
754        size: Size,
755    ) -> InterpResult<'tcx, Option<AllocRef<'a, 'tcx, M::Provenance, M::AllocExtra, M::Bytes>>>
756    {
757        let size_i64 = i64::try_from(size.bytes()).unwrap(); // it would be an error to even ask for more than isize::MAX bytes
758        let ptr_and_alloc = Self::check_and_deref_ptr(
759            self,
760            ptr,
761            size_i64,
762            CheckInAllocMsg::MemoryAccess,
763            |this, alloc_id, offset, prov| {
764                let alloc = this.get_alloc_raw(alloc_id)?;
765                interp_ok((alloc.size(), alloc.align, (alloc_id, offset, prov, alloc)))
766            },
767        )?;
768        // We want to call the hook on *all* accesses that involve an AllocId, including zero-sized
769        // accesses. That means we cannot rely on the closure above or the `Some` branch below. We
770        // do this after `check_and_deref_ptr` to ensure some basic sanity has already been checked.
771        if !self.memory.ghost_mode.get() {
772            if let Ok((alloc_id, ..)) = self.ptr_try_get_alloc_id(ptr, size_i64) {
773                M::before_alloc_access(self.tcx, &self.machine, alloc_id)?;
774            }
775        }
776
777        if let Some((alloc_id, offset, prov, alloc)) = ptr_and_alloc {
778            let range = alloc_range(offset, size);
779            if !self.memory.ghost_mode.get() {
780                M::before_memory_read(
781                    self.tcx,
782                    &self.machine,
783                    &alloc.extra,
784                    ptr,
785                    (alloc_id, prov),
786                    range,
787                )?;
788            }
789            interp_ok(Some(AllocRef { alloc, range, tcx: *self.tcx, alloc_id }))
790        } else {
791            interp_ok(None)
792        }
793    }
794
795    /// Return the `extra` field of the given allocation.
796    pub fn get_alloc_extra<'a>(&'a self, id: AllocId) -> InterpResult<'tcx, &'a M::AllocExtra> {
797        interp_ok(&self.get_alloc_raw(id)?.extra)
798    }
799
800    /// Return the `mutability` field of the given allocation.
801    pub fn get_alloc_mutability<'a>(&'a self, id: AllocId) -> InterpResult<'tcx, Mutability> {
802        interp_ok(self.get_alloc_raw(id)?.mutability)
803    }
804
805    /// Gives raw mutable access to the `Allocation`, without bounds or alignment checks.
806    /// The caller is responsible for calling the access hooks!
807    ///
808    /// Also returns a ptr to `self.extra` so that the caller can use it in parallel with the
809    /// allocation.
810    ///
811    /// You almost certainly want to use `get_ptr_alloc`/`get_ptr_alloc_mut` instead.
812    pub fn get_alloc_raw_mut(
813        &mut self,
814        id: AllocId,
815    ) -> InterpResult<'tcx, (&mut Allocation<M::Provenance, M::AllocExtra, M::Bytes>, &mut M)> {
816        // We have "NLL problem case #3" here, which cannot be worked around without loss of
817        // efficiency even for the common case where the key is in the map.
818        // <https://rust-lang.github.io/rfcs/2094-nll.html#problem-case-3-conditional-control-flow-across-functions>
819        // (Cannot use `get_mut_or` since `get_global_alloc` needs `&self`, and that boils down to
820        // Miri's `adjust_alloc_root_pointer` needing to look up the size of the allocation.
821        // It could be avoided with a totally separate codepath in Miri for handling the absolute address
822        // of global allocations, but that's not worth it.)
823        if self.memory.alloc_map.get_mut(id).is_none() {
824            // Slow path.
825            // Allocation not found locally, go look global.
826            let alloc = self.get_global_alloc(id, /*is_write*/ true)?;
827            let kind = M::GLOBAL_KIND.expect(
828                "I got a global allocation that I have to copy but the machine does \
829                    not expect that to happen",
830            );
831            self.memory.alloc_map.insert(id, (MemoryKind::Machine(kind), alloc.into_owned()));
832        }
833
834        let (_kind, alloc) = self.memory.alloc_map.get_mut(id).unwrap();
835        if alloc.mutability.is_not() {
836            do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::WriteToReadOnly(id))throw_ub!(WriteToReadOnly(id))
837        }
838        interp_ok((alloc, &mut self.machine))
839    }
840
841    /// Gives raw, mutable access to the `Allocation` address, without bounds or alignment checks.
842    /// The caller is responsible for calling the access hooks!
843    pub fn get_alloc_bytes_unchecked_raw_mut(
844        &mut self,
845        id: AllocId,
846    ) -> InterpResult<'tcx, *mut u8> {
847        let alloc = self.get_alloc_raw_mut(id)?.0;
848        interp_ok(alloc.get_bytes_unchecked_raw_mut())
849    }
850
851    /// Bounds-checked *but not align-checked* allocation access.
852    pub fn get_ptr_alloc_mut<'a>(
853        &'a mut self,
854        ptr: Pointer<Option<M::Provenance>>,
855        size: Size,
856    ) -> InterpResult<'tcx, Option<AllocRefMut<'a, 'tcx, M::Provenance, M::AllocExtra, M::Bytes>>>
857    {
858        let tcx = self.tcx;
859        let validation_in_progress = self.memory.ghost_mode.get();
860
861        let size_i64 = i64::try_from(size.bytes()).unwrap(); // it would be an error to even ask for more than isize::MAX bytes
862        let ptr_and_alloc = Self::check_and_deref_ptr(
863            self,
864            ptr,
865            size_i64,
866            CheckInAllocMsg::MemoryAccess,
867            |this, alloc_id, offset, prov| {
868                let (alloc, machine) = this.get_alloc_raw_mut(alloc_id)?;
869                interp_ok((alloc.size(), alloc.align, (alloc_id, offset, prov, alloc, machine)))
870            },
871        )?;
872
873        if let Some((alloc_id, offset, prov, alloc, machine)) = ptr_and_alloc {
874            let range = alloc_range(offset, size);
875            if !validation_in_progress {
876                // For writes, it's okay to only call those when there actually is a non-zero
877                // amount of bytes to be written: a zero-sized write doesn't manifest anything.
878                M::before_alloc_access(tcx, machine, alloc_id)?;
879                M::before_memory_write(
880                    tcx,
881                    machine,
882                    &mut alloc.extra,
883                    ptr,
884                    (alloc_id, prov),
885                    range,
886                )?;
887            }
888            interp_ok(Some(AllocRefMut { alloc, range, tcx: *tcx, alloc_id }))
889        } else {
890            interp_ok(None)
891        }
892    }
893
894    /// Return the `extra` field of the given allocation.
895    pub fn get_alloc_extra_mut<'a>(
896        &'a mut self,
897        id: AllocId,
898    ) -> InterpResult<'tcx, (&'a mut M::AllocExtra, &'a mut M)> {
899        let (alloc, machine) = self.get_alloc_raw_mut(id)?;
900        interp_ok((&mut alloc.extra, machine))
901    }
902
903    /// Check whether an allocation is live. This is faster than calling
904    /// [`InterpCx::get_alloc_info`] if all you need to check is whether the kind is
905    /// [`AllocKind::Dead`] because it doesn't have to look up the type and layout of statics.
906    pub fn is_alloc_live(&self, id: AllocId) -> bool {
907        self.memory.alloc_map.contains_key_ref(&id)
908            || self.memory.extra_fn_ptr_map.contains_key(&id)
909            || self.memory.va_list_map.contains_key(&id)
910            // We check `tcx` last as that has to acquire a lock in `many-seeds` mode.
911            // This also matches the order in `get_alloc_info`.
912            || self.tcx.try_get_global_alloc(id).is_some()
913    }
914
915    /// Check whether an allocation contains provenance.
916    pub fn has_provenance_in_alloc(&self, id: AllocId) -> InterpResult<'tcx, bool> {
917        let alloc = self.get_alloc_raw(id)?;
918        interp_ok(!alloc.provenance().range_empty(alloc_range(Size::ZERO, alloc.size()), &self.tcx))
919    }
920
921    /// Obtain the size and alignment of an allocation, even if that allocation has
922    /// been deallocated.
923    pub fn get_alloc_info(&self, id: AllocId) -> AllocInfo {
924        // # Regular allocations
925        // Don't use `self.get_raw` here as that will
926        // a) cause cycles in case `id` refers to a static
927        // b) duplicate a global's allocation in miri
928        if let Some((_, alloc)) = self.memory.alloc_map.get(id) {
929            return AllocInfo::new(
930                alloc.size(),
931                alloc.align,
932                AllocKind::LiveData,
933                alloc.mutability,
934            );
935        }
936
937        // # Function pointers
938        // (both global from `alloc_map` and local from `extra_fn_ptr_map`)
939        if let Some(fn_val) = self.get_fn_alloc(id) {
940            let align = match fn_val {
941                FnVal::Instance(_instance) => {
942                    // FIXME: Until we have a clear design for the effects of align(N) functions
943                    // on the address of function pointers, we don't consider the align(N)
944                    // attribute on functions in the interpreter.
945                    // See <https://github.com/rust-lang/rust/issues/144661> for more context.
946                    Align::ONE
947                }
948                // Machine-specific extra functions currently do not support alignment restrictions.
949                FnVal::Other(_) => Align::ONE,
950            };
951
952            return AllocInfo::new(Size::ZERO, align, AllocKind::Function, Mutability::Not);
953        }
954
955        // # Variable argument lists
956        if self.memory.va_list_map.contains_key(&id) {
957            return AllocInfo::new(Size::ZERO, Align::ONE, AllocKind::VaList, Mutability::Not);
958        }
959
960        // # Global allocations
961        if let Some(global_alloc) = self.tcx.try_get_global_alloc(id) {
962            // NOTE: `static` alignment from attributes has already been applied to the allocation.
963            let (size, align) = global_alloc.size_and_align(*self.tcx, self.typing_env);
964            let mutbl = global_alloc.mutability(*self.tcx, self.typing_env);
965            let kind = match global_alloc {
966                GlobalAlloc::Static { .. } | GlobalAlloc::Memory { .. } => AllocKind::LiveData,
967                GlobalAlloc::Function { .. } => bug_impl(None, format_args!("We already checked function pointers above"),
    Location::caller())bug!("We already checked function pointers above"),
968                GlobalAlloc::VTable { .. } => AllocKind::VTable,
969                GlobalAlloc::TypeId { .. } => AllocKind::TypeId,
970            };
971            return AllocInfo::new(size, align, kind, mutbl);
972        }
973
974        // # Dead pointers
975        let (size, align) = *self
976            .memory
977            .dead_alloc_map
978            .get(&id)
979            .expect("deallocated pointers should all be recorded in `dead_alloc_map`");
980        AllocInfo::new(size, align, AllocKind::Dead, Mutability::Not)
981    }
982
983    /// Obtain the size and alignment of a *live* allocation.
984    fn get_live_alloc_size_and_align(
985        &self,
986        id: AllocId,
987        msg: CheckInAllocMsg,
988    ) -> InterpResult<'tcx, (Size, Align)> {
989        let info = self.get_alloc_info(id);
990        if info.kind == AllocKind::Dead {
991            do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::PointerUseAfterFree(id,
            msg))throw_ub!(PointerUseAfterFree(id, msg))
992        }
993        interp_ok((info.size, info.align))
994    }
995
996    fn get_fn_alloc(&self, id: AllocId) -> Option<FnVal<'tcx, M::ExtraFnVal>> {
997        if let Some(extra) = self.memory.extra_fn_ptr_map.get(&id) {
998            Some(FnVal::Other(*extra))
999        } else {
1000            match self.tcx.try_get_global_alloc(id) {
1001                Some(GlobalAlloc::Function { instance, .. }) => Some(FnVal::Instance(instance)),
1002                _ => None,
1003            }
1004        }
1005    }
1006
1007    /// Takes a pointer that is the first chunk of a `TypeId` and return the type that its
1008    /// provenance refers to, as well as the segment of the hash that this pointer covers.
1009    pub fn get_ptr_type_id(
1010        &self,
1011        ptr: Pointer<Option<M::Provenance>>,
1012    ) -> InterpResult<'tcx, (Ty<'tcx>, u64)> {
1013        let (alloc_id, offset, _meta) = self.ptr_get_alloc_id(ptr, 0)?;
1014        let Some(GlobalAlloc::TypeId { ty }) = self.tcx.try_get_global_alloc(alloc_id) else {
1015            do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Ub(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("invalid `TypeId` value: not all bytes carry type id metadata"))
                })))throw_ub_format!("invalid `TypeId` value: not all bytes carry type id metadata")
1016        };
1017        interp_ok((ty, offset.bytes()))
1018    }
1019
1020    pub fn get_ptr_fn(
1021        &self,
1022        ptr: Pointer<Option<M::Provenance>>,
1023    ) -> InterpResult<'tcx, FnVal<'tcx, M::ExtraFnVal>> {
1024        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_const_eval/src/interpret/memory.rs:1024",
                        "rustc_const_eval::interpret::memory",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_const_eval/src/interpret/memory.rs"),
                        ::tracing_core::__macro_support::Option::Some(1024u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::memory"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("get_ptr_fn({0:?})",
                                                    ptr) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};trace!("get_ptr_fn({:?})", ptr);
1025        let (alloc_id, offset, _prov) = self.ptr_get_alloc_id(ptr, 0)?;
1026        if offset.bytes() != 0 {
1027            do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::InvalidFunctionPointer(Pointer::new(alloc_id,
                offset)))throw_ub!(InvalidFunctionPointer(Pointer::new(alloc_id, offset)))
1028        }
1029        self.get_fn_alloc(alloc_id)
1030            .ok_or_else(|| ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::InvalidFunctionPointer(Pointer::new(alloc_id,
            offset)))err_ub!(InvalidFunctionPointer(Pointer::new(alloc_id, offset))))
1031            .into()
1032    }
1033
1034    pub fn get_ptr_va_list(
1035        &self,
1036        ptr: Pointer<Option<M::Provenance>>,
1037    ) -> InterpResult<'tcx, &VecDeque<MPlaceTy<'tcx, M::Provenance>>> {
1038        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_const_eval/src/interpret/memory.rs:1038",
                        "rustc_const_eval::interpret::memory",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_const_eval/src/interpret/memory.rs"),
                        ::tracing_core::__macro_support::Option::Some(1038u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::memory"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("get_ptr_va_list({0:?})",
                                                    ptr) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};trace!("get_ptr_va_list({:?})", ptr);
1039        let (alloc_id, offset, _prov) = self.ptr_get_alloc_id(ptr, 0)?;
1040        if offset.bytes() != 0 {
1041            do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::InvalidVaListPointer(Pointer::new(alloc_id,
                offset)))throw_ub!(InvalidVaListPointer(Pointer::new(alloc_id, offset)))
1042        }
1043
1044        let Some(va_list) = self.memory.va_list_map.get(&alloc_id) else {
1045            do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::InvalidVaListPointer(Pointer::new(alloc_id,
                offset)))throw_ub!(InvalidVaListPointer(Pointer::new(alloc_id, offset)))
1046        };
1047
1048        interp_ok(va_list)
1049    }
1050
1051    /// Removes this VaList from the global map of variable argument lists. This does not deallocate
1052    /// the VaList elements, that happens when the Frame is popped.
1053    pub fn deallocate_va_list(
1054        &mut self,
1055        ptr: Pointer<Option<M::Provenance>>,
1056    ) -> InterpResult<'tcx, VecDeque<MPlaceTy<'tcx, M::Provenance>>> {
1057        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_const_eval/src/interpret/memory.rs:1057",
                        "rustc_const_eval::interpret::memory",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_const_eval/src/interpret/memory.rs"),
                        ::tracing_core::__macro_support::Option::Some(1057u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::memory"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("deallocate_va_list({0:?})",
                                                    ptr) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};trace!("deallocate_va_list({:?})", ptr);
1058        let (alloc_id, offset, _prov) = self.ptr_get_alloc_id(ptr, 0)?;
1059        if offset.bytes() != 0 {
1060            do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::InvalidVaListPointer(Pointer::new(alloc_id,
                offset)))throw_ub!(InvalidVaListPointer(Pointer::new(alloc_id, offset)))
1061        }
1062
1063        let Some(va_list) = self.memory.va_list_map.swap_remove(&alloc_id) else {
1064            do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::InvalidVaListPointer(Pointer::new(alloc_id,
                offset)))throw_ub!(InvalidVaListPointer(Pointer::new(alloc_id, offset)))
1065        };
1066
1067        self.memory.dead_alloc_map.insert(alloc_id, (Size::ZERO, Align::ONE));
1068        interp_ok(va_list)
1069    }
1070
1071    /// Get the dynamic type of the given vtable pointer.
1072    /// If `expected_trait` is `Some`, it must be a vtable for the given trait.
1073    pub fn get_ptr_vtable_ty(
1074        &self,
1075        ptr: Pointer<Option<M::Provenance>>,
1076        expected_trait: Option<&'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>>,
1077    ) -> InterpResult<'tcx, Ty<'tcx>> {
1078        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_const_eval/src/interpret/memory.rs:1078",
                        "rustc_const_eval::interpret::memory",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_const_eval/src/interpret/memory.rs"),
                        ::tracing_core::__macro_support::Option::Some(1078u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::memory"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("get_ptr_vtable({0:?})",
                                                    ptr) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};trace!("get_ptr_vtable({:?})", ptr);
1079        let (alloc_id, offset, _tag) = self.ptr_get_alloc_id(ptr, 0).map_err_kind(|err| {
1080            let ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::DanglingIntPointer {
addr, .. })err_ub!(DanglingIntPointer { addr, .. }) = err else { bug_impl(None, format_args!("impossible case reached"), Location::caller())bug!() };
1081            ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::InvalidVTablePointer(Pointer::without_provenance(addr)))err_ub!(InvalidVTablePointer(Pointer::without_provenance(addr)))
1082        })?;
1083        if offset.bytes() != 0 {
1084            do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::InvalidVTablePointer(Pointer::new(alloc_id,
                    offset).into()))throw_ub!(InvalidVTablePointer(Pointer::new(alloc_id, offset).into()))
1085        }
1086        let Some(GlobalAlloc::VTable(ty, vtable_dyn_type)) =
1087            self.tcx.try_get_global_alloc(alloc_id)
1088        else {
1089            do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::InvalidVTablePointer(Pointer::new(alloc_id,
                    offset).into()))throw_ub!(InvalidVTablePointer(Pointer::new(alloc_id, offset).into()))
1090        };
1091        if let Some(expected_dyn_type) = expected_trait {
1092            self.check_vtable_for_type(vtable_dyn_type, expected_dyn_type)?;
1093        }
1094        interp_ok(ty)
1095    }
1096
1097    pub fn alloc_mark_immutable(&mut self, id: AllocId) -> InterpResult<'tcx> {
1098        self.get_alloc_raw_mut(id)?.0.mutability = Mutability::Not;
1099        interp_ok(())
1100    }
1101
1102    /// Visit all allocations reachable from the given start set, by recursively traversing the
1103    /// provenance information of those allocations.
1104    pub fn visit_reachable_allocs(
1105        &mut self,
1106        start: Vec<AllocId>,
1107        mut visit: impl FnMut(&mut Self, AllocId, &AllocInfo) -> InterpResult<'tcx>,
1108    ) -> InterpResult<'tcx> {
1109        let mut done = FxHashSet::default();
1110        let mut todo = start;
1111        while let Some(id) = todo.pop() {
1112            if !done.insert(id) {
1113                // We already saw this allocation before, don't process it again.
1114                continue;
1115            }
1116            let info = self.get_alloc_info(id);
1117
1118            // Recurse, if there is data here.
1119            // Do this *before* invoking the callback, as the callback might mutate the
1120            // allocation and e.g. replace all provenance by wildcards!
1121            if info.kind == AllocKind::LiveData {
1122                let alloc = self.get_alloc_raw(id)?;
1123                for prov in alloc.provenance().provenances() {
1124                    if let Some(id) = prov.get_alloc_id() {
1125                        todo.push(id);
1126                    }
1127                }
1128            }
1129
1130            // Call the callback.
1131            visit(self, id, &info)?;
1132        }
1133        interp_ok(())
1134    }
1135
1136    /// Create a lazy debug printer that prints the given allocation and all allocations it points
1137    /// to, recursively.
1138    #[must_use]
1139    pub fn dump_alloc<'a>(&'a self, id: AllocId) -> DumpAllocs<'a, 'tcx, M> {
1140        self.dump_allocs(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [id]))vec![id])
1141    }
1142
1143    /// Create a lazy debug printer for a list of allocations and all allocations they point to,
1144    /// recursively.
1145    #[must_use]
1146    pub fn dump_allocs<'a>(&'a self, mut allocs: Vec<AllocId>) -> DumpAllocs<'a, 'tcx, M> {
1147        allocs.sort();
1148        allocs.dedup();
1149        DumpAllocs { ecx: self, allocs }
1150    }
1151
1152    /// Print the allocation's bytes, without any nested allocations.
1153    pub fn print_alloc_bytes_for_diagnostics(&self, id: AllocId) -> String {
1154        // Using the "raw" access to avoid the `before_alloc_read` hook, we specifically
1155        // want to be able to read all memory for diagnostics, even if that is cyclic.
1156        let alloc = self.get_alloc_raw(id).unwrap();
1157        let mut bytes = String::new();
1158        if alloc.size() != Size::ZERO {
1159            bytes = "\n".into();
1160            // FIXME(translation) there might be pieces that are translatable.
1161            rustc_middle::mir::pretty::write_allocation_bytes(*self.tcx, alloc, &mut bytes, "    ")
1162                .unwrap();
1163        }
1164        bytes
1165    }
1166
1167    /// Find leaked allocations, remove them from memory and return them. Allocations reachable from
1168    /// `static_roots` or a `Global` allocation are not considered leaked, as well as leaks whose
1169    /// kind's `may_leak()` returns true.
1170    ///
1171    /// This is highly destructive, no more execution can happen after this!
1172    pub fn take_leaked_allocations(
1173        &mut self,
1174        static_roots: impl FnOnce(&Self) -> &[AllocId],
1175    ) -> Vec<(AllocId, MemoryKind<M::MemoryKind>, Allocation<M::Provenance, M::AllocExtra, M::Bytes>)>
1176    {
1177        // Collect the set of allocations that are *reachable* from `Global` allocations.
1178        let reachable = {
1179            let mut reachable = FxHashSet::default();
1180            let global_kind = M::GLOBAL_KIND.map(MemoryKind::Machine);
1181            let mut todo: Vec<_> =
1182                self.memory.alloc_map.filter_map_collect(move |&id, &(kind, _)| {
1183                    if Some(kind) == global_kind { Some(id) } else { None }
1184                });
1185            todo.extend(static_roots(self));
1186            while let Some(id) = todo.pop() {
1187                if reachable.insert(id) {
1188                    // This is a new allocation, add the allocations it points to `todo`.
1189                    // We only need to care about `alloc_map` memory here, as entirely unchanged
1190                    // global memory cannot point to memory relevant for the leak check.
1191                    if let Some((_, alloc)) = self.memory.alloc_map.get(id) {
1192                        todo.extend(
1193                            alloc.provenance().provenances().filter_map(|prov| prov.get_alloc_id()),
1194                        );
1195                    }
1196                }
1197            }
1198            reachable
1199        };
1200
1201        // All allocations that are *not* `reachable` and *not* `may_leak` are considered leaking.
1202        let leaked: Vec<_> = self.memory.alloc_map.filter_map_collect(|&id, &(kind, _)| {
1203            if kind.may_leak() || reachable.contains(&id) { None } else { Some(id) }
1204        });
1205        let mut result = Vec::new();
1206        for &id in leaked.iter() {
1207            let (kind, alloc) = self.memory.alloc_map.remove(&id).unwrap();
1208            result.push((id, kind, alloc));
1209        }
1210        result
1211    }
1212
1213    /// Runs the closure in "ghost" mode, which means the machine's memory read hooks will be
1214    /// suppressed. Needless to say, this must only be set with great care! Cannot be nested.
1215    ///
1216    /// We do this so Miri's allocation access tracking does not show the validation
1217    /// reads as spurious accesses as those aren't "real" reads. Also useful for debuggers
1218    /// that want to just display the Miri machine state.
1219    pub fn ghost_run_mut<R>(&mut self, f: impl FnOnce(&mut Self) -> R) -> R {
1220        // This deliberately uses `==` on `bool` to follow the pattern
1221        // `assert!(val.replace(new) == old)`.
1222        if !(self.memory.ghost_mode.replace(true) == false) {
    {
        ::core::panicking::panic_fmt(format_args!("`ghost_mode` was already set"));
    }
};assert!(self.memory.ghost_mode.replace(true) == false, "`ghost_mode` was already set");
1223        let res = f(self);
1224        if !(self.memory.ghost_mode.replace(false) == true) {
    {
        ::core::panicking::panic_fmt(format_args!("`ghost_mode` was unset by someone else"));
    }
};assert!(
1225            self.memory.ghost_mode.replace(false) == true,
1226            "`ghost_mode` was unset by someone else"
1227        );
1228        res
1229    }
1230
1231    /// Runs the closure in "ghost" mode, which means the machine's memory read hooks will be
1232    /// suppressed. Needless to say, this must only be set with great care! Cannot be nested.
1233    ///
1234    /// We do this so Miri's allocation access tracking does not show the validation
1235    /// reads as spurious accesses as those aren't "real" reads. Also useful for debuggers
1236    /// that want to just display the Miri machine state.
1237    pub fn ghost_run<R>(&self, f: impl FnOnce(&Self) -> R) -> R {
1238        // This deliberately uses `==` on `bool` to follow the pattern
1239        // `assert!(val.replace(new) == old)`.
1240        if !(self.memory.ghost_mode.replace(true) == false) {
    {
        ::core::panicking::panic_fmt(format_args!("`ghost_mode` was already set"));
    }
};assert!(self.memory.ghost_mode.replace(true) == false, "`ghost_mode` was already set");
1241        let res = f(self);
1242        if !(self.memory.ghost_mode.replace(false) == true) {
    {
        ::core::panicking::panic_fmt(format_args!("`ghost_mode` was unset by someone else"));
    }
};assert!(
1243            self.memory.ghost_mode.replace(false) == true,
1244            "`ghost_mode` was unset by someone else"
1245        );
1246        res
1247    }
1248
1249    pub(super) fn validation_in_progress(&self) -> bool {
1250        self.memory.ghost_mode.get()
1251    }
1252}
1253
1254#[doc(hidden)]
1255/// There's no way to use this directly, it's just a helper struct for the `dump_alloc(s)` methods.
1256pub struct DumpAllocs<'a, 'tcx, M: Machine<'tcx>> {
1257    ecx: &'a InterpCx<'tcx, M>,
1258    allocs: Vec<AllocId>,
1259}
1260
1261impl<'a, 'tcx, M: Machine<'tcx>> std::fmt::Debug for DumpAllocs<'a, 'tcx, M> {
1262    fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1263        // Cannot be a closure because it is generic in `Prov`, `Extra`.
1264        fn write_allocation_track_relocs<'tcx, Prov: Provenance, Extra, Bytes: AllocBytes>(
1265            fmt: &mut std::fmt::Formatter<'_>,
1266            tcx: TyCtxt<'tcx>,
1267            allocs_to_print: &mut VecDeque<AllocId>,
1268            alloc: &Allocation<Prov, Extra, Bytes>,
1269        ) -> std::fmt::Result {
1270            for alloc_id in alloc.provenance().provenances().filter_map(|prov| prov.get_alloc_id())
1271            {
1272                allocs_to_print.push_back(alloc_id);
1273            }
1274            fmt.write_fmt(format_args!("{0}", display_allocation(tcx, alloc)))write!(fmt, "{}", display_allocation(tcx, alloc))
1275        }
1276
1277        let mut allocs_to_print: VecDeque<_> = self.allocs.iter().copied().collect();
1278        // `allocs_printed` contains all allocations that we have already printed.
1279        let mut allocs_printed = FxHashSet::default();
1280
1281        while let Some(id) = allocs_to_print.pop_front() {
1282            if !allocs_printed.insert(id) {
1283                // Already printed, so skip this.
1284                continue;
1285            }
1286
1287            fmt.write_fmt(format_args!("{0:?}", id))write!(fmt, "{id:?}")?;
1288            match self.ecx.memory.alloc_map.get(id) {
1289                Some((kind, alloc)) => {
1290                    // normal alloc
1291                    fmt.write_fmt(format_args!(" ({0}, ", kind))write!(fmt, " ({kind}, ")?;
1292                    write_allocation_track_relocs(
1293                        &mut *fmt,
1294                        *self.ecx.tcx,
1295                        &mut allocs_to_print,
1296                        alloc,
1297                    )?;
1298                }
1299                None => {
1300                    // global alloc
1301                    match self.ecx.tcx.try_get_global_alloc(id) {
1302                        Some(GlobalAlloc::Memory(alloc)) => {
1303                            fmt.write_fmt(format_args!(" (unchanged global, "))write!(fmt, " (unchanged global, ")?;
1304                            write_allocation_track_relocs(
1305                                &mut *fmt,
1306                                *self.ecx.tcx,
1307                                &mut allocs_to_print,
1308                                alloc.inner(),
1309                            )?;
1310                        }
1311                        Some(GlobalAlloc::Function { instance, .. }) => {
1312                            fmt.write_fmt(format_args!(" (fn: {0})", instance))write!(fmt, " (fn: {instance})")?;
1313                        }
1314                        Some(GlobalAlloc::VTable(ty, dyn_ty)) => {
1315                            fmt.write_fmt(format_args!(" (vtable: impl {0} for {1})", dyn_ty, ty))write!(fmt, " (vtable: impl {dyn_ty} for {ty})")?;
1316                        }
1317                        Some(GlobalAlloc::TypeId { ty }) => {
1318                            fmt.write_fmt(format_args!(" (typeid for {0})", ty))write!(fmt, " (typeid for {ty})")?;
1319                        }
1320                        Some(GlobalAlloc::Static(did)) => {
1321                            fmt.write_fmt(format_args!(" (static: {0})", self.ecx.tcx.def_path_str(did)))write!(fmt, " (static: {})", self.ecx.tcx.def_path_str(did))?;
1322                        }
1323                        None => {
1324                            fmt.write_fmt(format_args!(" (deallocated)"))write!(fmt, " (deallocated)")?;
1325                        }
1326                    }
1327                }
1328            }
1329            fmt.write_fmt(format_args!("\n"))writeln!(fmt)?;
1330        }
1331        Ok(())
1332    }
1333}
1334
1335/// Reading and writing.
1336impl<'a, 'tcx, Prov: Provenance, Extra, Bytes: AllocBytes>
1337    AllocRefMut<'a, 'tcx, Prov, Extra, Bytes>
1338{
1339    pub fn as_ref<'b>(&'b self) -> AllocRef<'b, 'tcx, Prov, Extra, Bytes> {
1340        AllocRef { alloc: self.alloc, range: self.range, tcx: self.tcx, alloc_id: self.alloc_id }
1341    }
1342
1343    /// `range` is relative to this allocation reference, not the base of the allocation.
1344    pub fn write_scalar(&mut self, range: AllocRange, val: Scalar<Prov>) -> InterpResult<'tcx> {
1345        let range = self.range.subrange(range);
1346        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_const_eval/src/interpret/memory.rs:1346",
                        "rustc_const_eval::interpret::memory",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_const_eval/src/interpret/memory.rs"),
                        ::tracing_core::__macro_support::Option::Some(1346u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::memory"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("write_scalar at {0:?}{1:?}: {2:?}",
                                                    self.alloc_id, range, val) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("write_scalar at {:?}{range:?}: {val:?}", self.alloc_id);
1347
1348        self.alloc
1349            .write_scalar(&self.tcx, range, val)
1350            .map_err(|e| e.to_interp_error(self.alloc_id))
1351            .into()
1352    }
1353
1354    /// `offset` is relative to this allocation reference, not the base of the allocation.
1355    pub fn write_ptr_sized(&mut self, offset: Size, val: Scalar<Prov>) -> InterpResult<'tcx> {
1356        self.write_scalar(alloc_range(offset, self.tcx.data_layout().pointer_size()), val)
1357    }
1358
1359    /// Mark the given sub-range (relative to this allocation reference) as uninitialized.
1360    pub fn write_uninit(&mut self, range: AllocRange) {
1361        let range = self.range.subrange(range);
1362
1363        self.alloc.write_uninit(&self.tcx, range);
1364    }
1365
1366    /// Mark the entire referenced range as uninitialized
1367    pub fn write_uninit_full(&mut self) {
1368        self.alloc.write_uninit(&self.tcx, self.range);
1369    }
1370
1371    /// Remove all provenance in the reference range.
1372    pub fn clear_provenance(&mut self) {
1373        self.alloc.clear_provenance(&self.tcx, self.range);
1374    }
1375}
1376
1377impl<'a, 'tcx, Prov: Provenance, Extra, Bytes: AllocBytes> AllocRef<'a, 'tcx, Prov, Extra, Bytes> {
1378    /// `range` is relative to this allocation reference, not the base of the allocation.
1379    pub fn read_scalar(
1380        &self,
1381        range: AllocRange,
1382        read_provenance: bool,
1383    ) -> InterpResult<'tcx, Scalar<Prov>> {
1384        let range = self.range.subrange(range);
1385        self.alloc
1386            .read_scalar(&self.tcx, range, read_provenance)
1387            .map_err(|e| e.to_interp_error(self.alloc_id))
1388            .into()
1389    }
1390
1391    /// `range` is relative to this allocation reference, not the base of the allocation.
1392    pub fn read_integer(&self, range: AllocRange) -> InterpResult<'tcx, Scalar<Prov>> {
1393        self.read_scalar(range, /*read_provenance*/ false)
1394    }
1395
1396    /// `offset` is relative to this allocation reference, not the base of the allocation.
1397    pub fn read_pointer(&self, offset: Size) -> InterpResult<'tcx, Scalar<Prov>> {
1398        self.read_scalar(
1399            alloc_range(offset, self.tcx.data_layout().pointer_size()),
1400            /*read_provenance*/ true,
1401        )
1402    }
1403
1404    /// `range` is relative to this allocation reference, not the base of the allocation.
1405    pub fn get_bytes_strip_provenance<'b>(&'b self) -> InterpResult<'tcx, &'a [u8]> {
1406        self.alloc
1407            .get_bytes_strip_provenance(&self.tcx, self.range)
1408            .map_err(|e| e.to_interp_error(self.alloc_id))
1409            .into()
1410    }
1411
1412    /// Returns whether the allocation has provenance anywhere in the range of the `AllocRef`.
1413    pub fn has_provenance(&self) -> bool {
1414        !self.alloc.provenance().range_empty(self.range, &self.tcx)
1415    }
1416}
1417
1418impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
1419    /// Reads the given number of bytes from memory, and strips their provenance if possible.
1420    /// Returns them as a slice.
1421    ///
1422    /// Performs appropriate bounds checks.
1423    pub fn read_bytes_ptr_strip_provenance(
1424        &self,
1425        ptr: Pointer<Option<M::Provenance>>,
1426        size: Size,
1427    ) -> InterpResult<'tcx, &[u8]> {
1428        let Some(alloc_ref) = self.get_ptr_alloc(ptr, size)? else {
1429            // zero-sized access
1430            return interp_ok(&[]);
1431        };
1432        // Side-step AllocRef and directly access the underlying bytes more efficiently.
1433        // (We are staying inside the bounds here so all is good.)
1434        interp_ok(
1435            alloc_ref
1436                .alloc
1437                .get_bytes_strip_provenance(&alloc_ref.tcx, alloc_ref.range)
1438                .map_err(|e| e.to_interp_error(alloc_ref.alloc_id))?,
1439        )
1440    }
1441
1442    /// Writes the given stream of bytes into memory.
1443    ///
1444    /// Performs appropriate bounds checks.
1445    pub fn write_bytes_ptr(
1446        &mut self,
1447        ptr: Pointer<Option<M::Provenance>>,
1448        src: impl IntoIterator<Item = u8>,
1449    ) -> InterpResult<'tcx> {
1450        let mut src = src.into_iter();
1451        let (lower, upper) = src.size_hint();
1452        let len = upper.expect("can only write bounded iterators");
1453        {
    match (&lower, &len) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val,
                    ::core::option::Option::Some(format_args!("can only write iterators with a precise length")));
            }
        }
    }
};assert_eq!(lower, len, "can only write iterators with a precise length");
1454
1455        let size = Size::from_bytes(len);
1456        let Some(alloc_ref) = self.get_ptr_alloc_mut(ptr, size)? else {
1457            // zero-sized access
1458            {
    match src.next() {
        None => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val, "None",
                ::core::option::Option::Some(format_args!("iterator said it was empty but returned an element")));
        }
    }
};assert_matches!(src.next(), None, "iterator said it was empty but returned an element");
1459            return interp_ok(());
1460        };
1461
1462        // Side-step AllocRef and directly access the underlying bytes more efficiently.
1463        // (We are staying inside the bounds here and all bytes do get overwritten so all is good.)
1464        let bytes =
1465            alloc_ref.alloc.get_bytes_unchecked_for_overwrite(&alloc_ref.tcx, alloc_ref.range);
1466        // `zip` would stop when the first iterator ends; we want to definitely
1467        // cover all of `bytes`.
1468        for dest in bytes {
1469            *dest = src.next().expect("iterator was shorter than it said it would be");
1470        }
1471        {
    match src.next() {
        None => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val, "None",
                ::core::option::Option::Some(format_args!("iterator was longer than it said it would be")));
        }
    }
};assert_matches!(src.next(), None, "iterator was longer than it said it would be");
1472        interp_ok(())
1473    }
1474
1475    pub fn mem_copy(
1476        &mut self,
1477        src: Pointer<Option<M::Provenance>>,
1478        dest: Pointer<Option<M::Provenance>>,
1479        size: Size,
1480        nonoverlapping: bool,
1481    ) -> InterpResult<'tcx> {
1482        self.mem_copy_repeatedly(src, dest, size, 1, nonoverlapping)
1483    }
1484
1485    /// Performs `num_copies` many copies of `size` many bytes from `src` to `dest + i*size` (where
1486    /// `i` is the index of the copy).
1487    ///
1488    /// Either `nonoverlapping` must be true or `num_copies` must be 1; doing repeated copies that
1489    /// may overlap is not supported.
1490    pub fn mem_copy_repeatedly(
1491        &mut self,
1492        src: Pointer<Option<M::Provenance>>,
1493        dest: Pointer<Option<M::Provenance>>,
1494        size: Size,
1495        num_copies: u64,
1496        nonoverlapping: bool,
1497    ) -> InterpResult<'tcx> {
1498        let tcx = self.tcx;
1499        // We need to do our own bounds-checks.
1500        let src_parts = self.get_ptr_access(src, size)?;
1501        let dest_parts = self.get_ptr_access(dest, size * num_copies)?; // `Size` multiplication
1502
1503        // Similar to `get_ptr_alloc`, we need to call `before_alloc_access` even for zero-sized
1504        // reads. However, just like in `get_ptr_alloc_mut`, the write part is okay to skip for
1505        // zero-sized writes.
1506        if let Ok((alloc_id, ..)) = self.ptr_try_get_alloc_id(src, size.bytes().try_into().unwrap())
1507        {
1508            M::before_alloc_access(tcx, &self.machine, alloc_id)?;
1509        }
1510
1511        // FIXME: we look up both allocations twice here, once before for the `check_ptr_access`
1512        // and once below to get the underlying `&[mut] Allocation`.
1513
1514        // Source alloc preparations and access hooks.
1515        let Some((src_alloc_id, src_offset, src_prov)) = src_parts else {
1516            // Zero-sized *source*, that means dest is also zero-sized and we have nothing to do.
1517            return interp_ok(());
1518        };
1519        let src_alloc = self.get_alloc_raw(src_alloc_id)?;
1520        let src_range = alloc_range(src_offset, size);
1521        if !!self.memory.ghost_mode.get() {
    {
        ::core::panicking::panic_fmt(format_args!("we can\'t be copying during validation"));
    }
};assert!(!self.memory.ghost_mode.get(), "we can't be copying during validation");
1522
1523        // Trigger read hook.
1524        // For the overlapping case, it is crucial that we trigger the read hook
1525        // before the write hook -- the aliasing model cares about the order.
1526        M::before_memory_read(
1527            tcx,
1528            &self.machine,
1529            &src_alloc.extra,
1530            src,
1531            (src_alloc_id, src_prov),
1532            src_range,
1533        )?;
1534        // We need the `dest` ptr for the next operation, so we get it now.
1535        // We already did the source checks and called the hooks so we are good to return early.
1536        let Some((dest_alloc_id, dest_offset, dest_prov)) = dest_parts else {
1537            // Zero-sized *destination*.
1538            return interp_ok(());
1539        };
1540
1541        // Prepare getting source provenance.
1542        let src_bytes = src_alloc.get_bytes_unchecked(src_range).as_ptr(); // raw ptr, so we can also get a ptr to the destination allocation
1543        // First copy the provenance to a temporary buffer, because
1544        // `get_bytes_unchecked_for_overwrite_ptr` will clear the provenance (in preparation for
1545        // inserting the new provenance), and that can overlap with the source range.
1546        let provenance = src_alloc.provenance_prepare_copy(src_range, self);
1547        // Prepare a copy of the initialization mask.
1548        let init = src_alloc.init_mask().prepare_copy(src_range);
1549
1550        // Destination alloc preparations...
1551        let (dest_alloc, machine) = self.get_alloc_raw_mut(dest_alloc_id)?;
1552        let dest_range = alloc_range(dest_offset, size * num_copies);
1553        // ...and access hooks.
1554        M::before_alloc_access(tcx, machine, dest_alloc_id)?;
1555        M::before_memory_write(
1556            tcx,
1557            machine,
1558            &mut dest_alloc.extra,
1559            dest,
1560            (dest_alloc_id, dest_prov),
1561            dest_range,
1562        )?;
1563        // Yes we do overwrite all bytes in `dest_bytes`.
1564        let dest_bytes =
1565            dest_alloc.get_bytes_unchecked_for_overwrite_ptr(&tcx, dest_range).as_mut_ptr();
1566
1567        if init.no_bytes_init() {
1568            // Fast path: If all bytes are `uninit` then there is nothing to copy. The target range
1569            // is marked as uninitialized but we otherwise omit changing the byte representation which may
1570            // be arbitrary for uninitialized bytes.
1571            // This also avoids writing to the target bytes so that the backing allocation is never
1572            // touched if the bytes stay uninitialized for the whole interpreter execution. On contemporary
1573            // operating system this can avoid physically allocating the page.
1574            dest_alloc.write_uninit(&tcx, dest_range);
1575            // `write_uninit` also resets the provenance, so we are done.
1576            return interp_ok(());
1577        }
1578
1579        // SAFE: The above indexing would have panicked if there weren't at least `size` bytes
1580        // behind `src` and `dest`. Also, we use the overlapping-safe `ptr::copy` if `src` and
1581        // `dest` could possibly overlap.
1582        // The pointers above remain valid even if the `HashMap` table is moved around because they
1583        // point into the `Vec` storing the bytes.
1584        unsafe {
1585            if src_alloc_id == dest_alloc_id {
1586                if nonoverlapping {
1587                    // `Size` additions
1588                    if (src_offset <= dest_offset && src_offset + size > dest_offset)
1589                        || (dest_offset <= src_offset && dest_offset + size > src_offset)
1590                    {
1591                        do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Ub(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("`copy_nonoverlapping` called on overlapping ranges"))
                })));throw_ub_format!("`copy_nonoverlapping` called on overlapping ranges");
1592                    }
1593                }
1594            }
1595            if num_copies > 1 {
1596                if !nonoverlapping {
    {
        ::core::panicking::panic_fmt(format_args!("multi-copy only supported in non-overlapping mode"));
    }
};assert!(nonoverlapping, "multi-copy only supported in non-overlapping mode");
1597            }
1598
1599            let size_in_bytes = size.bytes_usize();
1600            // For particularly large arrays (where this is perf-sensitive) it's common that
1601            // we're writing a single byte repeatedly. So, optimize that case to a memset.
1602            if size_in_bytes == 1 {
1603                if true {
    if !(num_copies >= 1) {
        ::core::panicking::panic("assertion failed: num_copies >= 1")
    };
};debug_assert!(num_copies >= 1); // we already handled the zero-sized cases above.
1604                // SAFETY: `src_bytes` would be read from anyway by `copy` below (num_copies >= 1).
1605                let value = *src_bytes;
1606                dest_bytes.write_bytes(value, (size * num_copies).bytes_usize());
1607            } else if src_alloc_id == dest_alloc_id {
1608                let mut dest_ptr = dest_bytes;
1609                for _ in 0..num_copies {
1610                    // Here we rely on `src` and `dest` being non-overlapping if there is more than
1611                    // one copy.
1612                    ptr::copy(src_bytes, dest_ptr, size_in_bytes);
1613                    dest_ptr = dest_ptr.add(size_in_bytes);
1614                }
1615            } else {
1616                let mut dest_ptr = dest_bytes;
1617                for _ in 0..num_copies {
1618                    ptr::copy_nonoverlapping(src_bytes, dest_ptr, size_in_bytes);
1619                    dest_ptr = dest_ptr.add(size_in_bytes);
1620                }
1621            }
1622        }
1623
1624        // now fill in all the "init" data
1625        dest_alloc.init_mask_apply_copy(
1626            init,
1627            alloc_range(dest_offset, size), // just a single copy (i.e., not full `dest_range`)
1628            num_copies,
1629        );
1630        // copy the provenance to the destination
1631        dest_alloc.provenance_apply_copy(provenance, alloc_range(dest_offset, size), num_copies);
1632
1633        interp_ok(())
1634    }
1635}
1636
1637/// Machine pointer introspection.
1638impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
1639    /// Test if this value might be null.
1640    /// If the machine does not support ptr-to-int casts, this is conservative.
1641    pub fn scalar_may_be_null(&self, scalar: Scalar<M::Provenance>) -> InterpResult<'tcx, bool> {
1642        match scalar.try_to_scalar_int() {
1643            Ok(int) => interp_ok(int.is_null()),
1644            Err(_) => {
1645                // We can't cast this pointer to an integer. Can only happen during CTFE.
1646                let ptr = scalar.to_pointer(self);
1647                match self.ptr_try_get_alloc_id(ptr, 0) {
1648                    Ok((alloc_id, offset, _)) => {
1649                        let info = self.get_alloc_info(alloc_id);
1650                        if info.kind == AllocKind::TypeId {
1651                            // We *could* actually precisely answer this question since here,
1652                            // the offset *is* the integer value. But the entire point of making
1653                            // this a pointer is not to leak the integer value, so we say everything
1654                            // might be null.
1655                            return interp_ok(true);
1656                        }
1657                        // If the pointer is in-bounds (including "at the end"), it is definitely not null.
1658                        if offset <= info.size {
1659                            return interp_ok(false);
1660                        }
1661                        // If the allocation is N-aligned, and the offset is not divisible by N,
1662                        // then `base + offset` has a non-zero remainder after division by `N`,
1663                        // which means `base + offset` cannot be null.
1664                        if !offset.bytes().is_multiple_of(info.align.bytes()) {
1665                            return interp_ok(false);
1666                        }
1667                        // We don't know enough, this might be null.
1668                        interp_ok(true)
1669                    }
1670                    Err(_offset) => bug_impl(None, format_args!("a non-int scalar is always a pointer"),
    Location::caller())bug!("a non-int scalar is always a pointer"),
1671                }
1672            }
1673        }
1674    }
1675
1676    /// Turning a "maybe pointer" into a proper pointer (and some information
1677    /// about where it points), or an absolute address.
1678    ///
1679    /// `size` says how many bytes of memory are expected at that pointer. This is largely only used
1680    /// for error messages; however, the *sign* of `size` can be used to disambiguate situations
1681    /// where a wildcard pointer sits right in between two allocations.
1682    /// It is almost always okay to just set the size to 0; this will be treated like a positive size
1683    /// for handling wildcard pointers.
1684    ///
1685    /// The result must be used immediately; it is not allowed to convert
1686    /// the returned data back into a `Pointer` and store that in machine state.
1687    /// (In fact that's not even possible since `M::ProvenanceExtra` is generic and
1688    /// we don't have an operation to turn it back into `M::Provenance`.)
1689    pub fn ptr_try_get_alloc_id(
1690        &self,
1691        ptr: Pointer<Option<M::Provenance>>,
1692        size: i64,
1693    ) -> Result<(AllocId, Size, M::ProvenanceExtra), u64> {
1694        match ptr.into_pointer_or_addr() {
1695            Ok(ptr) => match M::ptr_get_alloc(self, ptr, size) {
1696                Some((alloc_id, offset, extra)) => Ok((alloc_id, offset, extra)),
1697                None => {
1698                    if !M::Provenance::OFFSET_IS_ADDR {
    ::core::panicking::panic("assertion failed: M::Provenance::OFFSET_IS_ADDR")
};assert!(M::Provenance::OFFSET_IS_ADDR);
1699                    // Offset is absolute, as we just asserted.
1700                    let (_, addr) = ptr.into_raw_parts();
1701                    Err(addr.bytes())
1702                }
1703            },
1704            Err(addr) => Err(addr.bytes()),
1705        }
1706    }
1707
1708    /// Turning a "maybe pointer" into a proper pointer (and some information about where it points).
1709    ///
1710    /// `size` says how many bytes of memory are expected at that pointer. This is largely only used
1711    /// for error messages; however, the *sign* of `size` can be used to disambiguate situations
1712    /// where a wildcard pointer sits right in between two allocations.
1713    /// It is almost always okay to just set the size to 0; this will be treated like a positive size
1714    /// for handling wildcard pointers.
1715    ///
1716    /// The result must be used immediately; it is not allowed to convert
1717    /// the returned data back into a `Pointer` and store that in machine state.
1718    /// (In fact that's not even possible since `M::ProvenanceExtra` is generic and
1719    /// we don't have an operation to turn it back into `M::Provenance`.)
1720    #[inline(always)]
1721    pub fn ptr_get_alloc_id(
1722        &self,
1723        ptr: Pointer<Option<M::Provenance>>,
1724        size: i64,
1725    ) -> InterpResult<'tcx, (AllocId, Size, M::ProvenanceExtra)> {
1726        self.ptr_try_get_alloc_id(ptr, size)
1727            .map_err(|addr| {
1728                ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::DanglingIntPointer {
        addr,
        inbounds_size: size,
        msg: CheckInAllocMsg::Dereferenceable("pointer"),
    })err_ub!(DanglingIntPointer {
1729                    addr,
1730                    inbounds_size: size,
1731                    msg: CheckInAllocMsg::Dereferenceable("pointer")
1732                })
1733            })
1734            .into()
1735    }
1736}