Skip to main content

rustc_const_eval/interpret/
validity.rs

1//! Check the validity invariant of a given value, and tell the user
2//! where in the value it got violated.
3//! In const context, this goes even further and tries to approximate const safety.
4//! That's useful because it means other passes (e.g. promotion) can rely on `const`s
5//! to be const-safe.
6
7use std::borrow::Cow;
8use std::fmt::{self, Write};
9use std::hash::Hash;
10use std::mem;
11use std::num::NonZero;
12
13use either::{Left, Right};
14use hir::def::DefKind;
15use rustc_abi::{
16    BackendRepr, FieldIdx, FieldsShape, Scalar as ScalarAbi, Size, VariantIdx, Variants,
17    WrappingRange,
18};
19use rustc_ast::Mutability;
20use rustc_data_structures::fx::FxHashSet;
21use rustc_hir as hir;
22use rustc_middle::bug;
23use rustc_middle::mir::interpret::{
24    InterpErrorKind, InvalidMetaKind, Misalignment, Provenance, alloc_range, interp_ok,
25};
26use rustc_middle::ty::layout::{LayoutCx, TyAndLayout};
27use rustc_middle::ty::{self, Ty};
28use rustc_span::{Symbol, sym};
29use tracing::trace;
30
31use super::machine::AllocMap;
32use super::{
33    AllocId, CheckInAllocMsg, GlobalAlloc, ImmTy, Immediate, InterpCx, InterpResult, MPlaceTy,
34    Machine, MemPlaceMeta, PlaceTy, Pointer, Projectable, Scalar, ValueVisitor, err_ub,
35    format_interp_error,
36};
37use crate::enter_trace_span;
38
39// for the validation errors
40#[rustfmt::skip]
41use super::InterpErrorKind::UndefinedBehavior as Ub;
42use super::InterpErrorKind::Unsupported as Unsup;
43use super::UndefinedBehaviorInfo::*;
44use super::UnsupportedOpInfo::*;
45
46macro_rules! err_validation_failure {
47    ($where:expr,  $msg:expr ) => {{
48        let where_ = &$where;
49        let path = if !where_.projs.is_empty() {
50            let mut path = String::new();
51            write_path(&mut path, &where_.projs);
52            Some(path)
53        } else {
54            None
55        };
56
57        #[allow(unused)]
58        use ValidationErrorKind::*;
59        let msg = ValidationErrorKind::from($msg);
60        err_ub!(ValidationError {
61            orig_ty: where_.orig_ty,
62            path,
63            ptr_bytes_warning: msg.ptr_bytes_warning(),
64            msg: msg.to_string(),
65        })
66    }};
67}
68
69macro_rules! throw_validation_failure {
70    ($where:expr, $msg:expr ) => {
71        do yeet err_validation_failure!($where, $msg)
72    };
73}
74
75/// If $e throws an error matching the pattern, throw a validation failure.
76/// Other errors are passed back to the caller, unchanged -- and if they reach the root of
77/// the visitor, we make sure only validation errors and `InvalidProgram` errors are left.
78/// This lets you use the patterns as a kind of validation list, asserting which errors
79/// can possibly happen:
80///
81/// ```ignore(illustrative)
82/// let v = try_validation!(some_fn(x), some_path, {
83///     Foo | Bar | Baz => format!("some failure involving {x}"),
84/// });
85/// ```
86///
87/// The patterns must be of type `UndefinedBehaviorInfo`.
88macro_rules! try_validation {
89    ($e:expr, $where:expr,
90    $( $( $p:pat_param )|+ => $msg:expr ),+ $(,)?
91    ) => {{
92        $e.map_err_kind(|e| {
93            // We catch the error and turn it into a validation failure. We are okay with
94            // allocation here as this can only slow down builds that fail anyway.
95            match e {
96                $(
97                    $($p)|+ => {
98                        err_validation_failure!(
99                            $where,
100                            $msg
101                        )
102                    }
103                ),+,
104                e => e,
105            }
106        })?
107    }};
108}
109
110#[derive(#[automatically_derived]
impl ::core::fmt::Debug for PtrKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            PtrKind::Ref(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Ref",
                    &__self_0),
            PtrKind::Box => ::core::fmt::Formatter::write_str(f, "Box"),
        }
    }
}Debug, #[automatically_derived]
impl ::core::clone::Clone for PtrKind {
    #[inline]
    fn clone(&self) -> PtrKind {
        let _: ::core::clone::AssertParamIsClone<Mutability>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for PtrKind { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for PtrKind {
    #[inline]
    fn eq(&self, other: &PtrKind) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (PtrKind::Ref(__self_0), PtrKind::Ref(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for PtrKind {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Mutability>;
    }
}Eq)]
111enum PtrKind {
112    Ref(Mutability),
113    Box,
114}
115
116impl fmt::Display for PtrKind {
117    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118        let str = match self {
119            PtrKind::Ref(_) => "reference",
120            PtrKind::Box => "box",
121        };
122        f.write_fmt(format_args!("{0}", str))write!(f, "{str}")
123    }
124}
125
126#[derive(#[automatically_derived]
impl ::core::fmt::Debug for ExpectedKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                ExpectedKind::Reference => "Reference",
                ExpectedKind::Box => "Box",
                ExpectedKind::RawPtr => "RawPtr",
                ExpectedKind::Bool => "Bool",
                ExpectedKind::Char => "Char",
                ExpectedKind::Float => "Float",
                ExpectedKind::Int => "Int",
                ExpectedKind::FnPtr => "FnPtr",
                ExpectedKind::Str => "Str",
            })
    }
}Debug)]
127enum ExpectedKind {
128    Reference,
129    Box,
130    RawPtr,
131    Bool,
132    Char,
133    Float,
134    Int,
135    FnPtr,
136    Str,
137}
138
139impl fmt::Display for ExpectedKind {
140    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
141        let str = match self {
142            ExpectedKind::Reference => "expected a reference",
143            ExpectedKind::Box => "expected a box",
144            ExpectedKind::RawPtr => "expected a raw pointer",
145            ExpectedKind::Bool => "expected a boolean",
146            ExpectedKind::Char => "expected a unicode scalar value",
147            ExpectedKind::Float => "expected a floating point number",
148            ExpectedKind::Int => "expected an integer",
149            ExpectedKind::FnPtr => "expected a function pointer",
150            ExpectedKind::Str => "expected a string",
151        };
152        f.write_fmt(format_args!("{0}", str))write!(f, "{str}")
153    }
154}
155
156impl From<PtrKind> for ExpectedKind {
157    fn from(x: PtrKind) -> ExpectedKind {
158        match x {
159            PtrKind::Box => ExpectedKind::Box,
160            PtrKind::Ref(_) => ExpectedKind::Reference,
161        }
162    }
163}
164
165/// Validation errors that can be emitted in one than one place get a variant here so that
166/// we format them consistently. Everything else uses the `String` fallback.
167#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for ValidationErrorKind<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            ValidationErrorKind::Uninit { expected: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Uninit", "expected", &__self_0),
            ValidationErrorKind::PointerAsInt { expected: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "PointerAsInt", "expected", &__self_0),
            ValidationErrorKind::PartialPointer =>
                ::core::fmt::Formatter::write_str(f, "PartialPointer"),
            ValidationErrorKind::InvalidMetaWrongTrait {
                vtable_dyn_type: __self_0, expected_dyn_type: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "InvalidMetaWrongTrait", "vtable_dyn_type", __self_0,
                    "expected_dyn_type", &__self_1),
            ValidationErrorKind::GeneralError { msg: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "GeneralError", "msg", &__self_0),
        }
    }
}Debug)]
168enum ValidationErrorKind<'tcx> {
169    Uninit {
170        expected: ExpectedKind,
171    },
172    PointerAsInt {
173        expected: ExpectedKind,
174    },
175    PartialPointer,
176    InvalidMetaWrongTrait {
177        /// The vtable that was actually referenced by the wide pointer metadata.
178        vtable_dyn_type: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
179        /// The vtable that was expected at the point in MIR that it was accessed.
180        expected_dyn_type: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
181    },
182    GeneralError {
183        msg: String,
184    },
185}
186
187impl<'tcx> ValidationErrorKind<'tcx> {
188    // We don't do this via `fmt::Display` to so that we can do a move in the `GeneralError` case.
189    fn to_string(self) -> String {
190        use ValidationErrorKind::*;
191        match self {
192            Uninit { expected } => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("encountered uninitialized memory, but {0}",
                expected))
    })format!("encountered uninitialized memory, but {expected}"),
193            PointerAsInt { expected } => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("encountered a pointer, but {0}",
                expected))
    })format!("encountered a pointer, but {expected}"),
194            PartialPointer => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("encountered a partial pointer or a mix of pointers"))
    })format!("encountered a partial pointer or a mix of pointers"),
195            InvalidMetaWrongTrait { vtable_dyn_type, expected_dyn_type } => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("wrong trait in wide pointer vtable: expected `{0}`, but encountered `{1}`",
                expected_dyn_type, vtable_dyn_type))
    })format!(
196                "wrong trait in wide pointer vtable: expected `{expected_dyn_type}`, but encountered `{vtable_dyn_type}`"
197            ),
198            GeneralError { msg } => msg,
199        }
200    }
201
202    fn ptr_bytes_warning(&self) -> bool {
203        use ValidationErrorKind::*;
204        #[allow(non_exhaustive_omitted_patterns)] match self {
    PointerAsInt { .. } | PartialPointer => true,
    _ => false,
}matches!(self, PointerAsInt { .. } | PartialPointer)
205    }
206}
207
208impl<'tcx> From<String> for ValidationErrorKind<'tcx> {
209    fn from(msg: String) -> Self {
210        ValidationErrorKind::GeneralError { msg }
211    }
212}
213
214fn fmt_range(r: WrappingRange, max_hi: u128) -> String {
215    let WrappingRange { start: lo, end: hi } = r;
216    if !(hi <= max_hi) {
    ::core::panicking::panic("assertion failed: hi <= max_hi")
};assert!(hi <= max_hi);
217    if lo > hi {
218        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("less or equal to {0}, or greater or equal to {1}",
                hi, lo))
    })format!("less or equal to {hi}, or greater or equal to {lo}")
219    } else if lo == hi {
220        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("equal to {0}", lo))
    })format!("equal to {lo}")
221    } else if lo == 0 {
222        if !(hi < max_hi) {
    {
        ::core::panicking::panic_fmt(format_args!("should not be printing if the range covers everything"));
    }
};assert!(hi < max_hi, "should not be printing if the range covers everything");
223        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("less or equal to {0}", hi))
    })format!("less or equal to {hi}")
224    } else if hi == max_hi {
225        if !(lo > 0) {
    {
        ::core::panicking::panic_fmt(format_args!("should not be printing if the range covers everything"));
    }
};assert!(lo > 0, "should not be printing if the range covers everything");
226        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("greater or equal to {0}", lo))
    })format!("greater or equal to {lo}")
227    } else {
228        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("in the range {0}..={1}", lo, hi))
    })format!("in the range {lo}..={hi}")
229    }
230}
231
232/// We want to show a nice path to the invalid field for diagnostics,
233/// but avoid string operations in the happy case where no error happens.
234/// So we track a `Vec<PathElem>` where `PathElem` contains all the data we
235/// need to later print something for the user.
236#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for PathElem<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for PathElem<'tcx> {
    #[inline]
    fn clone(&self) -> PathElem<'tcx> {
        let _: ::core::clone::AssertParamIsClone<Symbol>;
        let _: ::core::clone::AssertParamIsClone<VariantIdx>;
        let _: ::core::clone::AssertParamIsClone<usize>;
        let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for PathElem<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            PathElem::Field(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Field",
                    &__self_0),
            PathElem::Variant(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Variant", &__self_0),
            PathElem::CoroutineState(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "CoroutineState", &__self_0),
            PathElem::CapturedVar(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "CapturedVar", &__self_0),
            PathElem::ArrayElem(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "ArrayElem", &__self_0),
            PathElem::TupleElem(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "TupleElem", &__self_0),
            PathElem::Deref => ::core::fmt::Formatter::write_str(f, "Deref"),
            PathElem::EnumTag =>
                ::core::fmt::Formatter::write_str(f, "EnumTag"),
            PathElem::CoroutineTag =>
                ::core::fmt::Formatter::write_str(f, "CoroutineTag"),
            PathElem::DynDowncast(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "DynDowncast", &__self_0),
            PathElem::Vtable =>
                ::core::fmt::Formatter::write_str(f, "Vtable"),
        }
    }
}Debug)]
237pub enum PathElem<'tcx> {
238    Field(Symbol),
239    Variant(Symbol),
240    CoroutineState(VariantIdx),
241    CapturedVar(Symbol),
242    ArrayElem(usize),
243    TupleElem(usize),
244    Deref,
245    EnumTag,
246    CoroutineTag,
247    DynDowncast(Ty<'tcx>),
248    Vtable,
249}
250
251#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for Path<'tcx> {
    #[inline]
    fn clone(&self) -> Path<'tcx> {
        Path {
            orig_ty: ::core::clone::Clone::clone(&self.orig_ty),
            projs: ::core::clone::Clone::clone(&self.projs),
        }
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for Path<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "Path",
            "orig_ty", &self.orig_ty, "projs", &&self.projs)
    }
}Debug)]
252pub struct Path<'tcx> {
253    orig_ty: Ty<'tcx>,
254    projs: Vec<PathElem<'tcx>>,
255}
256
257impl<'tcx> Path<'tcx> {
258    fn new(ty: Ty<'tcx>) -> Self {
259        Self { orig_ty: ty, projs: ::alloc::vec::Vec::new()vec![] }
260    }
261}
262
263/// Extra things to check for during validation of CTFE results.
264#[derive(#[automatically_derived]
impl ::core::marker::Copy for CtfeValidationMode { }Copy, #[automatically_derived]
impl ::core::clone::Clone for CtfeValidationMode {
    #[inline]
    fn clone(&self) -> CtfeValidationMode {
        let _: ::core::clone::AssertParamIsClone<Mutability>;
        let _: ::core::clone::AssertParamIsClone<bool>;
        *self
    }
}Clone)]
265pub enum CtfeValidationMode {
266    /// Validation of a `static`
267    Static { mutbl: Mutability },
268    /// Validation of a promoted.
269    Promoted,
270    /// Validation of a `const`.
271    /// `allow_immutable_unsafe_cell` says whether we allow `UnsafeCell` in immutable memory (which is the
272    /// case for the top-level allocation of a `const`, where this is fine because the allocation will be
273    /// copied at each use site).
274    Const { allow_immutable_unsafe_cell: bool },
275}
276
277impl CtfeValidationMode {
278    fn allow_immutable_unsafe_cell(self) -> bool {
279        match self {
280            CtfeValidationMode::Static { .. } => false,
281            CtfeValidationMode::Promoted { .. } => false,
282            CtfeValidationMode::Const { allow_immutable_unsafe_cell, .. } => {
283                allow_immutable_unsafe_cell
284            }
285        }
286    }
287}
288
289/// State for tracking recursive validation of references
290pub struct RefTracking<T, PATH = ()> {
291    seen: FxHashSet<T>,
292    todo: Vec<(T, PATH)>,
293}
294
295impl<T: Clone + Eq + Hash + std::fmt::Debug, PATH> RefTracking<T, PATH> {
296    pub fn empty() -> Self {
297        RefTracking { seen: FxHashSet::default(), todo: ::alloc::vec::Vec::new()vec![] }
298    }
299    pub fn next(&mut self) -> Option<(T, PATH)> {
300        self.todo.pop()
301    }
302
303    fn track(&mut self, val: T, path: impl FnOnce() -> PATH) {
304        if self.seen.insert(val.clone()) {
305            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_const_eval/src/interpret/validity.rs:305",
                        "rustc_const_eval::interpret::validity",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/validity.rs"),
                        ::tracing_core::__macro_support::Option::Some(305u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::validity"),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("Recursing below ptr {0:#?}",
                                                    val) as &dyn Value))])
            });
    } else { ; }
};trace!("Recursing below ptr {:#?}", val);
306            let path = path();
307            // Remember to come back to this later.
308            self.todo.push((val, path));
309        }
310    }
311}
312
313impl<'tcx, T: Clone + Eq + Hash + std::fmt::Debug> RefTracking<T, Path<'tcx>> {
314    pub fn new(val: T, ty: Ty<'tcx>) -> Self {
315        let mut ref_tracking_for_consts =
316            RefTracking { seen: FxHashSet::default(), todo: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(val.clone(), Path::new(ty))]))vec![(val.clone(), Path::new(ty))] };
317        ref_tracking_for_consts.seen.insert(val);
318        ref_tracking_for_consts
319    }
320}
321
322/// Format a path
323fn write_path(out: &mut String, path: &[PathElem<'_>]) {
324    use self::PathElem::*;
325
326    for elem in path.iter() {
327        match elem {
328            Field(name) => out.write_fmt(format_args!(".{0}", name))write!(out, ".{name}"),
329            EnumTag => out.write_fmt(format_args!(".<enum-tag>"))write!(out, ".<enum-tag>"),
330            Variant(name) => out.write_fmt(format_args!(".<enum-variant({0})>", name))write!(out, ".<enum-variant({name})>"),
331            CoroutineTag => out.write_fmt(format_args!(".<coroutine-tag>"))write!(out, ".<coroutine-tag>"),
332            CoroutineState(idx) => out.write_fmt(format_args!(".<coroutine-state({0})>", idx.index()))write!(out, ".<coroutine-state({})>", idx.index()),
333            CapturedVar(name) => out.write_fmt(format_args!(".<captured-var({0})>", name))write!(out, ".<captured-var({name})>"),
334            TupleElem(idx) => out.write_fmt(format_args!(".{0}", idx))write!(out, ".{idx}"),
335            ArrayElem(idx) => out.write_fmt(format_args!("[{0}]", idx))write!(out, "[{idx}]"),
336            // `.<deref>` does not match Rust syntax, but it is more readable for long paths -- and
337            // some of the other items here also are not Rust syntax. Actually we can't
338            // even use the usual syntax because we are just showing the projections,
339            // not the root.
340            Deref => out.write_fmt(format_args!(".<deref>"))write!(out, ".<deref>"),
341            DynDowncast(ty) => out.write_fmt(format_args!(".<dyn-downcast({0})>", ty))write!(out, ".<dyn-downcast({ty})>"),
342            Vtable => out.write_fmt(format_args!(".<vtable>"))write!(out, ".<vtable>"),
343        }
344        .unwrap()
345    }
346}
347
348pub type RangeSet = rustc_data_structures::range_set::RangeSet<Size>;
349
350struct ValidityVisitor<'rt, 'tcx, M: Machine<'tcx>> {
351    /// The `path` may be pushed to, but the part that is present when a function
352    /// starts must not be changed!  `with_elem` relies on this stack discipline.
353    path: Path<'tcx>,
354    ref_tracking: Option<&'rt mut RefTracking<MPlaceTy<'tcx, M::Provenance>, Path<'tcx>>>,
355    /// `None` indicates this is not validating for CTFE (but for runtime).
356    ctfe_mode: Option<CtfeValidationMode>,
357    ecx: &'rt mut InterpCx<'tcx, M>,
358    /// Whether provenance should be reset outside of pointers (emulating the effect of a typed
359    /// copy).
360    reset_provenance_and_padding: bool,
361    /// This tracks which byte ranges in this value contain data; the remaining bytes are padding.
362    /// The ideal representation here would be pointer-length pairs, but to keep things more compact
363    /// we only store a (range) set of offsets -- the base pointer is the same throughout the entire
364    /// visit, after all.
365    /// If this is `Some`, then `reset_provenance_and_padding` must be true (but not vice versa:
366    /// we might not track data vs padding bytes if the operand isn't stored in memory anyway).
367    data_bytes: Option<RangeSet>,
368    /// True if we are inside of `MaybeDangling`. This disables pointer access checks.
369    may_dangle: bool,
370}
371
372impl<'rt, 'tcx, M: Machine<'tcx>> ValidityVisitor<'rt, 'tcx, M> {
373    fn aggregate_field_path_elem(
374        &mut self,
375        layout: TyAndLayout<'tcx>,
376        field: usize,
377        field_ty: Ty<'tcx>,
378    ) -> PathElem<'tcx> {
379        // First, check if we are projecting to a variant.
380        match layout.variants {
381            Variants::Multiple { tag_field, .. } => {
382                if tag_field.as_usize() == field {
383                    return match layout.ty.kind() {
384                        ty::Adt(def, ..) if def.is_enum() => PathElem::EnumTag,
385                        ty::Coroutine(..) => PathElem::CoroutineTag,
386                        _ => ::rustc_middle::util::bug::bug_fmt(format_args!("non-variant type {0:?}",
        layout.ty))bug!("non-variant type {:?}", layout.ty),
387                    };
388                }
389            }
390            Variants::Single { .. } | Variants::Empty => {}
391        }
392
393        // Now we know we are projecting to a field, so figure out which one.
394        match layout.ty.kind() {
395            // coroutines, closures, and coroutine-closures all have upvars that may be named.
396            ty::Closure(def_id, _) | ty::Coroutine(def_id, _) | ty::CoroutineClosure(def_id, _) => {
397                let mut name = None;
398                // FIXME this should be more descriptive i.e. CapturePlace instead of CapturedVar
399                // https://github.com/rust-lang/project-rfc-2229/issues/46
400                if let Some(local_def_id) = def_id.as_local() {
401                    let captures = self.ecx.tcx.closure_captures(local_def_id);
402                    if let Some(captured_place) = captures.get(field) {
403                        // Sometimes the index is beyond the number of upvars (seen
404                        // for a coroutine).
405                        let var_hir_id = captured_place.get_root_variable();
406                        let node = self.ecx.tcx.hir_node(var_hir_id);
407                        if let hir::Node::Pat(pat) = node
408                            && let hir::PatKind::Binding(_, _, ident, _) = pat.kind
409                        {
410                            name = Some(ident.name);
411                        }
412                    }
413                }
414
415                PathElem::CapturedVar(name.unwrap_or_else(|| {
416                    // Fall back to showing the field index.
417                    sym::integer(field)
418                }))
419            }
420
421            // tuples
422            ty::Tuple(_) => PathElem::TupleElem(field),
423
424            // enums
425            ty::Adt(def, ..) if def.is_enum() => {
426                // we might be projecting *to* a variant, or to a field *in* a variant.
427                match layout.variants {
428                    Variants::Single { index } => {
429                        // Inside a variant
430                        PathElem::Field(def.variant(index).fields[FieldIdx::from_usize(field)].name)
431                    }
432                    Variants::Empty => {
    ::core::panicking::panic_fmt(format_args!("there is no field in Variants::Empty types"));
}panic!("there is no field in Variants::Empty types"),
433                    Variants::Multiple { .. } => ::rustc_middle::util::bug::bug_fmt(format_args!("we handled variants above"))bug!("we handled variants above"),
434                }
435            }
436
437            // other ADTs
438            ty::Adt(def, _) => {
439                PathElem::Field(def.non_enum_variant().fields[FieldIdx::from_usize(field)].name)
440            }
441
442            // arrays/slices
443            ty::Array(..) | ty::Slice(..) => PathElem::ArrayElem(field),
444
445            // dyn traits
446            ty::Dynamic(..) => {
447                {
    match (&field, &0) {
        (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::None);
            }
        }
    }
};assert_eq!(field, 0);
448                PathElem::DynDowncast(field_ty)
449            }
450
451            // nothing else has an aggregate layout
452            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("aggregate_field_path_elem: got non-aggregate type {0:?}",
        layout.ty))bug!("aggregate_field_path_elem: got non-aggregate type {:?}", layout.ty),
453        }
454    }
455
456    fn with_elem<R>(
457        &mut self,
458        elem: PathElem<'tcx>,
459        f: impl FnOnce(&mut Self) -> InterpResult<'tcx, R>,
460    ) -> InterpResult<'tcx, R> {
461        // Remember the old state
462        let path_len = self.path.projs.len();
463        // Record new element
464        self.path.projs.push(elem);
465        // Perform operation
466        let r = f(self)?;
467        // Undo changes
468        self.path.projs.truncate(path_len);
469        // Done
470        interp_ok(r)
471    }
472
473    fn read_immediate(
474        &self,
475        val: &PlaceTy<'tcx, M::Provenance>,
476        expected: ExpectedKind,
477    ) -> InterpResult<'tcx, ImmTy<'tcx, M::Provenance>> {
478        interp_ok({
    self.ecx.read_immediate(val).map_err_kind(|e|
                {
                    match e {
                        Ub(InvalidUninitBytes(_)) => {
                            {
                                let where_ = &self.path;
                                let path =
                                    if !where_.projs.is_empty() {
                                        let mut path = String::new();
                                        write_path(&mut path, &where_.projs);
                                        Some(path)
                                    } else { None };
                                #[allow(unused)]
                                use ValidationErrorKind::*;
                                let msg = ValidationErrorKind::from(Uninit { expected });
                                ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
                                        orig_ty: where_.orig_ty,
                                        path,
                                        ptr_bytes_warning: msg.ptr_bytes_warning(),
                                        msg: msg.to_string(),
                                    })
                            }
                        }
                        Unsup(ReadPointerAsInt(_)) => {
                            {
                                let where_ = &self.path;
                                let path =
                                    if !where_.projs.is_empty() {
                                        let mut path = String::new();
                                        write_path(&mut path, &where_.projs);
                                        Some(path)
                                    } else { None };
                                #[allow(unused)]
                                use ValidationErrorKind::*;
                                let msg =
                                    ValidationErrorKind::from(PointerAsInt { expected });
                                ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
                                        orig_ty: where_.orig_ty,
                                        path,
                                        ptr_bytes_warning: msg.ptr_bytes_warning(),
                                        msg: msg.to_string(),
                                    })
                            }
                        }
                        Unsup(ReadPartialPointer(_)) => {
                            {
                                let where_ = &self.path;
                                let path =
                                    if !where_.projs.is_empty() {
                                        let mut path = String::new();
                                        write_path(&mut path, &where_.projs);
                                        Some(path)
                                    } else { None };
                                #[allow(unused)]
                                use ValidationErrorKind::*;
                                let msg = ValidationErrorKind::from(PartialPointer);
                                ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
                                        orig_ty: where_.orig_ty,
                                        path,
                                        ptr_bytes_warning: msg.ptr_bytes_warning(),
                                        msg: msg.to_string(),
                                    })
                            }
                        }
                        e => e,
                    }
                })?
}try_validation!(
479            self.ecx.read_immediate(val),
480            self.path,
481            Ub(InvalidUninitBytes(_)) =>
482                Uninit { expected },
483            // The `Unsup` cases can only occur during CTFE
484            Unsup(ReadPointerAsInt(_)) =>
485                PointerAsInt { expected },
486            Unsup(ReadPartialPointer(_)) =>
487                PartialPointer,
488        ))
489    }
490
491    fn read_scalar(
492        &self,
493        val: &PlaceTy<'tcx, M::Provenance>,
494        expected: ExpectedKind,
495    ) -> InterpResult<'tcx, Scalar<M::Provenance>> {
496        interp_ok(self.read_immediate(val, expected)?.to_scalar())
497    }
498
499    /// Given a place and a pointer loaded from that place, ensure that the place does
500    /// not store any more provenance than the pointer does. IOW, if any provenance
501    /// was discarded when loading the pointer, it will also get discarded in-memory.
502    fn reset_pointer_provenance(
503        &mut self,
504        place: &PlaceTy<'tcx, M::Provenance>,
505        ptr: &ImmTy<'tcx, M::Provenance>,
506    ) -> InterpResult<'tcx> {
507        if #[allow(non_exhaustive_omitted_patterns)] match ptr.layout.backend_repr {
    BackendRepr::Scalar(..) => true,
    _ => false,
}matches!(ptr.layout.backend_repr, BackendRepr::Scalar(..)) {
508            // A thin pointer. If it has provenance, we don't have to do anything.
509            // If it does not, ensure we clear the provenance in memory.
510            if !#[allow(non_exhaustive_omitted_patterns)] match ptr.to_scalar() {
    Scalar::Ptr(..) => true,
    _ => false,
}matches!(ptr.to_scalar(), Scalar::Ptr(..)) {
511                // The loaded pointer has no provenance. Some bytes of its representation still
512                // might have provenance, which we have to clear.
513                self.ecx.clear_provenance(place)?;
514            }
515        } else {
516            // A wide pointer. This means we have to worry both about the pointer itself and the
517            // metadata. We do the lazy thing and just write back the value we got. Just
518            // clearing provenance in a targeted manner would be more efficient, but unless this
519            // is a perf hotspot it's just not worth the effort.
520            self.ecx.write_immediate_no_validate(**ptr, place)?;
521        }
522        interp_ok(())
523    }
524
525    fn check_wide_ptr_meta(
526        &mut self,
527        meta: MemPlaceMeta<M::Provenance>,
528        pointee: TyAndLayout<'tcx>,
529    ) -> InterpResult<'tcx> {
530        let tail = self.ecx.tcx.struct_tail_for_codegen(pointee.ty, self.ecx.typing_env);
531        match tail.kind() {
532            ty::Dynamic(data, _) => {
533                let vtable = meta.unwrap_meta().to_pointer(self.ecx)?;
534                // Make sure it is a genuine vtable pointer for the right trait.
535                {
    self.ecx.get_ptr_vtable_ty(vtable,
                Some(data)).map_err_kind(|e|
                {
                    match e {
                        Ub(DanglingIntPointer { .. } | InvalidVTablePointer(..)) =>
                            {
                            {
                                let where_ = &self.path;
                                let path =
                                    if !where_.projs.is_empty() {
                                        let mut path = String::new();
                                        write_path(&mut path, &where_.projs);
                                        Some(path)
                                    } else { None };
                                #[allow(unused)]
                                use ValidationErrorKind::*;
                                let msg =
                                    ValidationErrorKind::from(::alloc::__export::must_use({
                                                ::alloc::fmt::format(format_args!("encountered {0}, but expected a vtable pointer",
                                                        vtable))
                                            }));
                                ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
                                        orig_ty: where_.orig_ty,
                                        path,
                                        ptr_bytes_warning: msg.ptr_bytes_warning(),
                                        msg: msg.to_string(),
                                    })
                            }
                        }
                        Ub(InvalidVTableTrait { vtable_dyn_type, expected_dyn_type
                            }) => {
                            {
                                let where_ = &self.path;
                                let path =
                                    if !where_.projs.is_empty() {
                                        let mut path = String::new();
                                        write_path(&mut path, &where_.projs);
                                        Some(path)
                                    } else { None };
                                #[allow(unused)]
                                use ValidationErrorKind::*;
                                let msg =
                                    ValidationErrorKind::from(InvalidMetaWrongTrait {
                                            expected_dyn_type,
                                            vtable_dyn_type,
                                        });
                                ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
                                        orig_ty: where_.orig_ty,
                                        path,
                                        ptr_bytes_warning: msg.ptr_bytes_warning(),
                                        msg: msg.to_string(),
                                    })
                            }
                        }
                        e => e,
                    }
                })?
};try_validation!(
536                    self.ecx.get_ptr_vtable_ty(vtable, Some(data)),
537                    self.path,
538                    Ub(DanglingIntPointer{ .. } | InvalidVTablePointer(..)) =>
539                        format!("encountered {vtable}, but expected a vtable pointer"),
540                    Ub(InvalidVTableTrait { vtable_dyn_type, expected_dyn_type }) =>
541                        InvalidMetaWrongTrait { expected_dyn_type, vtable_dyn_type },
542                );
543            }
544            ty::Slice(..) | ty::Str => {
545                let _len = meta.unwrap_meta().to_target_usize(self.ecx)?;
546                // We do not check that `len * elem_size <= isize::MAX`:
547                // that is only required for references, and there it falls out of the
548                // "dereferenceable" check performed by Stacked Borrows.
549            }
550            ty::Foreign(..) => {
551                // Unsized, but not wide.
552            }
553            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("Unexpected unsized type tail: {0:?}",
        tail))bug!("Unexpected unsized type tail: {:?}", tail),
554        }
555
556        interp_ok(())
557    }
558
559    /// Check a reference or `Box`.
560    ///
561    /// `ty` is the actual type of `value`; for a Box, `value` will be just the inner raw pointer.
562    fn check_safe_pointer(
563        &mut self,
564        value: &PlaceTy<'tcx, M::Provenance>,
565        ty: Ty<'tcx>,
566        ptr_kind: PtrKind,
567    ) -> InterpResult<'tcx> {
568        let ptr = self.read_immediate(value, ptr_kind.into())?;
569        if self.reset_provenance_and_padding {
570            // There's no padding in a pointer.
571            self.add_data_range_place(value);
572            // Resetting provenance is done below, together with retagging, to avoid
573            // redundant writes.
574        }
575        let place = self.ecx.imm_ptr_to_mplace(&ptr)?;
576        // Handle wide pointers.
577        // Check metadata early, for better diagnostics
578        if place.layout.is_unsized() {
579            self.check_wide_ptr_meta(place.meta(), place.layout)?;
580        }
581
582        // Determine size and alignment of pointee.
583        let size_and_align = {
    self.ecx.size_and_align_of_val(&place).map_err_kind(|e|
                {
                    match e {
                        Ub(InvalidMeta(msg)) => {
                            {
                                let where_ = &self.path;
                                let path =
                                    if !where_.projs.is_empty() {
                                        let mut path = String::new();
                                        write_path(&mut path, &where_.projs);
                                        Some(path)
                                    } else { None };
                                #[allow(unused)]
                                use ValidationErrorKind::*;
                                let msg =
                                    ValidationErrorKind::from(::alloc::__export::must_use({
                                                ::alloc::fmt::format(format_args!("encountered invalid {1} metadata: {0}",
                                                        match msg {
                                                            InvalidMetaKind::SliceTooBig =>
                                                                "slice is bigger than largest supported object",
                                                            InvalidMetaKind::TooBig =>
                                                                "total size is bigger than largest supported object",
                                                        }, ptr_kind))
                                            }));
                                ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
                                        orig_ty: where_.orig_ty,
                                        path,
                                        ptr_bytes_warning: msg.ptr_bytes_warning(),
                                        msg: msg.to_string(),
                                    })
                            }
                        }
                        e => e,
                    }
                })?
}try_validation!(
584            self.ecx.size_and_align_of_val(&place),
585            self.path,
586            Ub(InvalidMeta(msg)) => format!(
587                "encountered invalid {ptr_kind} metadata: {}",
588                match msg {
589                    InvalidMetaKind::SliceTooBig => "slice is bigger than largest supported object",
590                    InvalidMetaKind::TooBig => "total size is bigger than largest supported object",
591                }
592            )
593        );
594        let (size, align) = size_and_align
595            // for the purpose of validity, consider foreign types to have
596            // alignment and size determined by the layout (size will be 0,
597            // alignment should take attributes into account).
598            .unwrap_or_else(|| (place.layout.size, place.layout.align.abi));
599
600        // If we're not allow to dangle, make sure this is dereferenceable and retag it for
601        // the aliasing model.
602        let adjusted_ptr = if !self.may_dangle {
603            {
    self.ecx.check_ptr_access(place.ptr(), size,
                CheckInAllocMsg::Dereferenceable).map_err_kind(|e|
                {
                    match e {
                        Ub(DanglingIntPointer { addr: 0, .. }) => {
                            {
                                let where_ = &self.path;
                                let path =
                                    if !where_.projs.is_empty() {
                                        let mut path = String::new();
                                        write_path(&mut path, &where_.projs);
                                        Some(path)
                                    } else { None };
                                #[allow(unused)]
                                use ValidationErrorKind::*;
                                let msg =
                                    ValidationErrorKind::from(::alloc::__export::must_use({
                                                ::alloc::fmt::format(format_args!("encountered a null {0}",
                                                        ptr_kind))
                                            }));
                                ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
                                        orig_ty: where_.orig_ty,
                                        path,
                                        ptr_bytes_warning: msg.ptr_bytes_warning(),
                                        msg: msg.to_string(),
                                    })
                            }
                        }
                        Ub(DanglingIntPointer { addr: i, .. }) => {
                            {
                                let where_ = &self.path;
                                let path =
                                    if !where_.projs.is_empty() {
                                        let mut path = String::new();
                                        write_path(&mut path, &where_.projs);
                                        Some(path)
                                    } else { None };
                                #[allow(unused)]
                                use ValidationErrorKind::*;
                                let msg =
                                    ValidationErrorKind::from(::alloc::__export::must_use({
                                                ::alloc::fmt::format(format_args!("encountered a dangling {1} ({0} has no provenance)",
                                                        Pointer::<Option<AllocId>>::without_provenance(i),
                                                        ptr_kind))
                                            }));
                                ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
                                        orig_ty: where_.orig_ty,
                                        path,
                                        ptr_bytes_warning: msg.ptr_bytes_warning(),
                                        msg: msg.to_string(),
                                    })
                            }
                        }
                        Ub(PointerOutOfBounds { .. }) => {
                            {
                                let where_ = &self.path;
                                let path =
                                    if !where_.projs.is_empty() {
                                        let mut path = String::new();
                                        write_path(&mut path, &where_.projs);
                                        Some(path)
                                    } else { None };
                                #[allow(unused)]
                                use ValidationErrorKind::*;
                                let msg =
                                    ValidationErrorKind::from(::alloc::__export::must_use({
                                                ::alloc::fmt::format(format_args!("encountered a dangling {0} (going beyond the bounds of its allocation)",
                                                        ptr_kind))
                                            }));
                                ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
                                        orig_ty: where_.orig_ty,
                                        path,
                                        ptr_bytes_warning: msg.ptr_bytes_warning(),
                                        msg: msg.to_string(),
                                    })
                            }
                        }
                        Ub(PointerUseAfterFree(..)) => {
                            {
                                let where_ = &self.path;
                                let path =
                                    if !where_.projs.is_empty() {
                                        let mut path = String::new();
                                        write_path(&mut path, &where_.projs);
                                        Some(path)
                                    } else { None };
                                #[allow(unused)]
                                use ValidationErrorKind::*;
                                let msg =
                                    ValidationErrorKind::from(::alloc::__export::must_use({
                                                ::alloc::fmt::format(format_args!("encountered a dangling {0} (use-after-free)",
                                                        ptr_kind))
                                            }));
                                ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
                                        orig_ty: where_.orig_ty,
                                        path,
                                        ptr_bytes_warning: msg.ptr_bytes_warning(),
                                        msg: msg.to_string(),
                                    })
                            }
                        }
                        e => e,
                    }
                })?
};try_validation!(
604                self.ecx.check_ptr_access(
605                    place.ptr(),
606                    size,
607                    CheckInAllocMsg::Dereferenceable, // will anyway be replaced by validity message
608                ),
609                self.path,
610                Ub(DanglingIntPointer { addr: 0, .. }) =>
611                    format!("encountered a null {ptr_kind}"),
612                Ub(DanglingIntPointer { addr: i, .. }) =>
613                    format!(
614                        "encountered a dangling {ptr_kind} ({ptr} has no provenance)",
615                        ptr = Pointer::<Option<AllocId>>::without_provenance(i)
616                    ),
617                Ub(PointerOutOfBounds { .. }) =>
618                    format!("encountered a dangling {ptr_kind} (going beyond the bounds of its allocation)"),
619                Ub(PointerUseAfterFree(..)) =>
620                    format!("encountered a dangling {ptr_kind} (use-after-free)"),
621            );
622            if self.reset_provenance_and_padding {
623                M::retag_ptr_value(self.ecx, &ptr, ty).map_err_kind(|e| match e {
624                    Ub(WriteToReadOnly(_)) => {
625                        {
    let where_ = &self.path;
    let path =
        if !where_.projs.is_empty() {
            let mut path = String::new();
            write_path(&mut path, &where_.projs);
            Some(path)
        } else { None };
    #[allow(unused)]
    use ValidationErrorKind::*;
    let msg =
        ValidationErrorKind::from(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("encountered {0} pointing to read-only memory",
                            if ptr_kind == PtrKind::Box {
                                "box"
                            } else { "mutable reference" }))
                }));
    ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
            orig_ty: where_.orig_ty,
            path,
            ptr_bytes_warning: msg.ptr_bytes_warning(),
            msg: msg.to_string(),
        })
}err_validation_failure!(
626                            self.path,
627                            format!(
628                                "encountered {} pointing to read-only memory",
629                                if ptr_kind == PtrKind::Box { "box" } else { "mutable reference" },
630                            )
631                        )
632                    }
633                    InterpErrorKind::MachineStop(mut machine_err) => {
634                        // Enhance the aliasing model error with the current path.
635                        if !self.path.projs.is_empty() {
636                            let mut path = String::new();
637                            write_path(&mut path, &self.path.projs);
638                            machine_err.with_validation_path(path);
639                        }
640                        InterpErrorKind::MachineStop(machine_err)
641                    }
642                    e => e,
643                })?
644            } else {
645                // We can't retag if we're not resetting provenance.
646                None
647            }
648        } else {
649            // Pointer remains unchanged.
650            None
651        };
652        // If the pointer needs adjusting, write back adjusted pointer. This automatically
653        // also clears any excess provenance. Otherwise, just clear the provenance.
654        if let Some(ptr) = adjusted_ptr {
655            self.ecx.write_immediate_no_validate(*ptr, value)?;
656        } else if self.reset_provenance_and_padding {
657            self.reset_pointer_provenance(value, &ptr)?;
658        }
659
660        // Check alignment after dereferenceable (if both are violated, trigger the error above).
661        {
    self.ecx.check_ptr_align(place.ptr(),
                align).map_err_kind(|e|
                {
                    match e {
                        Ub(AlignmentCheckFailed(Misalignment { required, has },
                            _msg)) => {
                            {
                                let where_ = &self.path;
                                let path =
                                    if !where_.projs.is_empty() {
                                        let mut path = String::new();
                                        write_path(&mut path, &where_.projs);
                                        Some(path)
                                    } else { None };
                                #[allow(unused)]
                                use ValidationErrorKind::*;
                                let msg =
                                    ValidationErrorKind::from(::alloc::__export::must_use({
                                                ::alloc::fmt::format(format_args!("encountered an unaligned {2} (required {0} byte alignment but found {1})",
                                                        required.bytes(), has.bytes(), ptr_kind))
                                            }));
                                ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
                                        orig_ty: where_.orig_ty,
                                        path,
                                        ptr_bytes_warning: msg.ptr_bytes_warning(),
                                        msg: msg.to_string(),
                                    })
                            }
                        }
                        e => e,
                    }
                })?
};try_validation!(
662            self.ecx.check_ptr_align(
663                place.ptr(),
664                align,
665            ),
666            self.path,
667            Ub(AlignmentCheckFailed(Misalignment { required, has }, _msg)) => format!(
668                "encountered an unaligned {ptr_kind} (required {required_bytes} byte alignment but found {found_bytes})",
669                required_bytes = required.bytes(),
670                found_bytes = has.bytes()
671            ),
672        );
673
674        // Make sure this is non-null. This is obviously needed when `may_dangle` is set,
675        // but even if we did check dereferenceability above that would still allow null
676        // pointers if `size` is zero.
677        let scalar = Scalar::from_maybe_pointer(place.ptr(), self.ecx);
678        if self.ecx.scalar_may_be_null(scalar)? {
679            let maybe = !M::Provenance::OFFSET_IS_ADDR && #[allow(non_exhaustive_omitted_patterns)] match scalar {
    Scalar::Ptr(..) => true,
    _ => false,
}matches!(scalar, Scalar::Ptr(..));
680            do yeet {
        let where_ = &self.path;
        let path =
            if !where_.projs.is_empty() {
                let mut path = String::new();
                write_path(&mut path, &where_.projs);
                Some(path)
            } else { None };
        #[allow(unused)]
        use ValidationErrorKind::*;
        let msg =
            ValidationErrorKind::from(::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("encountered a {0}null {1}",
                                if maybe { "maybe-" } else { "" }, ptr_kind))
                    }));
        ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
                orig_ty: where_.orig_ty,
                path,
                ptr_bytes_warning: msg.ptr_bytes_warning(),
                msg: msg.to_string(),
            })
    }throw_validation_failure!(
681                self.path,
682                format!(
683                    "encountered a {maybe}null {ptr_kind}",
684                    maybe = if maybe { "maybe-" } else { "" }
685                )
686            )
687        }
688        // Do not allow references to uninhabited types.
689        if place.layout.is_uninhabited() {
690            let ty = place.layout.ty;
691            do yeet {
        let where_ = &self.path;
        let path =
            if !where_.projs.is_empty() {
                let mut path = String::new();
                write_path(&mut path, &where_.projs);
                Some(path)
            } else { None };
        #[allow(unused)]
        use ValidationErrorKind::*;
        let msg =
            ValidationErrorKind::from(::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("encountered a {0} pointing to uninhabited type {1}",
                                ptr_kind, ty))
                    }));
        ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
                orig_ty: where_.orig_ty,
                path,
                ptr_bytes_warning: msg.ptr_bytes_warning(),
                msg: msg.to_string(),
            })
    }throw_validation_failure!(
692                self.path,
693                format!("encountered a {ptr_kind} pointing to uninhabited type {ty}")
694            )
695        }
696
697        // Recursive checking (but not inside `MaybeDangling` of course).
698        if let Some(ref_tracking) = self.ref_tracking.as_deref_mut()
699            && !self.may_dangle
700        {
701            // Proceed recursively even for ZST, no reason to skip them!
702            // `!` is a ZST and we want to validate it.
703            if let Some(ctfe_mode) = self.ctfe_mode {
704                let mut skip_recursive_check = false;
705                // CTFE imposes restrictions on what references can point to.
706                if let Ok((alloc_id, _offset, _prov)) =
707                    self.ecx.ptr_try_get_alloc_id(place.ptr(), 0)
708                {
709                    // Everything should be already interned.
710                    let Some(global_alloc) = self.ecx.tcx.try_get_global_alloc(alloc_id) else {
711                        if self.ecx.memory.alloc_map.contains_key(&alloc_id) {
712                            // This can happen when interning didn't complete due to, e.g.
713                            // missing `make_global`. This must mean other errors are already
714                            // being reported.
715                            self.ecx.tcx.dcx().delayed_bug(
716                                "interning did not complete, there should be an error",
717                            );
718                            return interp_ok(());
719                        }
720                        // We can't have *any* references to non-existing allocations in const-eval
721                        // as the rest of rustc isn't happy with them... so we throw an error, even
722                        // though for zero-sized references this isn't really UB.
723                        // A potential future alternative would be to resurrect this as a zero-sized allocation
724                        // (which codegen will then compile to an aligned dummy pointer anyway).
725                        do yeet {
        let where_ = &self.path;
        let path =
            if !where_.projs.is_empty() {
                let mut path = String::new();
                write_path(&mut path, &where_.projs);
                Some(path)
            } else { None };
        #[allow(unused)]
        use ValidationErrorKind::*;
        let msg =
            ValidationErrorKind::from(::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("encountered a dangling {0} (use-after-free)",
                                ptr_kind))
                    }));
        ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
                orig_ty: where_.orig_ty,
                path,
                ptr_bytes_warning: msg.ptr_bytes_warning(),
                msg: msg.to_string(),
            })
    };throw_validation_failure!(
726                            self.path,
727                            format!("encountered a dangling {ptr_kind} (use-after-free)")
728                        );
729                    };
730                    let (size, _align) =
731                        global_alloc.size_and_align(*self.ecx.tcx, self.ecx.typing_env);
732                    let alloc_actual_mutbl =
733                        global_alloc.mutability(*self.ecx.tcx, self.ecx.typing_env);
734
735                    match global_alloc {
736                        GlobalAlloc::Static(did) => {
737                            let DefKind::Static { nested, .. } = self.ecx.tcx.def_kind(did) else {
738                                ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!()
739                            };
740                            if !!self.ecx.tcx.is_thread_local_static(did) {
    ::core::panicking::panic("assertion failed: !self.ecx.tcx.is_thread_local_static(did)")
};assert!(!self.ecx.tcx.is_thread_local_static(did));
741                            if !self.ecx.tcx.is_static(did) {
    ::core::panicking::panic("assertion failed: self.ecx.tcx.is_static(did)")
};assert!(self.ecx.tcx.is_static(did));
742                            match ctfe_mode {
743                                CtfeValidationMode::Static { .. }
744                                | CtfeValidationMode::Promoted { .. } => {
745                                    // We skip recursively checking other statics. These statics must be sound by
746                                    // themselves, and the only way to get broken statics here is by using
747                                    // unsafe code.
748                                    // The reasons we don't check other statics is twofold. For one, in all
749                                    // sound cases, the static was already validated on its own, and second, we
750                                    // trigger cycle errors if we try to compute the value of the other static
751                                    // and that static refers back to us (potentially through a promoted).
752                                    // This could miss some UB, but that's fine.
753                                    // We still walk nested allocations, as they are fundamentally part of this validation run.
754                                    // This means we will also recurse into nested statics of *other*
755                                    // statics, even though we do not recurse into other statics directly.
756                                    // That's somewhat inconsistent but harmless.
757                                    skip_recursive_check = !nested;
758                                }
759                                CtfeValidationMode::Const { .. } => {
760                                    // If this is mutable memory or an `extern static`, there's no point in checking it -- we'd
761                                    // just get errors trying to read the value.
762                                    if alloc_actual_mutbl.is_mut()
763                                        || self.ecx.tcx.is_foreign_item(did)
764                                    {
765                                        skip_recursive_check = true;
766                                    }
767                                }
768                            }
769                        }
770                        _ => (),
771                    }
772
773                    // If this allocation has size zero, there is no actual mutability here.
774                    if size != Size::ZERO {
775                        // Determine whether this pointer expects to be pointing to something mutable.
776                        let ptr_expected_mutbl = match ptr_kind {
777                            PtrKind::Box => Mutability::Mut,
778                            PtrKind::Ref(mutbl) => {
779                                // We do not take into account interior mutability here since we cannot know if
780                                // there really is an `UnsafeCell` inside `Option<UnsafeCell>` -- so we check
781                                // that in the recursive descent behind this reference (controlled by
782                                // `allow_immutable_unsafe_cell`).
783                                mutbl
784                            }
785                        };
786                        // Mutable pointer to immutable memory is no good.
787                        if ptr_expected_mutbl == Mutability::Mut
788                            && alloc_actual_mutbl == Mutability::Not
789                        {
790                            // This can actually occur with transmutes.
791                            do yeet {
        let where_ = &self.path;
        let path =
            if !where_.projs.is_empty() {
                let mut path = String::new();
                write_path(&mut path, &where_.projs);
                Some(path)
            } else { None };
        #[allow(unused)]
        use ValidationErrorKind::*;
        let msg =
            ValidationErrorKind::from(::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("encountered mutable reference or box pointing to read-only memory"))
                    }));
        ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
                orig_ty: where_.orig_ty,
                path,
                ptr_bytes_warning: msg.ptr_bytes_warning(),
                msg: msg.to_string(),
            })
    };throw_validation_failure!(
792                                self.path,
793                                format!(
794                                    "encountered mutable reference or box pointing to read-only memory"
795                                )
796                            );
797                        }
798                    }
799                }
800                // Potentially skip recursive check.
801                if skip_recursive_check {
802                    return interp_ok(());
803                }
804            } else {
805                // This is not CTFE, so it's Miri with recursive checking.
806                // FIXME: should we skip `UnsafeCell` behind shared references? Currently that is
807                // not needed since validation reads bypass Stacked Borrows and data race checks,
808                // but is that really coherent?
809            }
810            let path = &self.path;
811            ref_tracking.track(place, || {
812                // We need to clone the path anyway, make sure it gets created
813                // with enough space for the additional `Deref`.
814                let mut new_projs = Vec::with_capacity(path.projs.len() + 1);
815                new_projs.extend(&path.projs);
816                new_projs.push(PathElem::Deref);
817                Path { projs: new_projs, orig_ty: path.orig_ty }
818            });
819        }
820        interp_ok(())
821    }
822
823    /// Check if this is a value of primitive type, and if yes check the validity of the value
824    /// at that type. Return `true` if the type is indeed primitive.
825    ///
826    /// Note that not all of these have `FieldsShape::Primitive`, e.g. wide references.
827    fn try_visit_primitive(
828        &mut self,
829        value: &PlaceTy<'tcx, M::Provenance>,
830    ) -> InterpResult<'tcx, bool> {
831        // Go over all the primitive types
832        let ty = value.layout.ty;
833        match ty.kind() {
834            ty::Bool => {
835                let scalar = self.read_scalar(value, ExpectedKind::Bool)?;
836                {
    scalar.to_bool().map_err_kind(|e|
                {
                    match e {
                        Ub(InvalidBool(..)) => {
                            {
                                let where_ = &self.path;
                                let path =
                                    if !where_.projs.is_empty() {
                                        let mut path = String::new();
                                        write_path(&mut path, &where_.projs);
                                        Some(path)
                                    } else { None };
                                #[allow(unused)]
                                use ValidationErrorKind::*;
                                let msg =
                                    ValidationErrorKind::from(::alloc::__export::must_use({
                                                ::alloc::fmt::format(format_args!("encountered {0:x}, but expected a boolean",
                                                        scalar))
                                            }));
                                ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
                                        orig_ty: where_.orig_ty,
                                        path,
                                        ptr_bytes_warning: msg.ptr_bytes_warning(),
                                        msg: msg.to_string(),
                                    })
                            }
                        }
                        e => e,
                    }
                })?
};try_validation!(
837                    scalar.to_bool(),
838                    self.path,
839                    Ub(InvalidBool(..)) =>
840                        format!("encountered {scalar:x}, but expected a boolean"),
841                );
842                if self.reset_provenance_and_padding {
843                    self.ecx.clear_provenance(value)?;
844                    self.add_data_range_place(value);
845                }
846                interp_ok(true)
847            }
848            ty::Char => {
849                let scalar = self.read_scalar(value, ExpectedKind::Char)?;
850                {
    scalar.to_char().map_err_kind(|e|
                {
                    match e {
                        Ub(InvalidChar(..)) => {
                            {
                                let where_ = &self.path;
                                let path =
                                    if !where_.projs.is_empty() {
                                        let mut path = String::new();
                                        write_path(&mut path, &where_.projs);
                                        Some(path)
                                    } else { None };
                                #[allow(unused)]
                                use ValidationErrorKind::*;
                                let msg =
                                    ValidationErrorKind::from(::alloc::__export::must_use({
                                                ::alloc::fmt::format(format_args!("encountered {0:x}, but expected a valid unicode scalar value (in `0..=0x10FFFF` but not in `0xD800..=0xDFFF`)",
                                                        scalar))
                                            }));
                                ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
                                        orig_ty: where_.orig_ty,
                                        path,
                                        ptr_bytes_warning: msg.ptr_bytes_warning(),
                                        msg: msg.to_string(),
                                    })
                            }
                        }
                        e => e,
                    }
                })?
};try_validation!(
851                    scalar.to_char(),
852                    self.path,
853                    Ub(InvalidChar(..)) =>
854                        format!("encountered {scalar:x}, but expected a valid unicode scalar value \
855                          (in `0..=0x10FFFF` but not in `0xD800..=0xDFFF`)")
856                );
857                if self.reset_provenance_and_padding {
858                    self.ecx.clear_provenance(value)?;
859                    self.add_data_range_place(value);
860                }
861                interp_ok(true)
862            }
863            ty::Float(_) | ty::Int(_) | ty::Uint(_) => {
864                // NOTE: Keep this in sync with the array optimization for int/float
865                // types below!
866                self.read_scalar(
867                    value,
868                    if #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
    ty::Float(..) => true,
    _ => false,
}matches!(ty.kind(), ty::Float(..)) {
869                        ExpectedKind::Float
870                    } else {
871                        ExpectedKind::Int
872                    },
873                )?;
874                if self.reset_provenance_and_padding {
875                    self.ecx.clear_provenance(value)?;
876                    self.add_data_range_place(value);
877                }
878                interp_ok(true)
879            }
880            ty::RawPtr(pointee, ..) => {
881                let ptr = self.read_immediate(value, ExpectedKind::RawPtr)?;
882                if self.reset_provenance_and_padding {
883                    self.reset_pointer_provenance(value, &ptr)?;
884                    // There's no padding in a pointer.
885                    self.add_data_range_place(value);
886                }
887
888                if !pointee.is_sized(*self.ecx.tcx, self.ecx.typing_env) {
889                    // Raw pointers to unsized types need to have their metadata checked.
890                    // We avoid creating this place for sized types to match codegen: those types
891                    // might actually be invalid (i.e., too big)!
892                    let place = self.ecx.imm_ptr_to_mplace(&ptr)?;
893                    if !place.layout.is_unsized() {
    ::core::panicking::panic("assertion failed: place.layout.is_unsized()")
};assert!(place.layout.is_unsized());
894                    self.check_wide_ptr_meta(place.meta(), place.layout)?;
895                }
896                interp_ok(true)
897            }
898            ty::Ref(_, _ty, mutbl) => {
899                self.check_safe_pointer(value, ty, PtrKind::Ref(*mutbl))?;
900                interp_ok(true)
901            }
902            ty::FnPtr(..) => {
903                let scalar = self.read_scalar(value, ExpectedKind::FnPtr)?;
904
905                // If we check references recursively, also check that this points to a function.
906                if let Some(_) = self.ref_tracking {
907                    let ptr = scalar.to_pointer(self.ecx)?;
908                    let _fn = {
    self.ecx.get_ptr_fn(ptr).map_err_kind(|e|
                {
                    match e {
                        Ub(DanglingIntPointer { .. } | InvalidFunctionPointer(..))
                            => {
                            {
                                let where_ = &self.path;
                                let path =
                                    if !where_.projs.is_empty() {
                                        let mut path = String::new();
                                        write_path(&mut path, &where_.projs);
                                        Some(path)
                                    } else { None };
                                #[allow(unused)]
                                use ValidationErrorKind::*;
                                let msg =
                                    ValidationErrorKind::from(::alloc::__export::must_use({
                                                ::alloc::fmt::format(format_args!("encountered {0}, but expected a function pointer",
                                                        ptr))
                                            }));
                                ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
                                        orig_ty: where_.orig_ty,
                                        path,
                                        ptr_bytes_warning: msg.ptr_bytes_warning(),
                                        msg: msg.to_string(),
                                    })
                            }
                        }
                        e => e,
                    }
                })?
}try_validation!(
909                        self.ecx.get_ptr_fn(ptr),
910                        self.path,
911                        Ub(DanglingIntPointer{ .. } | InvalidFunctionPointer(..)) =>
912                            format!("encountered {ptr}, but expected a function pointer"),
913                    );
914                    // FIXME: Check if the signature matches
915                } else {
916                    // Otherwise (for standalone Miri and for `-Zextra-const-ub-checks`),
917                    // we have to still check it to be non-null.
918                    if self.ecx.scalar_may_be_null(scalar)? {
919                        let maybe =
920                            !M::Provenance::OFFSET_IS_ADDR && #[allow(non_exhaustive_omitted_patterns)] match scalar {
    Scalar::Ptr(..) => true,
    _ => false,
}matches!(scalar, Scalar::Ptr(..));
921                        do yeet {
        let where_ = &self.path;
        let path =
            if !where_.projs.is_empty() {
                let mut path = String::new();
                write_path(&mut path, &where_.projs);
                Some(path)
            } else { None };
        #[allow(unused)]
        use ValidationErrorKind::*;
        let msg =
            ValidationErrorKind::from(::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("encountered a {0}null function pointer",
                                if maybe { "maybe-" } else { "" }))
                    }));
        ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
                orig_ty: where_.orig_ty,
                path,
                ptr_bytes_warning: msg.ptr_bytes_warning(),
                msg: msg.to_string(),
            })
    };throw_validation_failure!(
922                            self.path,
923                            format!(
924                                "encountered a {maybe}null function pointer",
925                                maybe = if maybe { "maybe-" } else { "" }
926                            )
927                        );
928                    }
929                }
930                if self.reset_provenance_and_padding {
931                    // Make sure we do not preserve partial provenance. This matches the thin
932                    // pointer handling in `deref_pointer`.
933                    if #[allow(non_exhaustive_omitted_patterns)] match scalar {
    Scalar::Int(..) => true,
    _ => false,
}matches!(scalar, Scalar::Int(..)) {
934                        self.ecx.clear_provenance(value)?;
935                    }
936                    self.add_data_range_place(value);
937                }
938                interp_ok(true)
939            }
940            ty::Never => {
941                do yeet {
        let where_ = &self.path;
        let path =
            if !where_.projs.is_empty() {
                let mut path = String::new();
                write_path(&mut path, &where_.projs);
                Some(path)
            } else { None };
        #[allow(unused)]
        use ValidationErrorKind::*;
        let msg =
            ValidationErrorKind::from(::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("encountered a value of the never type `!`"))
                    }));
        ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
                orig_ty: where_.orig_ty,
                path,
                ptr_bytes_warning: msg.ptr_bytes_warning(),
                msg: msg.to_string(),
            })
    }throw_validation_failure!(
942                    self.path,
943                    format!("encountered a value of the never type `!`")
944                )
945            }
946            ty::Foreign(..) | ty::FnDef(..) => {
947                // Nothing to check.
948                interp_ok(true)
949            }
950            ty::UnsafeBinder(_) => {
    ::core::panicking::panic_fmt(format_args!("not yet implemented: {0}",
            format_args!("FIXME(unsafe_binder)")));
}todo!("FIXME(unsafe_binder)"),
951            // The above should be all the primitive types. The rest is compound, we
952            // check them by visiting their fields/variants.
953            ty::Adt(..)
954            | ty::Tuple(..)
955            | ty::Array(..)
956            | ty::Slice(..)
957            | ty::Str
958            | ty::Dynamic(..)
959            | ty::Closure(..)
960            | ty::Pat(..)
961            | ty::CoroutineClosure(..)
962            | ty::Coroutine(..) => interp_ok(false),
963            // Some types only occur during typechecking, they have no layout.
964            // We should not see them here and we could not check them anyway.
965            ty::Error(_)
966            | ty::Infer(..)
967            | ty::Placeholder(..)
968            | ty::Bound(..)
969            | ty::Param(..)
970            | ty::Alias(..)
971            | ty::CoroutineWitness(..) => ::rustc_middle::util::bug::bug_fmt(format_args!("Encountered invalid type {0:?}",
        ty))bug!("Encountered invalid type {:?}", ty),
972        }
973    }
974
975    fn visit_scalar(
976        &mut self,
977        scalar: Scalar<M::Provenance>,
978        scalar_layout: ScalarAbi,
979    ) -> InterpResult<'tcx> {
980        let size = scalar_layout.size(self.ecx);
981        let valid_range = scalar_layout.valid_range(self.ecx);
982        let WrappingRange { start, end } = valid_range;
983        let max_value = size.unsigned_int_max();
984        if !(end <= max_value) {
    ::core::panicking::panic("assertion failed: end <= max_value")
};assert!(end <= max_value);
985        let bits = match scalar.try_to_scalar_int() {
986            Ok(int) => int.to_bits(size),
987            Err(_) => {
988                // So this is a pointer then, and casting to an int failed.
989                // Can only happen during CTFE.
990                // We support 2 kinds of ranges here: full range, and excluding zero.
991                if start == 1 && end == max_value {
992                    // Only null is the niche. So make sure the ptr is NOT null.
993                    if self.ecx.scalar_may_be_null(scalar)? {
994                        do yeet {
        let where_ = &self.path;
        let path =
            if !where_.projs.is_empty() {
                let mut path = String::new();
                write_path(&mut path, &where_.projs);
                Some(path)
            } else { None };
        #[allow(unused)]
        use ValidationErrorKind::*;
        let msg =
            ValidationErrorKind::from(::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("encountered a maybe-null pointer, but expected something that is definitely non-zero"))
                    }));
        ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
                orig_ty: where_.orig_ty,
                path,
                ptr_bytes_warning: msg.ptr_bytes_warning(),
                msg: msg.to_string(),
            })
    }throw_validation_failure!(
995                            self.path,
996                            format!(
997                                "encountered a maybe-null pointer, but expected something that is definitely non-zero"
998                            )
999                        )
1000                    } else {
1001                        return interp_ok(());
1002                    }
1003                } else if scalar_layout.is_always_valid(self.ecx) {
1004                    // Easy. (This is reachable if `enforce_number_validity` is set.)
1005                    return interp_ok(());
1006                } else {
1007                    // Conservatively, we reject, because the pointer *could* have a bad value.
1008                    do yeet {
        let where_ = &self.path;
        let path =
            if !where_.projs.is_empty() {
                let mut path = String::new();
                write_path(&mut path, &where_.projs);
                Some(path)
            } else { None };
        #[allow(unused)]
        use ValidationErrorKind::*;
        let msg =
            ValidationErrorKind::from(::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("encountered a pointer with unknown absolute address, but expected something that is definitely {0}",
                                fmt_range(valid_range, max_value)))
                    }));
        ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
                orig_ty: where_.orig_ty,
                path,
                ptr_bytes_warning: msg.ptr_bytes_warning(),
                msg: msg.to_string(),
            })
    }throw_validation_failure!(
1009                        self.path,
1010                        format!(
1011                            "encountered a pointer with unknown absolute address, but expected something that is definitely {in_range}",
1012                            in_range = fmt_range(valid_range, max_value)
1013                        )
1014                    )
1015                }
1016            }
1017        };
1018        // Now compare.
1019        if valid_range.contains(bits) {
1020            interp_ok(())
1021        } else {
1022            do yeet {
        let where_ = &self.path;
        let path =
            if !where_.projs.is_empty() {
                let mut path = String::new();
                write_path(&mut path, &where_.projs);
                Some(path)
            } else { None };
        #[allow(unused)]
        use ValidationErrorKind::*;
        let msg =
            ValidationErrorKind::from(::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("encountered {1}, but expected something {0}",
                                fmt_range(valid_range, max_value), bits))
                    }));
        ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
                orig_ty: where_.orig_ty,
                path,
                ptr_bytes_warning: msg.ptr_bytes_warning(),
                msg: msg.to_string(),
            })
    }throw_validation_failure!(
1023                self.path,
1024                format!(
1025                    "encountered {bits}, but expected something {in_range}",
1026                    in_range = fmt_range(valid_range, max_value)
1027                )
1028            )
1029        }
1030    }
1031
1032    fn in_mutable_memory(&self, val: &PlaceTy<'tcx, M::Provenance>) -> bool {
1033        if true {
    if !self.ctfe_mode.is_some() {
        ::core::panicking::panic("assertion failed: self.ctfe_mode.is_some()")
    };
};debug_assert!(self.ctfe_mode.is_some());
1034        if let Some(mplace) = val.as_mplace_or_local().left() {
1035            if let Some(alloc_id) = mplace.ptr().provenance.and_then(|p| p.get_alloc_id()) {
1036                let tcx = *self.ecx.tcx;
1037                // Everything must be already interned.
1038                let mutbl = tcx.global_alloc(alloc_id).mutability(tcx, self.ecx.typing_env);
1039                if let Some((_, alloc)) = self.ecx.memory.alloc_map.get(alloc_id) {
1040                    {
    match (&alloc.mutability, &mutbl) {
        (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::None);
            }
        }
    }
};assert_eq!(alloc.mutability, mutbl);
1041                }
1042                mutbl.is_mut()
1043            } else {
1044                // No memory at all.
1045                false
1046            }
1047        } else {
1048            // A local variable -- definitely mutable.
1049            true
1050        }
1051    }
1052
1053    /// Add the given pointer-length pair to the "data" range of this visit.
1054    fn add_data_range(&mut self, ptr: Pointer<Option<M::Provenance>>, size: Size) {
1055        if let Some(data_bytes) = self.data_bytes.as_mut() {
1056            // We only have to store the offset, the rest is the same for all pointers here.
1057            // The logic is agnostic to whether the offset is relative or absolute as long as
1058            // it is consistent.
1059            let (_prov, offset) = ptr.into_raw_parts();
1060            // Add this.
1061            data_bytes.add_range(offset, size);
1062        };
1063    }
1064
1065    /// Add the entire given place to the "data" range of this visit.
1066    fn add_data_range_place(&mut self, place: &PlaceTy<'tcx, M::Provenance>) {
1067        // Only sized places can be added this way.
1068        if true {
    if !place.layout.is_sized() {
        ::core::panicking::panic("assertion failed: place.layout.is_sized()")
    };
};debug_assert!(place.layout.is_sized());
1069        if let Some(data_bytes) = self.data_bytes.as_mut() {
1070            let offset = Self::data_range_offset(self.ecx, place);
1071            data_bytes.add_range(offset, place.layout.size);
1072        }
1073    }
1074
1075    /// Convert a place into the offset it starts at, for the purpose of data_range tracking.
1076    /// Must only be called if `data_bytes` is `Some(_)`.
1077    fn data_range_offset(ecx: &InterpCx<'tcx, M>, place: &PlaceTy<'tcx, M::Provenance>) -> Size {
1078        // The presence of `data_bytes` implies that our place is in memory.
1079        let ptr = ecx
1080            .place_to_op(place)
1081            .expect("place must be in memory")
1082            .as_mplace_or_imm()
1083            .expect_left("place must be in memory")
1084            .ptr();
1085        let (_prov, offset) = ptr.into_raw_parts();
1086        offset
1087    }
1088
1089    fn reset_padding(&mut self, place: &PlaceTy<'tcx, M::Provenance>) -> InterpResult<'tcx> {
1090        let Some(data_bytes) = self.data_bytes.as_mut() else { return interp_ok(()) };
1091        // Our value must be in memory, otherwise we would not have set up `data_bytes`.
1092        let mplace = self.ecx.force_allocation(place)?;
1093        // Determine starting offset and size.
1094        let (_prov, start_offset) = mplace.ptr().into_raw_parts();
1095        let (size, _align) = self
1096            .ecx
1097            .size_and_align_of_val(&mplace)?
1098            .unwrap_or((mplace.layout.size, mplace.layout.align.abi));
1099        // If there is no padding at all, we can skip the rest: check for
1100        // a single data range covering the entire value.
1101        if data_bytes.0 == &[(start_offset, size)] {
1102            return interp_ok(());
1103        }
1104        // Get a handle for the allocation. Do this only once, to avoid looking up the same
1105        // allocation over and over again. (Though to be fair, iterating the value already does
1106        // exactly that.)
1107        let Some(mut alloc) = self.ecx.get_ptr_alloc_mut(mplace.ptr(), size)? else {
1108            // A ZST, no padding to clear.
1109            return interp_ok(());
1110        };
1111        // Add a "finalizer" data range at the end, so that the iteration below finds all gaps
1112        // between ranges.
1113        data_bytes.0.push((start_offset + size, Size::ZERO));
1114        // Iterate, and reset gaps.
1115        let mut padding_cleared_until = start_offset;
1116        for &(offset, size) in data_bytes.0.iter() {
1117            if !(offset >= padding_cleared_until) {
    {
        ::core::panicking::panic_fmt(format_args!("reset_padding on {0}: previous field ended at offset {1}, next field starts at {2} (and has a size of {3} bytes)",
                mplace.layout.ty,
                (padding_cleared_until - start_offset).bytes(),
                (offset - start_offset).bytes(), size.bytes()));
    }
};assert!(
1118                offset >= padding_cleared_until,
1119                "reset_padding on {}: previous field ended at offset {}, next field starts at {} (and has a size of {} bytes)",
1120                mplace.layout.ty,
1121                (padding_cleared_until - start_offset).bytes(),
1122                (offset - start_offset).bytes(),
1123                size.bytes(),
1124            );
1125            if offset > padding_cleared_until {
1126                // We found padding. Adjust the range to be relative to `alloc`, and make it uninit.
1127                let padding_start = padding_cleared_until - start_offset;
1128                let padding_size = offset - padding_cleared_until;
1129                let range = alloc_range(padding_start, padding_size);
1130                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_const_eval/src/interpret/validity.rs:1130",
                        "rustc_const_eval::interpret::validity",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/validity.rs"),
                        ::tracing_core::__macro_support::Option::Some(1130u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::validity"),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("reset_padding on {0}: resetting padding range {1:?}",
                                                    mplace.layout.ty, range) as &dyn Value))])
            });
    } else { ; }
};trace!("reset_padding on {}: resetting padding range {range:?}", mplace.layout.ty);
1131                alloc.write_uninit(range);
1132            }
1133            padding_cleared_until = offset + size;
1134        }
1135        if !(padding_cleared_until == start_offset + size) {
    ::core::panicking::panic("assertion failed: padding_cleared_until == start_offset + size")
};assert!(padding_cleared_until == start_offset + size);
1136        interp_ok(())
1137    }
1138
1139    /// Computes the data range of this union type:
1140    /// which bytes are inside a field (i.e., not padding.)
1141    fn union_data_range<'e>(
1142        ecx: &'e mut InterpCx<'tcx, M>,
1143        layout: TyAndLayout<'tcx>,
1144    ) -> Cow<'e, RangeSet> {
1145        if !layout.ty.is_union() {
    ::core::panicking::panic("assertion failed: layout.ty.is_union()")
};assert!(layout.ty.is_union());
1146        if !layout.is_sized() {
    {
        ::core::panicking::panic_fmt(format_args!("there are no unsized unions"));
    }
};assert!(layout.is_sized(), "there are no unsized unions");
1147        let layout_cx = LayoutCx::new(*ecx.tcx, ecx.typing_env);
1148        return M::cached_union_data_range(ecx, layout.ty, || {
1149            let mut out = RangeSet::new();
1150            union_data_range_uncached(&layout_cx, layout, Size::ZERO, &mut out);
1151            out
1152        });
1153
1154        /// Helper for recursive traversal: add data ranges of the given type to `out`.
1155        fn union_data_range_uncached<'tcx>(
1156            cx: &LayoutCx<'tcx>,
1157            layout: TyAndLayout<'tcx>,
1158            base_offset: Size,
1159            out: &mut RangeSet,
1160        ) {
1161            // If this is a ZST, we don't contain any data. In particular, this helps us to quickly
1162            // skip over huge arrays of ZST.
1163            if layout.is_zst() {
1164                return;
1165            }
1166            // Just recursively add all the fields of everything to the output.
1167            match &layout.fields {
1168                FieldsShape::Primitive => {
1169                    out.add_range(base_offset, layout.size);
1170                }
1171                &FieldsShape::Union(fields) => {
1172                    // Currently, all fields start at offset 0 (relative to `base_offset`).
1173                    for field in 0..fields.get() {
1174                        let field = layout.field(cx, field);
1175                        union_data_range_uncached(cx, field, base_offset, out);
1176                    }
1177                }
1178                &FieldsShape::Array { stride, count } => {
1179                    let elem = layout.field(cx, 0);
1180
1181                    // Fast-path for large arrays of simple types that do not contain any padding.
1182                    if elem.backend_repr.is_scalar() {
1183                        out.add_range(base_offset, elem.size * count);
1184                    } else {
1185                        for idx in 0..count {
1186                            // This repeats the same computation for every array element... but the alternative
1187                            // is to allocate temporary storage for a dedicated `out` set for the array element,
1188                            // and replicating that N times. Is that better?
1189                            union_data_range_uncached(cx, elem, base_offset + idx * stride, out);
1190                        }
1191                    }
1192                }
1193                FieldsShape::Arbitrary { offsets, .. } => {
1194                    for (field, &offset) in offsets.iter_enumerated() {
1195                        let field = layout.field(cx, field.as_usize());
1196                        union_data_range_uncached(cx, field, base_offset + offset, out);
1197                    }
1198                }
1199            }
1200            // Don't forget potential other variants.
1201            match &layout.variants {
1202                Variants::Single { .. } | Variants::Empty => {
1203                    // Fully handled above.
1204                }
1205                Variants::Multiple { variants, .. } => {
1206                    for variant in variants.indices() {
1207                        let variant = layout.for_variant(cx, variant);
1208                        union_data_range_uncached(cx, variant, base_offset, out);
1209                    }
1210                }
1211            }
1212        }
1213    }
1214}
1215
1216impl<'rt, 'tcx, M: Machine<'tcx>> ValueVisitor<'tcx, M> for ValidityVisitor<'rt, 'tcx, M> {
1217    type V = PlaceTy<'tcx, M::Provenance>;
1218
1219    #[inline(always)]
1220    fn ecx(&self) -> &InterpCx<'tcx, M> {
1221        self.ecx
1222    }
1223
1224    fn read_discriminant(
1225        &mut self,
1226        val: &PlaceTy<'tcx, M::Provenance>,
1227    ) -> InterpResult<'tcx, VariantIdx> {
1228        self.with_elem(PathElem::EnumTag, move |this| {
1229            interp_ok({
    this.ecx.read_discriminant(val).map_err_kind(|e|
                {
                    match e {
                        Ub(InvalidTag(val)) => {
                            {
                                let where_ = &this.path;
                                let path =
                                    if !where_.projs.is_empty() {
                                        let mut path = String::new();
                                        write_path(&mut path, &where_.projs);
                                        Some(path)
                                    } else { None };
                                #[allow(unused)]
                                use ValidationErrorKind::*;
                                let msg =
                                    ValidationErrorKind::from(::alloc::__export::must_use({
                                                ::alloc::fmt::format(format_args!("encountered {0:x}, but expected a valid enum tag",
                                                        val))
                                            }));
                                ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
                                        orig_ty: where_.orig_ty,
                                        path,
                                        ptr_bytes_warning: msg.ptr_bytes_warning(),
                                        msg: msg.to_string(),
                                    })
                            }
                        }
                        Ub(UninhabitedEnumVariantRead(_)) => {
                            {
                                let where_ = &this.path;
                                let path =
                                    if !where_.projs.is_empty() {
                                        let mut path = String::new();
                                        write_path(&mut path, &where_.projs);
                                        Some(path)
                                    } else { None };
                                #[allow(unused)]
                                use ValidationErrorKind::*;
                                let msg =
                                    ValidationErrorKind::from(::alloc::__export::must_use({
                                                ::alloc::fmt::format(format_args!("encountered an uninhabited enum variant"))
                                            }));
                                ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
                                        orig_ty: where_.orig_ty,
                                        path,
                                        ptr_bytes_warning: msg.ptr_bytes_warning(),
                                        msg: msg.to_string(),
                                    })
                            }
                        }
                        e => e,
                    }
                })?
}try_validation!(
1230                this.ecx.read_discriminant(val),
1231                this.path,
1232                Ub(InvalidTag(val)) =>
1233                    format!("encountered {val:x}, but expected a valid enum tag"),
1234                Ub(UninhabitedEnumVariantRead(_)) =>
1235                    format!("encountered an uninhabited enum variant"),
1236                // Uninit / bad provenance are not possible since the field was already previously
1237                // checked at its integer type.
1238            ))
1239        })
1240    }
1241
1242    #[inline]
1243    fn visit_field(
1244        &mut self,
1245        old_val: &PlaceTy<'tcx, M::Provenance>,
1246        field: usize,
1247        new_val: &PlaceTy<'tcx, M::Provenance>,
1248    ) -> InterpResult<'tcx> {
1249        let elem = self.aggregate_field_path_elem(old_val.layout, field, new_val.layout.ty);
1250        self.with_elem(elem, move |this| this.visit_value(new_val))
1251    }
1252
1253    #[inline]
1254    fn visit_variant(
1255        &mut self,
1256        old_val: &PlaceTy<'tcx, M::Provenance>,
1257        variant_id: VariantIdx,
1258        new_val: &PlaceTy<'tcx, M::Provenance>,
1259    ) -> InterpResult<'tcx> {
1260        let name = match old_val.layout.ty.kind() {
1261            ty::Adt(adt, _) => PathElem::Variant(adt.variant(variant_id).name),
1262            // Coroutines also have variants
1263            ty::Coroutine(..) => PathElem::CoroutineState(variant_id),
1264            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("Unexpected type with variant: {0:?}",
        old_val.layout.ty))bug!("Unexpected type with variant: {:?}", old_val.layout.ty),
1265        };
1266        self.with_elem(name, move |this| this.visit_value(new_val))
1267    }
1268
1269    #[inline(always)]
1270    fn visit_union(
1271        &mut self,
1272        val: &PlaceTy<'tcx, M::Provenance>,
1273        _fields: NonZero<usize>,
1274    ) -> InterpResult<'tcx> {
1275        // Special check for CTFE validation, preventing `UnsafeCell` inside unions in immutable memory.
1276        if self.ctfe_mode.is_some_and(|c| !c.allow_immutable_unsafe_cell()) {
1277            // Unsized unions are currently not a thing, but let's keep this code consistent with
1278            // the check in `visit_value`.
1279            let zst = self.ecx.size_and_align_of_val(val)?.is_some_and(|(s, _a)| s.bytes() == 0);
1280            if !zst && !val.layout.ty.is_freeze(*self.ecx.tcx, self.ecx.typing_env) {
1281                if !self.in_mutable_memory(val) {
1282                    do yeet {
        let where_ = &self.path;
        let path =
            if !where_.projs.is_empty() {
                let mut path = String::new();
                write_path(&mut path, &where_.projs);
                Some(path)
            } else { None };
        #[allow(unused)]
        use ValidationErrorKind::*;
        let msg =
            ValidationErrorKind::from(::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("encountered `UnsafeCell` in read-only memory"))
                    }));
        ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
                orig_ty: where_.orig_ty,
                path,
                ptr_bytes_warning: msg.ptr_bytes_warning(),
                msg: msg.to_string(),
            })
    };throw_validation_failure!(
1283                        self.path,
1284                        format!("encountered `UnsafeCell` in read-only memory")
1285                    );
1286                }
1287            }
1288        }
1289        if self.reset_provenance_and_padding
1290            && let Some(data_bytes) = self.data_bytes.as_mut()
1291        {
1292            let base_offset = Self::data_range_offset(self.ecx, val);
1293            // Determine and add data range for this union.
1294            let union_data_range = Self::union_data_range(self.ecx, val.layout);
1295            for &(offset, size) in union_data_range.0.iter() {
1296                data_bytes.add_range(base_offset + offset, size);
1297            }
1298        }
1299        interp_ok(())
1300    }
1301
1302    #[inline]
1303    fn visit_box(
1304        &mut self,
1305        box_ty: Ty<'tcx>,
1306        val: &PlaceTy<'tcx, M::Provenance>,
1307    ) -> InterpResult<'tcx> {
1308        self.check_safe_pointer(&val, box_ty, PtrKind::Box)?;
1309        interp_ok(())
1310    }
1311
1312    #[inline]
1313    fn visit_variantless(&mut self, val: &PlaceTy<'tcx, M::Provenance>) -> InterpResult<'tcx> {
1314        let ty = val.layout.ty;
1315        if !ty.is_enum() {
    {
        ::core::panicking::panic_fmt(format_args!("encountered non-enum variantless type `{0}`",
                ty));
    }
};assert!(ty.is_enum(), "encountered non-enum variantless type `{ty}`");
1316        do yeet {
        let where_ = &self.path;
        let path =
            if !where_.projs.is_empty() {
                let mut path = String::new();
                write_path(&mut path, &where_.projs);
                Some(path)
            } else { None };
        #[allow(unused)]
        use ValidationErrorKind::*;
        let msg =
            ValidationErrorKind::from(::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("encountered a value of zero-variant enum `{0}`",
                                ty))
                    }));
        ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
                orig_ty: where_.orig_ty,
                path,
                ptr_bytes_warning: msg.ptr_bytes_warning(),
                msg: msg.to_string(),
            })
    };throw_validation_failure!(
1317            self.path,
1318            format!("encountered a value of zero-variant enum `{ty}`")
1319        );
1320    }
1321
1322    #[inline]
1323    fn visit_value(&mut self, val: &PlaceTy<'tcx, M::Provenance>) -> InterpResult<'tcx> {
1324        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_const_eval/src/interpret/validity.rs:1324",
                        "rustc_const_eval::interpret::validity",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/validity.rs"),
                        ::tracing_core::__macro_support::Option::Some(1324u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::validity"),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("visit_value: {0:?}, {1:?}",
                                                    *val, val.layout) as &dyn Value))])
            });
    } else { ; }
};trace!("visit_value: {:?}, {:?}", *val, val.layout);
1325
1326        // Check primitive types -- the leaves of our recursive descent.
1327        // This is called even for enum discriminants (which are "fields" of their enum),
1328        // so for integer-typed discriminants the provenance reset will happen here.
1329        // We assume that the Scalar validity range does not restrict these values
1330        // any further than `try_visit_primitive` does!
1331        if self.try_visit_primitive(val)? {
1332            return interp_ok(());
1333        }
1334
1335        // Special check preventing `UnsafeCell` in the inner part of constants
1336        if self.ctfe_mode.is_some_and(|c| !c.allow_immutable_unsafe_cell()) {
1337            // Exclude ZST values. We need to compute the dynamic size/align to properly
1338            // handle slices and trait objects.
1339            let zst = self.ecx.size_and_align_of_val(val)?.is_some_and(|(s, _a)| s.bytes() == 0);
1340            if !zst
1341                && let Some(def) = val.layout.ty.ty_adt_def()
1342                && def.is_unsafe_cell()
1343            {
1344                if !self.in_mutable_memory(val) {
1345                    do yeet {
        let where_ = &self.path;
        let path =
            if !where_.projs.is_empty() {
                let mut path = String::new();
                write_path(&mut path, &where_.projs);
                Some(path)
            } else { None };
        #[allow(unused)]
        use ValidationErrorKind::*;
        let msg =
            ValidationErrorKind::from(::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("encountered `UnsafeCell` in read-only memory"))
                    }));
        ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
                orig_ty: where_.orig_ty,
                path,
                ptr_bytes_warning: msg.ptr_bytes_warning(),
                msg: msg.to_string(),
            })
    };throw_validation_failure!(
1346                        self.path,
1347                        format!("encountered `UnsafeCell` in read-only memory")
1348                    );
1349                }
1350            }
1351        }
1352
1353        // Recursively walk the value at its type. Apply optimizations for some large types.
1354        match val.layout.ty.kind() {
1355            ty::Str => {
1356                let mplace = val.assert_mem_place(); // strings are unsized and hence never immediate
1357                let len = mplace.len(self.ecx)?;
1358                let expected = ExpectedKind::Str;
1359                {
    self.ecx.read_bytes_ptr_strip_provenance(mplace.ptr(),
                Size::from_bytes(len)).map_err_kind(|e|
                {
                    match e {
                        Ub(InvalidUninitBytes(..)) => {
                            {
                                let where_ = &self.path;
                                let path =
                                    if !where_.projs.is_empty() {
                                        let mut path = String::new();
                                        write_path(&mut path, &where_.projs);
                                        Some(path)
                                    } else { None };
                                #[allow(unused)]
                                use ValidationErrorKind::*;
                                let msg = ValidationErrorKind::from(Uninit { expected });
                                ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
                                        orig_ty: where_.orig_ty,
                                        path,
                                        ptr_bytes_warning: msg.ptr_bytes_warning(),
                                        msg: msg.to_string(),
                                    })
                            }
                        }
                        Unsup(ReadPointerAsInt(_)) => {
                            {
                                let where_ = &self.path;
                                let path =
                                    if !where_.projs.is_empty() {
                                        let mut path = String::new();
                                        write_path(&mut path, &where_.projs);
                                        Some(path)
                                    } else { None };
                                #[allow(unused)]
                                use ValidationErrorKind::*;
                                let msg =
                                    ValidationErrorKind::from(PointerAsInt { expected });
                                ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
                                        orig_ty: where_.orig_ty,
                                        path,
                                        ptr_bytes_warning: msg.ptr_bytes_warning(),
                                        msg: msg.to_string(),
                                    })
                            }
                        }
                        e => e,
                    }
                })?
};try_validation!(
1360                    self.ecx.read_bytes_ptr_strip_provenance(mplace.ptr(), Size::from_bytes(len)),
1361                    self.path,
1362                    Ub(InvalidUninitBytes(..)) =>
1363                        Uninit { expected },
1364                    Unsup(ReadPointerAsInt(_)) =>
1365                        PointerAsInt { expected },
1366                );
1367            }
1368            ty::Array(tys, ..) | ty::Slice(tys)
1369                // This optimization applies for types that can hold arbitrary non-provenance bytes (such as
1370                // integer and floating point types).
1371                // FIXME(wesleywiser) This logic could be extended further to arbitrary structs or
1372                // tuples made up of integer/floating point types or inhabited ZSTs with no padding.
1373                if #[allow(non_exhaustive_omitted_patterns)] match tys.kind() {
    ty::Int(..) | ty::Uint(..) | ty::Float(..) => true,
    _ => false,
}matches!(tys.kind(), ty::Int(..) | ty::Uint(..) | ty::Float(..))
1374                =>
1375            {
1376                let expected = if tys.is_integral() { ExpectedKind::Int } else { ExpectedKind::Float };
1377                // Optimized handling for arrays of integer/float type.
1378
1379                // This is the length of the array/slice.
1380                let len = val.len(self.ecx)?;
1381                // This is the element type size.
1382                let layout = self.ecx.layout_of(*tys)?;
1383                // This is the size in bytes of the whole array. (This checks for overflow.)
1384                let size = layout.size * len;
1385                // If the size is 0, there is nothing to check.
1386                // (`size` can only be 0 if `len` is 0, and empty arrays are always valid.)
1387                if size == Size::ZERO {
1388                    return interp_ok(());
1389                }
1390                // Now that we definitely have a non-ZST array, we know it lives in memory -- except it may
1391                // be an uninitialized local variable, those are also "immediate".
1392                let mplace = match val.to_op(self.ecx)?.as_mplace_or_imm() {
1393                    Left(mplace) => mplace,
1394                    Right(imm) => match *imm {
1395                        Immediate::Uninit =>
1396                            do yeet {
        let where_ = &self.path;
        let path =
            if !where_.projs.is_empty() {
                let mut path = String::new();
                write_path(&mut path, &where_.projs);
                Some(path)
            } else { None };
        #[allow(unused)]
        use ValidationErrorKind::*;
        let msg = ValidationErrorKind::from(Uninit { expected });
        ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
                orig_ty: where_.orig_ty,
                path,
                ptr_bytes_warning: msg.ptr_bytes_warning(),
                msg: msg.to_string(),
            })
    }throw_validation_failure!(
1397                                self.path,
1398                                Uninit { expected }
1399                            ),
1400                        Immediate::Scalar(..) | Immediate::ScalarPair(..) =>
1401                            ::rustc_middle::util::bug::bug_fmt(format_args!("arrays/slices can never have Scalar/ScalarPair layout"))bug!("arrays/slices can never have Scalar/ScalarPair layout"),
1402                    }
1403                };
1404
1405                // Optimization: we just check the entire range at once.
1406                // NOTE: Keep this in sync with the handling of integer and float
1407                // types above, in `visit_primitive`.
1408                // No need for an alignment check here, this is not an actual memory access.
1409                let alloc = self.ecx.get_ptr_alloc(mplace.ptr(), size)?.expect("we already excluded size 0");
1410
1411                alloc.get_bytes_strip_provenance().map_err_kind(|kind| {
1412                    // Some error happened, try to provide a more detailed description.
1413                    // For some errors we might be able to provide extra information.
1414                    // (This custom logic does not fit the `try_validation!` macro.)
1415                    match kind {
1416                        Ub(InvalidUninitBytes(Some((_alloc_id, access)))) | Unsup(ReadPointerAsInt(Some((_alloc_id, access)))) => {
1417                            // Some byte was uninitialized, determine which
1418                            // element that byte belongs to so we can
1419                            // provide an index.
1420                            let i = usize::try_from(
1421                                access.bad.start.bytes() / layout.size.bytes(),
1422                            )
1423                            .unwrap();
1424                            self.path.projs.push(PathElem::ArrayElem(i));
1425
1426                            if #[allow(non_exhaustive_omitted_patterns)] match kind {
    Ub(InvalidUninitBytes(_)) => true,
    _ => false,
}matches!(kind, Ub(InvalidUninitBytes(_))) {
1427                                {
    let where_ = &self.path;
    let path =
        if !where_.projs.is_empty() {
            let mut path = String::new();
            write_path(&mut path, &where_.projs);
            Some(path)
        } else { None };
    #[allow(unused)]
    use ValidationErrorKind::*;
    let msg = ValidationErrorKind::from(Uninit { expected });
    ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
            orig_ty: where_.orig_ty,
            path,
            ptr_bytes_warning: msg.ptr_bytes_warning(),
            msg: msg.to_string(),
        })
}err_validation_failure!(self.path, Uninit { expected })
1428                            } else {
1429                                {
    let where_ = &self.path;
    let path =
        if !where_.projs.is_empty() {
            let mut path = String::new();
            write_path(&mut path, &where_.projs);
            Some(path)
        } else { None };
    #[allow(unused)]
    use ValidationErrorKind::*;
    let msg = ValidationErrorKind::from(PointerAsInt { expected });
    ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
            orig_ty: where_.orig_ty,
            path,
            ptr_bytes_warning: msg.ptr_bytes_warning(),
            msg: msg.to_string(),
        })
}err_validation_failure!(self.path, PointerAsInt {expected})
1430                            }
1431                        }
1432
1433                        // Propagate upwards (that will also check for unexpected errors).
1434                        err => err,
1435                    }
1436                })?;
1437
1438                // Don't forget that these are all non-pointer types, and thus do not preserve
1439                // provenance.
1440                if self.reset_provenance_and_padding {
1441                    // We can't share this with above as above, we might be looking at read-only memory.
1442                    let mut alloc = self.ecx.get_ptr_alloc_mut(mplace.ptr(), size)?.expect("we already excluded size 0");
1443                    alloc.clear_provenance();
1444                    // Also, mark this as containing data, not padding.
1445                    self.add_data_range(mplace.ptr(), size);
1446                }
1447            }
1448            // Fast path for arrays and slices of ZSTs. We only need to check a single ZST element
1449            // of an array and not all of them, because there's only a single value of a specific
1450            // ZST type, so either validation fails for all elements or none.
1451            ty::Array(tys, ..) | ty::Slice(tys) if self.ecx.layout_of(*tys)?.is_zst() => {
1452                // Validate just the first element (if any).
1453                if val.len(self.ecx)? > 0 {
1454                    self.visit_field(val, 0, &self.ecx.project_index(val, 0)?)?;
1455                }
1456            }
1457            ty::Pat(base, pat) => {
1458                // First check that the base type is valid
1459                self.visit_value(&val.transmute(self.ecx.layout_of(*base)?, self.ecx)?)?;
1460                // When you extend this match, make sure to also add tests to
1461                // tests/ui/type/pattern_types/validity.rs
1462                match **pat {
1463                    // Range and non-null patterns are precisely reflected into `valid_range` and thus
1464                    // handled fully by `visit_scalar` (called below).
1465                    ty::PatternKind::Range { .. } => {},
1466                    ty::PatternKind::NotNull => {},
1467
1468                    // FIXME(pattern_types): check that the value is covered by one of the variants.
1469                    // For now, we rely on layout computation setting the scalar's `valid_range` to
1470                    // match the pattern. However, this cannot always work; the layout may
1471                    // pessimistically cover actually illegal ranges and Miri would miss that UB.
1472                    // The consolation here is that codegen also will miss that UB, so at least
1473                    // we won't see optimizations actually breaking such programs.
1474                    ty::PatternKind::Or(_patterns) => {}
1475                }
1476                // FIXME(pattern_types): handle everything based on the pattern, not on the layout.
1477                // it's ok to run scalar validation even if the pattern type is `u8 is 0..=255` and thus
1478                // allows uninit values, because that's rare and so not a perf issue.
1479                match val.layout.backend_repr {
1480                    BackendRepr::Scalar(scalar_layout) => {
1481                        if !scalar_layout.is_uninit_valid() {
1482                            // There is something to check here.
1483                            // We read directly via `ecx` since the read cannot fail -- we already read
1484                            // this field above when recursing into the field.
1485                            let scalar = self.ecx.read_scalar(val)?;
1486                            self.visit_scalar(scalar, scalar_layout)?;
1487                        }
1488                    }
1489                    BackendRepr::ScalarPair(a_layout, b_layout) => {
1490                        // We can only proceed if *both* scalars need to be initialized.
1491                        // FIXME: find a way to also check ScalarPair when one side can be uninit but
1492                        // the other must be init.
1493                        if !a_layout.is_uninit_valid() && !b_layout.is_uninit_valid() {
1494                            // We read directly via `ecx` since the read cannot fail -- we already read
1495                            // this field above when recursing into the field.
1496                            let (a, b) = self.ecx.read_immediate(val)?.to_scalar_pair();
1497                            self.visit_scalar(a, a_layout)?;
1498                            self.visit_scalar(b, b_layout)?;
1499                        }
1500                    }
1501                    BackendRepr::SimdVector { .. } | BackendRepr::SimdScalableVector { .. } => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1502                    BackendRepr::Memory { .. } => ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
1503                }
1504            }
1505            ty::Adt(adt, _) if adt.is_maybe_dangling() => {
1506                let old_may_dangle = mem::replace(&mut self.may_dangle, true);
1507
1508                let inner = self.ecx.project_field(val, FieldIdx::ZERO)?;
1509                self.visit_value(&inner)?;
1510
1511                self.may_dangle = old_may_dangle;
1512            }
1513            _ => {
1514                // default handler
1515                {
    self.walk_value(val).map_err_kind(|e|
                {
                    match e {
                        Ub(InvalidVTableTrait { vtable_dyn_type, expected_dyn_type
                            }) => {
                            {
                                let where_ = &self.path;
                                let path =
                                    if !where_.projs.is_empty() {
                                        let mut path = String::new();
                                        write_path(&mut path, &where_.projs);
                                        Some(path)
                                    } else { None };
                                #[allow(unused)]
                                use ValidationErrorKind::*;
                                let msg =
                                    ValidationErrorKind::from(InvalidMetaWrongTrait {
                                            expected_dyn_type,
                                            vtable_dyn_type,
                                        });
                                ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
                                        orig_ty: where_.orig_ty,
                                        path,
                                        ptr_bytes_warning: msg.ptr_bytes_warning(),
                                        msg: msg.to_string(),
                                    })
                            }
                        }
                        e => e,
                    }
                })?
};try_validation!(
1516                    self.walk_value(val),
1517                    self.path,
1518                    // It's not great to catch errors here, since we can't give a very good path,
1519                    // but it's better than ICEing.
1520                    Ub(InvalidVTableTrait { vtable_dyn_type, expected_dyn_type }) =>
1521                        InvalidMetaWrongTrait { expected_dyn_type, vtable_dyn_type },
1522                );
1523            }
1524        }
1525
1526        // Assert that we checked everything there is to check about this type.
1527        if !!val.layout.is_uninhabited() {
    {
        ::core::panicking::panic_fmt(format_args!("a value of type `{0}` passed validation but that type is uninhabited",
                val.layout.ty));
    }
};assert!(
1528            !val.layout.is_uninhabited(),
1529            "a value of type `{}` passed validation but that type is uninhabited",
1530            val.layout.ty
1531        );
1532        if truecfg!(debug_assertions) {
1533            // Only run expensive checks when debug assertions are enabled.
1534            match val.layout.backend_repr {
1535                BackendRepr::Scalar(scalar_layout) => {
1536                    if !scalar_layout.is_uninit_valid() {
1537                        // There is something to check here.
1538                        // We read directly via `ecx` since the read cannot fail -- we already read
1539                        // this field above when recursing into the field.
1540                        let scalar = self
1541                            .ecx
1542                            .read_scalar(val)
1543                            .expect("the above checks should have fully handled this situation");
1544                        self.visit_scalar(scalar, scalar_layout)
1545                            .expect("the above checks should have fully handled this situation");
1546                    }
1547                }
1548                BackendRepr::ScalarPair(a_layout, b_layout) => {
1549                    // We can only proceed if *both* scalars need to be initialized.
1550                    // FIXME: find a way to also check ScalarPair when one side can be uninit but
1551                    // the other must be init.
1552                    if !a_layout.is_uninit_valid() && !b_layout.is_uninit_valid() {
1553                        let (a, b) = self
1554                            .ecx
1555                            .read_immediate(val)
1556                            .expect("the above checks should have fully handled this situation")
1557                            .to_scalar_pair();
1558                        self.visit_scalar(a, a_layout)
1559                            .expect("the above checks should have fully handled this situation");
1560                        self.visit_scalar(b, b_layout)
1561                            .expect("the above checks should have fully handled this situation");
1562                    }
1563                }
1564                BackendRepr::SimdVector { .. } | BackendRepr::SimdScalableVector { .. } => {}
1565                BackendRepr::Memory { .. } => {}
1566            }
1567        }
1568
1569        interp_ok(())
1570    }
1571}
1572
1573impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
1574    /// The internal core entry point for all validation operations.
1575    fn validate_operand_internal(
1576        &mut self,
1577        val: &PlaceTy<'tcx, M::Provenance>,
1578        path: Path<'tcx>,
1579        ref_tracking: Option<&mut RefTracking<MPlaceTy<'tcx, M::Provenance>, Path<'tcx>>>,
1580        ctfe_mode: Option<CtfeValidationMode>,
1581        reset_provenance_and_padding: bool,
1582        start_in_may_dangle: bool,
1583    ) -> InterpResult<'tcx> {
1584        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_const_eval/src/interpret/validity.rs:1584",
                        "rustc_const_eval::interpret::validity",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/validity.rs"),
                        ::tracing_core::__macro_support::Option::Some(1584u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::validity"),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("validate_operand_internal: {0:?}, {1:?}",
                                                    *val, val.layout.ty) as &dyn Value))])
            });
    } else { ; }
};trace!("validate_operand_internal: {:?}, {:?}", *val, val.layout.ty);
1585
1586        // Run the visitor.
1587        self.run_for_validation_mut(|ecx| {
1588            let reset_padding = reset_provenance_and_padding && {
1589                // Check if `val` is actually stored in memory. If not, padding is not even
1590                // represented and we need not reset it.
1591                ecx.place_to_op(val)?.as_mplace_or_imm().is_left()
1592            };
1593            let mut v = ValidityVisitor {
1594                path,
1595                ref_tracking,
1596                ctfe_mode,
1597                ecx,
1598                reset_provenance_and_padding,
1599                data_bytes: reset_padding.then_some(RangeSet::new()),
1600                may_dangle: start_in_may_dangle,
1601            };
1602            v.visit_value(val)?;
1603            v.reset_padding(val)?;
1604            interp_ok(())
1605        })
1606        .map_err_info(|err| {
1607            if !#[allow(non_exhaustive_omitted_patterns)] match err.kind() {
    InterpErrorKind::UndefinedBehavior(ValidationError { .. }) |
        InterpErrorKind::InvalidProgram(_) | InterpErrorKind::Unsupported(_) |
        InterpErrorKind::MachineStop(_) => true,
    _ => false,
}matches!(
1608                err.kind(),
1609                InterpErrorKind::UndefinedBehavior(ValidationError { .. })
1610                    | InterpErrorKind::InvalidProgram(_)
1611                    | InterpErrorKind::Unsupported(_)
1612                // We have to also ignore machine-specific errors since we do retagging
1613                // during validation.
1614                | InterpErrorKind::MachineStop(_)
1615            ) {
1616                ::rustc_middle::util::bug::bug_fmt(format_args!("Unexpected error during validation: {0}",
        format_interp_error(err)));bug!("Unexpected error during validation: {}", format_interp_error(err));
1617            }
1618            err
1619        })
1620    }
1621
1622    /// This function checks the data at `val` to be const-valid.
1623    /// `val` is assumed to cover valid memory if it is an indirect operand.
1624    /// It will error if the bits at the destination do not match the ones described by the layout.
1625    ///
1626    /// `ref_tracking` is used to record references that we encounter so that they
1627    /// can be checked recursively by an outside driving loop.
1628    ///
1629    /// `constant` controls whether this must satisfy the rules for constants:
1630    /// - no pointers to statics.
1631    /// - no `UnsafeCell` or non-ZST `&mut`.
1632    #[inline(always)]
1633    pub(crate) fn const_validate_operand(
1634        &mut self,
1635        val: &PlaceTy<'tcx, M::Provenance>,
1636        path: Path<'tcx>,
1637        ref_tracking: &mut RefTracking<MPlaceTy<'tcx, M::Provenance>, Path<'tcx>>,
1638        ctfe_mode: CtfeValidationMode,
1639    ) -> InterpResult<'tcx> {
1640        self.validate_operand_internal(
1641            val,
1642            path,
1643            Some(ref_tracking),
1644            Some(ctfe_mode),
1645            /*reset_provenance*/ false,
1646            /*start_in_may_dangle*/ false,
1647        )
1648    }
1649
1650    /// This function checks the data at `val` to be runtime-valid.
1651    /// `val` is assumed to cover valid memory if it is an indirect operand.
1652    /// It will error if the bits at the destination do not match the ones described by the layout.
1653    #[inline(always)]
1654    pub fn validate_operand(
1655        &mut self,
1656        val: &PlaceTy<'tcx, M::Provenance>,
1657        recursive: bool,
1658        reset_provenance_and_padding: bool,
1659    ) -> InterpResult<'tcx> {
1660        let _trace = <M as
        crate::interpret::Machine>::enter_trace_span(||
        {
            use ::tracing::__macro_support::Callsite as _;
            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                {
                    static META: ::tracing::Metadata<'static> =
                        {
                            ::tracing_core::metadata::Metadata::new("validate_operand",
                                "rustc_const_eval::interpret::validity",
                                ::tracing::Level::INFO,
                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/validity.rs"),
                                ::tracing_core::__macro_support::Option::Some(1660u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::validity"),
                                ::tracing_core::field::FieldSet::new(&["recursive",
                                                "reset_provenance_and_padding", "val"],
                                    ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                ::tracing::metadata::Kind::SPAN)
                        };
                    ::tracing::callsite::DefaultCallsite::new(&META)
                };
            let mut interest = ::tracing::subscriber::Interest::never();
            if ::tracing::Level::INFO <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::INFO <=
                                ::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};
                            let mut iter = meta.fields().iter();
                            meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&recursive as
                                                        &dyn Value)),
                                            (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&reset_provenance_and_padding
                                                        as &dyn Value)),
                                            (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&val) as
                                                        &dyn Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        })enter_trace_span!(
1661            M,
1662            "validate_operand",
1663            recursive,
1664            reset_provenance_and_padding,
1665            ?val,
1666        );
1667        // Note that we *could* actually be in CTFE here with `-Zextra-const-ub-checks`, but it's
1668        // still correct to not use `ctfe_mode`: that mode is for validation of the final constant
1669        // value, it rules out things like `UnsafeCell` in awkward places.
1670        if !recursive {
1671            return self.validate_operand_internal(
1672                val,
1673                Path::new(val.layout.ty),
1674                None,
1675                None,
1676                reset_provenance_and_padding,
1677                /*start_in_may_dangle*/ false,
1678            );
1679        }
1680        // Do a recursive check.
1681        let mut ref_tracking = RefTracking::empty();
1682        self.validate_operand_internal(
1683            val,
1684            Path::new(val.layout.ty),
1685            Some(&mut ref_tracking),
1686            None,
1687            reset_provenance_and_padding,
1688            /*start_in_may_dangle*/ false,
1689        )?;
1690        while let Some((mplace, path)) = ref_tracking.todo.pop() {
1691            // Things behind reference do *not* have the provenance reset. In fact
1692            // we treat the entire thing as being inside MaybeDangling, i.e., references
1693            // do not have to be dereferenceable.
1694            self.validate_operand_internal(
1695                &mplace.into(),
1696                path,
1697                None, // no further recursion
1698                None,
1699                /*reset_provenance_and_padding*/ false,
1700                /*start_in_may_dangle*/ true,
1701            )?;
1702        }
1703        interp_ok(())
1704    }
1705}