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