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