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