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