]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/validity.rs
more English grammar
[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                     layout::Variants::Multiple { discr_index, .. } => {
211                         assert_eq!(discr_index, field);
212                         PathElem::Tag
213                     }
214                 }
215             }
216
217             // other ADTs
218             ty::Adt(def, _) => PathElem::Field(def.non_enum_variant().fields[field].ident.name),
219
220             // arrays/slices
221             ty::Array(..) | ty::Slice(..) => PathElem::ArrayElem(field),
222
223             // dyn traits
224             ty::Dynamic(..) => PathElem::DynDowncast,
225
226             // nothing else has an aggregate layout
227             _ => bug!("aggregate_field_path_elem: got non-aggregate type {:?}", layout.ty),
228         }
229     }
230
231     fn visit_elem(
232         &mut self,
233         new_op: OpTy<'tcx, M::PointerTag>,
234         elem: PathElem,
235     ) -> InterpResult<'tcx> {
236         // Remember the old state
237         let path_len = self.path.len();
238         // Perform operation
239         self.path.push(elem);
240         self.visit_value(new_op)?;
241         // Undo changes
242         self.path.truncate(path_len);
243         Ok(())
244     }
245
246     fn check_wide_ptr_meta(
247         &mut self,
248         meta: MemPlaceMeta<M::PointerTag>,
249         pointee: TyLayout<'tcx>,
250     ) -> InterpResult<'tcx> {
251         let tail = self.ecx.tcx.struct_tail_erasing_lifetimes(pointee.ty, self.ecx.param_env);
252         match tail.kind {
253             ty::Dynamic(..) => {
254                 let vtable = meta.unwrap_meta();
255                 try_validation!(
256                     self.ecx.memory.check_ptr_access(
257                         vtable,
258                         3 * self.ecx.tcx.data_layout.pointer_size, // drop, size, align
259                         self.ecx.tcx.data_layout.pointer_align.abi,
260                     ),
261                     "dangling or unaligned vtable pointer in wide pointer or too small vtable",
262                     self.path
263                 );
264                 try_validation!(
265                     self.ecx.read_drop_type_from_vtable(vtable),
266                     "invalid drop fn in vtable",
267                     self.path
268                 );
269                 try_validation!(
270                     self.ecx.read_size_and_align_from_vtable(vtable),
271                     "invalid size or align in vtable",
272                     self.path
273                 );
274                 // FIXME: More checks for the vtable.
275             }
276             ty::Slice(..) | ty::Str => {
277                 let _len = try_validation!(
278                     meta.unwrap_meta().to_machine_usize(self.ecx),
279                     "non-integer slice length in wide pointer",
280                     self.path
281                 );
282                 // We do not check that `len * elem_size <= isize::MAX`:
283                 // that is only required for references, and there it falls out of the
284                 // "dereferenceable" check performed by Stacked Borrows.
285             }
286             ty::Foreign(..) => {
287                 // Unsized, but not wide.
288             }
289             _ => bug!("Unexpected unsized type tail: {:?}", tail),
290         }
291
292         Ok(())
293     }
294
295     fn visit_primitive(&mut self, value: OpTy<'tcx, M::PointerTag>) -> InterpResult<'tcx> {
296         let value = self.ecx.read_immediate(value)?;
297         // Go over all the primitive types
298         let ty = value.layout.ty;
299         match ty.kind {
300             ty::Bool => {
301                 let value = value.to_scalar_or_undef();
302                 try_validation!(value.to_bool(), value, self.path, "a boolean");
303             }
304             ty::Char => {
305                 let value = value.to_scalar_or_undef();
306                 try_validation!(value.to_char(), value, self.path, "a valid unicode codepoint");
307             }
308             ty::Float(_) | ty::Int(_) | ty::Uint(_) => {
309                 // NOTE: Keep this in sync with the array optimization for int/float
310                 // types below!
311                 let size = value.layout.size;
312                 let value = value.to_scalar_or_undef();
313                 if self.ref_tracking_for_consts.is_some() {
314                     // Integers/floats in CTFE: Must be scalar bits, pointers are dangerous
315                     try_validation!(
316                         value.to_bits(size),
317                         value,
318                         self.path,
319                         "initialized plain (non-pointer) bytes"
320                     );
321                 } else {
322                     // At run-time, for now, we accept *anything* for these types, including
323                     // undef. We should fix that, but let's start low.
324                 }
325             }
326             ty::RawPtr(..) => {
327                 // We are conservative with undef for integers, but try to
328                 // actually enforce our current rules for raw pointers.
329                 let place =
330                     try_validation!(self.ecx.ref_to_mplace(value), "undefined pointer", self.path);
331                 if place.layout.is_unsized() {
332                     self.check_wide_ptr_meta(place.meta, place.layout)?;
333                 }
334             }
335             _ if ty.is_box() || ty.is_region_ptr() => {
336                 // Handle wide pointers.
337                 // Check metadata early, for better diagnostics
338                 let place =
339                     try_validation!(self.ecx.ref_to_mplace(value), "undefined pointer", self.path);
340                 if place.layout.is_unsized() {
341                     self.check_wide_ptr_meta(place.meta, place.layout)?;
342                 }
343                 // Make sure this is dereferenceable and all.
344                 let (size, align) = self
345                     .ecx
346                     .size_and_align_of(place.meta, place.layout)?
347                     // for the purpose of validity, consider foreign types to have
348                     // alignment and size determined by the layout (size will be 0,
349                     // alignment should take attributes into account).
350                     .unwrap_or_else(|| (place.layout.size, place.layout.align.abi));
351                 let ptr: Option<_> = match self.ecx.memory.check_ptr_access_align(
352                     place.ptr,
353                     size,
354                     Some(align),
355                     CheckInAllocMsg::InboundsTest,
356                 ) {
357                     Ok(ptr) => ptr,
358                     Err(err) => {
359                         info!(
360                             "{:?} did not pass access check for size {:?}, align {:?}",
361                             place.ptr, size, align
362                         );
363                         match err.kind {
364                             err_unsup!(InvalidNullPointerUsage) => {
365                                 throw_validation_failure!("a NULL reference", self.path)
366                             }
367                             err_unsup!(AlignmentCheckFailed { required, has }) => {
368                                 throw_validation_failure!(
369                                     format_args!(
370                                         "an unaligned reference \
371                                          (required {} byte alignment but found {})",
372                                         required.bytes(),
373                                         has.bytes()
374                                     ),
375                                     self.path
376                                 )
377                             }
378                             err_unsup!(ReadBytesAsPointer) => throw_validation_failure!(
379                                 "a dangling reference (created from integer)",
380                                 self.path
381                             ),
382                             _ => throw_validation_failure!(
383                                 "a dangling reference (not entirely in bounds)",
384                                 self.path
385                             ),
386                         }
387                     }
388                 };
389                 // Recursive checking
390                 if let Some(ref mut ref_tracking) = self.ref_tracking_for_consts {
391                     if let Some(ptr) = ptr {
392                         // not a ZST
393                         // Skip validation entirely for some external statics
394                         let alloc_kind = self.ecx.tcx.alloc_map.lock().get(ptr.alloc_id);
395                         if let Some(GlobalAlloc::Static(did)) = alloc_kind {
396                             // `extern static` cannot be validated as they have no body.
397                             // FIXME: Statics from other crates are also skipped.
398                             // They might be checked at a different type, but for now we
399                             // want to avoid recursing too deeply.  This is not sound!
400                             if !did.is_local() || self.ecx.tcx.is_foreign_item(did) {
401                                 return Ok(());
402                             }
403                         }
404                     }
405                     // Proceed recursively even for ZST, no reason to skip them!
406                     // `!` is a ZST and we want to validate it.
407                     // Normalize before handing `place` to tracking because that will
408                     // check for duplicates.
409                     let place = if size.bytes() > 0 {
410                         self.ecx.force_mplace_ptr(place).expect("we already bounds-checked")
411                     } else {
412                         place
413                     };
414                     let path = &self.path;
415                     ref_tracking.track(place, || {
416                         // We need to clone the path anyway, make sure it gets created
417                         // with enough space for the additional `Deref`.
418                         let mut new_path = Vec::with_capacity(path.len() + 1);
419                         new_path.clone_from(path);
420                         new_path.push(PathElem::Deref);
421                         new_path
422                     });
423                 }
424             }
425             ty::FnPtr(_sig) => {
426                 let value = value.to_scalar_or_undef();
427                 let _fn = try_validation!(
428                     value.not_undef().and_then(|ptr| self.ecx.memory.get_fn(ptr)),
429                     value,
430                     self.path,
431                     "a function pointer"
432                 );
433                 // FIXME: Check if the signature matches
434             }
435             // This should be all the (inhabited) primitive types
436             _ => bug!("Unexpected primitive type {}", value.layout.ty),
437         }
438         Ok(())
439     }
440
441     fn visit_scalar(
442         &mut self,
443         op: OpTy<'tcx, M::PointerTag>,
444         layout: &layout::Scalar,
445     ) -> InterpResult<'tcx> {
446         let value = self.ecx.read_scalar(op)?;
447         // Determine the allowed range
448         let (lo, hi) = layout.valid_range.clone().into_inner();
449         // `max_hi` is as big as the size fits
450         let max_hi = u128::max_value() >> (128 - op.layout.size.bits());
451         assert!(hi <= max_hi);
452         // We could also write `(hi + 1) % (max_hi + 1) == lo` but `max_hi + 1` overflows for `u128`
453         if (lo == 0 && hi == max_hi) || (hi + 1 == lo) {
454             // Nothing to check
455             return Ok(());
456         }
457         // At least one value is excluded. Get the bits.
458         let value = try_validation!(
459             value.not_undef(),
460             value,
461             self.path,
462             format_args!("something {}", wrapping_range_format(&layout.valid_range, max_hi),)
463         );
464         let bits = match value.to_bits_or_ptr(op.layout.size, self.ecx) {
465             Err(ptr) => {
466                 if lo == 1 && hi == max_hi {
467                     // Only NULL is the niche.  So make sure the ptr is NOT NULL.
468                     if self.ecx.memory.ptr_may_be_null(ptr) {
469                         throw_validation_failure!(
470                             "a potentially NULL pointer",
471                             self.path,
472                             format_args!(
473                                 "something that cannot possibly fail to be {}",
474                                 wrapping_range_format(&layout.valid_range, max_hi)
475                             )
476                         )
477                     }
478                     return Ok(());
479                 } else {
480                     // Conservatively, we reject, because the pointer *could* have a bad
481                     // value.
482                     throw_validation_failure!(
483                         "a pointer",
484                         self.path,
485                         format_args!(
486                             "something that cannot possibly fail to be {}",
487                             wrapping_range_format(&layout.valid_range, max_hi)
488                         )
489                     )
490                 }
491             }
492             Ok(data) => data,
493         };
494         // Now compare. This is slightly subtle because this is a special "wrap-around" range.
495         if wrapping_range_contains(&layout.valid_range, bits) {
496             Ok(())
497         } else {
498             throw_validation_failure!(
499                 bits,
500                 self.path,
501                 format_args!("something {}", wrapping_range_format(&layout.valid_range, max_hi))
502             )
503         }
504     }
505 }
506
507 impl<'rt, 'mir, 'tcx, M: Machine<'mir, 'tcx>> ValueVisitor<'mir, 'tcx, M>
508     for ValidityVisitor<'rt, 'mir, 'tcx, M>
509 {
510     type V = OpTy<'tcx, M::PointerTag>;
511
512     #[inline(always)]
513     fn ecx(&self) -> &InterpCx<'mir, 'tcx, M> {
514         &self.ecx
515     }
516
517     #[inline]
518     fn visit_field(
519         &mut self,
520         old_op: OpTy<'tcx, M::PointerTag>,
521         field: usize,
522         new_op: OpTy<'tcx, M::PointerTag>,
523     ) -> InterpResult<'tcx> {
524         let elem = self.aggregate_field_path_elem(old_op.layout, field);
525         self.visit_elem(new_op, elem)
526     }
527
528     #[inline]
529     fn visit_variant(
530         &mut self,
531         old_op: OpTy<'tcx, M::PointerTag>,
532         variant_id: VariantIdx,
533         new_op: OpTy<'tcx, M::PointerTag>,
534     ) -> InterpResult<'tcx> {
535         let name = match old_op.layout.ty.kind {
536             ty::Adt(adt, _) => PathElem::Variant(adt.variants[variant_id].ident.name),
537             // Generators also have variants
538             ty::Generator(..) => PathElem::GeneratorState(variant_id),
539             _ => bug!("Unexpected type with variant: {:?}", old_op.layout.ty),
540         };
541         self.visit_elem(new_op, name)
542     }
543
544     #[inline(always)]
545     fn visit_union(&mut self, _v: Self::V, fields: usize) -> InterpResult<'tcx> {
546         // Empty unions are not accepted by rustc. That's great, it means we can
547         // use that as a signal for detecting primitives.  Make sure
548         // we did not miss any primitive.
549         assert!(fields > 0);
550         Ok(())
551     }
552
553     #[inline]
554     fn visit_value(&mut self, op: OpTy<'tcx, M::PointerTag>) -> InterpResult<'tcx> {
555         trace!("visit_value: {:?}, {:?}", *op, op.layout);
556
557         if op.layout.abi.is_uninhabited() {
558             // Uninhabited types do not have sensible layout, stop right here.
559             throw_validation_failure!(
560                 format_args!("a value of uninhabited type {:?}", op.layout.ty),
561                 self.path
562             )
563         }
564
565         // Check primitive types.  We do this after checking for uninhabited types,
566         // to exclude fieldless enums (that also appear as fieldless unions here).
567         // Primitives can have varying layout, so we check them separately and before aggregate
568         // handling.
569         // It is CRITICAL that we get this check right, or we might be validating the wrong thing!
570         let primitive = match op.layout.fields {
571             // Primitives appear as Union with 0 fields - except for Boxes and fat pointers.
572             // (Fieldless enums also appear here, but they are uninhabited and thus handled above.)
573             layout::FieldPlacement::Union(0) => true,
574             _ => op.layout.ty.builtin_deref(true).is_some(),
575         };
576         if primitive {
577             // No need to recurse further or check scalar layout, this is a leaf type.
578             return self.visit_primitive(op);
579         }
580
581         // Recursively walk the type. Translate some possible errors to something nicer.
582         match self.walk_value(op) {
583             Ok(()) => {}
584             Err(err) => match err.kind {
585                 err_ub!(InvalidDiscriminant(val)) => {
586                     throw_validation_failure!(val, self.path, "a valid enum discriminant")
587                 }
588                 err_unsup!(ReadPointerAsBytes) => {
589                     throw_validation_failure!("a pointer", self.path, "plain (non-pointer) bytes")
590                 }
591                 _ => return Err(err),
592             },
593         }
594
595         // *After* all of this, check the ABI.  We need to check the ABI to handle
596         // types like `NonNull` where the `Scalar` info is more restrictive than what
597         // the fields say. But in most cases, this will just propagate what the fields say,
598         // and then we want the error to point at the field -- so, first recurse,
599         // then check ABI.
600         //
601         // FIXME: We could avoid some redundant checks here. For newtypes wrapping
602         // scalars, we do the same check on every "level" (e.g., first we check
603         // MyNewtype and then the scalar in there).
604         match op.layout.abi {
605             layout::Abi::Uninhabited => unreachable!(), // checked above
606             layout::Abi::Scalar(ref layout) => {
607                 self.visit_scalar(op, layout)?;
608             }
609             // FIXME: Should we do something for ScalarPair? Vector?
610             _ => {}
611         }
612
613         Ok(())
614     }
615
616     fn visit_aggregate(
617         &mut self,
618         op: OpTy<'tcx, M::PointerTag>,
619         fields: impl Iterator<Item = InterpResult<'tcx, Self::V>>,
620     ) -> InterpResult<'tcx> {
621         match op.layout.ty.kind {
622             ty::Str => {
623                 let mplace = op.assert_mem_place(self.ecx); // strings are never immediate
624                 try_validation!(
625                     self.ecx.read_str(mplace),
626                     "uninitialized or non-UTF-8 data in str",
627                     self.path
628                 );
629             }
630             ty::Array(tys, ..) | ty::Slice(tys)
631                 if {
632                     // This optimization applies for types that can hold arbitrary bytes (such as
633                     // integer and floating point types) or for structs or tuples with no fields.
634                     // FIXME(wesleywiser) This logic could be extended further to arbitrary structs
635                     // or tuples made up of integer/floating point types or inhabited ZSTs with no
636                     // padding.
637                     match tys.kind {
638                         ty::Int(..) | ty::Uint(..) | ty::Float(..) => true,
639                         _ => false,
640                     }
641                 } =>
642             {
643                 // Optimized handling for arrays of integer/float type.
644
645                 // Arrays cannot be immediate, slices are never immediate.
646                 let mplace = op.assert_mem_place(self.ecx);
647                 // This is the length of the array/slice.
648                 let len = mplace.len(self.ecx)?;
649                 // Zero length slices have nothing to be checked.
650                 if len == 0 {
651                     return Ok(());
652                 }
653                 // This is the element type size.
654                 let layout = self.ecx.layout_of(tys)?;
655                 // This is the size in bytes of the whole array.
656                 let size = layout.size * len;
657                 // Size is not 0, get a pointer.
658                 let ptr = self.ecx.force_ptr(mplace.ptr)?;
659
660                 // Optimization: we just check the entire range at once.
661                 // NOTE: Keep this in sync with the handling of integer and float
662                 // types above, in `visit_primitive`.
663                 // In run-time mode, we accept pointers in here.  This is actually more
664                 // permissive than a per-element check would be, e.g., we accept
665                 // an &[u8] that contains a pointer even though bytewise checking would
666                 // reject it.  However, that's good: We don't inherently want
667                 // to reject those pointers, we just do not have the machinery to
668                 // talk about parts of a pointer.
669                 // We also accept undef, for consistency with the slow path.
670                 match self.ecx.memory.get_raw(ptr.alloc_id)?.check_bytes(
671                     self.ecx,
672                     ptr,
673                     size,
674                     /*allow_ptr_and_undef*/ self.ref_tracking_for_consts.is_none(),
675                 ) {
676                     // In the happy case, we needn't check anything else.
677                     Ok(()) => {}
678                     // Some error happened, try to provide a more detailed description.
679                     Err(err) => {
680                         // For some errors we might be able to provide extra information
681                         match err.kind {
682                             err_unsup!(ReadUndefBytes(offset)) => {
683                                 // Some byte was undefined, determine which
684                                 // element that byte belongs to so we can
685                                 // provide an index.
686                                 let i = (offset.bytes() / layout.size.bytes()) as usize;
687                                 self.path.push(PathElem::ArrayElem(i));
688
689                                 throw_validation_failure!("undefined bytes", self.path)
690                             }
691                             // Other errors shouldn't be possible
692                             _ => return Err(err),
693                         }
694                     }
695                 }
696             }
697             // Fast path for arrays and slices of ZSTs. We only need to check a single ZST element
698             // of an array and not all of them, because there's only a single value of a specific
699             // ZST type, so either validation fails for all elements or none.
700             ty::Array(tys, ..) | ty::Slice(tys) if self.ecx.layout_of(tys)?.is_zst() => {
701                 // Validate just the first element
702                 self.walk_aggregate(op, fields.take(1))?
703             }
704             _ => {
705                 self.walk_aggregate(op, fields)? // default handler
706             }
707         }
708         Ok(())
709     }
710 }
711
712 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
713     /// This function checks the data at `op`. `op` is assumed to cover valid memory if it
714     /// is an indirect operand.
715     /// It will error if the bits at the destination do not match the ones described by the layout.
716     ///
717     /// `ref_tracking_for_consts` can be `None` to avoid recursive checking below references.
718     /// This also toggles between "run-time" (no recursion) and "compile-time" (with recursion)
719     /// validation (e.g., pointer values are fine in integers at runtime) and various other const
720     /// specific validation checks.
721     pub fn validate_operand(
722         &self,
723         op: OpTy<'tcx, M::PointerTag>,
724         path: Vec<PathElem>,
725         ref_tracking_for_consts: Option<
726             &mut RefTracking<MPlaceTy<'tcx, M::PointerTag>, Vec<PathElem>>,
727         >,
728     ) -> InterpResult<'tcx> {
729         trace!("validate_operand: {:?}, {:?}", *op, op.layout.ty);
730
731         // Construct a visitor
732         let mut visitor = ValidityVisitor { path, ref_tracking_for_consts, ecx: self };
733
734         // Try to cast to ptr *once* instead of all the time.
735         let op = self.force_op_ptr(op).unwrap_or(op);
736
737         // Run it
738         visitor.visit_value(op)
739     }
740 }