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_unsup!(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_unsup!(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_unsup!(InvalidNullPointerUsage) => {
357 throw_validation_failure!(format_args!("a NULL {}", kind), self.path)
359 err_unsup!(AlignmentCheckFailed { required, has }) => {
360 throw_validation_failure!(
363 (required {} byte alignment but found {})",
371 err_unsup!(ReadBytesAsPointer) => throw_validation_failure!(
372 format_args!("a dangling {} (created from integer)", kind),
375 err_unsup!(PointerOutOfBounds { .. }) | err_unsup!(DanglingPointerDeref) => {
376 throw_validation_failure!(
377 format_args!("a dangling {} (not entirely in bounds)", kind),
381 _ => bug!("Unexpected error during ptr inbounds test: {}", err),
385 // Recursive checking
386 if let Some(ref mut ref_tracking) = self.ref_tracking_for_consts {
387 if let Some(ptr) = ptr {
389 // Skip validation entirely for some external statics
390 let alloc_kind = self.ecx.tcx.alloc_map.lock().get(ptr.alloc_id);
391 if let Some(GlobalAlloc::Static(did)) = alloc_kind {
392 // `extern static` cannot be validated as they have no body.
393 // FIXME: Statics from other crates are also skipped.
394 // They might be checked at a different type, but for now we
395 // want to avoid recursing too deeply. This is not sound!
396 if !did.is_local() || self.ecx.tcx.is_foreign_item(did) {
399 if !self.may_ref_to_static && self.ecx.tcx.is_static(did) {
400 throw_validation_failure!(
401 format_args!("a {} pointing to a static variable", kind),
407 // Proceed recursively even for ZST, no reason to skip them!
408 // `!` is a ZST and we want to validate it.
409 // Normalize before handing `place` to tracking because that will
410 // check for duplicates.
411 let place = if size.bytes() > 0 {
412 self.ecx.force_mplace_ptr(place).expect("we already bounds-checked")
416 let path = &self.path;
417 ref_tracking.track(place, || {
418 // We need to clone the path anyway, make sure it gets created
419 // with enough space for the additional `Deref`.
420 let mut new_path = Vec::with_capacity(path.len() + 1);
421 new_path.clone_from(path);
422 new_path.push(PathElem::Deref);
429 /// Check if this is a value of primitive type, and if yes check the validity of the value
430 /// at that type. Return `true` if the type is indeed primitive.
431 fn try_visit_primitive(
433 value: OpTy<'tcx, M::PointerTag>,
434 ) -> InterpResult<'tcx, bool> {
435 // Go over all the primitive types
436 let ty = value.layout.ty;
439 let value = self.ecx.read_scalar(value)?;
440 try_validation!(value.to_bool(), value, self.path, "a boolean");
444 let value = self.ecx.read_scalar(value)?;
445 try_validation!(value.to_char(), value, self.path, "a valid unicode codepoint");
448 ty::Float(_) | ty::Int(_) | ty::Uint(_) => {
449 let value = self.ecx.read_scalar(value)?;
450 // NOTE: Keep this in sync with the array optimization for int/float
452 if self.ref_tracking_for_consts.is_some() {
453 // Integers/floats in CTFE: Must be scalar bits, pointers are dangerous
454 let is_bits = value.not_undef().map_or(false, |v| v.is_bits());
456 throw_validation_failure!(
459 "initialized plain (non-pointer) bytes"
463 // At run-time, for now, we accept *anything* for these types, including
464 // undef. We should fix that, but let's start low.
469 // We are conservative with undef for integers, but try to
470 // actually enforce our current rules for raw pointers.
471 let place = try_validation!(
472 self.ecx.ref_to_mplace(self.ecx.read_immediate(value)?),
476 if place.layout.is_unsized() {
477 self.check_wide_ptr_meta(place.meta, place.layout)?;
482 self.check_safe_pointer(value, "reference")?;
485 ty::Adt(def, ..) if def.is_box() => {
486 self.check_safe_pointer(value, "box")?;
490 let value = self.ecx.read_scalar(value)?;
491 let _fn = try_validation!(
492 value.not_undef().and_then(|ptr| self.ecx.memory.get_fn(ptr)),
497 // FIXME: Check if the signature matches
500 ty::Never => throw_validation_failure!("a value of the never type `!`", self.path),
501 ty::Foreign(..) | ty::FnDef(..) => {
505 // The above should be all the (inhabited) primitive types. The rest is compound, we
506 // check them by visiting their fields/variants.
507 // (`Str` UTF-8 check happens in `visit_aggregate`, too.)
515 | ty::Generator(..) => Ok(false),
516 // Some types only occur during typechecking, they have no layout.
517 // We should not see them here and we could not check them anyway.
520 | ty::Placeholder(..)
524 | ty::UnnormalizedProjection(..)
526 | ty::GeneratorWitness(..) => bug!("Encountered invalid type {:?}", ty),
532 op: OpTy<'tcx, M::PointerTag>,
533 scalar_layout: &layout::Scalar,
534 ) -> InterpResult<'tcx> {
535 let value = self.ecx.read_scalar(op)?;
536 let valid_range = &scalar_layout.valid_range;
537 let (lo, hi) = valid_range.clone().into_inner();
538 // Determine the allowed range
539 // `max_hi` is as big as the size fits
540 let max_hi = u128::MAX >> (128 - op.layout.size.bits());
541 assert!(hi <= max_hi);
542 // We could also write `(hi + 1) % (max_hi + 1) == lo` but `max_hi + 1` overflows for `u128`
543 if (lo == 0 && hi == max_hi) || (hi + 1 == lo) {
547 // At least one value is excluded. Get the bits.
548 let value = try_validation!(
552 format_args!("something {}", wrapping_range_format(valid_range, max_hi),)
554 let bits = match value.to_bits_or_ptr(op.layout.size, self.ecx) {
556 if lo == 1 && hi == max_hi {
557 // Only NULL is the niche. So make sure the ptr is NOT NULL.
558 if self.ecx.memory.ptr_may_be_null(ptr) {
559 throw_validation_failure!(
560 "a potentially NULL pointer",
563 "something that cannot possibly fail to be {}",
564 wrapping_range_format(valid_range, max_hi)
570 // Conservatively, we reject, because the pointer *could* have a bad
572 throw_validation_failure!(
576 "something that cannot possibly fail to be {}",
577 wrapping_range_format(valid_range, max_hi)
584 // Now compare. This is slightly subtle because this is a special "wrap-around" range.
585 if wrapping_range_contains(&valid_range, bits) {
588 throw_validation_failure!(
591 format_args!("something {}", wrapping_range_format(valid_range, max_hi))
597 impl<'rt, 'mir, 'tcx, M: Machine<'mir, 'tcx>> ValueVisitor<'mir, 'tcx, M>
598 for ValidityVisitor<'rt, 'mir, 'tcx, M>
600 type V = OpTy<'tcx, M::PointerTag>;
603 fn ecx(&self) -> &InterpCx<'mir, 'tcx, M> {
610 old_op: OpTy<'tcx, M::PointerTag>,
612 new_op: OpTy<'tcx, M::PointerTag>,
613 ) -> InterpResult<'tcx> {
614 let elem = self.aggregate_field_path_elem(old_op.layout, field);
615 self.visit_elem(new_op, elem)
621 old_op: OpTy<'tcx, M::PointerTag>,
622 variant_id: VariantIdx,
623 new_op: OpTy<'tcx, M::PointerTag>,
624 ) -> InterpResult<'tcx> {
625 let name = match old_op.layout.ty.kind {
626 ty::Adt(adt, _) => PathElem::Variant(adt.variants[variant_id].ident.name),
627 // Generators also have variants
628 ty::Generator(..) => PathElem::GeneratorState(variant_id),
629 _ => bug!("Unexpected type with variant: {:?}", old_op.layout.ty),
631 self.visit_elem(new_op, name)
635 fn visit_union(&mut self, op: OpTy<'tcx, M::PointerTag>, fields: usize) -> InterpResult<'tcx> {
636 // Empty unions are not accepted by rustc. But uninhabited enums
637 // claim to be unions, so allow them, too.
638 assert!(op.layout.abi.is_uninhabited() || fields > 0);
643 fn visit_value(&mut self, op: OpTy<'tcx, M::PointerTag>) -> InterpResult<'tcx> {
644 trace!("visit_value: {:?}, {:?}", *op, op.layout);
646 // Check primitive types -- the leafs of our recursive descend.
647 if self.try_visit_primitive(op)? {
650 // Sanity check: `builtin_deref` does not know any pointers that are not primitive.
651 assert!(op.layout.ty.builtin_deref(true).is_none());
653 // Recursively walk the type. Translate some possible errors to something nicer.
654 match self.walk_value(op) {
656 Err(err) => match err.kind {
657 err_ub!(InvalidDiscriminant(val)) => {
658 throw_validation_failure!(val, self.path, "a valid enum discriminant")
660 err_unsup!(ReadPointerAsBytes) => {
661 throw_validation_failure!("a pointer", self.path, "plain (non-pointer) bytes")
663 // Propagate upwards (that will also check for unexpected errors).
664 _ => return Err(err),
668 // *After* all of this, check the ABI. We need to check the ABI to handle
669 // types like `NonNull` where the `Scalar` info is more restrictive than what
670 // the fields say (`rustc_layout_scalar_valid_range_start`).
671 // But in most cases, this will just propagate what the fields say,
672 // and then we want the error to point at the field -- so, first recurse,
675 // FIXME: We could avoid some redundant checks here. For newtypes wrapping
676 // scalars, we do the same check on every "level" (e.g., first we check
677 // MyNewtype and then the scalar in there).
678 match op.layout.abi {
679 layout::Abi::Uninhabited => {
680 throw_validation_failure!(
681 format_args!("a value of uninhabited type {:?}", op.layout.ty),
685 layout::Abi::Scalar(ref scalar_layout) => {
686 self.visit_scalar(op, scalar_layout)?;
688 layout::Abi::ScalarPair { .. } | layout::Abi::Vector { .. } => {
689 // These have fields that we already visited above, so we already checked
690 // all their scalar-level restrictions.
691 // There is also no equivalent to `rustc_layout_scalar_valid_range_start`
692 // that would make skipping them here an issue.
694 layout::Abi::Aggregate { .. } => {
704 op: OpTy<'tcx, M::PointerTag>,
705 fields: impl Iterator<Item = InterpResult<'tcx, Self::V>>,
706 ) -> InterpResult<'tcx> {
707 match op.layout.ty.kind {
709 let mplace = op.assert_mem_place(self.ecx); // strings are never immediate
711 self.ecx.read_str(mplace),
712 "uninitialized or non-UTF-8 data in str",
716 ty::Array(tys, ..) | ty::Slice(tys)
718 // This optimization applies for types that can hold arbitrary bytes (such as
719 // integer and floating point types) or for structs or tuples with no fields.
720 // FIXME(wesleywiser) This logic could be extended further to arbitrary structs
721 // or tuples made up of integer/floating point types or inhabited ZSTs with no
724 ty::Int(..) | ty::Uint(..) | ty::Float(..) => true,
729 // Optimized handling for arrays of integer/float type.
731 // Arrays cannot be immediate, slices are never immediate.
732 let mplace = op.assert_mem_place(self.ecx);
733 // This is the length of the array/slice.
734 let len = mplace.len(self.ecx)?;
735 // Zero length slices have nothing to be checked.
739 // This is the element type size.
740 let layout = self.ecx.layout_of(tys)?;
741 // This is the size in bytes of the whole array.
742 let size = layout.size * len;
743 // Size is not 0, get a pointer.
744 let ptr = self.ecx.force_ptr(mplace.ptr)?;
746 // Optimization: we just check the entire range at once.
747 // NOTE: Keep this in sync with the handling of integer and float
748 // types above, in `visit_primitive`.
749 // In run-time mode, we accept pointers in here. This is actually more
750 // permissive than a per-element check would be, e.g., we accept
751 // an &[u8] that contains a pointer even though bytewise checking would
752 // reject it. However, that's good: We don't inherently want
753 // to reject those pointers, we just do not have the machinery to
754 // talk about parts of a pointer.
755 // We also accept undef, for consistency with the slow path.
756 match self.ecx.memory.get_raw(ptr.alloc_id)?.check_bytes(
760 /*allow_ptr_and_undef*/ self.ref_tracking_for_consts.is_none(),
762 // In the happy case, we needn't check anything else.
764 // Some error happened, try to provide a more detailed description.
766 // For some errors we might be able to provide extra information
768 err_unsup!(ReadUndefBytes(offset)) => {
769 // Some byte was undefined, determine which
770 // element that byte belongs to so we can
772 let i = (offset.bytes() / layout.size.bytes()) as usize;
773 self.path.push(PathElem::ArrayElem(i));
775 throw_validation_failure!("undefined bytes", self.path)
777 // Other errors shouldn't be possible
778 _ => return Err(err),
783 // Fast path for arrays and slices of ZSTs. We only need to check a single ZST element
784 // of an array and not all of them, because there's only a single value of a specific
785 // ZST type, so either validation fails for all elements or none.
786 ty::Array(tys, ..) | ty::Slice(tys) if self.ecx.layout_of(tys)?.is_zst() => {
787 // Validate just the first element
788 self.walk_aggregate(op, fields.take(1))?
791 self.walk_aggregate(op, fields)? // default handler
798 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
799 fn validate_operand_internal(
801 op: OpTy<'tcx, M::PointerTag>,
803 ref_tracking_for_consts: Option<
804 &mut RefTracking<MPlaceTy<'tcx, M::PointerTag>, Vec<PathElem>>,
806 may_ref_to_static: bool,
807 ) -> InterpResult<'tcx> {
808 trace!("validate_operand_internal: {:?}, {:?}", *op, op.layout.ty);
810 // Construct a visitor
812 ValidityVisitor { path, ref_tracking_for_consts, may_ref_to_static, ecx: self };
814 // Try to cast to ptr *once* instead of all the time.
815 let op = self.force_op_ptr(op).unwrap_or(op);
818 match visitor.visit_value(op) {
820 Err(err) if matches!(err.kind, err_unsup!(ValidationFailure { .. })) => Err(err),
821 Err(err) if cfg!(debug_assertions) => {
822 bug!("Unexpected error during validation: {}", err)
824 Err(err) => Err(err),
828 /// This function checks the data at `op` to be const-valid.
829 /// `op` is assumed to cover valid memory if it is an indirect operand.
830 /// It will error if the bits at the destination do not match the ones described by the layout.
832 /// `ref_tracking` is used to record references that we encounter so that they
833 /// can be checked recursively by an outside driving loop.
835 /// `may_ref_to_static` controls whether references are allowed to point to statics.
837 pub fn const_validate_operand(
839 op: OpTy<'tcx, M::PointerTag>,
841 ref_tracking: &mut RefTracking<MPlaceTy<'tcx, M::PointerTag>, Vec<PathElem>>,
842 may_ref_to_static: bool,
843 ) -> InterpResult<'tcx> {
844 self.validate_operand_internal(op, path, Some(ref_tracking), may_ref_to_static)
847 /// This function checks the data at `op` to be runtime-valid.
848 /// `op` is assumed to cover valid memory if it is an indirect operand.
849 /// It will error if the bits at the destination do not match the ones described by the layout.
851 pub fn validate_operand(&self, op: OpTy<'tcx, M::PointerTag>) -> InterpResult<'tcx> {
852 self.validate_operand_internal(op, vec![], None, false)