]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/validity.rs
Auto merge of #69716 - jonas-schievink:generator-size, r=tmandry
[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_unsup!(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_unsup!(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_unsup!(InvalidNullPointerUsage) => {
357                         throw_validation_failure!(format_args!("a NULL {}", kind), self.path)
358                     }
359                     err_unsup!(AlignmentCheckFailed { required, has }) => {
360                         throw_validation_failure!(
361                             format_args!(
362                                 "an unaligned {} \
363                                     (required {} byte alignment but found {})",
364                                 kind,
365                                 required.bytes(),
366                                 has.bytes()
367                             ),
368                             self.path
369                         )
370                     }
371                     err_unsup!(ReadBytesAsPointer) => throw_validation_failure!(
372                         format_args!("a dangling {} (created from integer)", kind),
373                         self.path
374                     ),
375                     err_unsup!(PointerOutOfBounds { .. }) | err_unsup!(DanglingPointerDeref) => {
376                         throw_validation_failure!(
377                             format_args!("a dangling {} (not entirely in bounds)", kind),
378                             self.path
379                         )
380                     }
381                     _ => bug!("Unexpected error during ptr inbounds test: {}", err),
382                 }
383             }
384         };
385         // Recursive checking
386         if let Some(ref mut ref_tracking) = self.ref_tracking_for_consts {
387             if let Some(ptr) = ptr {
388                 // not a ZST
389                 // Skip validation entirely for some external statics
390                 let alloc_kind = self.ecx.tcx.alloc_map.lock().get(ptr.alloc_id);
391                 if let Some(GlobalAlloc::Static(did)) = alloc_kind {
392                     // `extern static` cannot be validated as they have no body.
393                     // FIXME: Statics from other crates are also skipped.
394                     // They might be checked at a different type, but for now we
395                     // want to avoid recursing too deeply.  This is not sound!
396                     if !did.is_local() || self.ecx.tcx.is_foreign_item(did) {
397                         return Ok(());
398                     }
399                     if !self.may_ref_to_static && self.ecx.tcx.is_static(did) {
400                         throw_validation_failure!(
401                             format_args!("a {} pointing to a static variable", kind),
402                             self.path
403                         );
404                     }
405                 }
406             }
407             // Proceed recursively even for ZST, no reason to skip them!
408             // `!` is a ZST and we want to validate it.
409             // Normalize before handing `place` to tracking because that will
410             // check for duplicates.
411             let place = if size.bytes() > 0 {
412                 self.ecx.force_mplace_ptr(place).expect("we already bounds-checked")
413             } else {
414                 place
415             };
416             let path = &self.path;
417             ref_tracking.track(place, || {
418                 // We need to clone the path anyway, make sure it gets created
419                 // with enough space for the additional `Deref`.
420                 let mut new_path = Vec::with_capacity(path.len() + 1);
421                 new_path.clone_from(path);
422                 new_path.push(PathElem::Deref);
423                 new_path
424             });
425         }
426         Ok(())
427     }
428
429     /// Check if this is a value of primitive type, and if yes check the validity of the value
430     /// at that type.  Return `true` if the type is indeed primitive.
431     fn try_visit_primitive(
432         &mut self,
433         value: OpTy<'tcx, M::PointerTag>,
434     ) -> InterpResult<'tcx, bool> {
435         // Go over all the primitive types
436         let ty = value.layout.ty;
437         match ty.kind {
438             ty::Bool => {
439                 let value = self.ecx.read_scalar(value)?;
440                 try_validation!(value.to_bool(), value, self.path, "a boolean");
441                 Ok(true)
442             }
443             ty::Char => {
444                 let value = self.ecx.read_scalar(value)?;
445                 try_validation!(value.to_char(), value, self.path, "a valid unicode codepoint");
446                 Ok(true)
447             }
448             ty::Float(_) | ty::Int(_) | ty::Uint(_) => {
449                 let value = self.ecx.read_scalar(value)?;
450                 // NOTE: Keep this in sync with the array optimization for int/float
451                 // types below!
452                 if self.ref_tracking_for_consts.is_some() {
453                     // Integers/floats in CTFE: Must be scalar bits, pointers are dangerous
454                     let is_bits = value.not_undef().map_or(false, |v| v.is_bits());
455                     if !is_bits {
456                         throw_validation_failure!(
457                             value,
458                             self.path,
459                             "initialized plain (non-pointer) bytes"
460                         )
461                     }
462                 } else {
463                     // At run-time, for now, we accept *anything* for these types, including
464                     // undef. We should fix that, but let's start low.
465                 }
466                 Ok(true)
467             }
468             ty::RawPtr(..) => {
469                 // We are conservative with undef for integers, but try to
470                 // actually enforce our current rules for raw pointers.
471                 let place = try_validation!(
472                     self.ecx.ref_to_mplace(self.ecx.read_immediate(value)?),
473                     "undefined pointer",
474                     self.path
475                 );
476                 if place.layout.is_unsized() {
477                     self.check_wide_ptr_meta(place.meta, place.layout)?;
478                 }
479                 Ok(true)
480             }
481             ty::Ref(..) => {
482                 self.check_safe_pointer(value, "reference")?;
483                 Ok(true)
484             }
485             ty::Adt(def, ..) if def.is_box() => {
486                 self.check_safe_pointer(value, "box")?;
487                 Ok(true)
488             }
489             ty::FnPtr(_sig) => {
490                 let value = self.ecx.read_scalar(value)?;
491                 let _fn = try_validation!(
492                     value.not_undef().and_then(|ptr| self.ecx.memory.get_fn(ptr)),
493                     value,
494                     self.path,
495                     "a function pointer"
496                 );
497                 // FIXME: Check if the signature matches
498                 Ok(true)
499             }
500             ty::Never => throw_validation_failure!("a value of the never type `!`", self.path),
501             ty::Foreign(..) | ty::FnDef(..) => {
502                 // Nothing to check.
503                 Ok(true)
504             }
505             // The above should be all the (inhabited) primitive types. The rest is compound, we
506             // check them by visiting their fields/variants.
507             // (`Str` UTF-8 check happens in `visit_aggregate`, too.)
508             ty::Adt(..)
509             | ty::Tuple(..)
510             | ty::Array(..)
511             | ty::Slice(..)
512             | ty::Str
513             | ty::Dynamic(..)
514             | ty::Closure(..)
515             | ty::Generator(..) => Ok(false),
516             // Some types only occur during typechecking, they have no layout.
517             // We should not see them here and we could not check them anyway.
518             ty::Error
519             | ty::Infer(..)
520             | ty::Placeholder(..)
521             | ty::Bound(..)
522             | ty::Param(..)
523             | ty::Opaque(..)
524             | ty::UnnormalizedProjection(..)
525             | ty::Projection(..)
526             | ty::GeneratorWitness(..) => bug!("Encountered invalid type {:?}", ty),
527         }
528     }
529
530     fn visit_scalar(
531         &mut self,
532         op: OpTy<'tcx, M::PointerTag>,
533         scalar_layout: &layout::Scalar,
534     ) -> InterpResult<'tcx> {
535         let value = self.ecx.read_scalar(op)?;
536         let valid_range = &scalar_layout.valid_range;
537         let (lo, hi) = valid_range.clone().into_inner();
538         // Determine the allowed range
539         // `max_hi` is as big as the size fits
540         let max_hi = u128::MAX >> (128 - op.layout.size.bits());
541         assert!(hi <= max_hi);
542         // We could also write `(hi + 1) % (max_hi + 1) == lo` but `max_hi + 1` overflows for `u128`
543         if (lo == 0 && hi == max_hi) || (hi + 1 == lo) {
544             // Nothing to check
545             return Ok(());
546         }
547         // At least one value is excluded. Get the bits.
548         let value = try_validation!(
549             value.not_undef(),
550             value,
551             self.path,
552             format_args!("something {}", wrapping_range_format(valid_range, max_hi),)
553         );
554         let bits = match value.to_bits_or_ptr(op.layout.size, self.ecx) {
555             Err(ptr) => {
556                 if lo == 1 && hi == max_hi {
557                     // Only NULL is the niche.  So make sure the ptr is NOT NULL.
558                     if self.ecx.memory.ptr_may_be_null(ptr) {
559                         throw_validation_failure!(
560                             "a potentially NULL pointer",
561                             self.path,
562                             format_args!(
563                                 "something that cannot possibly fail to be {}",
564                                 wrapping_range_format(valid_range, max_hi)
565                             )
566                         )
567                     }
568                     return Ok(());
569                 } else {
570                     // Conservatively, we reject, because the pointer *could* have a bad
571                     // value.
572                     throw_validation_failure!(
573                         "a pointer",
574                         self.path,
575                         format_args!(
576                             "something that cannot possibly fail to be {}",
577                             wrapping_range_format(valid_range, max_hi)
578                         )
579                     )
580                 }
581             }
582             Ok(data) => data,
583         };
584         // Now compare. This is slightly subtle because this is a special "wrap-around" range.
585         if wrapping_range_contains(&valid_range, bits) {
586             Ok(())
587         } else {
588             throw_validation_failure!(
589                 bits,
590                 self.path,
591                 format_args!("something {}", wrapping_range_format(valid_range, max_hi))
592             )
593         }
594     }
595 }
596
597 impl<'rt, 'mir, 'tcx, M: Machine<'mir, 'tcx>> ValueVisitor<'mir, 'tcx, M>
598     for ValidityVisitor<'rt, 'mir, 'tcx, M>
599 {
600     type V = OpTy<'tcx, M::PointerTag>;
601
602     #[inline(always)]
603     fn ecx(&self) -> &InterpCx<'mir, 'tcx, M> {
604         &self.ecx
605     }
606
607     #[inline]
608     fn visit_field(
609         &mut self,
610         old_op: OpTy<'tcx, M::PointerTag>,
611         field: usize,
612         new_op: OpTy<'tcx, M::PointerTag>,
613     ) -> InterpResult<'tcx> {
614         let elem = self.aggregate_field_path_elem(old_op.layout, field);
615         self.visit_elem(new_op, elem)
616     }
617
618     #[inline]
619     fn visit_variant(
620         &mut self,
621         old_op: OpTy<'tcx, M::PointerTag>,
622         variant_id: VariantIdx,
623         new_op: OpTy<'tcx, M::PointerTag>,
624     ) -> InterpResult<'tcx> {
625         let name = match old_op.layout.ty.kind {
626             ty::Adt(adt, _) => PathElem::Variant(adt.variants[variant_id].ident.name),
627             // Generators also have variants
628             ty::Generator(..) => PathElem::GeneratorState(variant_id),
629             _ => bug!("Unexpected type with variant: {:?}", old_op.layout.ty),
630         };
631         self.visit_elem(new_op, name)
632     }
633
634     #[inline(always)]
635     fn visit_union(&mut self, op: OpTy<'tcx, M::PointerTag>, fields: usize) -> InterpResult<'tcx> {
636         // Empty unions are not accepted by rustc. But uninhabited enums
637         // claim to be unions, so allow them, too.
638         assert!(op.layout.abi.is_uninhabited() || fields > 0);
639         Ok(())
640     }
641
642     #[inline]
643     fn visit_value(&mut self, op: OpTy<'tcx, M::PointerTag>) -> InterpResult<'tcx> {
644         trace!("visit_value: {:?}, {:?}", *op, op.layout);
645
646         // Check primitive types -- the leafs of our recursive descend.
647         if self.try_visit_primitive(op)? {
648             return Ok(());
649         }
650         // Sanity check: `builtin_deref` does not know any pointers that are not primitive.
651         assert!(op.layout.ty.builtin_deref(true).is_none());
652
653         // Recursively walk the type. Translate some possible errors to something nicer.
654         match self.walk_value(op) {
655             Ok(()) => {}
656             Err(err) => match err.kind {
657                 err_ub!(InvalidDiscriminant(val)) => {
658                     throw_validation_failure!(val, self.path, "a valid enum discriminant")
659                 }
660                 err_unsup!(ReadPointerAsBytes) => {
661                     throw_validation_failure!("a pointer", self.path, "plain (non-pointer) bytes")
662                 }
663                 // Propagate upwards (that will also check for unexpected errors).
664                 _ => return Err(err),
665             },
666         }
667
668         // *After* all of this, check the ABI.  We need to check the ABI to handle
669         // types like `NonNull` where the `Scalar` info is more restrictive than what
670         // the fields say (`rustc_layout_scalar_valid_range_start`).
671         // But in most cases, this will just propagate what the fields say,
672         // and then we want the error to point at the field -- so, first recurse,
673         // then check ABI.
674         //
675         // FIXME: We could avoid some redundant checks here. For newtypes wrapping
676         // scalars, we do the same check on every "level" (e.g., first we check
677         // MyNewtype and then the scalar in there).
678         match op.layout.abi {
679             layout::Abi::Uninhabited => {
680                 throw_validation_failure!(
681                     format_args!("a value of uninhabited type {:?}", op.layout.ty),
682                     self.path
683                 );
684             }
685             layout::Abi::Scalar(ref scalar_layout) => {
686                 self.visit_scalar(op, scalar_layout)?;
687             }
688             layout::Abi::ScalarPair { .. } | layout::Abi::Vector { .. } => {
689                 // These have fields that we already visited above, so we already checked
690                 // all their scalar-level restrictions.
691                 // There is also no equivalent to `rustc_layout_scalar_valid_range_start`
692                 // that would make skipping them here an issue.
693             }
694             layout::Abi::Aggregate { .. } => {
695                 // Nothing to do.
696             }
697         }
698
699         Ok(())
700     }
701
702     fn visit_aggregate(
703         &mut self,
704         op: OpTy<'tcx, M::PointerTag>,
705         fields: impl Iterator<Item = InterpResult<'tcx, Self::V>>,
706     ) -> InterpResult<'tcx> {
707         match op.layout.ty.kind {
708             ty::Str => {
709                 let mplace = op.assert_mem_place(self.ecx); // strings are never immediate
710                 try_validation!(
711                     self.ecx.read_str(mplace),
712                     "uninitialized or non-UTF-8 data in str",
713                     self.path
714                 );
715             }
716             ty::Array(tys, ..) | ty::Slice(tys)
717                 if {
718                     // This optimization applies for types that can hold arbitrary bytes (such as
719                     // integer and floating point types) or for structs or tuples with no fields.
720                     // FIXME(wesleywiser) This logic could be extended further to arbitrary structs
721                     // or tuples made up of integer/floating point types or inhabited ZSTs with no
722                     // padding.
723                     match tys.kind {
724                         ty::Int(..) | ty::Uint(..) | ty::Float(..) => true,
725                         _ => false,
726                     }
727                 } =>
728             {
729                 // Optimized handling for arrays of integer/float type.
730
731                 // Arrays cannot be immediate, slices are never immediate.
732                 let mplace = op.assert_mem_place(self.ecx);
733                 // This is the length of the array/slice.
734                 let len = mplace.len(self.ecx)?;
735                 // Zero length slices have nothing to be checked.
736                 if len == 0 {
737                     return Ok(());
738                 }
739                 // This is the element type size.
740                 let layout = self.ecx.layout_of(tys)?;
741                 // This is the size in bytes of the whole array.
742                 let size = layout.size * len;
743                 // Size is not 0, get a pointer.
744                 let ptr = self.ecx.force_ptr(mplace.ptr)?;
745
746                 // Optimization: we just check the entire range at once.
747                 // NOTE: Keep this in sync with the handling of integer and float
748                 // types above, in `visit_primitive`.
749                 // In run-time mode, we accept pointers in here.  This is actually more
750                 // permissive than a per-element check would be, e.g., we accept
751                 // an &[u8] that contains a pointer even though bytewise checking would
752                 // reject it.  However, that's good: We don't inherently want
753                 // to reject those pointers, we just do not have the machinery to
754                 // talk about parts of a pointer.
755                 // We also accept undef, for consistency with the slow path.
756                 match self.ecx.memory.get_raw(ptr.alloc_id)?.check_bytes(
757                     self.ecx,
758                     ptr,
759                     size,
760                     /*allow_ptr_and_undef*/ self.ref_tracking_for_consts.is_none(),
761                 ) {
762                     // In the happy case, we needn't check anything else.
763                     Ok(()) => {}
764                     // Some error happened, try to provide a more detailed description.
765                     Err(err) => {
766                         // For some errors we might be able to provide extra information
767                         match err.kind {
768                             err_unsup!(ReadUndefBytes(offset)) => {
769                                 // Some byte was undefined, determine which
770                                 // element that byte belongs to so we can
771                                 // provide an index.
772                                 let i = (offset.bytes() / layout.size.bytes()) as usize;
773                                 self.path.push(PathElem::ArrayElem(i));
774
775                                 throw_validation_failure!("undefined bytes", self.path)
776                             }
777                             // Other errors shouldn't be possible
778                             _ => return Err(err),
779                         }
780                     }
781                 }
782             }
783             // Fast path for arrays and slices of ZSTs. We only need to check a single ZST element
784             // of an array and not all of them, because there's only a single value of a specific
785             // ZST type, so either validation fails for all elements or none.
786             ty::Array(tys, ..) | ty::Slice(tys) if self.ecx.layout_of(tys)?.is_zst() => {
787                 // Validate just the first element
788                 self.walk_aggregate(op, fields.take(1))?
789             }
790             _ => {
791                 self.walk_aggregate(op, fields)? // default handler
792             }
793         }
794         Ok(())
795     }
796 }
797
798 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
799     fn validate_operand_internal(
800         &self,
801         op: OpTy<'tcx, M::PointerTag>,
802         path: Vec<PathElem>,
803         ref_tracking_for_consts: Option<
804             &mut RefTracking<MPlaceTy<'tcx, M::PointerTag>, Vec<PathElem>>,
805         >,
806         may_ref_to_static: bool,
807     ) -> InterpResult<'tcx> {
808         trace!("validate_operand_internal: {:?}, {:?}", *op, op.layout.ty);
809
810         // Construct a visitor
811         let mut visitor =
812             ValidityVisitor { path, ref_tracking_for_consts, may_ref_to_static, ecx: self };
813
814         // Try to cast to ptr *once* instead of all the time.
815         let op = self.force_op_ptr(op).unwrap_or(op);
816
817         // Run it.
818         match visitor.visit_value(op) {
819             Ok(()) => Ok(()),
820             Err(err) if matches!(err.kind, err_unsup!(ValidationFailure { .. })) => Err(err),
821             Err(err) if cfg!(debug_assertions) => {
822                 bug!("Unexpected error during validation: {}", err)
823             }
824             Err(err) => Err(err),
825         }
826     }
827
828     /// This function checks the data at `op` to be const-valid.
829     /// `op` is assumed to cover valid memory if it is an indirect operand.
830     /// It will error if the bits at the destination do not match the ones described by the layout.
831     ///
832     /// `ref_tracking` is used to record references that we encounter so that they
833     /// can be checked recursively by an outside driving loop.
834     ///
835     /// `may_ref_to_static` controls whether references are allowed to point to statics.
836     #[inline(always)]
837     pub fn const_validate_operand(
838         &self,
839         op: OpTy<'tcx, M::PointerTag>,
840         path: Vec<PathElem>,
841         ref_tracking: &mut RefTracking<MPlaceTy<'tcx, M::PointerTag>, Vec<PathElem>>,
842         may_ref_to_static: bool,
843     ) -> InterpResult<'tcx> {
844         self.validate_operand_internal(op, path, Some(ref_tracking), may_ref_to_static)
845     }
846
847     /// This function checks the data at `op` to be runtime-valid.
848     /// `op` is assumed to cover valid memory if it is an indirect operand.
849     /// It will error if the bits at the destination do not match the ones described by the layout.
850     #[inline(always)]
851     pub fn validate_operand(&self, op: OpTy<'tcx, M::PointerTag>) -> InterpResult<'tcx> {
852         self.validate_operand_internal(op, vec![], None, false)
853     }
854 }