]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/validity.rs
Rollup merge of #71018 - lcnr:custom-const-param, r=eddyb
[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::ty;
15 use rustc_middle::ty::layout::TyAndLayout;
16 use rustc_span::symbol::{sym, Symbol};
17 use rustc_target::abi::{Abi, LayoutOf, Scalar, VariantIdx, Variants};
18
19 use std::hash::Hash;
20
21 use super::{
22     CheckInAllocMsg, GlobalAlloc, InterpCx, InterpResult, MPlaceTy, Machine, MemPlaceMeta, OpTy,
23     ValueVisitor,
24 };
25
26 macro_rules! throw_validation_failure {
27     ($what:expr, $where:expr, $details:expr) => {{
28         let mut msg = format!("encountered {}", $what);
29         let where_ = &$where;
30         if !where_.is_empty() {
31             msg.push_str(" at ");
32             write_path(&mut msg, where_);
33         }
34         write!(&mut msg, ", but expected {}", $details).unwrap();
35         throw_ub!(ValidationFailure(msg))
36     }};
37     ($what:expr, $where:expr) => {{
38         let mut msg = format!("encountered {}", $what);
39         let where_ = &$where;
40         if !where_.is_empty() {
41             msg.push_str(" at ");
42             write_path(&mut msg, where_);
43         }
44         throw_ub!(ValidationFailure(msg))
45     }};
46 }
47
48 macro_rules! try_validation {
49     ($e:expr, $what:expr, $where:expr, $details:expr) => {{
50         match $e {
51             Ok(x) => x,
52             // We re-throw the error, so we are okay with allocation:
53             // this can only slow down builds that fail anyway.
54             Err(_) => throw_validation_failure!($what, $where, $details),
55         }
56     }};
57
58     ($e:expr, $what:expr, $where:expr) => {{
59         match $e {
60             Ok(x) => x,
61             // We re-throw the error, so we are okay with allocation:
62             // this can only slow down builds that fail anyway.
63             Err(_) => throw_validation_failure!($what, $where),
64         }
65     }};
66 }
67
68 /// We want to show a nice path to the invalid field for diagnostics,
69 /// but avoid string operations in the happy case where no error happens.
70 /// So we track a `Vec<PathElem>` where `PathElem` contains all the data we
71 /// need to later print something for the user.
72 #[derive(Copy, Clone, Debug)]
73 pub enum PathElem {
74     Field(Symbol),
75     Variant(Symbol),
76     GeneratorState(VariantIdx),
77     CapturedVar(Symbol),
78     ArrayElem(usize),
79     TupleElem(usize),
80     Deref,
81     EnumTag,
82     GeneratorTag,
83     DynDowncast,
84 }
85
86 /// State for tracking recursive validation of references
87 pub struct RefTracking<T, PATH = ()> {
88     pub seen: FxHashSet<T>,
89     pub todo: Vec<(T, PATH)>,
90 }
91
92 impl<T: Copy + Eq + Hash + std::fmt::Debug, PATH: Default> RefTracking<T, PATH> {
93     pub fn empty() -> Self {
94         RefTracking { seen: FxHashSet::default(), todo: vec![] }
95     }
96     pub fn new(op: T) -> Self {
97         let mut ref_tracking_for_consts =
98             RefTracking { seen: FxHashSet::default(), todo: vec![(op, PATH::default())] };
99         ref_tracking_for_consts.seen.insert(op);
100         ref_tracking_for_consts
101     }
102
103     pub fn track(&mut self, op: T, path: impl FnOnce() -> PATH) {
104         if self.seen.insert(op) {
105             trace!("Recursing below ptr {:#?}", op);
106             let path = path();
107             // Remember to come back to this later.
108             self.todo.push((op, path));
109         }
110     }
111 }
112
113 /// Format a path
114 fn write_path(out: &mut String, path: &Vec<PathElem>) {
115     use self::PathElem::*;
116
117     for elem in path.iter() {
118         match elem {
119             Field(name) => write!(out, ".{}", name),
120             EnumTag => write!(out, ".<enum-tag>"),
121             Variant(name) => write!(out, ".<enum-variant({})>", name),
122             GeneratorTag => write!(out, ".<generator-tag>"),
123             GeneratorState(idx) => write!(out, ".<generator-state({})>", idx.index()),
124             CapturedVar(name) => write!(out, ".<captured-var({})>", name),
125             TupleElem(idx) => write!(out, ".{}", idx),
126             ArrayElem(idx) => write!(out, "[{}]", idx),
127             // `.<deref>` does not match Rust syntax, but it is more readable for long paths -- and
128             // some of the other items here also are not Rust syntax.  Actually we can't
129             // even use the usual syntax because we are just showing the projections,
130             // not the root.
131             Deref => write!(out, ".<deref>"),
132             DynDowncast => write!(out, ".<dyn-downcast>"),
133         }
134         .unwrap()
135     }
136 }
137
138 // Test if a range that wraps at overflow contains `test`
139 fn wrapping_range_contains(r: &RangeInclusive<u128>, test: u128) -> bool {
140     let (lo, hi) = r.clone().into_inner();
141     if lo > hi {
142         // Wrapped
143         (..=hi).contains(&test) || (lo..).contains(&test)
144     } else {
145         // Normal
146         r.contains(&test)
147     }
148 }
149
150 // Formats such that a sentence like "expected something {}" to mean
151 // "expected something <in the given range>" makes sense.
152 fn wrapping_range_format(r: &RangeInclusive<u128>, max_hi: u128) -> String {
153     let (lo, hi) = r.clone().into_inner();
154     assert!(hi <= max_hi);
155     if lo > hi {
156         format!("less or equal to {}, or greater or equal to {}", hi, lo)
157     } else if lo == hi {
158         format!("equal to {}", lo)
159     } else if lo == 0 {
160         assert!(hi < max_hi, "should not be printing if the range covers everything");
161         format!("less or equal to {}", hi)
162     } else if hi == max_hi {
163         assert!(lo > 0, "should not be printing if the range covers everything");
164         format!("greater or equal to {}", lo)
165     } else {
166         format!("in the range {:?}", r)
167     }
168 }
169
170 struct ValidityVisitor<'rt, 'mir, 'tcx, M: Machine<'mir, 'tcx>> {
171     /// The `path` may be pushed to, but the part that is present when a function
172     /// starts must not be changed!  `visit_fields` and `visit_array` rely on
173     /// this stack discipline.
174     path: Vec<PathElem>,
175     ref_tracking_for_consts:
176         Option<&'rt mut RefTracking<MPlaceTy<'tcx, M::PointerTag>, Vec<PathElem>>>,
177     may_ref_to_static: bool,
178     ecx: &'rt InterpCx<'mir, 'tcx, M>,
179 }
180
181 impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValidityVisitor<'rt, 'mir, 'tcx, M> {
182     fn aggregate_field_path_elem(&mut self, layout: TyAndLayout<'tcx>, field: usize) -> PathElem {
183         // First, check if we are projecting to a variant.
184         match layout.variants {
185             Variants::Multiple { discr_index, .. } => {
186                 if discr_index == field {
187                     return match layout.ty.kind {
188                         ty::Adt(def, ..) if def.is_enum() => PathElem::EnumTag,
189                         ty::Generator(..) => PathElem::GeneratorTag,
190                         _ => bug!("non-variant type {:?}", layout.ty),
191                     };
192                 }
193             }
194             Variants::Single { .. } => {}
195         }
196
197         // Now we know we are projecting to a field, so figure out which one.
198         match layout.ty.kind {
199             // generators and closures.
200             ty::Closure(def_id, _) | ty::Generator(def_id, _, _) => {
201                 let mut name = None;
202                 if let Some(def_id) = def_id.as_local() {
203                     let tables = self.ecx.tcx.typeck_tables_of(def_id);
204                     if let Some(upvars) = tables.upvar_list.get(&def_id.to_def_id()) {
205                         // Sometimes the index is beyond the number of upvars (seen
206                         // for a generator).
207                         if let Some((&var_hir_id, _)) = upvars.get_index(field) {
208                             let node = self.ecx.tcx.hir().get(var_hir_id);
209                             if let hir::Node::Binding(pat) = node {
210                                 if let hir::PatKind::Binding(_, _, ident, _) = pat.kind {
211                                     name = Some(ident.name);
212                                 }
213                             }
214                         }
215                     }
216                 }
217
218                 PathElem::CapturedVar(name.unwrap_or_else(|| {
219                     // Fall back to showing the field index.
220                     sym::integer(field)
221                 }))
222             }
223
224             // tuples
225             ty::Tuple(_) => PathElem::TupleElem(field),
226
227             // enums
228             ty::Adt(def, ..) if def.is_enum() => {
229                 // we might be projecting *to* a variant, or to a field *in* a variant.
230                 match layout.variants {
231                     Variants::Single { index } => {
232                         // Inside a variant
233                         PathElem::Field(def.variants[index].fields[field].ident.name)
234                     }
235                     Variants::Multiple { .. } => bug!("we handled variants above"),
236                 }
237             }
238
239             // other ADTs
240             ty::Adt(def, _) => PathElem::Field(def.non_enum_variant().fields[field].ident.name),
241
242             // arrays/slices
243             ty::Array(..) | ty::Slice(..) => PathElem::ArrayElem(field),
244
245             // dyn traits
246             ty::Dynamic(..) => PathElem::DynDowncast,
247
248             // nothing else has an aggregate layout
249             _ => bug!("aggregate_field_path_elem: got non-aggregate type {:?}", layout.ty),
250         }
251     }
252
253     fn visit_elem(
254         &mut self,
255         new_op: OpTy<'tcx, M::PointerTag>,
256         elem: PathElem,
257     ) -> InterpResult<'tcx> {
258         // Remember the old state
259         let path_len = self.path.len();
260         // Perform operation
261         self.path.push(elem);
262         self.visit_value(new_op)?;
263         // Undo changes
264         self.path.truncate(path_len);
265         Ok(())
266     }
267
268     fn check_wide_ptr_meta(
269         &mut self,
270         meta: MemPlaceMeta<M::PointerTag>,
271         pointee: TyAndLayout<'tcx>,
272     ) -> InterpResult<'tcx> {
273         let tail = self.ecx.tcx.struct_tail_erasing_lifetimes(pointee.ty, self.ecx.param_env);
274         match tail.kind {
275             ty::Dynamic(..) => {
276                 let vtable = meta.unwrap_meta();
277                 try_validation!(
278                     self.ecx.memory.check_ptr_access(
279                         vtable,
280                         3 * self.ecx.tcx.data_layout.pointer_size, // drop, size, align
281                         self.ecx.tcx.data_layout.pointer_align.abi,
282                     ),
283                     "dangling or unaligned vtable pointer in wide pointer or too small vtable",
284                     self.path
285                 );
286                 try_validation!(
287                     self.ecx.read_drop_type_from_vtable(vtable),
288                     "invalid drop fn in vtable",
289                     self.path
290                 );
291                 try_validation!(
292                     self.ecx.read_size_and_align_from_vtable(vtable),
293                     "invalid size or align in vtable",
294                     self.path
295                 );
296                 // FIXME: More checks for the vtable.
297             }
298             ty::Slice(..) | ty::Str => {
299                 let _len = try_validation!(
300                     meta.unwrap_meta().to_machine_usize(self.ecx),
301                     "non-integer slice length in wide pointer",
302                     self.path
303                 );
304                 // We do not check that `len * elem_size <= isize::MAX`:
305                 // that is only required for references, and there it falls out of the
306                 // "dereferenceable" check performed by Stacked Borrows.
307             }
308             ty::Foreign(..) => {
309                 // Unsized, but not wide.
310             }
311             _ => bug!("Unexpected unsized type tail: {:?}", tail),
312         }
313
314         Ok(())
315     }
316
317     /// Check a reference or `Box`.
318     fn check_safe_pointer(
319         &mut self,
320         value: OpTy<'tcx, M::PointerTag>,
321         kind: &str,
322     ) -> InterpResult<'tcx> {
323         let value = self.ecx.read_immediate(value)?;
324         // Handle wide pointers.
325         // Check metadata early, for better diagnostics
326         let place = try_validation!(
327             self.ecx.ref_to_mplace(value),
328             format_args!("uninitialized {}", kind),
329             self.path
330         );
331         if place.layout.is_unsized() {
332             self.check_wide_ptr_meta(place.meta, place.layout)?;
333         }
334         // Make sure this is dereferenceable and all.
335         let size_and_align = match self.ecx.size_and_align_of(place.meta, place.layout) {
336             Ok(res) => res,
337             Err(err) => match err.kind {
338                 err_ub!(InvalidMeta(msg)) => throw_validation_failure!(
339                     format_args!("invalid {} metadata: {}", kind, msg),
340                     self.path
341                 ),
342                 _ => bug!("unexpected error during ptr size_and_align_of: {}", err),
343             },
344         };
345         let (size, align) = size_and_align
346             // for the purpose of validity, consider foreign types to have
347             // alignment and size determined by the layout (size will be 0,
348             // alignment should take attributes into account).
349             .unwrap_or_else(|| (place.layout.size, place.layout.align.abi));
350         let ptr: Option<_> = match self.ecx.memory.check_ptr_access_align(
351             place.ptr,
352             size,
353             Some(align),
354             CheckInAllocMsg::InboundsTest,
355         ) {
356             Ok(ptr) => ptr,
357             Err(err) => {
358                 info!(
359                     "{:?} did not pass access check for size {:?}, align {:?}",
360                     place.ptr, size, align
361                 );
362                 match err.kind {
363                     err_ub!(DanglingIntPointer(0, _)) => {
364                         throw_validation_failure!(format_args!("a NULL {}", kind), self.path)
365                     }
366                     err_ub!(DanglingIntPointer(i, _)) => throw_validation_failure!(
367                         format_args!("a {} to unallocated address {}", kind, i),
368                         self.path
369                     ),
370                     err_ub!(AlignmentCheckFailed { required, has }) => throw_validation_failure!(
371                         format_args!(
372                             "an unaligned {} (required {} byte alignment but found {})",
373                             kind,
374                             required.bytes(),
375                             has.bytes()
376                         ),
377                         self.path
378                     ),
379                     err_unsup!(ReadBytesAsPointer) => throw_validation_failure!(
380                         format_args!("a dangling {} (created from integer)", kind),
381                         self.path
382                     ),
383                     err_ub!(PointerOutOfBounds { .. }) => throw_validation_failure!(
384                         format_args!(
385                             "a dangling {} (going beyond the bounds of its allocation)",
386                             kind
387                         ),
388                         self.path
389                     ),
390                     // This cannot happen during const-eval (because interning already detects
391                     // dangling pointers), but it can happen in Miri.
392                     err_ub!(PointerUseAfterFree(_)) => throw_validation_failure!(
393                         format_args!("a dangling {} (use-after-free)", kind),
394                         self.path
395                     ),
396                     _ => bug!("Unexpected error during ptr inbounds test: {}", err),
397                 }
398             }
399         };
400         // Recursive checking
401         if let Some(ref mut ref_tracking) = self.ref_tracking_for_consts {
402             if let Some(ptr) = ptr {
403                 // not a ZST
404                 // Skip validation entirely for some external statics
405                 let alloc_kind = self.ecx.tcx.alloc_map.lock().get(ptr.alloc_id);
406                 if let Some(GlobalAlloc::Static(did)) = alloc_kind {
407                     // See const_eval::machine::MemoryExtra::can_access_statics for why
408                     // this check is so important.
409                     // This check is reachable when the const just referenced the static,
410                     // but never read it (so we never entered `before_access_global`).
411                     // We also need to do it here instead of going on to avoid running
412                     // into the `before_access_global` check during validation.
413                     if !self.may_ref_to_static && self.ecx.tcx.is_static(did) {
414                         throw_validation_failure!(
415                             format_args!("a {} pointing to a static variable", kind),
416                             self.path
417                         );
418                     }
419                     // `extern static` cannot be validated as they have no body.
420                     // FIXME: Statics from other crates are also skipped.
421                     // They might be checked at a different type, but for now we
422                     // want to avoid recursing too deeply.  We might miss const-invalid data,
423                     // but things are still sound otherwise (in particular re: consts
424                     // referring to statics).
425                     if !did.is_local() || self.ecx.tcx.is_foreign_item(did) {
426                         return Ok(());
427                     }
428                 }
429             }
430             // Proceed recursively even for ZST, no reason to skip them!
431             // `!` is a ZST and we want to validate it.
432             // Normalize before handing `place` to tracking because that will
433             // check for duplicates.
434             let place = if size.bytes() > 0 {
435                 self.ecx.force_mplace_ptr(place).expect("we already bounds-checked")
436             } else {
437                 place
438             };
439             let path = &self.path;
440             ref_tracking.track(place, || {
441                 // We need to clone the path anyway, make sure it gets created
442                 // with enough space for the additional `Deref`.
443                 let mut new_path = Vec::with_capacity(path.len() + 1);
444                 new_path.clone_from(path);
445                 new_path.push(PathElem::Deref);
446                 new_path
447             });
448         }
449         Ok(())
450     }
451
452     /// Check if this is a value of primitive type, and if yes check the validity of the value
453     /// at that type.  Return `true` if the type is indeed primitive.
454     fn try_visit_primitive(
455         &mut self,
456         value: OpTy<'tcx, M::PointerTag>,
457     ) -> InterpResult<'tcx, bool> {
458         // Go over all the primitive types
459         let ty = value.layout.ty;
460         match ty.kind {
461             ty::Bool => {
462                 let value = self.ecx.read_scalar(value)?;
463                 try_validation!(value.to_bool(), value, self.path, "a boolean");
464                 Ok(true)
465             }
466             ty::Char => {
467                 let value = self.ecx.read_scalar(value)?;
468                 try_validation!(value.to_char(), value, self.path, "a valid unicode codepoint");
469                 Ok(true)
470             }
471             ty::Float(_) | ty::Int(_) | ty::Uint(_) => {
472                 let value = self.ecx.read_scalar(value)?;
473                 // NOTE: Keep this in sync with the array optimization for int/float
474                 // types below!
475                 if self.ref_tracking_for_consts.is_some() {
476                     // Integers/floats in CTFE: Must be scalar bits, pointers are dangerous
477                     let is_bits = value.not_undef().map_or(false, |v| v.is_bits());
478                     if !is_bits {
479                         throw_validation_failure!(
480                             value,
481                             self.path,
482                             "initialized plain (non-pointer) bytes"
483                         )
484                     }
485                 } else {
486                     // At run-time, for now, we accept *anything* for these types, including
487                     // undef. We should fix that, but let's start low.
488                 }
489                 Ok(true)
490             }
491             ty::RawPtr(..) => {
492                 // We are conservative with undef for integers, but try to
493                 // actually enforce the strict rules for raw pointers (mostly because
494                 // that lets us re-use `ref_to_mplace`).
495                 let place = try_validation!(
496                     self.ecx.ref_to_mplace(self.ecx.read_immediate(value)?),
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             // We should only get validation errors here. Avoid other errors as
847             // those do not show *where* in the value the issue lies.
848             Err(err) if matches!(err.kind, err_ub!(ValidationFailure { .. })) => Err(err),
849             Err(err) => bug!("Unexpected error during validation: {}", err),
850         }
851     }
852
853     /// This function checks the data at `op` to be const-valid.
854     /// `op` is assumed to cover valid memory if it is an indirect operand.
855     /// It will error if the bits at the destination do not match the ones described by the layout.
856     ///
857     /// `ref_tracking` is used to record references that we encounter so that they
858     /// can be checked recursively by an outside driving loop.
859     ///
860     /// `may_ref_to_static` controls whether references are allowed to point to statics.
861     #[inline(always)]
862     pub fn const_validate_operand(
863         &self,
864         op: OpTy<'tcx, M::PointerTag>,
865         path: Vec<PathElem>,
866         ref_tracking: &mut RefTracking<MPlaceTy<'tcx, M::PointerTag>, Vec<PathElem>>,
867         may_ref_to_static: bool,
868     ) -> InterpResult<'tcx> {
869         self.validate_operand_internal(op, path, Some(ref_tracking), may_ref_to_static)
870     }
871
872     /// This function checks the data at `op` to be runtime-valid.
873     /// `op` is assumed to cover valid memory if it is an indirect operand.
874     /// It will error if the bits at the destination do not match the ones described by the layout.
875     #[inline(always)]
876     pub fn validate_operand(&self, op: OpTy<'tcx, M::PointerTag>) -> InterpResult<'tcx> {
877         self.validate_operand_internal(op, vec![], None, false)
878     }
879 }