]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/validity.rs
Throw validation failure for InvalidUndefBytes.
[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::convert::TryFrom;
8 use std::fmt::Write;
9 use std::num::NonZeroUsize;
10 use std::ops::RangeInclusive;
11
12 use rustc_data_structures::fx::FxHashSet;
13 use rustc_hir as hir;
14 use rustc_middle::mir::interpret::{InterpError, InterpErrorInfo};
15 use rustc_middle::ty;
16 use rustc_middle::ty::layout::TyAndLayout;
17 use rustc_span::symbol::{sym, Symbol};
18 use rustc_target::abi::{Abi, LayoutOf, Scalar, VariantIdx, Variants};
19
20 use std::hash::Hash;
21
22 use super::{
23     CheckInAllocMsg, GlobalAlloc, InterpCx, InterpResult, MPlaceTy, Machine, MemPlaceMeta, OpTy,
24     ValueVisitor,
25 };
26
27 macro_rules! throw_validation_failure {
28     ($what:expr, $where:expr $(, $details:expr )?) => {{
29         let mut msg = format!("encountered {}", $what);
30         let where_ = &$where;
31         if !where_.is_empty() {
32             msg.push_str(" at ");
33             write_path(&mut msg, where_);
34         }
35         $( write!(&mut msg, ", but expected {}", $details).unwrap(); )?
36         throw_ub!(ValidationFailure(msg))
37     }};
38 }
39
40 /// Returns a validation failure for any Err value of $e.
41 macro_rules! try_validation {
42     ($e:expr, $what:expr, $where:expr $(, $details:expr )?) => {{
43         try_validation_pat!($e, _, $what, $where $(, $details )?)
44     }};
45 }
46 /// Like try_validation, but will throw a validation error if any of the patterns in $p are
47 /// matched. Other errors are passed back to the caller, unchanged. This lets you use the patterns
48 /// as a kind of validation blacklist:
49 ///
50 /// ```rust
51 /// let v = try_validation_pat(some_fn(), Foo | Bar | Baz, "some failure", "some place");
52 /// // Failures that match $p are thrown up as validation errors, but other errors are passed back
53 /// // unchanged.
54 /// ```
55 macro_rules! try_validation_pat {
56     ($e:expr, $( $p:pat )|*, $what:expr, $where:expr $(, $details:expr )?) => {{
57         match $e {
58             Ok(x) => x,
59             // We catch the error and turn it into a validation failure. We are okay with
60             // allocation here as this can only slow down builds that fail anyway.
61             $( Err($p) )|* if true => throw_validation_failure!($what, $where $(, $details)?),
62             Err(e) =>  Err::<!, _>(e)?,
63         }
64     }};
65 }
66
67 /// We want to show a nice path to the invalid field for diagnostics,
68 /// but avoid string operations in the happy case where no error happens.
69 /// So we track a `Vec<PathElem>` where `PathElem` contains all the data we
70 /// need to later print something for the user.
71 #[derive(Copy, Clone, Debug)]
72 pub enum PathElem {
73     Field(Symbol),
74     Variant(Symbol),
75     GeneratorState(VariantIdx),
76     CapturedVar(Symbol),
77     ArrayElem(usize),
78     TupleElem(usize),
79     Deref,
80     EnumTag,
81     GeneratorTag,
82     DynDowncast,
83 }
84
85 /// State for tracking recursive validation of references
86 pub struct RefTracking<T, PATH = ()> {
87     pub seen: FxHashSet<T>,
88     pub todo: Vec<(T, PATH)>,
89 }
90
91 impl<T: Copy + Eq + Hash + std::fmt::Debug, PATH: Default> RefTracking<T, PATH> {
92     pub fn empty() -> Self {
93         RefTracking { seen: FxHashSet::default(), todo: vec![] }
94     }
95     pub fn new(op: T) -> Self {
96         let mut ref_tracking_for_consts =
97             RefTracking { seen: FxHashSet::default(), todo: vec![(op, PATH::default())] };
98         ref_tracking_for_consts.seen.insert(op);
99         ref_tracking_for_consts
100     }
101
102     pub fn track(&mut self, op: T, path: impl FnOnce() -> PATH) {
103         if self.seen.insert(op) {
104             trace!("Recursing below ptr {:#?}", op);
105             let path = path();
106             // Remember to come back to this later.
107             self.todo.push((op, path));
108         }
109     }
110 }
111
112 /// Format a path
113 fn write_path(out: &mut String, path: &Vec<PathElem>) {
114     use self::PathElem::*;
115
116     for elem in path.iter() {
117         match elem {
118             Field(name) => write!(out, ".{}", name),
119             EnumTag => write!(out, ".<enum-tag>"),
120             Variant(name) => write!(out, ".<enum-variant({})>", name),
121             GeneratorTag => write!(out, ".<generator-tag>"),
122             GeneratorState(idx) => write!(out, ".<generator-state({})>", idx.index()),
123             CapturedVar(name) => write!(out, ".<captured-var({})>", name),
124             TupleElem(idx) => write!(out, ".{}", idx),
125             ArrayElem(idx) => write!(out, "[{}]", idx),
126             // `.<deref>` does not match Rust syntax, but it is more readable for long paths -- and
127             // some of the other items here also are not Rust syntax.  Actually we can't
128             // even use the usual syntax because we are just showing the projections,
129             // not the root.
130             Deref => write!(out, ".<deref>"),
131             DynDowncast => write!(out, ".<dyn-downcast>"),
132         }
133         .unwrap()
134     }
135 }
136
137 // Test if a range that wraps at overflow contains `test`
138 fn wrapping_range_contains(r: &RangeInclusive<u128>, test: u128) -> bool {
139     let (lo, hi) = r.clone().into_inner();
140     if lo > hi {
141         // Wrapped
142         (..=hi).contains(&test) || (lo..).contains(&test)
143     } else {
144         // Normal
145         r.contains(&test)
146     }
147 }
148
149 // Formats such that a sentence like "expected something {}" to mean
150 // "expected something <in the given range>" makes sense.
151 fn wrapping_range_format(r: &RangeInclusive<u128>, max_hi: u128) -> String {
152     let (lo, hi) = r.clone().into_inner();
153     assert!(hi <= max_hi);
154     if lo > hi {
155         format!("less or equal to {}, or greater or equal to {}", hi, lo)
156     } else if lo == hi {
157         format!("equal to {}", lo)
158     } else if lo == 0 {
159         assert!(hi < max_hi, "should not be printing if the range covers everything");
160         format!("less or equal to {}", hi)
161     } else if hi == max_hi {
162         assert!(lo > 0, "should not be printing if the range covers everything");
163         format!("greater or equal to {}", lo)
164     } else {
165         format!("in the range {:?}", r)
166     }
167 }
168
169 struct ValidityVisitor<'rt, 'mir, 'tcx, M: Machine<'mir, 'tcx>> {
170     /// The `path` may be pushed to, but the part that is present when a function
171     /// starts must not be changed!  `visit_fields` and `visit_array` rely on
172     /// this stack discipline.
173     path: Vec<PathElem>,
174     ref_tracking_for_consts:
175         Option<&'rt mut RefTracking<MPlaceTy<'tcx, M::PointerTag>, Vec<PathElem>>>,
176     may_ref_to_static: bool,
177     ecx: &'rt InterpCx<'mir, 'tcx, M>,
178 }
179
180 impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValidityVisitor<'rt, 'mir, 'tcx, M> {
181     fn aggregate_field_path_elem(&mut self, layout: TyAndLayout<'tcx>, field: usize) -> PathElem {
182         // First, check if we are projecting to a variant.
183         match layout.variants {
184             Variants::Multiple { discr_index, .. } => {
185                 if discr_index == field {
186                     return match layout.ty.kind {
187                         ty::Adt(def, ..) if def.is_enum() => PathElem::EnumTag,
188                         ty::Generator(..) => PathElem::GeneratorTag,
189                         _ => bug!("non-variant type {:?}", layout.ty),
190                     };
191                 }
192             }
193             Variants::Single { .. } => {}
194         }
195
196         // Now we know we are projecting to a field, so figure out which one.
197         match layout.ty.kind {
198             // generators and closures.
199             ty::Closure(def_id, _) | ty::Generator(def_id, _, _) => {
200                 let mut name = None;
201                 if let Some(def_id) = def_id.as_local() {
202                     let tables = self.ecx.tcx.typeck_tables_of(def_id);
203                     if let Some(upvars) = tables.upvar_list.get(&def_id.to_def_id()) {
204                         // Sometimes the index is beyond the number of upvars (seen
205                         // for a generator).
206                         if let Some((&var_hir_id, _)) = upvars.get_index(field) {
207                             let node = self.ecx.tcx.hir().get(var_hir_id);
208                             if let hir::Node::Binding(pat) = node {
209                                 if let hir::PatKind::Binding(_, _, ident, _) = pat.kind {
210                                     name = Some(ident.name);
211                                 }
212                             }
213                         }
214                     }
215                 }
216
217                 PathElem::CapturedVar(name.unwrap_or_else(|| {
218                     // Fall back to showing the field index.
219                     sym::integer(field)
220                 }))
221             }
222
223             // tuples
224             ty::Tuple(_) => PathElem::TupleElem(field),
225
226             // enums
227             ty::Adt(def, ..) if def.is_enum() => {
228                 // we might be projecting *to* a variant, or to a field *in* a variant.
229                 match layout.variants {
230                     Variants::Single { index } => {
231                         // Inside a variant
232                         PathElem::Field(def.variants[index].fields[field].ident.name)
233                     }
234                     Variants::Multiple { .. } => bug!("we handled variants above"),
235                 }
236             }
237
238             // other ADTs
239             ty::Adt(def, _) => PathElem::Field(def.non_enum_variant().fields[field].ident.name),
240
241             // arrays/slices
242             ty::Array(..) | ty::Slice(..) => PathElem::ArrayElem(field),
243
244             // dyn traits
245             ty::Dynamic(..) => PathElem::DynDowncast,
246
247             // nothing else has an aggregate layout
248             _ => bug!("aggregate_field_path_elem: got non-aggregate type {:?}", layout.ty),
249         }
250     }
251
252     fn visit_elem(
253         &mut self,
254         new_op: OpTy<'tcx, M::PointerTag>,
255         elem: PathElem,
256     ) -> InterpResult<'tcx> {
257         // Remember the old state
258         let path_len = self.path.len();
259         // Perform operation
260         self.path.push(elem);
261         self.visit_value(new_op)?;
262         // Undo changes
263         self.path.truncate(path_len);
264         Ok(())
265     }
266
267     fn check_wide_ptr_meta(
268         &mut self,
269         meta: MemPlaceMeta<M::PointerTag>,
270         pointee: TyAndLayout<'tcx>,
271     ) -> InterpResult<'tcx> {
272         let tail = self.ecx.tcx.struct_tail_erasing_lifetimes(pointee.ty, self.ecx.param_env);
273         match tail.kind {
274             ty::Dynamic(..) => {
275                 let vtable = meta.unwrap_meta();
276                 try_validation!(
277                     self.ecx.memory.check_ptr_access(
278                         vtable,
279                         3 * self.ecx.tcx.data_layout.pointer_size, // drop, size, align
280                         self.ecx.tcx.data_layout.pointer_align.abi,
281                     ),
282                     "dangling or unaligned vtable pointer in wide pointer or too small vtable",
283                     self.path
284                 );
285                 try_validation!(
286                     self.ecx.read_drop_type_from_vtable(vtable),
287                     "invalid drop fn in vtable",
288                     self.path
289                 );
290                 try_validation!(
291                     self.ecx.read_size_and_align_from_vtable(vtable),
292                     "invalid size or align in vtable",
293                     self.path
294                 );
295                 // FIXME: More checks for the vtable.
296             }
297             ty::Slice(..) | ty::Str => {
298                 let _len = try_validation!(
299                     meta.unwrap_meta().to_machine_usize(self.ecx),
300                     "non-integer slice length in wide pointer",
301                     self.path
302                 );
303                 // We do not check that `len * elem_size <= isize::MAX`:
304                 // that is only required for references, and there it falls out of the
305                 // "dereferenceable" check performed by Stacked Borrows.
306             }
307             ty::Foreign(..) => {
308                 // Unsized, but not wide.
309             }
310             _ => bug!("Unexpected unsized type tail: {:?}", tail),
311         }
312
313         Ok(())
314     }
315
316     /// Check a reference or `Box`.
317     fn check_safe_pointer(
318         &mut self,
319         value: OpTy<'tcx, M::PointerTag>,
320         kind: &str,
321     ) -> InterpResult<'tcx> {
322         let value = self.ecx.read_immediate(value)?;
323         // Handle wide pointers.
324         // Check metadata early, for better diagnostics
325         let place = try_validation!(
326             self.ecx.ref_to_mplace(value),
327             format_args!("uninitialized {}", kind),
328             self.path
329         );
330         if place.layout.is_unsized() {
331             self.check_wide_ptr_meta(place.meta, place.layout)?;
332         }
333         // Make sure this is dereferenceable and all.
334         let size_and_align = match self.ecx.size_and_align_of(place.meta, place.layout) {
335             Ok(res) => res,
336             Err(err) => match err.kind {
337                 err_ub!(InvalidMeta(msg)) => throw_validation_failure!(
338                     format_args!("invalid {} metadata: {}", kind, msg),
339                     self.path
340                 ),
341                 _ => bug!("unexpected error during ptr size_and_align_of: {}", err),
342             },
343         };
344         let (size, align) = size_and_align
345             // for the purpose of validity, consider foreign types to have
346             // alignment and size determined by the layout (size will be 0,
347             // alignment should take attributes into account).
348             .unwrap_or_else(|| (place.layout.size, place.layout.align.abi));
349         let ptr: Option<_> = match self.ecx.memory.check_ptr_access_align(
350             place.ptr,
351             size,
352             Some(align),
353             CheckInAllocMsg::InboundsTest,
354         ) {
355             Ok(ptr) => ptr,
356             Err(err) => {
357                 info!(
358                     "{:?} did not pass access check for size {:?}, align {:?}",
359                     place.ptr, size, align
360                 );
361                 match err.kind {
362                     err_ub!(InvalidIntPointerUsage(0)) => {
363                         throw_validation_failure!(format_args!("a NULL {}", kind), self.path)
364                     }
365                     err_ub!(InvalidIntPointerUsage(i)) => throw_validation_failure!(
366                         format_args!("a {} to unallocated address {}", kind, i),
367                         self.path
368                     ),
369                     err_ub!(AlignmentCheckFailed { required, has }) => throw_validation_failure!(
370                         format_args!(
371                             "an unaligned {} (required {} byte alignment but found {})",
372                             kind,
373                             required.bytes(),
374                             has.bytes()
375                         ),
376                         self.path
377                     ),
378                     err_unsup!(ReadBytesAsPointer) => throw_validation_failure!(
379                         format_args!("a dangling {} (created from integer)", kind),
380                         self.path
381                     ),
382                     err_ub!(PointerOutOfBounds { .. }) => throw_validation_failure!(
383                         format_args!(
384                             "a dangling {} (going beyond the bounds of its allocation)",
385                             kind
386                         ),
387                         self.path
388                     ),
389                     // This cannot happen during const-eval (because interning already detects
390                     // dangling pointers), but it can happen in Miri.
391                     err_ub!(PointerUseAfterFree(_)) => throw_validation_failure!(
392                         format_args!("a dangling {} (use-after-free)", kind),
393                         self.path
394                     ),
395                     _ => bug!("Unexpected error during ptr inbounds test: {}", err),
396                 }
397             }
398         };
399         // Recursive checking
400         if let Some(ref mut ref_tracking) = self.ref_tracking_for_consts {
401             if let Some(ptr) = ptr {
402                 // not a ZST
403                 // Skip validation entirely for some external statics
404                 let alloc_kind = self.ecx.tcx.alloc_map.lock().get(ptr.alloc_id);
405                 if let Some(GlobalAlloc::Static(did)) = alloc_kind {
406                     // See const_eval::machine::MemoryExtra::can_access_statics for why
407                     // this check is so important.
408                     // This check is reachable when the const just referenced the static,
409                     // but never read it (so we never entered `before_access_global`).
410                     // We also need to do it here instead of going on to avoid running
411                     // into the `before_access_global` check during validation.
412                     if !self.may_ref_to_static && self.ecx.tcx.is_static(did) {
413                         throw_validation_failure!(
414                             format_args!("a {} pointing to a static variable", kind),
415                             self.path
416                         );
417                     }
418                     // `extern static` cannot be validated as they have no body.
419                     // FIXME: Statics from other crates are also skipped.
420                     // They might be checked at a different type, but for now we
421                     // want to avoid recursing too deeply.  We might miss const-invalid data,
422                     // but things are still sound otherwise (in particular re: consts
423                     // referring to statics).
424                     if !did.is_local() || self.ecx.tcx.is_foreign_item(did) {
425                         return Ok(());
426                     }
427                 }
428             }
429             // Proceed recursively even for ZST, no reason to skip them!
430             // `!` is a ZST and we want to validate it.
431             // Normalize before handing `place` to tracking because that will
432             // check for duplicates.
433             let place = if size.bytes() > 0 {
434                 self.ecx.force_mplace_ptr(place).expect("we already bounds-checked")
435             } else {
436                 place
437             };
438             let path = &self.path;
439             ref_tracking.track(place, || {
440                 // We need to clone the path anyway, make sure it gets created
441                 // with enough space for the additional `Deref`.
442                 let mut new_path = Vec::with_capacity(path.len() + 1);
443                 new_path.clone_from(path);
444                 new_path.push(PathElem::Deref);
445                 new_path
446             });
447         }
448         Ok(())
449     }
450
451     /// Check if this is a value of primitive type, and if yes check the validity of the value
452     /// at that type.  Return `true` if the type is indeed primitive.
453     fn try_visit_primitive(
454         &mut self,
455         value: OpTy<'tcx, M::PointerTag>,
456     ) -> InterpResult<'tcx, bool> {
457         // Go over all the primitive types
458         let ty = value.layout.ty;
459         match ty.kind {
460             ty::Bool => {
461                 let value = self.ecx.read_scalar(value)?;
462                 try_validation!(value.to_bool(), value, self.path, "a boolean");
463                 Ok(true)
464             }
465             ty::Char => {
466                 let value = self.ecx.read_scalar(value)?;
467                 try_validation!(value.to_char(), value, self.path, "a valid unicode codepoint");
468                 Ok(true)
469             }
470             ty::Float(_) | ty::Int(_) | ty::Uint(_) => {
471                 let value = self.ecx.read_scalar(value)?;
472                 // NOTE: Keep this in sync with the array optimization for int/float
473                 // types below!
474                 if self.ref_tracking_for_consts.is_some() {
475                     // Integers/floats in CTFE: Must be scalar bits, pointers are dangerous
476                     let is_bits = value.not_undef().map_or(false, |v| v.is_bits());
477                     if !is_bits {
478                         throw_validation_failure!(
479                             value,
480                             self.path,
481                             "initialized plain (non-pointer) bytes"
482                         )
483                     }
484                 } else {
485                     // At run-time, for now, we accept *anything* for these types, including
486                     // undef. We should fix that, but let's start low.
487                 }
488                 Ok(true)
489             }
490             ty::RawPtr(..) => {
491                 // We are conservative with undef for integers, but try to
492                 // actually enforce the strict rules for raw pointers (mostly because
493                 // that lets us re-use `ref_to_mplace`).
494                 let place = try_validation_pat!(
495                     self.ecx.ref_to_mplace(self.ecx.read_immediate(value)?),
496                     InterpErrorInfo { kind: err_ub!(InvalidUndefBytes(..)), ..},
497                     "uninitialized raw pointer",
498                     self.path
499                 );
500                 if place.layout.is_unsized() {
501                     self.check_wide_ptr_meta(place.meta, place.layout)?;
502                 }
503                 Ok(true)
504             }
505             ty::Ref(..) => {
506                 self.check_safe_pointer(value, "reference")?;
507                 Ok(true)
508             }
509             ty::Adt(def, ..) if def.is_box() => {
510                 self.check_safe_pointer(value, "box")?;
511                 Ok(true)
512             }
513             ty::FnPtr(_sig) => {
514                 let value = self.ecx.read_scalar(value)?;
515                 let _fn = try_validation!(
516                     value.not_undef().and_then(|ptr| self.ecx.memory.get_fn(ptr)),
517                     value,
518                     self.path,
519                     "a function pointer"
520                 );
521                 // FIXME: Check if the signature matches
522                 Ok(true)
523             }
524             ty::Never => throw_validation_failure!("a value of the never type `!`", self.path),
525             ty::Foreign(..) | ty::FnDef(..) => {
526                 // Nothing to check.
527                 Ok(true)
528             }
529             // The above should be all the (inhabited) primitive types. The rest is compound, we
530             // check them by visiting their fields/variants.
531             // (`Str` UTF-8 check happens in `visit_aggregate`, too.)
532             ty::Adt(..)
533             | ty::Tuple(..)
534             | ty::Array(..)
535             | ty::Slice(..)
536             | ty::Str
537             | ty::Dynamic(..)
538             | ty::Closure(..)
539             | ty::Generator(..) => Ok(false),
540             // Some types only occur during typechecking, they have no layout.
541             // We should not see them here and we could not check them anyway.
542             ty::Error
543             | ty::Infer(..)
544             | ty::Placeholder(..)
545             | ty::Bound(..)
546             | ty::Param(..)
547             | ty::Opaque(..)
548             | ty::UnnormalizedProjection(..)
549             | ty::Projection(..)
550             | ty::GeneratorWitness(..) => bug!("Encountered invalid type {:?}", ty),
551         }
552     }
553
554     fn visit_scalar(
555         &mut self,
556         op: OpTy<'tcx, M::PointerTag>,
557         scalar_layout: &Scalar,
558     ) -> InterpResult<'tcx> {
559         let value = self.ecx.read_scalar(op)?;
560         let valid_range = &scalar_layout.valid_range;
561         let (lo, hi) = valid_range.clone().into_inner();
562         // Determine the allowed range
563         // `max_hi` is as big as the size fits
564         let max_hi = u128::MAX >> (128 - op.layout.size.bits());
565         assert!(hi <= max_hi);
566         // We could also write `(hi + 1) % (max_hi + 1) == lo` but `max_hi + 1` overflows for `u128`
567         if (lo == 0 && hi == max_hi) || (hi + 1 == lo) {
568             // Nothing to check
569             return Ok(());
570         }
571         // At least one value is excluded. Get the bits.
572         let value = try_validation!(
573             value.not_undef(),
574             value,
575             self.path,
576             format_args!("something {}", wrapping_range_format(valid_range, max_hi),)
577         );
578         let bits = match value.to_bits_or_ptr(op.layout.size, self.ecx) {
579             Err(ptr) => {
580                 if lo == 1 && hi == max_hi {
581                     // Only NULL is the niche.  So make sure the ptr is NOT NULL.
582                     if self.ecx.memory.ptr_may_be_null(ptr) {
583                         throw_validation_failure!(
584                             "a potentially NULL pointer",
585                             self.path,
586                             format_args!(
587                                 "something that cannot possibly fail to be {}",
588                                 wrapping_range_format(valid_range, max_hi)
589                             )
590                         )
591                     }
592                     return Ok(());
593                 } else {
594                     // Conservatively, we reject, because the pointer *could* have a bad
595                     // value.
596                     throw_validation_failure!(
597                         "a pointer",
598                         self.path,
599                         format_args!(
600                             "something that cannot possibly fail to be {}",
601                             wrapping_range_format(valid_range, max_hi)
602                         )
603                     )
604                 }
605             }
606             Ok(data) => data,
607         };
608         // Now compare. This is slightly subtle because this is a special "wrap-around" range.
609         if wrapping_range_contains(&valid_range, bits) {
610             Ok(())
611         } else {
612             throw_validation_failure!(
613                 bits,
614                 self.path,
615                 format_args!("something {}", wrapping_range_format(valid_range, max_hi))
616             )
617         }
618     }
619 }
620
621 impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValueVisitor<'mir, 'tcx, M>
622     for ValidityVisitor<'rt, 'mir, 'tcx, M>
623 {
624     type V = OpTy<'tcx, M::PointerTag>;
625
626     #[inline(always)]
627     fn ecx(&self) -> &InterpCx<'mir, 'tcx, M> {
628         &self.ecx
629     }
630
631     #[inline]
632     fn visit_field(
633         &mut self,
634         old_op: OpTy<'tcx, M::PointerTag>,
635         field: usize,
636         new_op: OpTy<'tcx, M::PointerTag>,
637     ) -> InterpResult<'tcx> {
638         let elem = self.aggregate_field_path_elem(old_op.layout, field);
639         self.visit_elem(new_op, elem)
640     }
641
642     #[inline]
643     fn visit_variant(
644         &mut self,
645         old_op: OpTy<'tcx, M::PointerTag>,
646         variant_id: VariantIdx,
647         new_op: OpTy<'tcx, M::PointerTag>,
648     ) -> InterpResult<'tcx> {
649         let name = match old_op.layout.ty.kind {
650             ty::Adt(adt, _) => PathElem::Variant(adt.variants[variant_id].ident.name),
651             // Generators also have variants
652             ty::Generator(..) => PathElem::GeneratorState(variant_id),
653             _ => bug!("Unexpected type with variant: {:?}", old_op.layout.ty),
654         };
655         self.visit_elem(new_op, name)
656     }
657
658     #[inline(always)]
659     fn visit_union(
660         &mut self,
661         _op: OpTy<'tcx, M::PointerTag>,
662         _fields: NonZeroUsize,
663     ) -> InterpResult<'tcx> {
664         Ok(())
665     }
666
667     #[inline]
668     fn visit_value(&mut self, op: OpTy<'tcx, M::PointerTag>) -> InterpResult<'tcx> {
669         trace!("visit_value: {:?}, {:?}", *op, op.layout);
670
671         // Check primitive types -- the leafs of our recursive descend.
672         if self.try_visit_primitive(op)? {
673             return Ok(());
674         }
675         // Sanity check: `builtin_deref` does not know any pointers that are not primitive.
676         assert!(op.layout.ty.builtin_deref(true).is_none());
677
678         // Recursively walk the type. Translate some possible errors to something nicer.
679         match self.walk_value(op) {
680             Ok(()) => {}
681             Err(err) => match err.kind {
682                 err_ub!(InvalidDiscriminant(val)) => {
683                     throw_validation_failure!(val, self.path, "a valid enum discriminant")
684                 }
685                 err_unsup!(ReadPointerAsBytes) => {
686                     throw_validation_failure!("a pointer", self.path, "plain (non-pointer) bytes")
687                 }
688                 // Propagate upwards (that will also check for unexpected errors).
689                 _ => return Err(err),
690             },
691         }
692
693         // *After* all of this, check the ABI.  We need to check the ABI to handle
694         // types like `NonNull` where the `Scalar` info is more restrictive than what
695         // the fields say (`rustc_layout_scalar_valid_range_start`).
696         // But in most cases, this will just propagate what the fields say,
697         // and then we want the error to point at the field -- so, first recurse,
698         // then check ABI.
699         //
700         // FIXME: We could avoid some redundant checks here. For newtypes wrapping
701         // scalars, we do the same check on every "level" (e.g., first we check
702         // MyNewtype and then the scalar in there).
703         match op.layout.abi {
704             Abi::Uninhabited => {
705                 throw_validation_failure!(
706                     format_args!("a value of uninhabited type {:?}", op.layout.ty),
707                     self.path
708                 );
709             }
710             Abi::Scalar(ref scalar_layout) => {
711                 self.visit_scalar(op, scalar_layout)?;
712             }
713             Abi::ScalarPair { .. } | Abi::Vector { .. } => {
714                 // These have fields that we already visited above, so we already checked
715                 // all their scalar-level restrictions.
716                 // There is also no equivalent to `rustc_layout_scalar_valid_range_start`
717                 // that would make skipping them here an issue.
718             }
719             Abi::Aggregate { .. } => {
720                 // Nothing to do.
721             }
722         }
723
724         Ok(())
725     }
726
727     fn visit_aggregate(
728         &mut self,
729         op: OpTy<'tcx, M::PointerTag>,
730         fields: impl Iterator<Item = InterpResult<'tcx, Self::V>>,
731     ) -> InterpResult<'tcx> {
732         match op.layout.ty.kind {
733             ty::Str => {
734                 let mplace = op.assert_mem_place(self.ecx); // strings are never immediate
735                 try_validation!(
736                     self.ecx.read_str(mplace),
737                     "uninitialized or non-UTF-8 data in str",
738                     self.path
739                 );
740             }
741             ty::Array(tys, ..) | ty::Slice(tys)
742                 if {
743                     // This optimization applies for types that can hold arbitrary bytes (such as
744                     // integer and floating point types) or for structs or tuples with no fields.
745                     // FIXME(wesleywiser) This logic could be extended further to arbitrary structs
746                     // or tuples made up of integer/floating point types or inhabited ZSTs with no
747                     // padding.
748                     match tys.kind {
749                         ty::Int(..) | ty::Uint(..) | ty::Float(..) => true,
750                         _ => false,
751                     }
752                 } =>
753             {
754                 // Optimized handling for arrays of integer/float type.
755
756                 // Arrays cannot be immediate, slices are never immediate.
757                 let mplace = op.assert_mem_place(self.ecx);
758                 // This is the length of the array/slice.
759                 let len = mplace.len(self.ecx)?;
760                 // Zero length slices have nothing to be checked.
761                 if len == 0 {
762                     return Ok(());
763                 }
764                 // This is the element type size.
765                 let layout = self.ecx.layout_of(tys)?;
766                 // This is the size in bytes of the whole array. (This checks for overflow.)
767                 let size = layout.size * len;
768                 // Size is not 0, get a pointer.
769                 let ptr = self.ecx.force_ptr(mplace.ptr)?;
770
771                 // Optimization: we just check the entire range at once.
772                 // NOTE: Keep this in sync with the handling of integer and float
773                 // types above, in `visit_primitive`.
774                 // In run-time mode, we accept pointers in here.  This is actually more
775                 // permissive than a per-element check would be, e.g., we accept
776                 // an &[u8] that contains a pointer even though bytewise checking would
777                 // reject it.  However, that's good: We don't inherently want
778                 // to reject those pointers, we just do not have the machinery to
779                 // talk about parts of a pointer.
780                 // We also accept undef, for consistency with the slow path.
781                 match self.ecx.memory.get_raw(ptr.alloc_id)?.check_bytes(
782                     self.ecx,
783                     ptr,
784                     size,
785                     /*allow_ptr_and_undef*/ self.ref_tracking_for_consts.is_none(),
786                 ) {
787                     // In the happy case, we needn't check anything else.
788                     Ok(()) => {}
789                     // Some error happened, try to provide a more detailed description.
790                     Err(err) => {
791                         // For some errors we might be able to provide extra information
792                         match err.kind {
793                             err_ub!(InvalidUndefBytes(Some(ptr))) => {
794                                 // Some byte was uninitialized, determine which
795                                 // element that byte belongs to so we can
796                                 // provide an index.
797                                 let i = usize::try_from(ptr.offset.bytes() / layout.size.bytes())
798                                     .unwrap();
799                                 self.path.push(PathElem::ArrayElem(i));
800
801                                 throw_validation_failure!("uninitialized bytes", self.path)
802                             }
803                             // Other errors shouldn't be possible
804                             _ => return Err(err),
805                         }
806                     }
807                 }
808             }
809             // Fast path for arrays and slices of ZSTs. We only need to check a single ZST element
810             // of an array and not all of them, because there's only a single value of a specific
811             // ZST type, so either validation fails for all elements or none.
812             ty::Array(tys, ..) | ty::Slice(tys) if self.ecx.layout_of(tys)?.is_zst() => {
813                 // Validate just the first element
814                 self.walk_aggregate(op, fields.take(1))?
815             }
816             _ => {
817                 self.walk_aggregate(op, fields)? // default handler
818             }
819         }
820         Ok(())
821     }
822 }
823
824 impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
825     fn validate_operand_internal(
826         &self,
827         op: OpTy<'tcx, M::PointerTag>,
828         path: Vec<PathElem>,
829         ref_tracking_for_consts: Option<
830             &mut RefTracking<MPlaceTy<'tcx, M::PointerTag>, Vec<PathElem>>,
831         >,
832         may_ref_to_static: bool,
833     ) -> InterpResult<'tcx> {
834         trace!("validate_operand_internal: {:?}, {:?}", *op, op.layout.ty);
835
836         // Construct a visitor
837         let mut visitor =
838             ValidityVisitor { path, ref_tracking_for_consts, may_ref_to_static, ecx: self };
839
840         // Try to cast to ptr *once* instead of all the time.
841         let op = self.force_op_ptr(op).unwrap_or(op);
842
843         // Run it.
844         match visitor.visit_value(op) {
845             Ok(()) => Ok(()),
846             // Allow validation failures to be returned.
847             Err(err) if matches!(err.kind, err_ub!(ValidationFailure { .. })) => Err(err),
848             // Also allow InvalidProgram to be returned, because it's likely that different callers
849             // will want to do different things in this situation.
850             Err(err) if matches!(err.kind, InterpError::InvalidProgram(_)) => Err(err),
851             // Avoid other errors as those do not show *where* in the value the issue lies.
852             Err(err) => bug!("Unexpected error during validation: {}", err),
853         }
854     }
855
856     /// This function checks the data at `op` to be const-valid.
857     /// `op` is assumed to cover valid memory if it is an indirect operand.
858     /// It will error if the bits at the destination do not match the ones described by the layout.
859     ///
860     /// `ref_tracking` is used to record references that we encounter so that they
861     /// can be checked recursively by an outside driving loop.
862     ///
863     /// `may_ref_to_static` controls whether references are allowed to point to statics.
864     #[inline(always)]
865     pub fn const_validate_operand(
866         &self,
867         op: OpTy<'tcx, M::PointerTag>,
868         path: Vec<PathElem>,
869         ref_tracking: &mut RefTracking<MPlaceTy<'tcx, M::PointerTag>, Vec<PathElem>>,
870         may_ref_to_static: bool,
871     ) -> InterpResult<'tcx> {
872         self.validate_operand_internal(op, path, Some(ref_tracking), may_ref_to_static)
873     }
874
875     /// This function checks the data at `op` to be runtime-valid.
876     /// `op` is assumed to cover valid memory if it is an indirect operand.
877     /// It will error if the bits at the destination do not match the ones described by the layout.
878     #[inline(always)]
879     pub fn validate_operand(&self, op: OpTy<'tcx, M::PointerTag>) -> InterpResult<'tcx> {
880         self.validate_operand_internal(op, vec![], None, false)
881     }
882 }