]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/validity.rs
adjust Deref comment
[rust.git] / src / librustc_mir / interpret / validity.rs
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
5 //! to be const-safe.
6
7 use std::fmt::Write;
8 use std::ops::RangeInclusive;
9
10 use rustc::ty;
11 use rustc::ty::layout::{self, LayoutOf, TyLayout, VariantIdx};
12 use rustc_data_structures::fx::FxHashSet;
13 use rustc_hir as hir;
14 use rustc_span::symbol::{sym, Symbol};
15
16 use std::hash::Hash;
17
18 use super::{
19     CheckInAllocMsg, GlobalAlloc, InterpCx, InterpResult, MPlaceTy, Machine, MemPlaceMeta, OpTy,
20     ValueVisitor,
21 };
22
23 macro_rules! throw_validation_failure {
24     ($what:expr, $where:expr, $details:expr) => {{
25         let mut msg = format!("encountered {}", $what);
26         let where_ = &$where;
27         if !where_.is_empty() {
28             msg.push_str(" at ");
29             write_path(&mut msg, where_);
30         }
31         write!(&mut msg, ", but expected {}", $details).unwrap();
32         throw_unsup!(ValidationFailure(msg))
33     }};
34     ($what:expr, $where:expr) => {{
35         let mut msg = format!("encountered {}", $what);
36         let where_ = &$where;
37         if !where_.is_empty() {
38             msg.push_str(" at ");
39             write_path(&mut msg, where_);
40         }
41         throw_unsup!(ValidationFailure(msg))
42     }};
43 }
44
45 macro_rules! try_validation {
46     ($e:expr, $what:expr, $where:expr, $details:expr) => {{
47         match $e {
48             Ok(x) => x,
49             Err(_) => throw_validation_failure!($what, $where, $details),
50         }
51     }};
52
53     ($e:expr, $what:expr, $where:expr) => {{
54         match $e {
55             Ok(x) => x,
56             Err(_) => throw_validation_failure!($what, $where),
57         }
58     }};
59 }
60
61 /// We want to show a nice path to the invalid field for diagnostics,
62 /// but avoid string operations in the happy case where no error happens.
63 /// So we track a `Vec<PathElem>` where `PathElem` contains all the data we
64 /// need to later print something for the user.
65 #[derive(Copy, Clone, Debug)]
66 pub enum PathElem {
67     Field(Symbol),
68     Variant(Symbol),
69     GeneratorState(VariantIdx),
70     ClosureVar(Symbol),
71     ArrayElem(usize),
72     TupleElem(usize),
73     Deref,
74     Tag,
75     DynDowncast,
76 }
77
78 /// State for tracking recursive validation of references
79 pub struct RefTracking<T, PATH = ()> {
80     pub seen: FxHashSet<T>,
81     pub todo: Vec<(T, PATH)>,
82 }
83
84 impl<T: Copy + Eq + Hash + std::fmt::Debug, PATH: Default> RefTracking<T, PATH> {
85     pub fn empty() -> Self {
86         RefTracking { seen: FxHashSet::default(), todo: vec![] }
87     }
88     pub fn new(op: T) -> Self {
89         let mut ref_tracking_for_consts =
90             RefTracking { seen: FxHashSet::default(), todo: vec![(op, PATH::default())] };
91         ref_tracking_for_consts.seen.insert(op);
92         ref_tracking_for_consts
93     }
94
95     pub fn track(&mut self, op: T, path: impl FnOnce() -> PATH) {
96         if self.seen.insert(op) {
97             trace!("Recursing below ptr {:#?}", op);
98             let path = path();
99             // Remember to come back to this later.
100             self.todo.push((op, path));
101         }
102     }
103 }
104
105 /// Format a path
106 fn write_path(out: &mut String, path: &Vec<PathElem>) {
107     use self::PathElem::*;
108
109     for elem in path.iter() {
110         match elem {
111             Field(name) => write!(out, ".{}", name),
112             Variant(name) => write!(out, ".<downcast-variant({})>", name),
113             GeneratorState(idx) => write!(out, ".<generator-state({})>", idx.index()),
114             ClosureVar(name) => write!(out, ".<closure-var({})>", name),
115             TupleElem(idx) => write!(out, ".{}", idx),
116             ArrayElem(idx) => write!(out, "[{}]", idx),
117             // `.<deref>` does not match Rust syntax, but it is more readable for long paths -- and
118             // some of the other items here also are not Rust syntax.  Actually we can't
119             // even use the usual syntax because we are just showing the projections,
120             // not the root.
121             Deref => write!(out, ".<deref>"),
122             Tag => write!(out, ".<enum-tag>"),
123             DynDowncast => write!(out, ".<dyn-downcast>"),
124         }
125         .unwrap()
126     }
127 }
128
129 // Test if a range that wraps at overflow contains `test`
130 fn wrapping_range_contains(r: &RangeInclusive<u128>, test: u128) -> bool {
131     let (lo, hi) = r.clone().into_inner();
132     if lo > hi {
133         // Wrapped
134         (..=hi).contains(&test) || (lo..).contains(&test)
135     } else {
136         // Normal
137         r.contains(&test)
138     }
139 }
140
141 // Formats such that a sentence like "expected something {}" to mean
142 // "expected something <in the given range>" makes sense.
143 fn wrapping_range_format(r: &RangeInclusive<u128>, max_hi: u128) -> String {
144     let (lo, hi) = r.clone().into_inner();
145     debug_assert!(hi <= max_hi);
146     if lo > hi {
147         format!("less or equal to {}, or greater or equal to {}", hi, lo)
148     } else if lo == hi {
149         format!("equal to {}", lo)
150     } else if lo == 0 {
151         debug_assert!(hi < max_hi, "should not be printing if the range covers everything");
152         format!("less or equal to {}", hi)
153     } else if hi == max_hi {
154         debug_assert!(lo > 0, "should not be printing if the range covers everything");
155         format!("greater or equal to {}", lo)
156     } else {
157         format!("in the range {:?}", r)
158     }
159 }
160
161 struct ValidityVisitor<'rt, 'mir, 'tcx, M: Machine<'mir, 'tcx>> {
162     /// The `path` may be pushed to, but the part that is present when a function
163     /// starts must not be changed!  `visit_fields` and `visit_array` rely on
164     /// this stack discipline.
165     path: Vec<PathElem>,
166     ref_tracking_for_consts:
167         Option<&'rt mut RefTracking<MPlaceTy<'tcx, M::PointerTag>, Vec<PathElem>>>,
168     ecx: &'rt InterpCx<'mir, 'tcx, M>,
169 }
170
171 impl<'rt, 'mir, 'tcx, M: Machine<'mir, 'tcx>> ValidityVisitor<'rt, 'mir, 'tcx, M> {
172     fn aggregate_field_path_elem(&mut self, layout: TyLayout<'tcx>, field: usize) -> PathElem {
173         match layout.ty.kind {
174             // generators and closures.
175             ty::Closure(def_id, _) | ty::Generator(def_id, _, _) => {
176                 let mut name = None;
177                 if def_id.is_local() {
178                     let tables = self.ecx.tcx.typeck_tables_of(def_id);
179                     if let Some(upvars) = tables.upvar_list.get(&def_id) {
180                         // Sometimes the index is beyond the number of upvars (seen
181                         // for a generator).
182                         if let Some((&var_hir_id, _)) = upvars.get_index(field) {
183                             let node = self.ecx.tcx.hir().get(var_hir_id);
184                             if let hir::Node::Binding(pat) = node {
185                                 if let hir::PatKind::Binding(_, _, ident, _) = pat.kind {
186                                     name = Some(ident.name);
187                                 }
188                             }
189                         }
190                     }
191                 }
192
193                 PathElem::ClosureVar(name.unwrap_or_else(|| {
194                     // Fall back to showing the field index.
195                     sym::integer(field)
196                 }))
197             }
198
199             // tuples
200             ty::Tuple(_) => PathElem::TupleElem(field),
201
202             // enums
203             ty::Adt(def, ..) if def.is_enum() => {
204                 // we might be projecting *to* a variant, or to a field *in*a variant.
205                 match layout.variants {
206                     layout::Variants::Single { index } => {
207                         // Inside a variant
208                         PathElem::Field(def.variants[index].fields[field].ident.name)
209                     }
210                     _ => bug!(),
211                 }
212             }
213
214             // other ADTs
215             ty::Adt(def, _) => PathElem::Field(def.non_enum_variant().fields[field].ident.name),
216
217             // arrays/slices
218             ty::Array(..) | ty::Slice(..) => PathElem::ArrayElem(field),
219
220             // dyn traits
221             ty::Dynamic(..) => PathElem::DynDowncast,
222
223             // nothing else has an aggregate layout
224             _ => bug!("aggregate_field_path_elem: got non-aggregate type {:?}", layout.ty),
225         }
226     }
227
228     fn visit_elem(
229         &mut self,
230         new_op: OpTy<'tcx, M::PointerTag>,
231         elem: PathElem,
232     ) -> InterpResult<'tcx> {
233         // Remember the old state
234         let path_len = self.path.len();
235         // Perform operation
236         self.path.push(elem);
237         self.visit_value(new_op)?;
238         // Undo changes
239         self.path.truncate(path_len);
240         Ok(())
241     }
242
243     fn check_wide_ptr_meta(
244         &mut self,
245         meta: MemPlaceMeta<M::PointerTag>,
246         pointee: TyLayout<'tcx>,
247     ) -> InterpResult<'tcx> {
248         let tail = self.ecx.tcx.struct_tail_erasing_lifetimes(pointee.ty, self.ecx.param_env);
249         match tail.kind {
250             ty::Dynamic(..) => {
251                 let vtable = meta.unwrap_meta();
252                 try_validation!(
253                     self.ecx.memory.check_ptr_access(
254                         vtable,
255                         3 * self.ecx.tcx.data_layout.pointer_size, // drop, size, align
256                         self.ecx.tcx.data_layout.pointer_align.abi,
257                     ),
258                     "dangling or unaligned vtable pointer in wide pointer or too small vtable",
259                     self.path
260                 );
261                 try_validation!(
262                     self.ecx.read_drop_type_from_vtable(vtable),
263                     "invalid drop fn in vtable",
264                     self.path
265                 );
266                 try_validation!(
267                     self.ecx.read_size_and_align_from_vtable(vtable),
268                     "invalid size or align in vtable",
269                     self.path
270                 );
271                 // FIXME: More checks for the vtable.
272             }
273             ty::Slice(..) | ty::Str => {
274                 let _len = try_validation!(
275                     meta.unwrap_meta().to_machine_usize(self.ecx),
276                     "non-integer slice length in wide pointer",
277                     self.path
278                 );
279                 // We do not check that `len * elem_size <= isize::MAX`:
280                 // that is only required for references, and there it falls out of the
281                 // "dereferenceable" check performed by Stacked Borrows.
282             }
283             ty::Foreign(..) => {
284                 // Unsized, but not wide.
285             }
286             _ => bug!("Unexpected unsized type tail: {:?}", tail),
287         }
288
289         Ok(())
290     }
291 }
292
293 impl<'rt, 'mir, 'tcx, M: Machine<'mir, 'tcx>> ValueVisitor<'mir, 'tcx, M>
294     for ValidityVisitor<'rt, 'mir, 'tcx, M>
295 {
296     type V = OpTy<'tcx, M::PointerTag>;
297
298     #[inline(always)]
299     fn ecx(&self) -> &InterpCx<'mir, 'tcx, M> {
300         &self.ecx
301     }
302
303     #[inline]
304     fn visit_field(
305         &mut self,
306         old_op: OpTy<'tcx, M::PointerTag>,
307         field: usize,
308         new_op: OpTy<'tcx, M::PointerTag>,
309     ) -> InterpResult<'tcx> {
310         let elem = self.aggregate_field_path_elem(old_op.layout, field);
311         self.visit_elem(new_op, elem)
312     }
313
314     #[inline]
315     fn visit_variant(
316         &mut self,
317         old_op: OpTy<'tcx, M::PointerTag>,
318         variant_id: VariantIdx,
319         new_op: OpTy<'tcx, M::PointerTag>,
320     ) -> InterpResult<'tcx> {
321         let name = match old_op.layout.ty.kind {
322             ty::Adt(adt, _) => PathElem::Variant(adt.variants[variant_id].ident.name),
323             // Generators also have variants
324             ty::Generator(..) => PathElem::GeneratorState(variant_id),
325             _ => bug!("Unexpected type with variant: {:?}", old_op.layout.ty),
326         };
327         self.visit_elem(new_op, name)
328     }
329
330     #[inline]
331     fn visit_value(&mut self, op: OpTy<'tcx, M::PointerTag>) -> InterpResult<'tcx> {
332         trace!("visit_value: {:?}, {:?}", *op, op.layout);
333         // Translate some possible errors to something nicer.
334         match self.walk_value(op) {
335             Ok(()) => Ok(()),
336             Err(err) => match err.kind {
337                 err_ub!(InvalidDiscriminant(val)) => {
338                     throw_validation_failure!(val, self.path, "a valid enum discriminant")
339                 }
340                 err_unsup!(ReadPointerAsBytes) => {
341                     throw_validation_failure!("a pointer", self.path, "plain (non-pointer) bytes")
342                 }
343                 _ => Err(err),
344             },
345         }
346     }
347
348     fn visit_primitive(&mut self, value: OpTy<'tcx, M::PointerTag>) -> InterpResult<'tcx> {
349         let value = self.ecx.read_immediate(value)?;
350         // Go over all the primitive types
351         let ty = value.layout.ty;
352         match ty.kind {
353             ty::Bool => {
354                 let value = value.to_scalar_or_undef();
355                 try_validation!(value.to_bool(), value, self.path, "a boolean");
356             }
357             ty::Char => {
358                 let value = value.to_scalar_or_undef();
359                 try_validation!(value.to_char(), value, self.path, "a valid unicode codepoint");
360             }
361             ty::Float(_) | ty::Int(_) | ty::Uint(_) => {
362                 // NOTE: Keep this in sync with the array optimization for int/float
363                 // types below!
364                 let size = value.layout.size;
365                 let value = value.to_scalar_or_undef();
366                 if self.ref_tracking_for_consts.is_some() {
367                     // Integers/floats in CTFE: Must be scalar bits, pointers are dangerous
368                     try_validation!(
369                         value.to_bits(size),
370                         value,
371                         self.path,
372                         "initialized plain (non-pointer) bytes"
373                     );
374                 } else {
375                     // At run-time, for now, we accept *anything* for these types, including
376                     // undef. We should fix that, but let's start low.
377                 }
378             }
379             ty::RawPtr(..) => {
380                 // We are conservative with undef for integers, but try to
381                 // actually enforce our current rules for raw pointers.
382                 let place =
383                     try_validation!(self.ecx.ref_to_mplace(value), "undefined pointer", self.path);
384                 if place.layout.is_unsized() {
385                     self.check_wide_ptr_meta(place.meta, place.layout)?;
386                 }
387             }
388             _ if ty.is_box() || ty.is_region_ptr() => {
389                 // Handle wide pointers.
390                 // Check metadata early, for better diagnostics
391                 let place =
392                     try_validation!(self.ecx.ref_to_mplace(value), "undefined pointer", self.path);
393                 if place.layout.is_unsized() {
394                     self.check_wide_ptr_meta(place.meta, place.layout)?;
395                 }
396                 // Make sure this is dereferenceable and all.
397                 let (size, align) = self
398                     .ecx
399                     .size_and_align_of(place.meta, place.layout)?
400                     // for the purpose of validity, consider foreign types to have
401                     // alignment and size determined by the layout (size will be 0,
402                     // alignment should take attributes into account).
403                     .unwrap_or_else(|| (place.layout.size, place.layout.align.abi));
404                 let ptr: Option<_> = match self.ecx.memory.check_ptr_access_align(
405                     place.ptr,
406                     size,
407                     Some(align),
408                     CheckInAllocMsg::InboundsTest,
409                 ) {
410                     Ok(ptr) => ptr,
411                     Err(err) => {
412                         info!(
413                             "{:?} did not pass access check for size {:?}, align {:?}",
414                             place.ptr, size, align
415                         );
416                         match err.kind {
417                             err_unsup!(InvalidNullPointerUsage) => {
418                                 throw_validation_failure!("NULL reference", self.path)
419                             }
420                             err_unsup!(AlignmentCheckFailed { required, has }) => {
421                                 throw_validation_failure!(
422                                     format_args!(
423                                         "unaligned reference \
424                                     (required {} byte alignment but found {})",
425                                         required.bytes(),
426                                         has.bytes()
427                                     ),
428                                     self.path
429                                 )
430                             }
431                             err_unsup!(ReadBytesAsPointer) => throw_validation_failure!(
432                                 "dangling reference (created from integer)",
433                                 self.path
434                             ),
435                             _ => throw_validation_failure!(
436                                 "dangling reference (not entirely in bounds)",
437                                 self.path
438                             ),
439                         }
440                     }
441                 };
442                 // Recursive checking
443                 if let Some(ref mut ref_tracking) = self.ref_tracking_for_consts {
444                     if let Some(ptr) = ptr {
445                         // not a ZST
446                         // Skip validation entirely for some external statics
447                         let alloc_kind = self.ecx.tcx.alloc_map.lock().get(ptr.alloc_id);
448                         if let Some(GlobalAlloc::Static(did)) = alloc_kind {
449                             // `extern static` cannot be validated as they have no body.
450                             // FIXME: Statics from other crates are also skipped.
451                             // They might be checked at a different type, but for now we
452                             // want to avoid recursing too deeply.  This is not sound!
453                             if !did.is_local() || self.ecx.tcx.is_foreign_item(did) {
454                                 return Ok(());
455                             }
456                         }
457                     }
458                     // Proceed recursively even for ZST, no reason to skip them!
459                     // `!` is a ZST and we want to validate it.
460                     // Normalize before handing `place` to tracking because that will
461                     // check for duplicates.
462                     let place = if size.bytes() > 0 {
463                         self.ecx.force_mplace_ptr(place).expect("we already bounds-checked")
464                     } else {
465                         place
466                     };
467                     let path = &self.path;
468                     ref_tracking.track(place, || {
469                         // We need to clone the path anyway, make sure it gets created
470                         // with enough space for the additional `Deref`.
471                         let mut new_path = Vec::with_capacity(path.len() + 1);
472                         new_path.clone_from(path);
473                         new_path.push(PathElem::Deref);
474                         new_path
475                     });
476                 }
477             }
478             ty::FnPtr(_sig) => {
479                 let value = value.to_scalar_or_undef();
480                 let _fn = try_validation!(
481                     value.not_undef().and_then(|ptr| self.ecx.memory.get_fn(ptr)),
482                     value,
483                     self.path,
484                     "a function pointer"
485                 );
486                 // FIXME: Check if the signature matches
487             }
488             // This should be all the primitive types
489             _ => bug!("Unexpected primitive type {}", value.layout.ty),
490         }
491         Ok(())
492     }
493
494     fn visit_uninhabited(&mut self) -> InterpResult<'tcx> {
495         throw_validation_failure!("a value of an uninhabited type", self.path)
496     }
497
498     fn visit_scalar(
499         &mut self,
500         op: OpTy<'tcx, M::PointerTag>,
501         layout: &layout::Scalar,
502     ) -> InterpResult<'tcx> {
503         let value = self.ecx.read_scalar(op)?;
504         // Determine the allowed range
505         let (lo, hi) = layout.valid_range.clone().into_inner();
506         // `max_hi` is as big as the size fits
507         let max_hi = u128::max_value() >> (128 - op.layout.size.bits());
508         assert!(hi <= max_hi);
509         // We could also write `(hi + 1) % (max_hi + 1) == lo` but `max_hi + 1` overflows for `u128`
510         if (lo == 0 && hi == max_hi) || (hi + 1 == lo) {
511             // Nothing to check
512             return Ok(());
513         }
514         // At least one value is excluded. Get the bits.
515         let value = try_validation!(
516             value.not_undef(),
517             value,
518             self.path,
519             format_args!("something {}", wrapping_range_format(&layout.valid_range, max_hi),)
520         );
521         let bits = match value.to_bits_or_ptr(op.layout.size, self.ecx) {
522             Err(ptr) => {
523                 if lo == 1 && hi == max_hi {
524                     // Only NULL is the niche.  So make sure the ptr is NOT NULL.
525                     if self.ecx.memory.ptr_may_be_null(ptr) {
526                         throw_validation_failure!(
527                             "a potentially NULL pointer",
528                             self.path,
529                             format_args!(
530                                 "something that cannot possibly fail to be {}",
531                                 wrapping_range_format(&layout.valid_range, max_hi)
532                             )
533                         )
534                     }
535                     return Ok(());
536                 } else {
537                     // Conservatively, we reject, because the pointer *could* have a bad
538                     // value.
539                     throw_validation_failure!(
540                         "a pointer",
541                         self.path,
542                         format_args!(
543                             "something that cannot possibly fail to be {}",
544                             wrapping_range_format(&layout.valid_range, max_hi)
545                         )
546                     )
547                 }
548             }
549             Ok(data) => data,
550         };
551         // Now compare. This is slightly subtle because this is a special "wrap-around" range.
552         if wrapping_range_contains(&layout.valid_range, bits) {
553             Ok(())
554         } else {
555             throw_validation_failure!(
556                 bits,
557                 self.path,
558                 format_args!("something {}", wrapping_range_format(&layout.valid_range, max_hi))
559             )
560         }
561     }
562
563     fn visit_aggregate(
564         &mut self,
565         op: OpTy<'tcx, M::PointerTag>,
566         fields: impl Iterator<Item = InterpResult<'tcx, Self::V>>,
567     ) -> InterpResult<'tcx> {
568         match op.layout.ty.kind {
569             ty::Str => {
570                 let mplace = op.assert_mem_place(self.ecx); // strings are never immediate
571                 try_validation!(
572                     self.ecx.read_str(mplace),
573                     "uninitialized or non-UTF-8 data in str",
574                     self.path
575                 );
576             }
577             ty::Array(tys, ..) | ty::Slice(tys)
578                 if {
579                     // This optimization applies for types that can hold arbitrary bytes (such as
580                     // integer and floating point types) or for structs or tuples with no fields.
581                     // FIXME(wesleywiser) This logic could be extended further to arbitrary structs
582                     // or tuples made up of integer/floating point types or inhabited ZSTs with no
583                     // padding.
584                     match tys.kind {
585                         ty::Int(..) | ty::Uint(..) | ty::Float(..) => true,
586                         ty::Tuple(tys) if tys.len() == 0 => true,
587                         ty::Adt(adt_def, _)
588                             if adt_def.is_struct() && adt_def.all_fields().next().is_none() =>
589                         {
590                             true
591                         }
592                         _ => false,
593                     }
594                 } =>
595             {
596                 // Optimized handling for arrays of integer/float type.
597
598                 // Arrays cannot be immediate, slices are never immediate.
599                 let mplace = op.assert_mem_place(self.ecx);
600                 // This is the length of the array/slice.
601                 let len = mplace.len(self.ecx)?;
602                 // Zero length slices have nothing to be checked.
603                 if len == 0 {
604                     return Ok(());
605                 }
606                 // This is the element type size.
607                 let layout = self.ecx.layout_of(tys)?;
608                 // Empty tuples and fieldless structs (the only ZSTs that allow reaching this code)
609                 // have no data to be checked.
610                 if layout.is_zst() {
611                     return Ok(());
612                 }
613                 // This is the size in bytes of the whole array.
614                 let size = layout.size * len;
615                 // Size is not 0, get a pointer.
616                 let ptr = self.ecx.force_ptr(mplace.ptr)?;
617
618                 // Optimization: we just check the entire range at once.
619                 // NOTE: Keep this in sync with the handling of integer and float
620                 // types above, in `visit_primitive`.
621                 // In run-time mode, we accept pointers in here.  This is actually more
622                 // permissive than a per-element check would be, e.g., we accept
623                 // an &[u8] that contains a pointer even though bytewise checking would
624                 // reject it.  However, that's good: We don't inherently want
625                 // to reject those pointers, we just do not have the machinery to
626                 // talk about parts of a pointer.
627                 // We also accept undef, for consistency with the slow path.
628                 match self.ecx.memory.get_raw(ptr.alloc_id)?.check_bytes(
629                     self.ecx,
630                     ptr,
631                     size,
632                     /*allow_ptr_and_undef*/ self.ref_tracking_for_consts.is_none(),
633                 ) {
634                     // In the happy case, we needn't check anything else.
635                     Ok(()) => {}
636                     // Some error happened, try to provide a more detailed description.
637                     Err(err) => {
638                         // For some errors we might be able to provide extra information
639                         match err.kind {
640                             err_unsup!(ReadUndefBytes(offset)) => {
641                                 // Some byte was undefined, determine which
642                                 // element that byte belongs to so we can
643                                 // provide an index.
644                                 let i = (offset.bytes() / layout.size.bytes()) as usize;
645                                 self.path.push(PathElem::ArrayElem(i));
646
647                                 throw_validation_failure!("undefined bytes", self.path)
648                             }
649                             // Other errors shouldn't be possible
650                             _ => return Err(err),
651                         }
652                     }
653                 }
654             }
655             _ => {
656                 self.walk_aggregate(op, fields)? // default handler
657             }
658         }
659         Ok(())
660     }
661 }
662
663 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
664     /// This function checks the data at `op`. `op` is assumed to cover valid memory if it
665     /// is an indirect operand.
666     /// It will error if the bits at the destination do not match the ones described by the layout.
667     ///
668     /// `ref_tracking_for_consts` can be `None` to avoid recursive checking below references.
669     /// This also toggles between "run-time" (no recursion) and "compile-time" (with recursion)
670     /// validation (e.g., pointer values are fine in integers at runtime) and various other const
671     /// specific validation checks.
672     pub fn validate_operand(
673         &self,
674         op: OpTy<'tcx, M::PointerTag>,
675         path: Vec<PathElem>,
676         ref_tracking_for_consts: Option<
677             &mut RefTracking<MPlaceTy<'tcx, M::PointerTag>, Vec<PathElem>>,
678         >,
679     ) -> InterpResult<'tcx> {
680         trace!("validate_operand: {:?}, {:?}", *op, op.layout.ty);
681
682         // Construct a visitor
683         let mut visitor = ValidityVisitor { path, ref_tracking_for_consts, ecx: self };
684
685         // Try to cast to ptr *once* instead of all the time.
686         let op = self.force_op_ptr(op).unwrap_or(op);
687
688         // Run it
689         visitor.visit_value(op)
690     }
691 }