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
7 use std::convert::TryFrom;
9 use std::num::NonZeroUsize;
10 use std::ops::RangeInclusive;
12 use rustc_data_structures::fx::FxHashSet;
15 use rustc_middle::ty::layout::TyAndLayout;
16 use rustc_span::symbol::{sym, Symbol};
17 use rustc_target::abi::{Abi, LayoutOf, Scalar, VariantIdx, Variants};
22 CheckInAllocMsg, GlobalAlloc, InterpCx, InterpResult, MPlaceTy, Machine, MemPlaceMeta, OpTy,
26 macro_rules! throw_validation_failure {
27 ($what:expr, $where:expr $(, $details:expr )?) => {{
28 let mut msg = format!("encountered {}", $what);
30 if !where_.is_empty() {
32 write_path(&mut msg, where_);
34 $( write!(&mut msg, ", but expected {}", $details).unwrap(); )?
35 throw_ub!(ValidationFailure(msg))
39 /// Returns a validation failure for any Err value of $e.
40 macro_rules! try_validation {
41 ($e:expr, $what:expr, $where:expr $(, $details:expr )?) => {{
42 try_validation_pat!($e, _, $what, $where $(, $details )?)
45 /// Like try_validation, but will throw a validation error if any of the patterns in $p are
46 /// matched. Other errors are passed back to the caller, unchanged. This lets you use the patterns
47 /// as a kind of validation blacklist:
50 /// let v = try_validation_pat(some_fn(), Foo | Bar | Baz, "some failure", "some place");
51 /// // Failures that match $p are thrown up as validation errors, but other errors are passed back
54 macro_rules! try_validation_pat {
55 ($e:expr, $( $p:pat )|*, $what:expr, $where:expr $(, $details:expr )?) => {{
58 // We catch the error and turn it into a validation failure. We are okay with
59 // allocation here as this can only slow down builds that fail anyway.
60 $( Err($p) )|* if true => throw_validation_failure!($what, $where $(, $details)?),
61 Err(e) => Err::<!, _>(e)?,
66 /// We want to show a nice path to the invalid field for diagnostics,
67 /// but avoid string operations in the happy case where no error happens.
68 /// So we track a `Vec<PathElem>` where `PathElem` contains all the data we
69 /// need to later print something for the user.
70 #[derive(Copy, Clone, Debug)]
74 GeneratorState(VariantIdx),
84 /// State for tracking recursive validation of references
85 pub struct RefTracking<T, PATH = ()> {
86 pub seen: FxHashSet<T>,
87 pub todo: Vec<(T, PATH)>,
90 impl<T: Copy + Eq + Hash + std::fmt::Debug, PATH: Default> RefTracking<T, PATH> {
91 pub fn empty() -> Self {
92 RefTracking { seen: FxHashSet::default(), todo: vec![] }
94 pub fn new(op: T) -> Self {
95 let mut ref_tracking_for_consts =
96 RefTracking { seen: FxHashSet::default(), todo: vec![(op, PATH::default())] };
97 ref_tracking_for_consts.seen.insert(op);
98 ref_tracking_for_consts
101 pub fn track(&mut self, op: T, path: impl FnOnce() -> PATH) {
102 if self.seen.insert(op) {
103 trace!("Recursing below ptr {:#?}", op);
105 // Remember to come back to this later.
106 self.todo.push((op, path));
112 fn write_path(out: &mut String, path: &Vec<PathElem>) {
113 use self::PathElem::*;
115 for elem in path.iter() {
117 Field(name) => write!(out, ".{}", name),
118 EnumTag => write!(out, ".<enum-tag>"),
119 Variant(name) => write!(out, ".<enum-variant({})>", name),
120 GeneratorTag => write!(out, ".<generator-tag>"),
121 GeneratorState(idx) => write!(out, ".<generator-state({})>", idx.index()),
122 CapturedVar(name) => write!(out, ".<captured-var({})>", name),
123 TupleElem(idx) => write!(out, ".{}", idx),
124 ArrayElem(idx) => write!(out, "[{}]", idx),
125 // `.<deref>` does not match Rust syntax, but it is more readable for long paths -- and
126 // some of the other items here also are not Rust syntax. Actually we can't
127 // even use the usual syntax because we are just showing the projections,
129 Deref => write!(out, ".<deref>"),
130 DynDowncast => write!(out, ".<dyn-downcast>"),
136 // Test if a range that wraps at overflow contains `test`
137 fn wrapping_range_contains(r: &RangeInclusive<u128>, test: u128) -> bool {
138 let (lo, hi) = r.clone().into_inner();
141 (..=hi).contains(&test) || (lo..).contains(&test)
148 // Formats such that a sentence like "expected something {}" to mean
149 // "expected something <in the given range>" makes sense.
150 fn wrapping_range_format(r: &RangeInclusive<u128>, max_hi: u128) -> String {
151 let (lo, hi) = r.clone().into_inner();
152 assert!(hi <= max_hi);
154 format!("less or equal to {}, or greater or equal to {}", hi, lo)
156 format!("equal to {}", lo)
158 assert!(hi < max_hi, "should not be printing if the range covers everything");
159 format!("less or equal to {}", hi)
160 } else if hi == max_hi {
161 assert!(lo > 0, "should not be printing if the range covers everything");
162 format!("greater or equal to {}", lo)
164 format!("in the range {:?}", r)
168 struct ValidityVisitor<'rt, 'mir, 'tcx, M: Machine<'mir, 'tcx>> {
169 /// The `path` may be pushed to, but the part that is present when a function
170 /// starts must not be changed! `visit_fields` and `visit_array` rely on
171 /// this stack discipline.
173 ref_tracking_for_consts:
174 Option<&'rt mut RefTracking<MPlaceTy<'tcx, M::PointerTag>, Vec<PathElem>>>,
175 may_ref_to_static: bool,
176 ecx: &'rt InterpCx<'mir, 'tcx, M>,
179 impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValidityVisitor<'rt, 'mir, 'tcx, M> {
180 fn aggregate_field_path_elem(&mut self, layout: TyAndLayout<'tcx>, field: usize) -> PathElem {
181 // First, check if we are projecting to a variant.
182 match layout.variants {
183 Variants::Multiple { discr_index, .. } => {
184 if discr_index == field {
185 return match layout.ty.kind {
186 ty::Adt(def, ..) if def.is_enum() => PathElem::EnumTag,
187 ty::Generator(..) => PathElem::GeneratorTag,
188 _ => bug!("non-variant type {:?}", layout.ty),
192 Variants::Single { .. } => {}
195 // Now we know we are projecting to a field, so figure out which one.
196 match layout.ty.kind {
197 // generators and closures.
198 ty::Closure(def_id, _) | ty::Generator(def_id, _, _) => {
200 if let Some(def_id) = def_id.as_local() {
201 let tables = self.ecx.tcx.typeck_tables_of(def_id);
202 if let Some(upvars) = tables.upvar_list.get(&def_id.to_def_id()) {
203 // Sometimes the index is beyond the number of upvars (seen
205 if let Some((&var_hir_id, _)) = upvars.get_index(field) {
206 let node = self.ecx.tcx.hir().get(var_hir_id);
207 if let hir::Node::Binding(pat) = node {
208 if let hir::PatKind::Binding(_, _, ident, _) = pat.kind {
209 name = Some(ident.name);
216 PathElem::CapturedVar(name.unwrap_or_else(|| {
217 // Fall back to showing the field index.
223 ty::Tuple(_) => PathElem::TupleElem(field),
226 ty::Adt(def, ..) if def.is_enum() => {
227 // we might be projecting *to* a variant, or to a field *in* a variant.
228 match layout.variants {
229 Variants::Single { index } => {
231 PathElem::Field(def.variants[index].fields[field].ident.name)
233 Variants::Multiple { .. } => bug!("we handled variants above"),
238 ty::Adt(def, _) => PathElem::Field(def.non_enum_variant().fields[field].ident.name),
241 ty::Array(..) | ty::Slice(..) => PathElem::ArrayElem(field),
244 ty::Dynamic(..) => PathElem::DynDowncast,
246 // nothing else has an aggregate layout
247 _ => bug!("aggregate_field_path_elem: got non-aggregate type {:?}", layout.ty),
253 new_op: OpTy<'tcx, M::PointerTag>,
255 ) -> InterpResult<'tcx> {
256 // Remember the old state
257 let path_len = self.path.len();
259 self.path.push(elem);
260 self.visit_value(new_op)?;
262 self.path.truncate(path_len);
266 fn check_wide_ptr_meta(
268 meta: MemPlaceMeta<M::PointerTag>,
269 pointee: TyAndLayout<'tcx>,
270 ) -> InterpResult<'tcx> {
271 let tail = self.ecx.tcx.struct_tail_erasing_lifetimes(pointee.ty, self.ecx.param_env);
274 let vtable = meta.unwrap_meta();
276 self.ecx.memory.check_ptr_access(
278 3 * self.ecx.tcx.data_layout.pointer_size, // drop, size, align
279 self.ecx.tcx.data_layout.pointer_align.abi,
281 "dangling or unaligned vtable pointer in wide pointer or too small vtable",
285 self.ecx.read_drop_type_from_vtable(vtable),
286 "invalid drop fn in vtable",
290 self.ecx.read_size_and_align_from_vtable(vtable),
291 "invalid size or align in vtable",
294 // FIXME: More checks for the vtable.
296 ty::Slice(..) | ty::Str => {
297 let _len = try_validation!(
298 meta.unwrap_meta().to_machine_usize(self.ecx),
299 "non-integer slice length in wide pointer",
302 // We do not check that `len * elem_size <= isize::MAX`:
303 // that is only required for references, and there it falls out of the
304 // "dereferenceable" check performed by Stacked Borrows.
307 // Unsized, but not wide.
309 _ => bug!("Unexpected unsized type tail: {:?}", tail),
315 /// Check a reference or `Box`.
316 fn check_safe_pointer(
318 value: OpTy<'tcx, M::PointerTag>,
320 ) -> InterpResult<'tcx> {
321 let value = self.ecx.read_immediate(value)?;
322 // Handle wide pointers.
323 // Check metadata early, for better diagnostics
324 let place = try_validation!(
325 self.ecx.ref_to_mplace(value),
326 format_args!("uninitialized {}", kind),
329 if place.layout.is_unsized() {
330 self.check_wide_ptr_meta(place.meta, place.layout)?;
332 // Make sure this is dereferenceable and all.
333 let size_and_align = match self.ecx.size_and_align_of(place.meta, place.layout) {
335 Err(err) => match err.kind {
336 err_ub!(InvalidMeta(msg)) => throw_validation_failure!(
337 format_args!("invalid {} metadata: {}", kind, msg),
340 _ => bug!("unexpected error during ptr size_and_align_of: {}", err),
343 let (size, align) = size_and_align
344 // for the purpose of validity, consider foreign types to have
345 // alignment and size determined by the layout (size will be 0,
346 // alignment should take attributes into account).
347 .unwrap_or_else(|| (place.layout.size, place.layout.align.abi));
348 let ptr: Option<_> = match self.ecx.memory.check_ptr_access_align(
352 CheckInAllocMsg::InboundsTest,
357 "{:?} did not pass access check for size {:?}, align {:?}",
358 place.ptr, size, align
361 err_ub!(InvalidIntPointerUsage(0)) => {
362 throw_validation_failure!(format_args!("a NULL {}", kind), self.path)
364 err_ub!(InvalidIntPointerUsage(i)) => throw_validation_failure!(
365 format_args!("a {} to unallocated address {}", kind, i),
368 err_ub!(AlignmentCheckFailed { required, has }) => throw_validation_failure!(
370 "an unaligned {} (required {} byte alignment but found {})",
377 err_unsup!(ReadBytesAsPointer) => throw_validation_failure!(
378 format_args!("a dangling {} (created from integer)", kind),
381 err_ub!(PointerOutOfBounds { .. }) => throw_validation_failure!(
383 "a dangling {} (going beyond the bounds of its allocation)",
388 // This cannot happen during const-eval (because interning already detects
389 // dangling pointers), but it can happen in Miri.
390 err_ub!(PointerUseAfterFree(_)) => throw_validation_failure!(
391 format_args!("a dangling {} (use-after-free)", kind),
394 _ => bug!("Unexpected error during ptr inbounds test: {}", err),
398 // Recursive checking
399 if let Some(ref mut ref_tracking) = self.ref_tracking_for_consts {
400 if let Some(ptr) = ptr {
402 // Skip validation entirely for some external statics
403 let alloc_kind = self.ecx.tcx.alloc_map.lock().get(ptr.alloc_id);
404 if let Some(GlobalAlloc::Static(did)) = alloc_kind {
405 // See const_eval::machine::MemoryExtra::can_access_statics for why
406 // this check is so important.
407 // This check is reachable when the const just referenced the static,
408 // but never read it (so we never entered `before_access_global`).
409 // We also need to do it here instead of going on to avoid running
410 // into the `before_access_global` check during validation.
411 if !self.may_ref_to_static && self.ecx.tcx.is_static(did) {
412 throw_validation_failure!(
413 format_args!("a {} pointing to a static variable", kind),
417 // `extern static` cannot be validated as they have no body.
418 // FIXME: Statics from other crates are also skipped.
419 // They might be checked at a different type, but for now we
420 // want to avoid recursing too deeply. We might miss const-invalid data,
421 // but things are still sound otherwise (in particular re: consts
422 // referring to statics).
423 if !did.is_local() || self.ecx.tcx.is_foreign_item(did) {
428 // Proceed recursively even for ZST, no reason to skip them!
429 // `!` is a ZST and we want to validate it.
430 // Normalize before handing `place` to tracking because that will
431 // check for duplicates.
432 let place = if size.bytes() > 0 {
433 self.ecx.force_mplace_ptr(place).expect("we already bounds-checked")
437 let path = &self.path;
438 ref_tracking.track(place, || {
439 // We need to clone the path anyway, make sure it gets created
440 // with enough space for the additional `Deref`.
441 let mut new_path = Vec::with_capacity(path.len() + 1);
442 new_path.clone_from(path);
443 new_path.push(PathElem::Deref);
450 /// Check if this is a value of primitive type, and if yes check the validity of the value
451 /// at that type. Return `true` if the type is indeed primitive.
452 fn try_visit_primitive(
454 value: OpTy<'tcx, M::PointerTag>,
455 ) -> InterpResult<'tcx, bool> {
456 // Go over all the primitive types
457 let ty = value.layout.ty;
460 let value = self.ecx.read_scalar(value)?;
461 try_validation!(value.to_bool(), value, self.path, "a boolean");
465 let value = self.ecx.read_scalar(value)?;
466 try_validation!(value.to_char(), value, self.path, "a valid unicode codepoint");
469 ty::Float(_) | ty::Int(_) | ty::Uint(_) => {
470 let value = self.ecx.read_scalar(value)?;
471 // NOTE: Keep this in sync with the array optimization for int/float
473 if self.ref_tracking_for_consts.is_some() {
474 // Integers/floats in CTFE: Must be scalar bits, pointers are dangerous
475 let is_bits = value.not_undef().map_or(false, |v| v.is_bits());
477 throw_validation_failure!(
480 "initialized plain (non-pointer) bytes"
484 // At run-time, for now, we accept *anything* for these types, including
485 // undef. We should fix that, but let's start low.
490 // We are conservative with undef for integers, but try to
491 // actually enforce the strict rules for raw pointers (mostly because
492 // that lets us re-use `ref_to_mplace`).
493 let place = try_validation_pat!(
494 self.ecx.ref_to_mplace(self.ecx.read_immediate(value)?),
496 "uninitialized raw pointer",
499 if place.layout.is_unsized() {
500 self.check_wide_ptr_meta(place.meta, place.layout)?;
505 self.check_safe_pointer(value, "reference")?;
508 ty::Adt(def, ..) if def.is_box() => {
509 self.check_safe_pointer(value, "box")?;
513 let value = self.ecx.read_scalar(value)?;
514 let _fn = try_validation!(
515 value.not_undef().and_then(|ptr| self.ecx.memory.get_fn(ptr)),
520 // FIXME: Check if the signature matches
523 ty::Never => throw_validation_failure!("a value of the never type `!`", self.path),
524 ty::Foreign(..) | ty::FnDef(..) => {
528 // The above should be all the (inhabited) primitive types. The rest is compound, we
529 // check them by visiting their fields/variants.
530 // (`Str` UTF-8 check happens in `visit_aggregate`, too.)
538 | ty::Generator(..) => Ok(false),
539 // Some types only occur during typechecking, they have no layout.
540 // We should not see them here and we could not check them anyway.
543 | ty::Placeholder(..)
547 | ty::UnnormalizedProjection(..)
549 | ty::GeneratorWitness(..) => bug!("Encountered invalid type {:?}", ty),
555 op: OpTy<'tcx, M::PointerTag>,
556 scalar_layout: &Scalar,
557 ) -> InterpResult<'tcx> {
558 let value = self.ecx.read_scalar(op)?;
559 let valid_range = &scalar_layout.valid_range;
560 let (lo, hi) = valid_range.clone().into_inner();
561 // Determine the allowed range
562 // `max_hi` is as big as the size fits
563 let max_hi = u128::MAX >> (128 - op.layout.size.bits());
564 assert!(hi <= max_hi);
565 // We could also write `(hi + 1) % (max_hi + 1) == lo` but `max_hi + 1` overflows for `u128`
566 if (lo == 0 && hi == max_hi) || (hi + 1 == lo) {
570 // At least one value is excluded. Get the bits.
571 let value = try_validation!(
575 format_args!("something {}", wrapping_range_format(valid_range, max_hi),)
577 let bits = match value.to_bits_or_ptr(op.layout.size, self.ecx) {
579 if lo == 1 && hi == max_hi {
580 // Only NULL is the niche. So make sure the ptr is NOT NULL.
581 if self.ecx.memory.ptr_may_be_null(ptr) {
582 throw_validation_failure!(
583 "a potentially NULL pointer",
586 "something that cannot possibly fail to be {}",
587 wrapping_range_format(valid_range, max_hi)
593 // Conservatively, we reject, because the pointer *could* have a bad
595 throw_validation_failure!(
599 "something that cannot possibly fail to be {}",
600 wrapping_range_format(valid_range, max_hi)
607 // Now compare. This is slightly subtle because this is a special "wrap-around" range.
608 if wrapping_range_contains(&valid_range, bits) {
611 throw_validation_failure!(
614 format_args!("something {}", wrapping_range_format(valid_range, max_hi))
620 impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValueVisitor<'mir, 'tcx, M>
621 for ValidityVisitor<'rt, 'mir, 'tcx, M>
623 type V = OpTy<'tcx, M::PointerTag>;
626 fn ecx(&self) -> &InterpCx<'mir, 'tcx, M> {
633 old_op: OpTy<'tcx, M::PointerTag>,
635 new_op: OpTy<'tcx, M::PointerTag>,
636 ) -> InterpResult<'tcx> {
637 let elem = self.aggregate_field_path_elem(old_op.layout, field);
638 self.visit_elem(new_op, elem)
644 old_op: OpTy<'tcx, M::PointerTag>,
645 variant_id: VariantIdx,
646 new_op: OpTy<'tcx, M::PointerTag>,
647 ) -> InterpResult<'tcx> {
648 let name = match old_op.layout.ty.kind {
649 ty::Adt(adt, _) => PathElem::Variant(adt.variants[variant_id].ident.name),
650 // Generators also have variants
651 ty::Generator(..) => PathElem::GeneratorState(variant_id),
652 _ => bug!("Unexpected type with variant: {:?}", old_op.layout.ty),
654 self.visit_elem(new_op, name)
660 _op: OpTy<'tcx, M::PointerTag>,
661 _fields: NonZeroUsize,
662 ) -> InterpResult<'tcx> {
667 fn visit_value(&mut self, op: OpTy<'tcx, M::PointerTag>) -> InterpResult<'tcx> {
668 trace!("visit_value: {:?}, {:?}", *op, op.layout);
670 // Check primitive types -- the leafs of our recursive descend.
671 if self.try_visit_primitive(op)? {
674 // Sanity check: `builtin_deref` does not know any pointers that are not primitive.
675 assert!(op.layout.ty.builtin_deref(true).is_none());
677 // Recursively walk the type. Translate some possible errors to something nicer.
678 match self.walk_value(op) {
680 Err(err) => match err.kind {
681 err_ub!(InvalidDiscriminant(val)) => {
682 throw_validation_failure!(val, self.path, "a valid enum discriminant")
684 err_unsup!(ReadPointerAsBytes) => {
685 throw_validation_failure!("a pointer", self.path, "plain (non-pointer) bytes")
687 // Propagate upwards (that will also check for unexpected errors).
688 _ => return Err(err),
692 // *After* all of this, check the ABI. We need to check the ABI to handle
693 // types like `NonNull` where the `Scalar` info is more restrictive than what
694 // the fields say (`rustc_layout_scalar_valid_range_start`).
695 // But in most cases, this will just propagate what the fields say,
696 // and then we want the error to point at the field -- so, first recurse,
699 // FIXME: We could avoid some redundant checks here. For newtypes wrapping
700 // scalars, we do the same check on every "level" (e.g., first we check
701 // MyNewtype and then the scalar in there).
702 match op.layout.abi {
703 Abi::Uninhabited => {
704 throw_validation_failure!(
705 format_args!("a value of uninhabited type {:?}", op.layout.ty),
709 Abi::Scalar(ref scalar_layout) => {
710 self.visit_scalar(op, scalar_layout)?;
712 Abi::ScalarPair { .. } | Abi::Vector { .. } => {
713 // These have fields that we already visited above, so we already checked
714 // all their scalar-level restrictions.
715 // There is also no equivalent to `rustc_layout_scalar_valid_range_start`
716 // that would make skipping them here an issue.
718 Abi::Aggregate { .. } => {
728 op: OpTy<'tcx, M::PointerTag>,
729 fields: impl Iterator<Item = InterpResult<'tcx, Self::V>>,
730 ) -> InterpResult<'tcx> {
731 match op.layout.ty.kind {
733 let mplace = op.assert_mem_place(self.ecx); // strings are never immediate
735 self.ecx.read_str(mplace),
736 "uninitialized or non-UTF-8 data in str",
740 ty::Array(tys, ..) | ty::Slice(tys)
742 // This optimization applies for types that can hold arbitrary bytes (such as
743 // integer and floating point types) or for structs or tuples with no fields.
744 // FIXME(wesleywiser) This logic could be extended further to arbitrary structs
745 // or tuples made up of integer/floating point types or inhabited ZSTs with no
748 ty::Int(..) | ty::Uint(..) | ty::Float(..) => true,
753 // Optimized handling for arrays of integer/float type.
755 // Arrays cannot be immediate, slices are never immediate.
756 let mplace = op.assert_mem_place(self.ecx);
757 // This is the length of the array/slice.
758 let len = mplace.len(self.ecx)?;
759 // Zero length slices have nothing to be checked.
763 // This is the element type size.
764 let layout = self.ecx.layout_of(tys)?;
765 // This is the size in bytes of the whole array. (This checks for overflow.)
766 let size = layout.size * len;
767 // Size is not 0, get a pointer.
768 let ptr = self.ecx.force_ptr(mplace.ptr)?;
770 // Optimization: we just check the entire range at once.
771 // NOTE: Keep this in sync with the handling of integer and float
772 // types above, in `visit_primitive`.
773 // In run-time mode, we accept pointers in here. This is actually more
774 // permissive than a per-element check would be, e.g., we accept
775 // an &[u8] that contains a pointer even though bytewise checking would
776 // reject it. However, that's good: We don't inherently want
777 // to reject those pointers, we just do not have the machinery to
778 // talk about parts of a pointer.
779 // We also accept undef, for consistency with the slow path.
780 match self.ecx.memory.get_raw(ptr.alloc_id)?.check_bytes(
784 /*allow_ptr_and_undef*/ self.ref_tracking_for_consts.is_none(),
786 // In the happy case, we needn't check anything else.
788 // Some error happened, try to provide a more detailed description.
790 // For some errors we might be able to provide extra information
792 err_ub!(InvalidUndefBytes(Some(ptr))) => {
793 // Some byte was uninitialized, determine which
794 // element that byte belongs to so we can
796 let i = usize::try_from(ptr.offset.bytes() / layout.size.bytes())
798 self.path.push(PathElem::ArrayElem(i));
800 throw_validation_failure!("uninitialized bytes", self.path)
802 // Other errors shouldn't be possible
803 _ => return Err(err),
808 // Fast path for arrays and slices of ZSTs. We only need to check a single ZST element
809 // of an array and not all of them, because there's only a single value of a specific
810 // ZST type, so either validation fails for all elements or none.
811 ty::Array(tys, ..) | ty::Slice(tys) if self.ecx.layout_of(tys)?.is_zst() => {
812 // Validate just the first element
813 self.walk_aggregate(op, fields.take(1))?
816 self.walk_aggregate(op, fields)? // default handler
823 impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
824 fn validate_operand_internal(
826 op: OpTy<'tcx, M::PointerTag>,
828 ref_tracking_for_consts: Option<
829 &mut RefTracking<MPlaceTy<'tcx, M::PointerTag>, Vec<PathElem>>,
831 may_ref_to_static: bool,
832 ) -> InterpResult<'tcx> {
833 trace!("validate_operand_internal: {:?}, {:?}", *op, op.layout.ty);
835 // Construct a visitor
837 ValidityVisitor { path, ref_tracking_for_consts, may_ref_to_static, ecx: self };
839 // Try to cast to ptr *once* instead of all the time.
840 let op = self.force_op_ptr(op).unwrap_or(op);
843 match visitor.visit_value(op) {
845 // We should only get validation errors here. Avoid other errors as
846 // those do not show *where* in the value the issue lies.
847 Err(err) if matches!(err.kind, err_ub!(ValidationFailure { .. })) => Err(err),
848 Err(err) => bug!("Unexpected error during validation: {}", err),
852 /// This function checks the data at `op` to be const-valid.
853 /// `op` is assumed to cover valid memory if it is an indirect operand.
854 /// It will error if the bits at the destination do not match the ones described by the layout.
856 /// `ref_tracking` is used to record references that we encounter so that they
857 /// can be checked recursively by an outside driving loop.
859 /// `may_ref_to_static` controls whether references are allowed to point to statics.
861 pub fn const_validate_operand(
863 op: OpTy<'tcx, M::PointerTag>,
865 ref_tracking: &mut RefTracking<MPlaceTy<'tcx, M::PointerTag>, Vec<PathElem>>,
866 may_ref_to_static: bool,
867 ) -> InterpResult<'tcx> {
868 self.validate_operand_internal(op, path, Some(ref_tracking), may_ref_to_static)
871 /// This function checks the data at `op` to be runtime-valid.
872 /// `op` is assumed to cover valid memory if it is an indirect operand.
873 /// It will error if the bits at the destination do not match the ones described by the layout.
875 pub fn validate_operand(&self, op: OpTy<'tcx, M::PointerTag>) -> InterpResult<'tcx> {
876 self.validate_operand_internal(op, vec![], None, false)