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;
14 use rustc_middle::mir::interpret::{InterpError, InterpErrorInfo};
16 use rustc_middle::ty::layout::TyAndLayout;
17 use rustc_span::symbol::{sym, Symbol};
18 use rustc_target::abi::{Abi, LayoutOf, Scalar, VariantIdx, Variants};
23 CheckInAllocMsg, GlobalAlloc, InterpCx, InterpResult, MPlaceTy, Machine, MemPlaceMeta, OpTy,
27 macro_rules! throw_validation_failure {
28 ($what:expr, $where:expr $(, $expected:expr )?) => {{
29 let mut msg = format!("encountered {}", $what);
31 if !where_.is_empty() {
33 write_path(&mut msg, where_);
35 $( write!(&mut msg, ", but expected {}", $expected).unwrap(); )?
36 throw_ub!(ValidationFailure(msg))
40 /// Returns a validation failure for any Err value of $e.
41 // FIXME: Replace all usages of try_validation! with try_validation_pat!.
42 macro_rules! try_validation {
43 ($e:expr, $what:expr, $where:expr $(, $expected:expr )?) => {{
44 try_validation_pat!($e, $where, {
45 _ => { "{}", $what } $( expected { $expected } )?,
49 /// Like try_validation, but will throw a validation error if any of the patterns in $p are
50 /// matched. Other errors are passed back to the caller, unchanged. This lets you use the patterns
51 /// as a kind of validation blacklist:
54 /// let v = try_validation_pat!(some_fn(), some_path, {
55 /// Foo | Bar | Baz => { "some failure" },
57 /// // Failures that match $p are thrown up as validation errors, but other errors are passed back
61 /// An additional expected parameter can also be added to the failure message:
64 /// let v = try_validation_pat!(some_fn(), some_path, {
65 /// Foo | Bar | Baz => { "some failure" } expected { "something that wasn't a failure" },
69 macro_rules! try_validation_pat {
70 ($e:expr, $where:expr, { $( $p:pat )|* => { $( $what_fmt:expr ),* } $( expected { $expected:expr } )? $( , )?}) => {{
73 // We catch the error and turn it into a validation failure. We are okay with
74 // allocation here as this can only slow down builds that fail anyway.
75 $( Err(InterpErrorInfo { kind: $p, .. }) )|* => throw_validation_failure!(format_args!($( $what_fmt ),*), $where $(, $expected)?),
76 #[allow(unreachable_patterns)]
77 Err(e) => Err::<!, _>(e)?,
82 /// We want to show a nice path to the invalid field for diagnostics,
83 /// but avoid string operations in the happy case where no error happens.
84 /// So we track a `Vec<PathElem>` where `PathElem` contains all the data we
85 /// need to later print something for the user.
86 #[derive(Copy, Clone, Debug)]
90 GeneratorState(VariantIdx),
100 /// State for tracking recursive validation of references
101 pub struct RefTracking<T, PATH = ()> {
102 pub seen: FxHashSet<T>,
103 pub todo: Vec<(T, PATH)>,
106 impl<T: Copy + Eq + Hash + std::fmt::Debug, PATH: Default> RefTracking<T, PATH> {
107 pub fn empty() -> Self {
108 RefTracking { seen: FxHashSet::default(), todo: vec![] }
110 pub fn new(op: T) -> Self {
111 let mut ref_tracking_for_consts =
112 RefTracking { seen: FxHashSet::default(), todo: vec![(op, PATH::default())] };
113 ref_tracking_for_consts.seen.insert(op);
114 ref_tracking_for_consts
117 pub fn track(&mut self, op: T, path: impl FnOnce() -> PATH) {
118 if self.seen.insert(op) {
119 trace!("Recursing below ptr {:#?}", op);
121 // Remember to come back to this later.
122 self.todo.push((op, path));
128 fn write_path(out: &mut String, path: &Vec<PathElem>) {
129 use self::PathElem::*;
131 for elem in path.iter() {
133 Field(name) => write!(out, ".{}", name),
134 EnumTag => write!(out, ".<enum-tag>"),
135 Variant(name) => write!(out, ".<enum-variant({})>", name),
136 GeneratorTag => write!(out, ".<generator-tag>"),
137 GeneratorState(idx) => write!(out, ".<generator-state({})>", idx.index()),
138 CapturedVar(name) => write!(out, ".<captured-var({})>", name),
139 TupleElem(idx) => write!(out, ".{}", idx),
140 ArrayElem(idx) => write!(out, "[{}]", idx),
141 // `.<deref>` does not match Rust syntax, but it is more readable for long paths -- and
142 // some of the other items here also are not Rust syntax. Actually we can't
143 // even use the usual syntax because we are just showing the projections,
145 Deref => write!(out, ".<deref>"),
146 DynDowncast => write!(out, ".<dyn-downcast>"),
152 // Test if a range that wraps at overflow contains `test`
153 fn wrapping_range_contains(r: &RangeInclusive<u128>, test: u128) -> bool {
154 let (lo, hi) = r.clone().into_inner();
157 (..=hi).contains(&test) || (lo..).contains(&test)
164 // Formats such that a sentence like "expected something {}" to mean
165 // "expected something <in the given range>" makes sense.
166 fn wrapping_range_format(r: &RangeInclusive<u128>, max_hi: u128) -> String {
167 let (lo, hi) = r.clone().into_inner();
168 assert!(hi <= max_hi);
170 format!("less or equal to {}, or greater or equal to {}", hi, lo)
172 format!("equal to {}", lo)
174 assert!(hi < max_hi, "should not be printing if the range covers everything");
175 format!("less or equal to {}", hi)
176 } else if hi == max_hi {
177 assert!(lo > 0, "should not be printing if the range covers everything");
178 format!("greater or equal to {}", lo)
180 format!("in the range {:?}", r)
184 struct ValidityVisitor<'rt, 'mir, 'tcx, M: Machine<'mir, 'tcx>> {
185 /// The `path` may be pushed to, but the part that is present when a function
186 /// starts must not be changed! `visit_fields` and `visit_array` rely on
187 /// this stack discipline.
189 ref_tracking_for_consts:
190 Option<&'rt mut RefTracking<MPlaceTy<'tcx, M::PointerTag>, Vec<PathElem>>>,
191 may_ref_to_static: bool,
192 ecx: &'rt InterpCx<'mir, 'tcx, M>,
195 impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValidityVisitor<'rt, 'mir, 'tcx, M> {
196 fn aggregate_field_path_elem(&mut self, layout: TyAndLayout<'tcx>, field: usize) -> PathElem {
197 // First, check if we are projecting to a variant.
198 match layout.variants {
199 Variants::Multiple { discr_index, .. } => {
200 if discr_index == field {
201 return match layout.ty.kind {
202 ty::Adt(def, ..) if def.is_enum() => PathElem::EnumTag,
203 ty::Generator(..) => PathElem::GeneratorTag,
204 _ => bug!("non-variant type {:?}", layout.ty),
208 Variants::Single { .. } => {}
211 // Now we know we are projecting to a field, so figure out which one.
212 match layout.ty.kind {
213 // generators and closures.
214 ty::Closure(def_id, _) | ty::Generator(def_id, _, _) => {
216 if let Some(def_id) = def_id.as_local() {
217 let tables = self.ecx.tcx.typeck_tables_of(def_id);
218 if let Some(upvars) = tables.upvar_list.get(&def_id.to_def_id()) {
219 // Sometimes the index is beyond the number of upvars (seen
221 if let Some((&var_hir_id, _)) = upvars.get_index(field) {
222 let node = self.ecx.tcx.hir().get(var_hir_id);
223 if let hir::Node::Binding(pat) = node {
224 if let hir::PatKind::Binding(_, _, ident, _) = pat.kind {
225 name = Some(ident.name);
232 PathElem::CapturedVar(name.unwrap_or_else(|| {
233 // Fall back to showing the field index.
239 ty::Tuple(_) => PathElem::TupleElem(field),
242 ty::Adt(def, ..) if def.is_enum() => {
243 // we might be projecting *to* a variant, or to a field *in* a variant.
244 match layout.variants {
245 Variants::Single { index } => {
247 PathElem::Field(def.variants[index].fields[field].ident.name)
249 Variants::Multiple { .. } => bug!("we handled variants above"),
254 ty::Adt(def, _) => PathElem::Field(def.non_enum_variant().fields[field].ident.name),
257 ty::Array(..) | ty::Slice(..) => PathElem::ArrayElem(field),
260 ty::Dynamic(..) => PathElem::DynDowncast,
262 // nothing else has an aggregate layout
263 _ => bug!("aggregate_field_path_elem: got non-aggregate type {:?}", layout.ty),
269 new_op: OpTy<'tcx, M::PointerTag>,
271 ) -> InterpResult<'tcx> {
272 // Remember the old state
273 let path_len = self.path.len();
275 self.path.push(elem);
276 self.visit_value(new_op)?;
278 self.path.truncate(path_len);
282 fn check_wide_ptr_meta(
284 meta: MemPlaceMeta<M::PointerTag>,
285 pointee: TyAndLayout<'tcx>,
286 ) -> InterpResult<'tcx> {
287 let tail = self.ecx.tcx.struct_tail_erasing_lifetimes(pointee.ty, self.ecx.param_env);
290 let vtable = meta.unwrap_meta();
292 self.ecx.memory.check_ptr_access(
294 3 * self.ecx.tcx.data_layout.pointer_size, // drop, size, align
295 self.ecx.tcx.data_layout.pointer_align.abi,
297 "dangling or unaligned vtable pointer in wide pointer or too small vtable",
301 self.ecx.read_drop_type_from_vtable(vtable),
302 "invalid drop fn in vtable",
306 self.ecx.read_size_and_align_from_vtable(vtable),
307 "invalid size or align in vtable",
310 // FIXME: More checks for the vtable.
312 ty::Slice(..) | ty::Str => {
313 let _len = try_validation!(
314 meta.unwrap_meta().to_machine_usize(self.ecx),
315 "non-integer slice length in wide pointer",
318 // We do not check that `len * elem_size <= isize::MAX`:
319 // that is only required for references, and there it falls out of the
320 // "dereferenceable" check performed by Stacked Borrows.
323 // Unsized, but not wide.
325 _ => bug!("Unexpected unsized type tail: {:?}", tail),
331 /// Check a reference or `Box`.
332 fn check_safe_pointer(
334 value: OpTy<'tcx, M::PointerTag>,
336 ) -> InterpResult<'tcx> {
337 let value = self.ecx.read_immediate(value)?;
338 // Handle wide pointers.
339 // Check metadata early, for better diagnostics
340 let place = try_validation!(
341 self.ecx.ref_to_mplace(value),
342 format_args!("uninitialized {}", kind),
345 if place.layout.is_unsized() {
346 self.check_wide_ptr_meta(place.meta, place.layout)?;
348 // Make sure this is dereferenceable and all.
349 let size_and_align = match self.ecx.size_and_align_of(place.meta, place.layout) {
351 Err(err) => match err.kind {
352 err_ub!(InvalidMeta(msg)) => throw_validation_failure!(
353 format_args!("invalid {} metadata: {}", kind, msg),
356 _ => bug!("unexpected error during ptr size_and_align_of: {}", err),
359 let (size, align) = size_and_align
360 // for the purpose of validity, consider foreign types to have
361 // alignment and size determined by the layout (size will be 0,
362 // alignment should take attributes into account).
363 .unwrap_or_else(|| (place.layout.size, place.layout.align.abi));
364 let ptr: Option<_> = match self.ecx.memory.check_ptr_access_align(
368 CheckInAllocMsg::InboundsTest,
373 "{:?} did not pass access check for size {:?}, align {:?}",
374 place.ptr, size, align
377 err_ub!(InvalidIntPointerUsage(0)) => {
378 throw_validation_failure!(format_args!("a NULL {}", kind), self.path)
380 err_ub!(InvalidIntPointerUsage(i)) => throw_validation_failure!(
381 format_args!("a {} to unallocated address {}", kind, i),
384 err_ub!(AlignmentCheckFailed { required, has }) => throw_validation_failure!(
386 "an unaligned {} (required {} byte alignment but found {})",
393 err_unsup!(ReadBytesAsPointer) => throw_validation_failure!(
394 format_args!("a dangling {} (created from integer)", kind),
397 err_ub!(PointerOutOfBounds { .. }) => throw_validation_failure!(
399 "a dangling {} (going beyond the bounds of its allocation)",
404 // This cannot happen during const-eval (because interning already detects
405 // dangling pointers), but it can happen in Miri.
406 err_ub!(PointerUseAfterFree(_)) => throw_validation_failure!(
407 format_args!("a dangling {} (use-after-free)", kind),
410 _ => bug!("Unexpected error during ptr inbounds test: {}", err),
414 // Recursive checking
415 if let Some(ref mut ref_tracking) = self.ref_tracking_for_consts {
416 if let Some(ptr) = ptr {
418 // Skip validation entirely for some external statics
419 let alloc_kind = self.ecx.tcx.alloc_map.lock().get(ptr.alloc_id);
420 if let Some(GlobalAlloc::Static(did)) = alloc_kind {
421 // See const_eval::machine::MemoryExtra::can_access_statics for why
422 // this check is so important.
423 // This check is reachable when the const just referenced the static,
424 // but never read it (so we never entered `before_access_global`).
425 // We also need to do it here instead of going on to avoid running
426 // into the `before_access_global` check during validation.
427 if !self.may_ref_to_static && self.ecx.tcx.is_static(did) {
428 throw_validation_failure!(
429 format_args!("a {} pointing to a static variable", kind),
433 // `extern static` cannot be validated as they have no body.
434 // FIXME: Statics from other crates are also skipped.
435 // They might be checked at a different type, but for now we
436 // want to avoid recursing too deeply. We might miss const-invalid data,
437 // but things are still sound otherwise (in particular re: consts
438 // referring to statics).
439 if !did.is_local() || self.ecx.tcx.is_foreign_item(did) {
444 // Proceed recursively even for ZST, no reason to skip them!
445 // `!` is a ZST and we want to validate it.
446 // Normalize before handing `place` to tracking because that will
447 // check for duplicates.
448 let place = if size.bytes() > 0 {
449 self.ecx.force_mplace_ptr(place).expect("we already bounds-checked")
453 let path = &self.path;
454 ref_tracking.track(place, || {
455 // We need to clone the path anyway, make sure it gets created
456 // with enough space for the additional `Deref`.
457 let mut new_path = Vec::with_capacity(path.len() + 1);
458 new_path.clone_from(path);
459 new_path.push(PathElem::Deref);
466 /// Check if this is a value of primitive type, and if yes check the validity of the value
467 /// at that type. Return `true` if the type is indeed primitive.
468 fn try_visit_primitive(
470 value: OpTy<'tcx, M::PointerTag>,
471 ) -> InterpResult<'tcx, bool> {
472 // Go over all the primitive types
473 let ty = value.layout.ty;
476 let value = self.ecx.read_scalar(value)?;
477 try_validation!(value.to_bool(), value, self.path, "a boolean");
481 let value = self.ecx.read_scalar(value)?;
482 try_validation!(value.to_char(), value, self.path, "a valid unicode codepoint");
485 ty::Float(_) | ty::Int(_) | ty::Uint(_) => {
486 let value = self.ecx.read_scalar(value)?;
487 // NOTE: Keep this in sync with the array optimization for int/float
489 if self.ref_tracking_for_consts.is_some() {
490 // Integers/floats in CTFE: Must be scalar bits, pointers are dangerous
491 let is_bits = value.not_undef().map_or(false, |v| v.is_bits());
493 throw_validation_failure!(
496 "initialized plain (non-pointer) bytes"
500 // At run-time, for now, we accept *anything* for these types, including
501 // undef. We should fix that, but let's start low.
506 // We are conservative with undef for integers, but try to
507 // actually enforce the strict rules for raw pointers (mostly because
508 // that lets us re-use `ref_to_mplace`).
509 let place = try_validation_pat!(self.ecx.ref_to_mplace(self.ecx.read_immediate(value)?), self.path, {
510 err_ub!(InvalidUndefBytes(..)) => { "uninitialized raw pointer" },
512 if place.layout.is_unsized() {
513 self.check_wide_ptr_meta(place.meta, place.layout)?;
518 self.check_safe_pointer(value, "reference")?;
521 ty::Adt(def, ..) if def.is_box() => {
522 self.check_safe_pointer(value, "box")?;
526 let value = self.ecx.read_scalar(value)?;
527 let _fn = try_validation!(
528 value.not_undef().and_then(|ptr| self.ecx.memory.get_fn(ptr)),
533 // FIXME: Check if the signature matches
536 ty::Never => throw_validation_failure!("a value of the never type `!`", self.path),
537 ty::Foreign(..) | ty::FnDef(..) => {
541 // The above should be all the (inhabited) primitive types. The rest is compound, we
542 // check them by visiting their fields/variants.
543 // (`Str` UTF-8 check happens in `visit_aggregate`, too.)
551 | ty::Generator(..) => Ok(false),
552 // Some types only occur during typechecking, they have no layout.
553 // We should not see them here and we could not check them anyway.
556 | ty::Placeholder(..)
560 | ty::UnnormalizedProjection(..)
562 | ty::GeneratorWitness(..) => bug!("Encountered invalid type {:?}", ty),
568 op: OpTy<'tcx, M::PointerTag>,
569 scalar_layout: &Scalar,
570 ) -> InterpResult<'tcx> {
571 let value = self.ecx.read_scalar(op)?;
572 let valid_range = &scalar_layout.valid_range;
573 let (lo, hi) = valid_range.clone().into_inner();
574 // Determine the allowed range
575 // `max_hi` is as big as the size fits
576 let max_hi = u128::MAX >> (128 - op.layout.size.bits());
577 assert!(hi <= max_hi);
578 // We could also write `(hi + 1) % (max_hi + 1) == lo` but `max_hi + 1` overflows for `u128`
579 if (lo == 0 && hi == max_hi) || (hi + 1 == lo) {
583 // At least one value is excluded. Get the bits.
584 let value = try_validation!(
588 format_args!("something {}", wrapping_range_format(valid_range, max_hi),)
590 let bits = match value.to_bits_or_ptr(op.layout.size, self.ecx) {
592 if lo == 1 && hi == max_hi {
593 // Only NULL is the niche. So make sure the ptr is NOT NULL.
594 if self.ecx.memory.ptr_may_be_null(ptr) {
595 throw_validation_failure!(
596 "a potentially NULL pointer",
599 "something that cannot possibly fail to be {}",
600 wrapping_range_format(valid_range, max_hi)
606 // Conservatively, we reject, because the pointer *could* have a bad
608 throw_validation_failure!(
612 "something that cannot possibly fail to be {}",
613 wrapping_range_format(valid_range, max_hi)
620 // Now compare. This is slightly subtle because this is a special "wrap-around" range.
621 if wrapping_range_contains(&valid_range, bits) {
624 throw_validation_failure!(
627 format_args!("something {}", wrapping_range_format(valid_range, max_hi))
633 impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValueVisitor<'mir, 'tcx, M>
634 for ValidityVisitor<'rt, 'mir, 'tcx, M>
636 type V = OpTy<'tcx, M::PointerTag>;
639 fn ecx(&self) -> &InterpCx<'mir, 'tcx, M> {
646 old_op: OpTy<'tcx, M::PointerTag>,
648 new_op: OpTy<'tcx, M::PointerTag>,
649 ) -> InterpResult<'tcx> {
650 let elem = self.aggregate_field_path_elem(old_op.layout, field);
651 self.visit_elem(new_op, elem)
657 old_op: OpTy<'tcx, M::PointerTag>,
658 variant_id: VariantIdx,
659 new_op: OpTy<'tcx, M::PointerTag>,
660 ) -> InterpResult<'tcx> {
661 let name = match old_op.layout.ty.kind {
662 ty::Adt(adt, _) => PathElem::Variant(adt.variants[variant_id].ident.name),
663 // Generators also have variants
664 ty::Generator(..) => PathElem::GeneratorState(variant_id),
665 _ => bug!("Unexpected type with variant: {:?}", old_op.layout.ty),
667 self.visit_elem(new_op, name)
673 _op: OpTy<'tcx, M::PointerTag>,
674 _fields: NonZeroUsize,
675 ) -> InterpResult<'tcx> {
680 fn visit_value(&mut self, op: OpTy<'tcx, M::PointerTag>) -> InterpResult<'tcx> {
681 trace!("visit_value: {:?}, {:?}", *op, op.layout);
683 // Check primitive types -- the leafs of our recursive descend.
684 if self.try_visit_primitive(op)? {
687 // Sanity check: `builtin_deref` does not know any pointers that are not primitive.
688 assert!(op.layout.ty.builtin_deref(true).is_none());
690 // Recursively walk the type. Translate some possible errors to something nicer.
691 match self.walk_value(op) {
693 Err(err) => match err.kind {
694 err_ub!(InvalidDiscriminant(val)) => {
695 throw_validation_failure!(val, self.path, "a valid enum discriminant")
697 err_unsup!(ReadPointerAsBytes) => {
698 throw_validation_failure!("a pointer", self.path, "plain (non-pointer) bytes")
700 // Propagate upwards (that will also check for unexpected errors).
701 _ => return Err(err),
705 // *After* all of this, check the ABI. We need to check the ABI to handle
706 // types like `NonNull` where the `Scalar` info is more restrictive than what
707 // the fields say (`rustc_layout_scalar_valid_range_start`).
708 // But in most cases, this will just propagate what the fields say,
709 // and then we want the error to point at the field -- so, first recurse,
712 // FIXME: We could avoid some redundant checks here. For newtypes wrapping
713 // scalars, we do the same check on every "level" (e.g., first we check
714 // MyNewtype and then the scalar in there).
715 match op.layout.abi {
716 Abi::Uninhabited => {
717 throw_validation_failure!(
718 format_args!("a value of uninhabited type {:?}", op.layout.ty),
722 Abi::Scalar(ref scalar_layout) => {
723 self.visit_scalar(op, scalar_layout)?;
725 Abi::ScalarPair { .. } | Abi::Vector { .. } => {
726 // These have fields that we already visited above, so we already checked
727 // all their scalar-level restrictions.
728 // There is also no equivalent to `rustc_layout_scalar_valid_range_start`
729 // that would make skipping them here an issue.
731 Abi::Aggregate { .. } => {
741 op: OpTy<'tcx, M::PointerTag>,
742 fields: impl Iterator<Item = InterpResult<'tcx, Self::V>>,
743 ) -> InterpResult<'tcx> {
744 match op.layout.ty.kind {
746 let mplace = op.assert_mem_place(self.ecx); // strings are never immediate
748 self.ecx.read_str(mplace),
749 "uninitialized or non-UTF-8 data in str",
753 ty::Array(tys, ..) | ty::Slice(tys)
755 // This optimization applies for types that can hold arbitrary bytes (such as
756 // integer and floating point types) or for structs or tuples with no fields.
757 // FIXME(wesleywiser) This logic could be extended further to arbitrary structs
758 // or tuples made up of integer/floating point types or inhabited ZSTs with no
761 ty::Int(..) | ty::Uint(..) | ty::Float(..) => true,
766 // Optimized handling for arrays of integer/float type.
768 // Arrays cannot be immediate, slices are never immediate.
769 let mplace = op.assert_mem_place(self.ecx);
770 // This is the length of the array/slice.
771 let len = mplace.len(self.ecx)?;
772 // Zero length slices have nothing to be checked.
776 // This is the element type size.
777 let layout = self.ecx.layout_of(tys)?;
778 // This is the size in bytes of the whole array. (This checks for overflow.)
779 let size = layout.size * len;
780 // Size is not 0, get a pointer.
781 let ptr = self.ecx.force_ptr(mplace.ptr)?;
783 // Optimization: we just check the entire range at once.
784 // NOTE: Keep this in sync with the handling of integer and float
785 // types above, in `visit_primitive`.
786 // In run-time mode, we accept pointers in here. This is actually more
787 // permissive than a per-element check would be, e.g., we accept
788 // an &[u8] that contains a pointer even though bytewise checking would
789 // reject it. However, that's good: We don't inherently want
790 // to reject those pointers, we just do not have the machinery to
791 // talk about parts of a pointer.
792 // We also accept undef, for consistency with the slow path.
793 match self.ecx.memory.get_raw(ptr.alloc_id)?.check_bytes(
797 /*allow_ptr_and_undef*/ self.ref_tracking_for_consts.is_none(),
799 // In the happy case, we needn't check anything else.
801 // Some error happened, try to provide a more detailed description.
803 // For some errors we might be able to provide extra information
805 err_ub!(InvalidUndefBytes(Some(ptr))) => {
806 // Some byte was uninitialized, determine which
807 // element that byte belongs to so we can
809 let i = usize::try_from(ptr.offset.bytes() / layout.size.bytes())
811 self.path.push(PathElem::ArrayElem(i));
813 throw_validation_failure!("uninitialized bytes", self.path)
815 // Propagate upwards (that will also check for unexpected errors).
816 _ => return Err(err),
821 // Fast path for arrays and slices of ZSTs. We only need to check a single ZST element
822 // of an array and not all of them, because there's only a single value of a specific
823 // ZST type, so either validation fails for all elements or none.
824 ty::Array(tys, ..) | ty::Slice(tys) if self.ecx.layout_of(tys)?.is_zst() => {
825 // Validate just the first element
826 self.walk_aggregate(op, fields.take(1))?
829 self.walk_aggregate(op, fields)? // default handler
836 impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
837 fn validate_operand_internal(
839 op: OpTy<'tcx, M::PointerTag>,
841 ref_tracking_for_consts: Option<
842 &mut RefTracking<MPlaceTy<'tcx, M::PointerTag>, Vec<PathElem>>,
844 may_ref_to_static: bool,
845 ) -> InterpResult<'tcx> {
846 trace!("validate_operand_internal: {:?}, {:?}", *op, op.layout.ty);
848 // Construct a visitor
850 ValidityVisitor { path, ref_tracking_for_consts, may_ref_to_static, ecx: self };
852 // Try to cast to ptr *once* instead of all the time.
853 let op = self.force_op_ptr(op).unwrap_or(op);
856 match visitor.visit_value(op) {
858 // Pass through validation failures.
859 Err(err) if matches!(err.kind, err_ub!(ValidationFailure { .. })) => Err(err),
860 // Also pass through InvalidProgram, those just indicate that we could not
861 // validate and each caller will know best what to do with them.
862 Err(err) if matches!(err.kind, InterpError::InvalidProgram(_)) => Err(err),
863 // Avoid other errors as those do not show *where* in the value the issue lies.
864 Err(err) => bug!("Unexpected error during validation: {}", err),
868 /// This function checks the data at `op` to be const-valid.
869 /// `op` is assumed to cover valid memory if it is an indirect operand.
870 /// It will error if the bits at the destination do not match the ones described by the layout.
872 /// `ref_tracking` is used to record references that we encounter so that they
873 /// can be checked recursively by an outside driving loop.
875 /// `may_ref_to_static` controls whether references are allowed to point to statics.
877 pub fn const_validate_operand(
879 op: OpTy<'tcx, M::PointerTag>,
881 ref_tracking: &mut RefTracking<MPlaceTy<'tcx, M::PointerTag>, Vec<PathElem>>,
882 may_ref_to_static: bool,
883 ) -> InterpResult<'tcx> {
884 self.validate_operand_internal(op, path, Some(ref_tracking), may_ref_to_static)
887 /// This function checks the data at `op` to be runtime-valid.
888 /// `op` is assumed to cover valid memory if it is an indirect operand.
889 /// It will error if the bits at the destination do not match the ones described by the layout.
891 pub fn validate_operand(&self, op: OpTy<'tcx, M::PointerTag>) -> InterpResult<'tcx> {
892 self.validate_operand_internal(op, vec![], None, false)