]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/validity.rs
Auto merge of #71418 - hbina:rename_miri_undef, r=RalfJung
[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, 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 { discr_index, .. } => {
212                 if discr_index == 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.upvar_list.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.alloc_map.lock().get(ptr.alloc_id);
420                 if let Some(GlobalAlloc::Static(did)) = alloc_kind {
421                     // See const_eval::machine::MemoryExtra::can_access_statics for why
422                     // this check is so important.
423                     // This check is reachable when the const just referenced the static,
424                     // but never read it (so we never entered `before_access_global`).
425                     // We also need to do it here instead of going on to avoid running
426                     // into the `before_access_global` check during validation.
427                     if !self.may_ref_to_static && self.ecx.tcx.is_static(did) {
428                         throw_validation_failure!(self.path,
429                             { "a {} pointing to a static variable", kind }
430                         );
431                     }
432                     // `extern static` cannot be validated as they have no body.
433                     // FIXME: Statics from other crates are also skipped.
434                     // They might be checked at a different type, but for now we
435                     // want to avoid recursing too deeply.  We might miss const-invalid data,
436                     // but things are still sound otherwise (in particular re: consts
437                     // referring to statics).
438                     if !did.is_local() || self.ecx.tcx.is_foreign_item(did) {
439                         return Ok(());
440                     }
441                 }
442             }
443             // Proceed recursively even for ZST, no reason to skip them!
444             // `!` is a ZST and we want to validate it.
445             // Normalize before handing `place` to tracking because that will
446             // check for duplicates.
447             let place = if size.bytes() > 0 {
448                 self.ecx.force_mplace_ptr(place).expect("we already bounds-checked")
449             } else {
450                 place
451             };
452             let path = &self.path;
453             ref_tracking.track(place, || {
454                 // We need to clone the path anyway, make sure it gets created
455                 // with enough space for the additional `Deref`.
456                 let mut new_path = Vec::with_capacity(path.len() + 1);
457                 new_path.clone_from(path);
458                 new_path.push(PathElem::Deref);
459                 new_path
460             });
461         }
462         Ok(())
463     }
464
465     /// Check if this is a value of primitive type, and if yes check the validity of the value
466     /// at that type.  Return `true` if the type is indeed primitive.
467     fn try_visit_primitive(
468         &mut self,
469         value: OpTy<'tcx, M::PointerTag>,
470     ) -> InterpResult<'tcx, bool> {
471         // Go over all the primitive types
472         let ty = value.layout.ty;
473         match ty.kind {
474             ty::Bool => {
475                 let value = self.ecx.read_scalar(value)?;
476                 try_validation!(
477                     value.to_bool(),
478                     self.path,
479                     err_ub!(InvalidBool(..)) => { "{}", value } expected { "a boolean" },
480                 );
481                 Ok(true)
482             }
483             ty::Char => {
484                 let value = self.ecx.read_scalar(value)?;
485                 try_validation!(
486                     value.to_char(),
487                     self.path,
488                     err_ub!(InvalidChar(..)) => { "{}", value } expected { "a valid unicode codepoint" },
489                 );
490                 Ok(true)
491             }
492             ty::Float(_) | ty::Int(_) | ty::Uint(_) => {
493                 let value = self.ecx.read_scalar(value)?;
494                 // NOTE: Keep this in sync with the array optimization for int/float
495                 // types below!
496                 if self.ref_tracking_for_consts.is_some() {
497                     // Integers/floats in CTFE: Must be scalar bits, pointers are dangerous
498                     let is_bits = value.not_undef().map_or(false, |v| v.is_bits());
499                     if !is_bits {
500                         throw_validation_failure!(self.path,
501                             { "{}", value } expected { "initialized plain (non-pointer) bytes" }
502                         )
503                     }
504                 } else {
505                     // At run-time, for now, we accept *anything* for these types, including
506                     // undef. We should fix that, but let's start low.
507                 }
508                 Ok(true)
509             }
510             ty::RawPtr(..) => {
511                 // We are conservative with undef for integers, but try to
512                 // actually enforce the strict rules for raw pointers (mostly because
513                 // that lets us re-use `ref_to_mplace`).
514                 let place = try_validation!(
515                     self.ecx.ref_to_mplace(self.ecx.read_immediate(value)?),
516                     self.path,
517                     err_ub!(InvalidUninitBytes(..)) => { "uninitialized raw pointer" },
518                 );
519                 if place.layout.is_unsized() {
520                     self.check_wide_ptr_meta(place.meta, place.layout)?;
521                 }
522                 Ok(true)
523             }
524             ty::Ref(..) => {
525                 self.check_safe_pointer(value, "reference")?;
526                 Ok(true)
527             }
528             ty::Adt(def, ..) if def.is_box() => {
529                 self.check_safe_pointer(value, "box")?;
530                 Ok(true)
531             }
532             ty::FnPtr(_sig) => {
533                 let value = self.ecx.read_scalar(value)?;
534                 let _fn = try_validation!(
535                     value.not_undef().and_then(|ptr| self.ecx.memory.get_fn(ptr)),
536                     self.path,
537                     err_ub!(DanglingIntPointer(..)) |
538                     err_ub!(InvalidFunctionPointer(..)) |
539                     err_unsup!(ReadBytesAsPointer) =>
540                         { "{}", value } expected { "a function pointer" },
541                 );
542                 // FIXME: Check if the signature matches
543                 Ok(true)
544             }
545             ty::Never => throw_validation_failure!(self.path, { "a value of the never type `!`" }),
546             ty::Foreign(..) | ty::FnDef(..) => {
547                 // Nothing to check.
548                 Ok(true)
549             }
550             // The above should be all the (inhabited) primitive types. The rest is compound, we
551             // check them by visiting their fields/variants.
552             // (`Str` UTF-8 check happens in `visit_aggregate`, too.)
553             ty::Adt(..)
554             | ty::Tuple(..)
555             | ty::Array(..)
556             | ty::Slice(..)
557             | ty::Str
558             | ty::Dynamic(..)
559             | ty::Closure(..)
560             | ty::Generator(..) => Ok(false),
561             // Some types only occur during typechecking, they have no layout.
562             // We should not see them here and we could not check them anyway.
563             ty::Error
564             | ty::Infer(..)
565             | ty::Placeholder(..)
566             | ty::Bound(..)
567             | ty::Param(..)
568             | ty::Opaque(..)
569             | ty::UnnormalizedProjection(..)
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!(InvalidDiscriminant(val)) =>
701                 { "{}", val } expected { "a valid enum discriminant" },
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                 try_validation!(
748                     self.ecx.read_str(mplace),
749                     self.path,
750                     err_ub!(InvalidStr(..)) => { "uninitialized or non-UTF-8 data in str" },
751                 );
752             }
753             ty::Array(tys, ..) | ty::Slice(tys)
754                 if {
755                     // This optimization applies for types that can hold arbitrary bytes (such as
756                     // integer and floating point types) or for structs or tuples with no fields.
757                     // FIXME(wesleywiser) This logic could be extended further to arbitrary structs
758                     // or tuples made up of integer/floating point types or inhabited ZSTs with no
759                     // padding.
760                     match tys.kind {
761                         ty::Int(..) | ty::Uint(..) | ty::Float(..) => true,
762                         _ => false,
763                     }
764                 } =>
765             {
766                 // Optimized handling for arrays of integer/float type.
767
768                 // Arrays cannot be immediate, slices are never immediate.
769                 let mplace = op.assert_mem_place(self.ecx);
770                 // This is the length of the array/slice.
771                 let len = mplace.len(self.ecx)?;
772                 // Zero length slices have nothing to be checked.
773                 if len == 0 {
774                     return Ok(());
775                 }
776                 // This is the element type size.
777                 let layout = self.ecx.layout_of(tys)?;
778                 // This is the size in bytes of the whole array. (This checks for overflow.)
779                 let size = layout.size * len;
780                 // Size is not 0, get a pointer.
781                 let ptr = self.ecx.force_ptr(mplace.ptr)?;
782
783                 // Optimization: we just check the entire range at once.
784                 // NOTE: Keep this in sync with the handling of integer and float
785                 // types above, in `visit_primitive`.
786                 // In run-time mode, we accept pointers in here.  This is actually more
787                 // permissive than a per-element check would be, e.g., we accept
788                 // an &[u8] that contains a pointer even though bytewise checking would
789                 // reject it.  However, that's good: We don't inherently want
790                 // to reject those pointers, we just do not have the machinery to
791                 // talk about parts of a pointer.
792                 // We also accept undef, for consistency with the slow path.
793                 match self.ecx.memory.get_raw(ptr.alloc_id)?.check_bytes(
794                     self.ecx,
795                     ptr,
796                     size,
797                     /*allow_ptr_and_undef*/ self.ref_tracking_for_consts.is_none(),
798                 ) {
799                     // In the happy case, we needn't check anything else.
800                     Ok(()) => {}
801                     // Some error happened, try to provide a more detailed description.
802                     Err(err) => {
803                         // For some errors we might be able to provide extra information.
804                         // (This custom logic does not fit the `try_validation!` macro.)
805                         match err.kind {
806                             err_ub!(InvalidUninitBytes(Some(ptr))) => {
807                                 // Some byte was uninitialized, determine which
808                                 // element that byte belongs to so we can
809                                 // provide an index.
810                                 let i = usize::try_from(ptr.offset.bytes() / layout.size.bytes())
811                                     .unwrap();
812                                 self.path.push(PathElem::ArrayElem(i));
813
814                                 throw_validation_failure!(self.path, { "uninitialized bytes" })
815                             }
816                             // Propagate upwards (that will also check for unexpected errors).
817                             _ => return Err(err),
818                         }
819                     }
820                 }
821             }
822             // Fast path for arrays and slices of ZSTs. We only need to check a single ZST element
823             // of an array and not all of them, because there's only a single value of a specific
824             // ZST type, so either validation fails for all elements or none.
825             ty::Array(tys, ..) | ty::Slice(tys) if self.ecx.layout_of(tys)?.is_zst() => {
826                 // Validate just the first element
827                 self.walk_aggregate(op, fields.take(1))?
828             }
829             _ => {
830                 self.walk_aggregate(op, fields)? // default handler
831             }
832         }
833         Ok(())
834     }
835 }
836
837 impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
838     fn validate_operand_internal(
839         &self,
840         op: OpTy<'tcx, M::PointerTag>,
841         path: Vec<PathElem>,
842         ref_tracking_for_consts: Option<
843             &mut RefTracking<MPlaceTy<'tcx, M::PointerTag>, Vec<PathElem>>,
844         >,
845         may_ref_to_static: bool,
846     ) -> InterpResult<'tcx> {
847         trace!("validate_operand_internal: {:?}, {:?}", *op, op.layout.ty);
848
849         // Construct a visitor
850         let mut visitor =
851             ValidityVisitor { path, ref_tracking_for_consts, may_ref_to_static, ecx: self };
852
853         // Try to cast to ptr *once* instead of all the time.
854         let op = self.force_op_ptr(op).unwrap_or(op);
855
856         // Run it.
857         match visitor.visit_value(op) {
858             Ok(()) => Ok(()),
859             // Pass through validation failures.
860             Err(err) if matches!(err.kind, err_ub!(ValidationFailure { .. })) => Err(err),
861             // Also pass through InvalidProgram, those just indicate that we could not
862             // validate and each caller will know best what to do with them.
863             Err(err) if matches!(err.kind, InterpError::InvalidProgram(_)) => Err(err),
864             // Avoid other errors as those do not show *where* in the value the issue lies.
865             Err(err) => {
866                 err.print_backtrace();
867                 bug!("Unexpected error during validation: {}", err);
868             }
869         }
870     }
871
872     /// This function checks the data at `op` to be const-valid.
873     /// `op` is assumed to cover valid memory if it is an indirect operand.
874     /// It will error if the bits at the destination do not match the ones described by the layout.
875     ///
876     /// `ref_tracking` is used to record references that we encounter so that they
877     /// can be checked recursively by an outside driving loop.
878     ///
879     /// `may_ref_to_static` controls whether references are allowed to point to statics.
880     #[inline(always)]
881     pub fn const_validate_operand(
882         &self,
883         op: OpTy<'tcx, M::PointerTag>,
884         path: Vec<PathElem>,
885         ref_tracking: &mut RefTracking<MPlaceTy<'tcx, M::PointerTag>, Vec<PathElem>>,
886         may_ref_to_static: bool,
887     ) -> InterpResult<'tcx> {
888         self.validate_operand_internal(op, path, Some(ref_tracking), may_ref_to_static)
889     }
890
891     /// This function checks the data at `op` to be runtime-valid.
892     /// `op` is assumed to cover valid memory if it is an indirect operand.
893     /// It will error if the bits at the destination do not match the ones described by the layout.
894     #[inline(always)]
895     pub fn validate_operand(&self, op: OpTy<'tcx, M::PointerTag>) -> InterpResult<'tcx> {
896         self.validate_operand_internal(op, vec![], None, false)
897     }
898 }