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))
37 ($what:expr, $where:expr) => {{
38 let mut msg = format!("encountered {}", $what);
40 if !where_.is_empty() {
42 write_path(&mut msg, where_);
44 throw_ub!(ValidationFailure(msg))
48 macro_rules! try_validation {
49 ($e:expr, $what:expr, $where:expr, $details:expr) => {{
52 // We re-throw the error, so we are okay with allocation:
53 // this can only slow down builds that fail anyway.
54 Err(_) => throw_validation_failure!($what, $where, $details),
58 ($e:expr, $what:expr, $where:expr) => {{
61 // We re-throw the error, so we are okay with allocation:
62 // this can only slow down builds that fail anyway.
63 Err(_) => throw_validation_failure!($what, $where),
68 /// We want to show a nice path to the invalid field for diagnostics,
69 /// but avoid string operations in the happy case where no error happens.
70 /// So we track a `Vec<PathElem>` where `PathElem` contains all the data we
71 /// need to later print something for the user.
72 #[derive(Copy, Clone, Debug)]
76 GeneratorState(VariantIdx),
86 /// State for tracking recursive validation of references
87 pub struct RefTracking<T, PATH = ()> {
88 pub seen: FxHashSet<T>,
89 pub todo: Vec<(T, PATH)>,
92 impl<T: Copy + Eq + Hash + std::fmt::Debug, PATH: Default> RefTracking<T, PATH> {
93 pub fn empty() -> Self {
94 RefTracking { seen: FxHashSet::default(), todo: vec![] }
96 pub fn new(op: T) -> Self {
97 let mut ref_tracking_for_consts =
98 RefTracking { seen: FxHashSet::default(), todo: vec![(op, PATH::default())] };
99 ref_tracking_for_consts.seen.insert(op);
100 ref_tracking_for_consts
103 pub fn track(&mut self, op: T, path: impl FnOnce() -> PATH) {
104 if self.seen.insert(op) {
105 trace!("Recursing below ptr {:#?}", op);
107 // Remember to come back to this later.
108 self.todo.push((op, path));
114 fn write_path(out: &mut String, path: &Vec<PathElem>) {
115 use self::PathElem::*;
117 for elem in path.iter() {
119 Field(name) => write!(out, ".{}", name),
120 EnumTag => write!(out, ".<enum-tag>"),
121 Variant(name) => write!(out, ".<enum-variant({})>", name),
122 GeneratorTag => write!(out, ".<generator-tag>"),
123 GeneratorState(idx) => write!(out, ".<generator-state({})>", idx.index()),
124 CapturedVar(name) => write!(out, ".<captured-var({})>", name),
125 TupleElem(idx) => write!(out, ".{}", idx),
126 ArrayElem(idx) => write!(out, "[{}]", idx),
127 // `.<deref>` does not match Rust syntax, but it is more readable for long paths -- and
128 // some of the other items here also are not Rust syntax. Actually we can't
129 // even use the usual syntax because we are just showing the projections,
131 Deref => write!(out, ".<deref>"),
132 DynDowncast => write!(out, ".<dyn-downcast>"),
138 // Test if a range that wraps at overflow contains `test`
139 fn wrapping_range_contains(r: &RangeInclusive<u128>, test: u128) -> bool {
140 let (lo, hi) = r.clone().into_inner();
143 (..=hi).contains(&test) || (lo..).contains(&test)
150 // Formats such that a sentence like "expected something {}" to mean
151 // "expected something <in the given range>" makes sense.
152 fn wrapping_range_format(r: &RangeInclusive<u128>, max_hi: u128) -> String {
153 let (lo, hi) = r.clone().into_inner();
154 assert!(hi <= max_hi);
156 format!("less or equal to {}, or greater or equal to {}", hi, lo)
158 format!("equal to {}", lo)
160 assert!(hi < max_hi, "should not be printing if the range covers everything");
161 format!("less or equal to {}", hi)
162 } else if hi == max_hi {
163 assert!(lo > 0, "should not be printing if the range covers everything");
164 format!("greater or equal to {}", lo)
166 format!("in the range {:?}", r)
170 struct ValidityVisitor<'rt, 'mir, 'tcx, M: Machine<'mir, 'tcx>> {
171 /// The `path` may be pushed to, but the part that is present when a function
172 /// starts must not be changed! `visit_fields` and `visit_array` rely on
173 /// this stack discipline.
175 ref_tracking_for_consts:
176 Option<&'rt mut RefTracking<MPlaceTy<'tcx, M::PointerTag>, Vec<PathElem>>>,
177 may_ref_to_static: bool,
178 ecx: &'rt InterpCx<'mir, 'tcx, M>,
181 impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValidityVisitor<'rt, 'mir, 'tcx, M> {
182 fn aggregate_field_path_elem(&mut self, layout: TyAndLayout<'tcx>, field: usize) -> PathElem {
183 // First, check if we are projecting to a variant.
184 match layout.variants {
185 Variants::Multiple { discr_index, .. } => {
186 if discr_index == field {
187 return match layout.ty.kind {
188 ty::Adt(def, ..) if def.is_enum() => PathElem::EnumTag,
189 ty::Generator(..) => PathElem::GeneratorTag,
190 _ => bug!("non-variant type {:?}", layout.ty),
194 Variants::Single { .. } => {}
197 // Now we know we are projecting to a field, so figure out which one.
198 match layout.ty.kind {
199 // generators and closures.
200 ty::Closure(def_id, _) | ty::Generator(def_id, _, _) => {
202 if def_id.is_local() {
203 let tables = self.ecx.tcx.typeck_tables_of(def_id);
204 if let Some(upvars) = tables.upvar_list.get(&def_id) {
205 // Sometimes the index is beyond the number of upvars (seen
207 if let Some((&var_hir_id, _)) = upvars.get_index(field) {
208 let node = self.ecx.tcx.hir().get(var_hir_id);
209 if let hir::Node::Binding(pat) = node {
210 if let hir::PatKind::Binding(_, _, ident, _) = pat.kind {
211 name = Some(ident.name);
218 PathElem::CapturedVar(name.unwrap_or_else(|| {
219 // Fall back to showing the field index.
225 ty::Tuple(_) => PathElem::TupleElem(field),
228 ty::Adt(def, ..) if def.is_enum() => {
229 // we might be projecting *to* a variant, or to a field *in* a variant.
230 match layout.variants {
231 Variants::Single { index } => {
233 PathElem::Field(def.variants[index].fields[field].ident.name)
235 Variants::Multiple { .. } => bug!("we handled variants above"),
240 ty::Adt(def, _) => PathElem::Field(def.non_enum_variant().fields[field].ident.name),
243 ty::Array(..) | ty::Slice(..) => PathElem::ArrayElem(field),
246 ty::Dynamic(..) => PathElem::DynDowncast,
248 // nothing else has an aggregate layout
249 _ => bug!("aggregate_field_path_elem: got non-aggregate type {:?}", layout.ty),
255 new_op: OpTy<'tcx, M::PointerTag>,
257 ) -> InterpResult<'tcx> {
258 // Remember the old state
259 let path_len = self.path.len();
261 self.path.push(elem);
262 self.visit_value(new_op)?;
264 self.path.truncate(path_len);
268 fn check_wide_ptr_meta(
270 meta: MemPlaceMeta<M::PointerTag>,
271 pointee: TyAndLayout<'tcx>,
272 ) -> InterpResult<'tcx> {
273 let tail = self.ecx.tcx.struct_tail_erasing_lifetimes(pointee.ty, self.ecx.param_env);
276 let vtable = meta.unwrap_meta();
278 self.ecx.memory.check_ptr_access(
280 3 * self.ecx.tcx.data_layout.pointer_size, // drop, size, align
281 self.ecx.tcx.data_layout.pointer_align.abi,
283 "dangling or unaligned vtable pointer in wide pointer or too small vtable",
287 self.ecx.read_drop_type_from_vtable(vtable),
288 "invalid drop fn in vtable",
292 self.ecx.read_size_and_align_from_vtable(vtable),
293 "invalid size or align in vtable",
296 // FIXME: More checks for the vtable.
298 ty::Slice(..) | ty::Str => {
299 let _len = try_validation!(
300 meta.unwrap_meta().to_machine_usize(self.ecx),
301 "non-integer slice length in wide pointer",
304 // We do not check that `len * elem_size <= isize::MAX`:
305 // that is only required for references, and there it falls out of the
306 // "dereferenceable" check performed by Stacked Borrows.
309 // Unsized, but not wide.
311 _ => bug!("Unexpected unsized type tail: {:?}", tail),
317 /// Check a reference or `Box`.
318 fn check_safe_pointer(
320 value: OpTy<'tcx, M::PointerTag>,
322 ) -> InterpResult<'tcx> {
323 let value = self.ecx.read_immediate(value)?;
324 // Handle wide pointers.
325 // Check metadata early, for better diagnostics
326 let place = try_validation!(
327 self.ecx.ref_to_mplace(value),
328 format_args!("uninitialized {}", kind),
331 if place.layout.is_unsized() {
332 self.check_wide_ptr_meta(place.meta, place.layout)?;
334 // Make sure this is dereferenceable and all.
335 let size_and_align = match self.ecx.size_and_align_of(place.meta, place.layout) {
337 Err(err) => match err.kind {
338 err_ub!(InvalidMeta(msg)) => throw_validation_failure!(
339 format_args!("invalid {} metadata: {}", kind, msg),
342 _ => bug!("unexpected error during ptr size_and_align_of: {}", err),
345 let (size, align) = size_and_align
346 // for the purpose of validity, consider foreign types to have
347 // alignment and size determined by the layout (size will be 0,
348 // alignment should take attributes into account).
349 .unwrap_or_else(|| (place.layout.size, place.layout.align.abi));
350 let ptr: Option<_> = match self.ecx.memory.check_ptr_access_align(
354 CheckInAllocMsg::InboundsTest,
359 "{:?} did not pass access check for size {:?}, align {:?}",
360 place.ptr, size, align
363 err_ub!(InvalidIntPointerUsage(0)) => {
364 throw_validation_failure!(format_args!("a NULL {}", kind), self.path)
366 err_ub!(InvalidIntPointerUsage(i)) => throw_validation_failure!(
367 format_args!("a {} to unallocated address {}", kind, i),
370 err_ub!(AlignmentCheckFailed { required, has }) => throw_validation_failure!(
372 "an unaligned {} (required {} byte alignment but found {})",
379 err_unsup!(ReadBytesAsPointer) => throw_validation_failure!(
380 format_args!("a dangling {} (created from integer)", kind),
383 err_ub!(PointerOutOfBounds { .. }) => throw_validation_failure!(
385 "a dangling {} (going beyond the bounds of its allocation)",
390 // This cannot happen during const-eval (because interning already detects
391 // dangling pointers), but it can happen in Miri.
392 err_ub!(PointerUseAfterFree(_)) => throw_validation_failure!(
393 format_args!("a dangling {} (use-after-free)", kind),
396 _ => bug!("Unexpected error during ptr inbounds test: {}", err),
400 // Recursive checking
401 if let Some(ref mut ref_tracking) = self.ref_tracking_for_consts {
402 if let Some(ptr) = ptr {
404 // Skip validation entirely for some external statics
405 let alloc_kind = self.ecx.tcx.alloc_map.lock().get(ptr.alloc_id);
406 if let Some(GlobalAlloc::Static(did)) = alloc_kind {
407 // `extern static` cannot be validated as they have no body.
408 // FIXME: Statics from other crates are also skipped.
409 // They might be checked at a different type, but for now we
410 // want to avoid recursing too deeply. This is not sound!
411 if !did.is_local() || self.ecx.tcx.is_foreign_item(did) {
414 if !self.may_ref_to_static && self.ecx.tcx.is_static(did) {
415 throw_validation_failure!(
416 format_args!("a {} pointing to a static variable", kind),
422 // Proceed recursively even for ZST, no reason to skip them!
423 // `!` is a ZST and we want to validate it.
424 // Normalize before handing `place` to tracking because that will
425 // check for duplicates.
426 let place = if size.bytes() > 0 {
427 self.ecx.force_mplace_ptr(place).expect("we already bounds-checked")
431 let path = &self.path;
432 ref_tracking.track(place, || {
433 // We need to clone the path anyway, make sure it gets created
434 // with enough space for the additional `Deref`.
435 let mut new_path = Vec::with_capacity(path.len() + 1);
436 new_path.clone_from(path);
437 new_path.push(PathElem::Deref);
444 /// Check if this is a value of primitive type, and if yes check the validity of the value
445 /// at that type. Return `true` if the type is indeed primitive.
446 fn try_visit_primitive(
448 value: OpTy<'tcx, M::PointerTag>,
449 ) -> InterpResult<'tcx, bool> {
450 // Go over all the primitive types
451 let ty = value.layout.ty;
454 let value = self.ecx.read_scalar(value)?;
455 try_validation!(value.to_bool(), value, self.path, "a boolean");
459 let value = self.ecx.read_scalar(value)?;
460 try_validation!(value.to_char(), value, self.path, "a valid unicode codepoint");
463 ty::Float(_) | ty::Int(_) | ty::Uint(_) => {
464 let value = self.ecx.read_scalar(value)?;
465 // NOTE: Keep this in sync with the array optimization for int/float
467 if self.ref_tracking_for_consts.is_some() {
468 // Integers/floats in CTFE: Must be scalar bits, pointers are dangerous
469 let is_bits = value.not_undef().map_or(false, |v| v.is_bits());
471 throw_validation_failure!(
474 "initialized plain (non-pointer) bytes"
478 // At run-time, for now, we accept *anything* for these types, including
479 // undef. We should fix that, but let's start low.
484 // We are conservative with undef for integers, but try to
485 // actually enforce the strict rules for raw pointers (mostly because
486 // that lets us re-use `ref_to_mplace`).
487 let place = try_validation!(
488 self.ecx.ref_to_mplace(self.ecx.read_immediate(value)?),
489 "uninitialized raw pointer",
492 if place.layout.is_unsized() {
493 self.check_wide_ptr_meta(place.meta, place.layout)?;
498 self.check_safe_pointer(value, "reference")?;
501 ty::Adt(def, ..) if def.is_box() => {
502 self.check_safe_pointer(value, "box")?;
506 let value = self.ecx.read_scalar(value)?;
507 let _fn = try_validation!(
508 value.not_undef().and_then(|ptr| self.ecx.memory.get_fn(ptr)),
513 // FIXME: Check if the signature matches
516 ty::Never => throw_validation_failure!("a value of the never type `!`", self.path),
517 ty::Foreign(..) | ty::FnDef(..) => {
521 // The above should be all the (inhabited) primitive types. The rest is compound, we
522 // check them by visiting their fields/variants.
523 // (`Str` UTF-8 check happens in `visit_aggregate`, too.)
531 | ty::Generator(..) => Ok(false),
532 // Some types only occur during typechecking, they have no layout.
533 // We should not see them here and we could not check them anyway.
536 | ty::Placeholder(..)
540 | ty::UnnormalizedProjection(..)
542 | ty::GeneratorWitness(..) => bug!("Encountered invalid type {:?}", ty),
548 op: OpTy<'tcx, M::PointerTag>,
549 scalar_layout: &Scalar,
550 ) -> InterpResult<'tcx> {
551 let value = self.ecx.read_scalar(op)?;
552 let valid_range = &scalar_layout.valid_range;
553 let (lo, hi) = valid_range.clone().into_inner();
554 // Determine the allowed range
555 // `max_hi` is as big as the size fits
556 let max_hi = u128::MAX >> (128 - op.layout.size.bits());
557 assert!(hi <= max_hi);
558 // We could also write `(hi + 1) % (max_hi + 1) == lo` but `max_hi + 1` overflows for `u128`
559 if (lo == 0 && hi == max_hi) || (hi + 1 == lo) {
563 // At least one value is excluded. Get the bits.
564 let value = try_validation!(
568 format_args!("something {}", wrapping_range_format(valid_range, max_hi),)
570 let bits = match value.to_bits_or_ptr(op.layout.size, self.ecx) {
572 if lo == 1 && hi == max_hi {
573 // Only NULL is the niche. So make sure the ptr is NOT NULL.
574 if self.ecx.memory.ptr_may_be_null(ptr) {
575 throw_validation_failure!(
576 "a potentially NULL pointer",
579 "something that cannot possibly fail to be {}",
580 wrapping_range_format(valid_range, max_hi)
586 // Conservatively, we reject, because the pointer *could* have a bad
588 throw_validation_failure!(
592 "something that cannot possibly fail to be {}",
593 wrapping_range_format(valid_range, max_hi)
600 // Now compare. This is slightly subtle because this is a special "wrap-around" range.
601 if wrapping_range_contains(&valid_range, bits) {
604 throw_validation_failure!(
607 format_args!("something {}", wrapping_range_format(valid_range, max_hi))
613 impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValueVisitor<'mir, 'tcx, M>
614 for ValidityVisitor<'rt, 'mir, 'tcx, M>
616 type V = OpTy<'tcx, M::PointerTag>;
619 fn ecx(&self) -> &InterpCx<'mir, 'tcx, M> {
626 old_op: OpTy<'tcx, M::PointerTag>,
628 new_op: OpTy<'tcx, M::PointerTag>,
629 ) -> InterpResult<'tcx> {
630 let elem = self.aggregate_field_path_elem(old_op.layout, field);
631 self.visit_elem(new_op, elem)
637 old_op: OpTy<'tcx, M::PointerTag>,
638 variant_id: VariantIdx,
639 new_op: OpTy<'tcx, M::PointerTag>,
640 ) -> InterpResult<'tcx> {
641 let name = match old_op.layout.ty.kind {
642 ty::Adt(adt, _) => PathElem::Variant(adt.variants[variant_id].ident.name),
643 // Generators also have variants
644 ty::Generator(..) => PathElem::GeneratorState(variant_id),
645 _ => bug!("Unexpected type with variant: {:?}", old_op.layout.ty),
647 self.visit_elem(new_op, name)
653 _op: OpTy<'tcx, M::PointerTag>,
654 _fields: NonZeroUsize,
655 ) -> InterpResult<'tcx> {
660 fn visit_value(&mut self, op: OpTy<'tcx, M::PointerTag>) -> InterpResult<'tcx> {
661 trace!("visit_value: {:?}, {:?}", *op, op.layout);
663 // Check primitive types -- the leafs of our recursive descend.
664 if self.try_visit_primitive(op)? {
667 // Sanity check: `builtin_deref` does not know any pointers that are not primitive.
668 assert!(op.layout.ty.builtin_deref(true).is_none());
670 // Recursively walk the type. Translate some possible errors to something nicer.
671 match self.walk_value(op) {
673 Err(err) => match err.kind {
674 err_ub!(InvalidDiscriminant(val)) => {
675 throw_validation_failure!(val, self.path, "a valid enum discriminant")
677 err_unsup!(ReadPointerAsBytes) => {
678 throw_validation_failure!("a pointer", self.path, "plain (non-pointer) bytes")
680 // Propagate upwards (that will also check for unexpected errors).
681 _ => return Err(err),
685 // *After* all of this, check the ABI. We need to check the ABI to handle
686 // types like `NonNull` where the `Scalar` info is more restrictive than what
687 // the fields say (`rustc_layout_scalar_valid_range_start`).
688 // But in most cases, this will just propagate what the fields say,
689 // and then we want the error to point at the field -- so, first recurse,
692 // FIXME: We could avoid some redundant checks here. For newtypes wrapping
693 // scalars, we do the same check on every "level" (e.g., first we check
694 // MyNewtype and then the scalar in there).
695 match op.layout.abi {
696 Abi::Uninhabited => {
697 throw_validation_failure!(
698 format_args!("a value of uninhabited type {:?}", op.layout.ty),
702 Abi::Scalar(ref scalar_layout) => {
703 self.visit_scalar(op, scalar_layout)?;
705 Abi::ScalarPair { .. } | Abi::Vector { .. } => {
706 // These have fields that we already visited above, so we already checked
707 // all their scalar-level restrictions.
708 // There is also no equivalent to `rustc_layout_scalar_valid_range_start`
709 // that would make skipping them here an issue.
711 Abi::Aggregate { .. } => {
721 op: OpTy<'tcx, M::PointerTag>,
722 fields: impl Iterator<Item = InterpResult<'tcx, Self::V>>,
723 ) -> InterpResult<'tcx> {
724 match op.layout.ty.kind {
726 let mplace = op.assert_mem_place(self.ecx); // strings are never immediate
728 self.ecx.read_str(mplace),
729 "uninitialized or non-UTF-8 data in str",
733 ty::Array(tys, ..) | ty::Slice(tys)
735 // This optimization applies for types that can hold arbitrary bytes (such as
736 // integer and floating point types) or for structs or tuples with no fields.
737 // FIXME(wesleywiser) This logic could be extended further to arbitrary structs
738 // or tuples made up of integer/floating point types or inhabited ZSTs with no
741 ty::Int(..) | ty::Uint(..) | ty::Float(..) => true,
746 // Optimized handling for arrays of integer/float type.
748 // Arrays cannot be immediate, slices are never immediate.
749 let mplace = op.assert_mem_place(self.ecx);
750 // This is the length of the array/slice.
751 let len = mplace.len(self.ecx)?;
752 // Zero length slices have nothing to be checked.
756 // This is the element type size.
757 let layout = self.ecx.layout_of(tys)?;
758 // This is the size in bytes of the whole array. (This checks for overflow.)
759 let size = layout.size * len;
760 // Size is not 0, get a pointer.
761 let ptr = self.ecx.force_ptr(mplace.ptr)?;
763 // Optimization: we just check the entire range at once.
764 // NOTE: Keep this in sync with the handling of integer and float
765 // types above, in `visit_primitive`.
766 // In run-time mode, we accept pointers in here. This is actually more
767 // permissive than a per-element check would be, e.g., we accept
768 // an &[u8] that contains a pointer even though bytewise checking would
769 // reject it. However, that's good: We don't inherently want
770 // to reject those pointers, we just do not have the machinery to
771 // talk about parts of a pointer.
772 // We also accept undef, for consistency with the slow path.
773 match self.ecx.memory.get_raw(ptr.alloc_id)?.check_bytes(
777 /*allow_ptr_and_undef*/ self.ref_tracking_for_consts.is_none(),
779 // In the happy case, we needn't check anything else.
781 // Some error happened, try to provide a more detailed description.
783 // For some errors we might be able to provide extra information
785 err_ub!(InvalidUndefBytes(Some(ptr))) => {
786 // Some byte was uninitialized, determine which
787 // element that byte belongs to so we can
789 let i = usize::try_from(ptr.offset.bytes() / layout.size.bytes())
791 self.path.push(PathElem::ArrayElem(i));
793 throw_validation_failure!("uninitialized bytes", self.path)
795 // Other errors shouldn't be possible
796 _ => return Err(err),
801 // Fast path for arrays and slices of ZSTs. We only need to check a single ZST element
802 // of an array and not all of them, because there's only a single value of a specific
803 // ZST type, so either validation fails for all elements or none.
804 ty::Array(tys, ..) | ty::Slice(tys) if self.ecx.layout_of(tys)?.is_zst() => {
805 // Validate just the first element
806 self.walk_aggregate(op, fields.take(1))?
809 self.walk_aggregate(op, fields)? // default handler
816 impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
817 fn validate_operand_internal(
819 op: OpTy<'tcx, M::PointerTag>,
821 ref_tracking_for_consts: Option<
822 &mut RefTracking<MPlaceTy<'tcx, M::PointerTag>, Vec<PathElem>>,
824 may_ref_to_static: bool,
825 ) -> InterpResult<'tcx> {
826 trace!("validate_operand_internal: {:?}, {:?}", *op, op.layout.ty);
828 // Construct a visitor
830 ValidityVisitor { path, ref_tracking_for_consts, may_ref_to_static, ecx: self };
832 // Try to cast to ptr *once* instead of all the time.
833 let op = self.force_op_ptr(op).unwrap_or(op);
836 match visitor.visit_value(op) {
838 // We should only get validation errors here. Avoid other errors as
839 // those do not show *where* in the value the issue lies.
840 Err(err) if matches!(err.kind, err_ub!(ValidationFailure { .. })) => Err(err),
841 Err(err) => bug!("Unexpected error during validation: {}", err),
845 /// This function checks the data at `op` to be const-valid.
846 /// `op` is assumed to cover valid memory if it is an indirect operand.
847 /// It will error if the bits at the destination do not match the ones described by the layout.
849 /// `ref_tracking` is used to record references that we encounter so that they
850 /// can be checked recursively by an outside driving loop.
852 /// `may_ref_to_static` controls whether references are allowed to point to statics.
854 pub fn const_validate_operand(
856 op: OpTy<'tcx, M::PointerTag>,
858 ref_tracking: &mut RefTracking<MPlaceTy<'tcx, M::PointerTag>, Vec<PathElem>>,
859 may_ref_to_static: bool,
860 ) -> InterpResult<'tcx> {
861 self.validate_operand_internal(op, path, Some(ref_tracking), may_ref_to_static)
864 /// This function checks the data at `op` to be runtime-valid.
865 /// `op` is assumed to cover valid memory if it is an indirect operand.
866 /// It will error if the bits at the destination do not match the ones described by the layout.
868 pub fn validate_operand(&self, op: OpTy<'tcx, M::PointerTag>) -> InterpResult<'tcx> {
869 self.validate_operand_internal(op, vec![], None, false)