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
8 use std::ops::RangeInclusive;
11 use rustc::ty::layout::{self, LayoutOf, TyLayout, VariantIdx};
12 use rustc_data_structures::fx::FxHashSet;
14 use rustc_span::symbol::{sym, Symbol};
19 CheckInAllocMsg, GlobalAlloc, InterpCx, InterpResult, MPlaceTy, Machine, MemPlaceMeta, OpTy,
23 macro_rules! throw_validation_failure {
24 ($what:expr, $where:expr, $details:expr) => {{
25 let mut msg = format!("encountered {}", $what);
27 if !where_.is_empty() {
29 write_path(&mut msg, where_);
31 write!(&mut msg, ", but expected {}", $details).unwrap();
32 throw_ub!(ValidationFailure(msg))
34 ($what:expr, $where:expr) => {{
35 let mut msg = format!("encountered {}", $what);
37 if !where_.is_empty() {
39 write_path(&mut msg, where_);
41 throw_ub!(ValidationFailure(msg))
45 macro_rules! try_validation {
46 ($e:expr, $what:expr, $where:expr, $details:expr) => {{
49 // We re-throw the error, so we are okay with allocation:
50 // this can only slow down builds that fail anyway.
51 Err(_) => throw_validation_failure!($what, $where, $details),
55 ($e:expr, $what:expr, $where:expr) => {{
58 // We re-throw the error, so we are okay with allocation:
59 // this can only slow down builds that fail anyway.
60 Err(_) => throw_validation_failure!($what, $where),
65 /// We want to show a nice path to the invalid field for diagnostics,
66 /// but avoid string operations in the happy case where no error happens.
67 /// So we track a `Vec<PathElem>` where `PathElem` contains all the data we
68 /// need to later print something for the user.
69 #[derive(Copy, Clone, Debug)]
73 GeneratorState(VariantIdx),
83 /// State for tracking recursive validation of references
84 pub struct RefTracking<T, PATH = ()> {
85 pub seen: FxHashSet<T>,
86 pub todo: Vec<(T, PATH)>,
89 impl<T: Copy + Eq + Hash + std::fmt::Debug, PATH: Default> RefTracking<T, PATH> {
90 pub fn empty() -> Self {
91 RefTracking { seen: FxHashSet::default(), todo: vec![] }
93 pub fn new(op: T) -> Self {
94 let mut ref_tracking_for_consts =
95 RefTracking { seen: FxHashSet::default(), todo: vec![(op, PATH::default())] };
96 ref_tracking_for_consts.seen.insert(op);
97 ref_tracking_for_consts
100 pub fn track(&mut self, op: T, path: impl FnOnce() -> PATH) {
101 if self.seen.insert(op) {
102 trace!("Recursing below ptr {:#?}", op);
104 // Remember to come back to this later.
105 self.todo.push((op, path));
111 fn write_path(out: &mut String, path: &Vec<PathElem>) {
112 use self::PathElem::*;
114 for elem in path.iter() {
116 Field(name) => write!(out, ".{}", name),
117 EnumTag => write!(out, ".<enum-tag>"),
118 Variant(name) => write!(out, ".<enum-variant({})>", name),
119 GeneratorTag => write!(out, ".<generator-tag>"),
120 GeneratorState(idx) => write!(out, ".<generator-state({})>", idx.index()),
121 CapturedVar(name) => write!(out, ".<captured-var({})>", name),
122 TupleElem(idx) => write!(out, ".{}", idx),
123 ArrayElem(idx) => write!(out, "[{}]", idx),
124 // `.<deref>` does not match Rust syntax, but it is more readable for long paths -- and
125 // some of the other items here also are not Rust syntax. Actually we can't
126 // even use the usual syntax because we are just showing the projections,
128 Deref => write!(out, ".<deref>"),
129 DynDowncast => write!(out, ".<dyn-downcast>"),
135 // Test if a range that wraps at overflow contains `test`
136 fn wrapping_range_contains(r: &RangeInclusive<u128>, test: u128) -> bool {
137 let (lo, hi) = r.clone().into_inner();
140 (..=hi).contains(&test) || (lo..).contains(&test)
147 // Formats such that a sentence like "expected something {}" to mean
148 // "expected something <in the given range>" makes sense.
149 fn wrapping_range_format(r: &RangeInclusive<u128>, max_hi: u128) -> String {
150 let (lo, hi) = r.clone().into_inner();
151 assert!(hi <= max_hi);
153 format!("less or equal to {}, or greater or equal to {}", hi, lo)
155 format!("equal to {}", lo)
157 assert!(hi < max_hi, "should not be printing if the range covers everything");
158 format!("less or equal to {}", hi)
159 } else if hi == max_hi {
160 assert!(lo > 0, "should not be printing if the range covers everything");
161 format!("greater or equal to {}", lo)
163 format!("in the range {:?}", r)
167 struct ValidityVisitor<'rt, 'mir, 'tcx, M: Machine<'mir, 'tcx>> {
168 /// The `path` may be pushed to, but the part that is present when a function
169 /// starts must not be changed! `visit_fields` and `visit_array` rely on
170 /// this stack discipline.
172 ref_tracking_for_consts:
173 Option<&'rt mut RefTracking<MPlaceTy<'tcx, M::PointerTag>, Vec<PathElem>>>,
174 may_ref_to_static: bool,
175 ecx: &'rt InterpCx<'mir, 'tcx, M>,
178 impl<'rt, 'mir, 'tcx, M: Machine<'mir, 'tcx>> ValidityVisitor<'rt, 'mir, 'tcx, M> {
179 fn aggregate_field_path_elem(&mut self, layout: TyLayout<'tcx>, field: usize) -> PathElem {
180 // First, check if we are projecting to a variant.
181 match layout.variants {
182 layout::Variants::Multiple { discr_index, .. } => {
183 if discr_index == field {
184 return match layout.ty.kind {
185 ty::Adt(def, ..) if def.is_enum() => PathElem::EnumTag,
186 ty::Generator(..) => PathElem::GeneratorTag,
187 _ => bug!("non-variant type {:?}", layout.ty),
191 layout::Variants::Single { .. } => {}
194 // Now we know we are projecting to a field, so figure out which one.
195 match layout.ty.kind {
196 // generators and closures.
197 ty::Closure(def_id, _) | ty::Generator(def_id, _, _) => {
199 if def_id.is_local() {
200 let tables = self.ecx.tcx.typeck_tables_of(def_id);
201 if let Some(upvars) = tables.upvar_list.get(&def_id) {
202 // Sometimes the index is beyond the number of upvars (seen
204 if let Some((&var_hir_id, _)) = upvars.get_index(field) {
205 let node = self.ecx.tcx.hir().get(var_hir_id);
206 if let hir::Node::Binding(pat) = node {
207 if let hir::PatKind::Binding(_, _, ident, _) = pat.kind {
208 name = Some(ident.name);
215 PathElem::CapturedVar(name.unwrap_or_else(|| {
216 // Fall back to showing the field index.
222 ty::Tuple(_) => PathElem::TupleElem(field),
225 ty::Adt(def, ..) if def.is_enum() => {
226 // we might be projecting *to* a variant, or to a field *in* a variant.
227 match layout.variants {
228 layout::Variants::Single { index } => {
230 PathElem::Field(def.variants[index].fields[field].ident.name)
232 layout::Variants::Multiple { .. } => bug!("we handled variants above"),
237 ty::Adt(def, _) => PathElem::Field(def.non_enum_variant().fields[field].ident.name),
240 ty::Array(..) | ty::Slice(..) => PathElem::ArrayElem(field),
243 ty::Dynamic(..) => PathElem::DynDowncast,
245 // nothing else has an aggregate layout
246 _ => bug!("aggregate_field_path_elem: got non-aggregate type {:?}", layout.ty),
252 new_op: OpTy<'tcx, M::PointerTag>,
254 ) -> InterpResult<'tcx> {
255 // Remember the old state
256 let path_len = self.path.len();
258 self.path.push(elem);
259 self.visit_value(new_op)?;
261 self.path.truncate(path_len);
265 fn check_wide_ptr_meta(
267 meta: MemPlaceMeta<M::PointerTag>,
268 pointee: TyLayout<'tcx>,
269 ) -> InterpResult<'tcx> {
270 let tail = self.ecx.tcx.struct_tail_erasing_lifetimes(pointee.ty, self.ecx.param_env);
273 let vtable = meta.unwrap_meta();
275 self.ecx.memory.check_ptr_access(
277 3 * self.ecx.tcx.data_layout.pointer_size, // drop, size, align
278 self.ecx.tcx.data_layout.pointer_align.abi,
280 "dangling or unaligned vtable pointer in wide pointer or too small vtable",
284 self.ecx.read_drop_type_from_vtable(vtable),
285 "invalid drop fn in vtable",
289 self.ecx.read_size_and_align_from_vtable(vtable),
290 "invalid size or align in vtable",
293 // FIXME: More checks for the vtable.
295 ty::Slice(..) | ty::Str => {
296 let _len = try_validation!(
297 meta.unwrap_meta().to_machine_usize(self.ecx),
298 "non-integer slice length in wide pointer",
301 // We do not check that `len * elem_size <= isize::MAX`:
302 // that is only required for references, and there it falls out of the
303 // "dereferenceable" check performed by Stacked Borrows.
306 // Unsized, but not wide.
308 _ => bug!("Unexpected unsized type tail: {:?}", tail),
314 /// Check a reference or `Box`.
315 fn check_safe_pointer(
317 value: OpTy<'tcx, M::PointerTag>,
319 ) -> InterpResult<'tcx> {
320 let value = self.ecx.read_immediate(value)?;
321 // Handle wide pointers.
322 // Check metadata early, for better diagnostics
323 let place = try_validation!(self.ecx.ref_to_mplace(value), "undefined pointer", self.path);
324 if place.layout.is_unsized() {
325 self.check_wide_ptr_meta(place.meta, place.layout)?;
327 // Make sure this is dereferenceable and all.
328 let size_and_align = match self.ecx.size_and_align_of(place.meta, place.layout) {
330 Err(err) => match err.kind {
331 err_ub!(InvalidMeta(msg)) => throw_validation_failure!(
332 format_args!("invalid {} metadata: {}", kind, msg),
335 _ => bug!("Unexpected error during ptr size_and_align_of: {}", err),
338 let (size, align) = size_and_align
339 // for the purpose of validity, consider foreign types to have
340 // alignment and size determined by the layout (size will be 0,
341 // alignment should take attributes into account).
342 .unwrap_or_else(|| (place.layout.size, place.layout.align.abi));
343 let ptr: Option<_> = match self.ecx.memory.check_ptr_access_align(
347 CheckInAllocMsg::InboundsTest,
352 "{:?} did not pass access check for size {:?}, align {:?}",
353 place.ptr, size, align
356 err_ub!(InvalidIntPointerUsage(0)) => {
357 throw_validation_failure!(format_args!("a NULL {}", kind), self.path)
359 err_ub!(InvalidIntPointerUsage(i)) => throw_validation_failure!(
360 format_args!("a {} to unallocated address {}", kind, i),
363 err_ub!(AlignmentCheckFailed { required, has }) => throw_validation_failure!(
365 "an unaligned {} (required {} byte alignment but found {})",
372 err_unsup!(ReadBytesAsPointer) => throw_validation_failure!(
373 format_args!("a dangling {} (created from integer)", kind),
376 err_ub!(PointerOutOfBounds { .. }) => throw_validation_failure!(
378 "a dangling {} (going beyond the bounds of its allocation)",
383 // This cannot happen during const-eval (because interning already detects
384 // dangling pointers), but it can happen in Miri.
385 err_ub!(PointerUseAfterFree(_)) => throw_validation_failure!(
386 format_args!("a dangling {} (use-after-free)", kind),
389 _ => bug!("Unexpected error during ptr inbounds test: {}", err),
393 // Recursive checking
394 if let Some(ref mut ref_tracking) = self.ref_tracking_for_consts {
395 if let Some(ptr) = ptr {
397 // Skip validation entirely for some external statics
398 let alloc_kind = self.ecx.tcx.alloc_map.lock().get(ptr.alloc_id);
399 if let Some(GlobalAlloc::Static(did)) = alloc_kind {
400 // `extern static` cannot be validated as they have no body.
401 // FIXME: Statics from other crates are also skipped.
402 // They might be checked at a different type, but for now we
403 // want to avoid recursing too deeply. This is not sound!
404 if !did.is_local() || self.ecx.tcx.is_foreign_item(did) {
407 if !self.may_ref_to_static && self.ecx.tcx.is_static(did) {
408 throw_validation_failure!(
409 format_args!("a {} pointing to a static variable", kind),
415 // Proceed recursively even for ZST, no reason to skip them!
416 // `!` is a ZST and we want to validate it.
417 // Normalize before handing `place` to tracking because that will
418 // check for duplicates.
419 let place = if size.bytes() > 0 {
420 self.ecx.force_mplace_ptr(place).expect("we already bounds-checked")
424 let path = &self.path;
425 ref_tracking.track(place, || {
426 // We need to clone the path anyway, make sure it gets created
427 // with enough space for the additional `Deref`.
428 let mut new_path = Vec::with_capacity(path.len() + 1);
429 new_path.clone_from(path);
430 new_path.push(PathElem::Deref);
437 /// Check if this is a value of primitive type, and if yes check the validity of the value
438 /// at that type. Return `true` if the type is indeed primitive.
439 fn try_visit_primitive(
441 value: OpTy<'tcx, M::PointerTag>,
442 ) -> InterpResult<'tcx, bool> {
443 // Go over all the primitive types
444 let ty = value.layout.ty;
447 let value = self.ecx.read_scalar(value)?;
448 try_validation!(value.to_bool(), value, self.path, "a boolean");
452 let value = self.ecx.read_scalar(value)?;
453 try_validation!(value.to_char(), value, self.path, "a valid unicode codepoint");
456 ty::Float(_) | ty::Int(_) | ty::Uint(_) => {
457 let value = self.ecx.read_scalar(value)?;
458 // NOTE: Keep this in sync with the array optimization for int/float
460 if self.ref_tracking_for_consts.is_some() {
461 // Integers/floats in CTFE: Must be scalar bits, pointers are dangerous
462 let is_bits = value.not_undef().map_or(false, |v| v.is_bits());
464 throw_validation_failure!(
467 "initialized plain (non-pointer) bytes"
471 // At run-time, for now, we accept *anything* for these types, including
472 // undef. We should fix that, but let's start low.
477 // We are conservative with undef for integers, but try to
478 // actually enforce our current rules for raw pointers.
479 let place = try_validation!(
480 self.ecx.ref_to_mplace(self.ecx.read_immediate(value)?),
484 if place.layout.is_unsized() {
485 self.check_wide_ptr_meta(place.meta, place.layout)?;
490 self.check_safe_pointer(value, "reference")?;
493 ty::Adt(def, ..) if def.is_box() => {
494 self.check_safe_pointer(value, "box")?;
498 let value = self.ecx.read_scalar(value)?;
499 let _fn = try_validation!(
500 value.not_undef().and_then(|ptr| self.ecx.memory.get_fn(ptr)),
505 // FIXME: Check if the signature matches
508 ty::Never => throw_validation_failure!("a value of the never type `!`", self.path),
509 ty::Foreign(..) | ty::FnDef(..) => {
513 // The above should be all the (inhabited) primitive types. The rest is compound, we
514 // check them by visiting their fields/variants.
515 // (`Str` UTF-8 check happens in `visit_aggregate`, too.)
523 | ty::Generator(..) => Ok(false),
524 // Some types only occur during typechecking, they have no layout.
525 // We should not see them here and we could not check them anyway.
528 | ty::Placeholder(..)
532 | ty::UnnormalizedProjection(..)
534 | ty::GeneratorWitness(..) => bug!("Encountered invalid type {:?}", ty),
540 op: OpTy<'tcx, M::PointerTag>,
541 scalar_layout: &layout::Scalar,
542 ) -> InterpResult<'tcx> {
543 let value = self.ecx.read_scalar(op)?;
544 let valid_range = &scalar_layout.valid_range;
545 let (lo, hi) = valid_range.clone().into_inner();
546 // Determine the allowed range
547 // `max_hi` is as big as the size fits
548 let max_hi = u128::MAX >> (128 - op.layout.size.bits());
549 assert!(hi <= max_hi);
550 // We could also write `(hi + 1) % (max_hi + 1) == lo` but `max_hi + 1` overflows for `u128`
551 if (lo == 0 && hi == max_hi) || (hi + 1 == lo) {
555 // At least one value is excluded. Get the bits.
556 let value = try_validation!(
560 format_args!("something {}", wrapping_range_format(valid_range, max_hi),)
562 let bits = match value.to_bits_or_ptr(op.layout.size, self.ecx) {
564 if lo == 1 && hi == max_hi {
565 // Only NULL is the niche. So make sure the ptr is NOT NULL.
566 if self.ecx.memory.ptr_may_be_null(ptr) {
567 throw_validation_failure!(
568 "a potentially NULL pointer",
571 "something that cannot possibly fail to be {}",
572 wrapping_range_format(valid_range, max_hi)
578 // Conservatively, we reject, because the pointer *could* have a bad
580 throw_validation_failure!(
584 "something that cannot possibly fail to be {}",
585 wrapping_range_format(valid_range, max_hi)
592 // Now compare. This is slightly subtle because this is a special "wrap-around" range.
593 if wrapping_range_contains(&valid_range, bits) {
596 throw_validation_failure!(
599 format_args!("something {}", wrapping_range_format(valid_range, max_hi))
605 impl<'rt, 'mir, 'tcx, M: Machine<'mir, 'tcx>> ValueVisitor<'mir, 'tcx, M>
606 for ValidityVisitor<'rt, 'mir, 'tcx, M>
608 type V = OpTy<'tcx, M::PointerTag>;
611 fn ecx(&self) -> &InterpCx<'mir, 'tcx, M> {
618 old_op: OpTy<'tcx, M::PointerTag>,
620 new_op: OpTy<'tcx, M::PointerTag>,
621 ) -> InterpResult<'tcx> {
622 let elem = self.aggregate_field_path_elem(old_op.layout, field);
623 self.visit_elem(new_op, elem)
629 old_op: OpTy<'tcx, M::PointerTag>,
630 variant_id: VariantIdx,
631 new_op: OpTy<'tcx, M::PointerTag>,
632 ) -> InterpResult<'tcx> {
633 let name = match old_op.layout.ty.kind {
634 ty::Adt(adt, _) => PathElem::Variant(adt.variants[variant_id].ident.name),
635 // Generators also have variants
636 ty::Generator(..) => PathElem::GeneratorState(variant_id),
637 _ => bug!("Unexpected type with variant: {:?}", old_op.layout.ty),
639 self.visit_elem(new_op, name)
643 fn visit_union(&mut self, op: OpTy<'tcx, M::PointerTag>, fields: usize) -> InterpResult<'tcx> {
644 // Empty unions are not accepted by rustc. But uninhabited enums
645 // claim to be unions, so allow them, too.
646 assert!(op.layout.abi.is_uninhabited() || fields > 0);
651 fn visit_value(&mut self, op: OpTy<'tcx, M::PointerTag>) -> InterpResult<'tcx> {
652 trace!("visit_value: {:?}, {:?}", *op, op.layout);
654 // Check primitive types -- the leafs of our recursive descend.
655 if self.try_visit_primitive(op)? {
658 // Sanity check: `builtin_deref` does not know any pointers that are not primitive.
659 assert!(op.layout.ty.builtin_deref(true).is_none());
661 // Recursively walk the type. Translate some possible errors to something nicer.
662 match self.walk_value(op) {
664 Err(err) => match err.kind {
665 err_ub!(InvalidDiscriminant(val)) => {
666 throw_validation_failure!(val, self.path, "a valid enum discriminant")
668 err_unsup!(ReadPointerAsBytes) => {
669 throw_validation_failure!("a pointer", self.path, "plain (non-pointer) bytes")
671 // Propagate upwards (that will also check for unexpected errors).
672 _ => return Err(err),
676 // *After* all of this, check the ABI. We need to check the ABI to handle
677 // types like `NonNull` where the `Scalar` info is more restrictive than what
678 // the fields say (`rustc_layout_scalar_valid_range_start`).
679 // But in most cases, this will just propagate what the fields say,
680 // and then we want the error to point at the field -- so, first recurse,
683 // FIXME: We could avoid some redundant checks here. For newtypes wrapping
684 // scalars, we do the same check on every "level" (e.g., first we check
685 // MyNewtype and then the scalar in there).
686 match op.layout.abi {
687 layout::Abi::Uninhabited => {
688 throw_validation_failure!(
689 format_args!("a value of uninhabited type {:?}", op.layout.ty),
693 layout::Abi::Scalar(ref scalar_layout) => {
694 self.visit_scalar(op, scalar_layout)?;
696 layout::Abi::ScalarPair { .. } | layout::Abi::Vector { .. } => {
697 // These have fields that we already visited above, so we already checked
698 // all their scalar-level restrictions.
699 // There is also no equivalent to `rustc_layout_scalar_valid_range_start`
700 // that would make skipping them here an issue.
702 layout::Abi::Aggregate { .. } => {
712 op: OpTy<'tcx, M::PointerTag>,
713 fields: impl Iterator<Item = InterpResult<'tcx, Self::V>>,
714 ) -> InterpResult<'tcx> {
715 match op.layout.ty.kind {
717 let mplace = op.assert_mem_place(self.ecx); // strings are never immediate
719 self.ecx.read_str(mplace),
720 "uninitialized or non-UTF-8 data in str",
724 ty::Array(tys, ..) | ty::Slice(tys)
726 // This optimization applies for types that can hold arbitrary bytes (such as
727 // integer and floating point types) or for structs or tuples with no fields.
728 // FIXME(wesleywiser) This logic could be extended further to arbitrary structs
729 // or tuples made up of integer/floating point types or inhabited ZSTs with no
732 ty::Int(..) | ty::Uint(..) | ty::Float(..) => true,
737 // Optimized handling for arrays of integer/float type.
739 // Arrays cannot be immediate, slices are never immediate.
740 let mplace = op.assert_mem_place(self.ecx);
741 // This is the length of the array/slice.
742 let len = mplace.len(self.ecx)?;
743 // Zero length slices have nothing to be checked.
747 // This is the element type size.
748 let layout = self.ecx.layout_of(tys)?;
749 // This is the size in bytes of the whole array.
750 let size = layout.size * len;
751 // Size is not 0, get a pointer.
752 let ptr = self.ecx.force_ptr(mplace.ptr)?;
754 // Optimization: we just check the entire range at once.
755 // NOTE: Keep this in sync with the handling of integer and float
756 // types above, in `visit_primitive`.
757 // In run-time mode, we accept pointers in here. This is actually more
758 // permissive than a per-element check would be, e.g., we accept
759 // an &[u8] that contains a pointer even though bytewise checking would
760 // reject it. However, that's good: We don't inherently want
761 // to reject those pointers, we just do not have the machinery to
762 // talk about parts of a pointer.
763 // We also accept undef, for consistency with the slow path.
764 match self.ecx.memory.get_raw(ptr.alloc_id)?.check_bytes(
768 /*allow_ptr_and_undef*/ self.ref_tracking_for_consts.is_none(),
770 // In the happy case, we needn't check anything else.
772 // Some error happened, try to provide a more detailed description.
774 // For some errors we might be able to provide extra information
776 err_ub!(InvalidUndefBytes(Some(ptr))) => {
777 // Some byte was undefined, determine which
778 // element that byte belongs to so we can
780 let i = (ptr.offset.bytes() / layout.size.bytes()) as usize;
781 self.path.push(PathElem::ArrayElem(i));
783 throw_validation_failure!("undefined bytes", self.path)
785 // Other errors shouldn't be possible
786 _ => return Err(err),
791 // Fast path for arrays and slices of ZSTs. We only need to check a single ZST element
792 // of an array and not all of them, because there's only a single value of a specific
793 // ZST type, so either validation fails for all elements or none.
794 ty::Array(tys, ..) | ty::Slice(tys) if self.ecx.layout_of(tys)?.is_zst() => {
795 // Validate just the first element
796 self.walk_aggregate(op, fields.take(1))?
799 self.walk_aggregate(op, fields)? // default handler
806 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
807 fn validate_operand_internal(
809 op: OpTy<'tcx, M::PointerTag>,
811 ref_tracking_for_consts: Option<
812 &mut RefTracking<MPlaceTy<'tcx, M::PointerTag>, Vec<PathElem>>,
814 may_ref_to_static: bool,
815 ) -> InterpResult<'tcx> {
816 trace!("validate_operand_internal: {:?}, {:?}", *op, op.layout.ty);
818 // Construct a visitor
820 ValidityVisitor { path, ref_tracking_for_consts, may_ref_to_static, ecx: self };
822 // Try to cast to ptr *once* instead of all the time.
823 let op = self.force_op_ptr(op).unwrap_or(op);
826 match visitor.visit_value(op) {
828 Err(err) if matches!(err.kind, err_ub!(ValidationFailure { .. })) => Err(err),
829 Err(err) if cfg!(debug_assertions) => {
830 bug!("Unexpected error during validation: {}", err)
832 Err(err) => Err(err),
836 /// This function checks the data at `op` to be const-valid.
837 /// `op` is assumed to cover valid memory if it is an indirect operand.
838 /// It will error if the bits at the destination do not match the ones described by the layout.
840 /// `ref_tracking` is used to record references that we encounter so that they
841 /// can be checked recursively by an outside driving loop.
843 /// `may_ref_to_static` controls whether references are allowed to point to statics.
845 pub fn const_validate_operand(
847 op: OpTy<'tcx, M::PointerTag>,
849 ref_tracking: &mut RefTracking<MPlaceTy<'tcx, M::PointerTag>, Vec<PathElem>>,
850 may_ref_to_static: bool,
851 ) -> InterpResult<'tcx> {
852 self.validate_operand_internal(op, path, Some(ref_tracking), may_ref_to_static)
855 /// This function checks the data at `op` to be runtime-valid.
856 /// `op` is assumed to cover valid memory if it is an indirect operand.
857 /// It will error if the bits at the destination do not match the ones described by the layout.
859 pub fn validate_operand(&self, op: OpTy<'tcx, M::PointerTag>) -> InterpResult<'tcx> {
860 self.validate_operand_internal(op, vec![], None, false)