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