]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/validity.rs
Wrap try_validation_pat! args in format_args!
[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 macro_rules! try_validation_pat {
70     ($e:expr, $where:expr, { $( $p:pat )|* => { $( $what_fmt:expr ),* } $( expected { $expected:expr } )? $( , )?}) => {{
71         match $e {
72             Ok(x) => x,
73             // We catch the error and turn it into a validation failure. We are okay with
74             // allocation here as this can only slow down builds that fail anyway.
75             $( Err(InterpErrorInfo { kind: $p, .. }) )|* => throw_validation_failure!(format_args!($( $what_fmt ),*), $where $(, $expected)?),
76             #[allow(unreachable_patterns)]
77             Err(e) => Err::<!, _>(e)?,
78         }
79     }};
80 }
81
82 /// We want to show a nice path to the invalid field for diagnostics,
83 /// but avoid string operations in the happy case where no error happens.
84 /// So we track a `Vec<PathElem>` where `PathElem` contains all the data we
85 /// need to later print something for the user.
86 #[derive(Copy, Clone, Debug)]
87 pub enum PathElem {
88     Field(Symbol),
89     Variant(Symbol),
90     GeneratorState(VariantIdx),
91     CapturedVar(Symbol),
92     ArrayElem(usize),
93     TupleElem(usize),
94     Deref,
95     EnumTag,
96     GeneratorTag,
97     DynDowncast,
98 }
99
100 /// State for tracking recursive validation of references
101 pub struct RefTracking<T, PATH = ()> {
102     pub seen: FxHashSet<T>,
103     pub todo: Vec<(T, PATH)>,
104 }
105
106 impl<T: Copy + Eq + Hash + std::fmt::Debug, PATH: Default> RefTracking<T, PATH> {
107     pub fn empty() -> Self {
108         RefTracking { seen: FxHashSet::default(), todo: vec![] }
109     }
110     pub fn new(op: T) -> Self {
111         let mut ref_tracking_for_consts =
112             RefTracking { seen: FxHashSet::default(), todo: vec![(op, PATH::default())] };
113         ref_tracking_for_consts.seen.insert(op);
114         ref_tracking_for_consts
115     }
116
117     pub fn track(&mut self, op: T, path: impl FnOnce() -> PATH) {
118         if self.seen.insert(op) {
119             trace!("Recursing below ptr {:#?}", op);
120             let path = path();
121             // Remember to come back to this later.
122             self.todo.push((op, path));
123         }
124     }
125 }
126
127 /// Format a path
128 fn write_path(out: &mut String, path: &Vec<PathElem>) {
129     use self::PathElem::*;
130
131     for elem in path.iter() {
132         match elem {
133             Field(name) => write!(out, ".{}", name),
134             EnumTag => write!(out, ".<enum-tag>"),
135             Variant(name) => write!(out, ".<enum-variant({})>", name),
136             GeneratorTag => write!(out, ".<generator-tag>"),
137             GeneratorState(idx) => write!(out, ".<generator-state({})>", idx.index()),
138             CapturedVar(name) => write!(out, ".<captured-var({})>", name),
139             TupleElem(idx) => write!(out, ".{}", idx),
140             ArrayElem(idx) => write!(out, "[{}]", idx),
141             // `.<deref>` does not match Rust syntax, but it is more readable for long paths -- and
142             // some of the other items here also are not Rust syntax.  Actually we can't
143             // even use the usual syntax because we are just showing the projections,
144             // not the root.
145             Deref => write!(out, ".<deref>"),
146             DynDowncast => write!(out, ".<dyn-downcast>"),
147         }
148         .unwrap()
149     }
150 }
151
152 // Test if a range that wraps at overflow contains `test`
153 fn wrapping_range_contains(r: &RangeInclusive<u128>, test: u128) -> bool {
154     let (lo, hi) = r.clone().into_inner();
155     if lo > hi {
156         // Wrapped
157         (..=hi).contains(&test) || (lo..).contains(&test)
158     } else {
159         // Normal
160         r.contains(&test)
161     }
162 }
163
164 // Formats such that a sentence like "expected something {}" to mean
165 // "expected something <in the given range>" makes sense.
166 fn wrapping_range_format(r: &RangeInclusive<u128>, max_hi: u128) -> String {
167     let (lo, hi) = r.clone().into_inner();
168     assert!(hi <= max_hi);
169     if lo > hi {
170         format!("less or equal to {}, or greater or equal to {}", hi, lo)
171     } else if lo == hi {
172         format!("equal to {}", lo)
173     } else if lo == 0 {
174         assert!(hi < max_hi, "should not be printing if the range covers everything");
175         format!("less or equal to {}", hi)
176     } else if hi == max_hi {
177         assert!(lo > 0, "should not be printing if the range covers everything");
178         format!("greater or equal to {}", lo)
179     } else {
180         format!("in the range {:?}", r)
181     }
182 }
183
184 struct ValidityVisitor<'rt, 'mir, 'tcx, M: Machine<'mir, 'tcx>> {
185     /// The `path` may be pushed to, but the part that is present when a function
186     /// starts must not be changed!  `visit_fields` and `visit_array` rely on
187     /// this stack discipline.
188     path: Vec<PathElem>,
189     ref_tracking_for_consts:
190         Option<&'rt mut RefTracking<MPlaceTy<'tcx, M::PointerTag>, Vec<PathElem>>>,
191     may_ref_to_static: bool,
192     ecx: &'rt InterpCx<'mir, 'tcx, M>,
193 }
194
195 impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValidityVisitor<'rt, 'mir, 'tcx, M> {
196     fn aggregate_field_path_elem(&mut self, layout: TyAndLayout<'tcx>, field: usize) -> PathElem {
197         // First, check if we are projecting to a variant.
198         match layout.variants {
199             Variants::Multiple { discr_index, .. } => {
200                 if discr_index == field {
201                     return match layout.ty.kind {
202                         ty::Adt(def, ..) if def.is_enum() => PathElem::EnumTag,
203                         ty::Generator(..) => PathElem::GeneratorTag,
204                         _ => bug!("non-variant type {:?}", layout.ty),
205                     };
206                 }
207             }
208             Variants::Single { .. } => {}
209         }
210
211         // Now we know we are projecting to a field, so figure out which one.
212         match layout.ty.kind {
213             // generators and closures.
214             ty::Closure(def_id, _) | ty::Generator(def_id, _, _) => {
215                 let mut name = None;
216                 if let Some(def_id) = def_id.as_local() {
217                     let tables = self.ecx.tcx.typeck_tables_of(def_id);
218                     if let Some(upvars) = tables.upvar_list.get(&def_id.to_def_id()) {
219                         // Sometimes the index is beyond the number of upvars (seen
220                         // for a generator).
221                         if let Some((&var_hir_id, _)) = upvars.get_index(field) {
222                             let node = self.ecx.tcx.hir().get(var_hir_id);
223                             if let hir::Node::Binding(pat) = node {
224                                 if let hir::PatKind::Binding(_, _, ident, _) = pat.kind {
225                                     name = Some(ident.name);
226                                 }
227                             }
228                         }
229                     }
230                 }
231
232                 PathElem::CapturedVar(name.unwrap_or_else(|| {
233                     // Fall back to showing the field index.
234                     sym::integer(field)
235                 }))
236             }
237
238             // tuples
239             ty::Tuple(_) => PathElem::TupleElem(field),
240
241             // enums
242             ty::Adt(def, ..) if def.is_enum() => {
243                 // we might be projecting *to* a variant, or to a field *in* a variant.
244                 match layout.variants {
245                     Variants::Single { index } => {
246                         // Inside a variant
247                         PathElem::Field(def.variants[index].fields[field].ident.name)
248                     }
249                     Variants::Multiple { .. } => bug!("we handled variants above"),
250                 }
251             }
252
253             // other ADTs
254             ty::Adt(def, _) => PathElem::Field(def.non_enum_variant().fields[field].ident.name),
255
256             // arrays/slices
257             ty::Array(..) | ty::Slice(..) => PathElem::ArrayElem(field),
258
259             // dyn traits
260             ty::Dynamic(..) => PathElem::DynDowncast,
261
262             // nothing else has an aggregate layout
263             _ => bug!("aggregate_field_path_elem: got non-aggregate type {:?}", layout.ty),
264         }
265     }
266
267     fn visit_elem(
268         &mut self,
269         new_op: OpTy<'tcx, M::PointerTag>,
270         elem: PathElem,
271     ) -> InterpResult<'tcx> {
272         // Remember the old state
273         let path_len = self.path.len();
274         // Perform operation
275         self.path.push(elem);
276         self.visit_value(new_op)?;
277         // Undo changes
278         self.path.truncate(path_len);
279         Ok(())
280     }
281
282     fn check_wide_ptr_meta(
283         &mut self,
284         meta: MemPlaceMeta<M::PointerTag>,
285         pointee: TyAndLayout<'tcx>,
286     ) -> InterpResult<'tcx> {
287         let tail = self.ecx.tcx.struct_tail_erasing_lifetimes(pointee.ty, self.ecx.param_env);
288         match tail.kind {
289             ty::Dynamic(..) => {
290                 let vtable = meta.unwrap_meta();
291                 try_validation!(
292                     self.ecx.memory.check_ptr_access(
293                         vtable,
294                         3 * self.ecx.tcx.data_layout.pointer_size, // drop, size, align
295                         self.ecx.tcx.data_layout.pointer_align.abi,
296                     ),
297                     "dangling or unaligned vtable pointer in wide pointer or too small vtable",
298                     self.path
299                 );
300                 try_validation!(
301                     self.ecx.read_drop_type_from_vtable(vtable),
302                     "invalid drop fn in vtable",
303                     self.path
304                 );
305                 try_validation!(
306                     self.ecx.read_size_and_align_from_vtable(vtable),
307                     "invalid size or align in vtable",
308                     self.path
309                 );
310                 // FIXME: More checks for the vtable.
311             }
312             ty::Slice(..) | ty::Str => {
313                 let _len = try_validation!(
314                     meta.unwrap_meta().to_machine_usize(self.ecx),
315                     "non-integer slice length in wide pointer",
316                     self.path
317                 );
318                 // We do not check that `len * elem_size <= isize::MAX`:
319                 // that is only required for references, and there it falls out of the
320                 // "dereferenceable" check performed by Stacked Borrows.
321             }
322             ty::Foreign(..) => {
323                 // Unsized, but not wide.
324             }
325             _ => bug!("Unexpected unsized type tail: {:?}", tail),
326         }
327
328         Ok(())
329     }
330
331     /// Check a reference or `Box`.
332     fn check_safe_pointer(
333         &mut self,
334         value: OpTy<'tcx, M::PointerTag>,
335         kind: &str,
336     ) -> InterpResult<'tcx> {
337         let value = self.ecx.read_immediate(value)?;
338         // Handle wide pointers.
339         // Check metadata early, for better diagnostics
340         let place = try_validation!(
341             self.ecx.ref_to_mplace(value),
342             format_args!("uninitialized {}", kind),
343             self.path
344         );
345         if place.layout.is_unsized() {
346             self.check_wide_ptr_meta(place.meta, place.layout)?;
347         }
348         // Make sure this is dereferenceable and all.
349         let size_and_align = match self.ecx.size_and_align_of(place.meta, place.layout) {
350             Ok(res) => res,
351             Err(err) => match err.kind {
352                 err_ub!(InvalidMeta(msg)) => throw_validation_failure!(
353                     format_args!("invalid {} metadata: {}", kind, msg),
354                     self.path
355                 ),
356                 _ => bug!("unexpected error during ptr size_and_align_of: {}", err),
357             },
358         };
359         let (size, align) = size_and_align
360             // for the purpose of validity, consider foreign types to have
361             // alignment and size determined by the layout (size will be 0,
362             // alignment should take attributes into account).
363             .unwrap_or_else(|| (place.layout.size, place.layout.align.abi));
364         let ptr: Option<_> = match self.ecx.memory.check_ptr_access_align(
365             place.ptr,
366             size,
367             Some(align),
368             CheckInAllocMsg::InboundsTest,
369         ) {
370             Ok(ptr) => ptr,
371             Err(err) => {
372                 info!(
373                     "{:?} did not pass access check for size {:?}, align {:?}",
374                     place.ptr, size, align
375                 );
376                 match err.kind {
377                     err_ub!(InvalidIntPointerUsage(0)) => {
378                         throw_validation_failure!(format_args!("a NULL {}", kind), self.path)
379                     }
380                     err_ub!(InvalidIntPointerUsage(i)) => throw_validation_failure!(
381                         format_args!("a {} to unallocated address {}", kind, i),
382                         self.path
383                     ),
384                     err_ub!(AlignmentCheckFailed { required, has }) => throw_validation_failure!(
385                         format_args!(
386                             "an unaligned {} (required {} byte alignment but found {})",
387                             kind,
388                             required.bytes(),
389                             has.bytes()
390                         ),
391                         self.path
392                     ),
393                     err_unsup!(ReadBytesAsPointer) => throw_validation_failure!(
394                         format_args!("a dangling {} (created from integer)", kind),
395                         self.path
396                     ),
397                     err_ub!(PointerOutOfBounds { .. }) => throw_validation_failure!(
398                         format_args!(
399                             "a dangling {} (going beyond the bounds of its allocation)",
400                             kind
401                         ),
402                         self.path
403                     ),
404                     // This cannot happen during const-eval (because interning already detects
405                     // dangling pointers), but it can happen in Miri.
406                     err_ub!(PointerUseAfterFree(_)) => throw_validation_failure!(
407                         format_args!("a dangling {} (use-after-free)", kind),
408                         self.path
409                     ),
410                     _ => bug!("Unexpected error during ptr inbounds test: {}", err),
411                 }
412             }
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!(
429                             format_args!("a {} pointing to a static variable", kind),
430                             self.path
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!(value.to_bool(), value, self.path, "a boolean");
478                 Ok(true)
479             }
480             ty::Char => {
481                 let value = self.ecx.read_scalar(value)?;
482                 try_validation!(value.to_char(), value, self.path, "a valid unicode codepoint");
483                 Ok(true)
484             }
485             ty::Float(_) | ty::Int(_) | ty::Uint(_) => {
486                 let value = self.ecx.read_scalar(value)?;
487                 // NOTE: Keep this in sync with the array optimization for int/float
488                 // types below!
489                 if self.ref_tracking_for_consts.is_some() {
490                     // Integers/floats in CTFE: Must be scalar bits, pointers are dangerous
491                     let is_bits = value.not_undef().map_or(false, |v| v.is_bits());
492                     if !is_bits {
493                         throw_validation_failure!(
494                             value,
495                             self.path,
496                             "initialized plain (non-pointer) bytes"
497                         )
498                     }
499                 } else {
500                     // At run-time, for now, we accept *anything* for these types, including
501                     // undef. We should fix that, but let's start low.
502                 }
503                 Ok(true)
504             }
505             ty::RawPtr(..) => {
506                 // We are conservative with undef for integers, but try to
507                 // actually enforce the strict rules for raw pointers (mostly because
508                 // that lets us re-use `ref_to_mplace`).
509                 let place = try_validation_pat!(self.ecx.ref_to_mplace(self.ecx.read_immediate(value)?), self.path, {
510                     err_ub!(InvalidUndefBytes(..)) => { "uninitialized raw pointer" },
511                 });
512                 if place.layout.is_unsized() {
513                     self.check_wide_ptr_meta(place.meta, place.layout)?;
514                 }
515                 Ok(true)
516             }
517             ty::Ref(..) => {
518                 self.check_safe_pointer(value, "reference")?;
519                 Ok(true)
520             }
521             ty::Adt(def, ..) if def.is_box() => {
522                 self.check_safe_pointer(value, "box")?;
523                 Ok(true)
524             }
525             ty::FnPtr(_sig) => {
526                 let value = self.ecx.read_scalar(value)?;
527                 let _fn = try_validation!(
528                     value.not_undef().and_then(|ptr| self.ecx.memory.get_fn(ptr)),
529                     value,
530                     self.path,
531                     "a function pointer"
532                 );
533                 // FIXME: Check if the signature matches
534                 Ok(true)
535             }
536             ty::Never => throw_validation_failure!("a value of the never type `!`", self.path),
537             ty::Foreign(..) | ty::FnDef(..) => {
538                 // Nothing to check.
539                 Ok(true)
540             }
541             // The above should be all the (inhabited) primitive types. The rest is compound, we
542             // check them by visiting their fields/variants.
543             // (`Str` UTF-8 check happens in `visit_aggregate`, too.)
544             ty::Adt(..)
545             | ty::Tuple(..)
546             | ty::Array(..)
547             | ty::Slice(..)
548             | ty::Str
549             | ty::Dynamic(..)
550             | ty::Closure(..)
551             | ty::Generator(..) => Ok(false),
552             // Some types only occur during typechecking, they have no layout.
553             // We should not see them here and we could not check them anyway.
554             ty::Error
555             | ty::Infer(..)
556             | ty::Placeholder(..)
557             | ty::Bound(..)
558             | ty::Param(..)
559             | ty::Opaque(..)
560             | ty::UnnormalizedProjection(..)
561             | ty::Projection(..)
562             | ty::GeneratorWitness(..) => bug!("Encountered invalid type {:?}", ty),
563         }
564     }
565
566     fn visit_scalar(
567         &mut self,
568         op: OpTy<'tcx, M::PointerTag>,
569         scalar_layout: &Scalar,
570     ) -> InterpResult<'tcx> {
571         let value = self.ecx.read_scalar(op)?;
572         let valid_range = &scalar_layout.valid_range;
573         let (lo, hi) = valid_range.clone().into_inner();
574         // Determine the allowed range
575         // `max_hi` is as big as the size fits
576         let max_hi = u128::MAX >> (128 - op.layout.size.bits());
577         assert!(hi <= max_hi);
578         // We could also write `(hi + 1) % (max_hi + 1) == lo` but `max_hi + 1` overflows for `u128`
579         if (lo == 0 && hi == max_hi) || (hi + 1 == lo) {
580             // Nothing to check
581             return Ok(());
582         }
583         // At least one value is excluded. Get the bits.
584         let value = try_validation!(
585             value.not_undef(),
586             value,
587             self.path,
588             format_args!("something {}", wrapping_range_format(valid_range, max_hi),)
589         );
590         let bits = match value.to_bits_or_ptr(op.layout.size, self.ecx) {
591             Err(ptr) => {
592                 if lo == 1 && hi == max_hi {
593                     // Only NULL is the niche.  So make sure the ptr is NOT NULL.
594                     if self.ecx.memory.ptr_may_be_null(ptr) {
595                         throw_validation_failure!(
596                             "a potentially NULL pointer",
597                             self.path,
598                             format_args!(
599                                 "something that cannot possibly fail to be {}",
600                                 wrapping_range_format(valid_range, max_hi)
601                             )
602                         )
603                     }
604                     return Ok(());
605                 } else {
606                     // Conservatively, we reject, because the pointer *could* have a bad
607                     // value.
608                     throw_validation_failure!(
609                         "a pointer",
610                         self.path,
611                         format_args!(
612                             "something that cannot possibly fail to be {}",
613                             wrapping_range_format(valid_range, max_hi)
614                         )
615                     )
616                 }
617             }
618             Ok(data) => data,
619         };
620         // Now compare. This is slightly subtle because this is a special "wrap-around" range.
621         if wrapping_range_contains(&valid_range, bits) {
622             Ok(())
623         } else {
624             throw_validation_failure!(
625                 bits,
626                 self.path,
627                 format_args!("something {}", wrapping_range_format(valid_range, max_hi))
628             )
629         }
630     }
631 }
632
633 impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValueVisitor<'mir, 'tcx, M>
634     for ValidityVisitor<'rt, 'mir, 'tcx, M>
635 {
636     type V = OpTy<'tcx, M::PointerTag>;
637
638     #[inline(always)]
639     fn ecx(&self) -> &InterpCx<'mir, 'tcx, M> {
640         &self.ecx
641     }
642
643     #[inline]
644     fn visit_field(
645         &mut self,
646         old_op: OpTy<'tcx, M::PointerTag>,
647         field: usize,
648         new_op: OpTy<'tcx, M::PointerTag>,
649     ) -> InterpResult<'tcx> {
650         let elem = self.aggregate_field_path_elem(old_op.layout, field);
651         self.visit_elem(new_op, elem)
652     }
653
654     #[inline]
655     fn visit_variant(
656         &mut self,
657         old_op: OpTy<'tcx, M::PointerTag>,
658         variant_id: VariantIdx,
659         new_op: OpTy<'tcx, M::PointerTag>,
660     ) -> InterpResult<'tcx> {
661         let name = match old_op.layout.ty.kind {
662             ty::Adt(adt, _) => PathElem::Variant(adt.variants[variant_id].ident.name),
663             // Generators also have variants
664             ty::Generator(..) => PathElem::GeneratorState(variant_id),
665             _ => bug!("Unexpected type with variant: {:?}", old_op.layout.ty),
666         };
667         self.visit_elem(new_op, name)
668     }
669
670     #[inline(always)]
671     fn visit_union(
672         &mut self,
673         _op: OpTy<'tcx, M::PointerTag>,
674         _fields: NonZeroUsize,
675     ) -> InterpResult<'tcx> {
676         Ok(())
677     }
678
679     #[inline]
680     fn visit_value(&mut self, op: OpTy<'tcx, M::PointerTag>) -> InterpResult<'tcx> {
681         trace!("visit_value: {:?}, {:?}", *op, op.layout);
682
683         // Check primitive types -- the leafs of our recursive descend.
684         if self.try_visit_primitive(op)? {
685             return Ok(());
686         }
687         // Sanity check: `builtin_deref` does not know any pointers that are not primitive.
688         assert!(op.layout.ty.builtin_deref(true).is_none());
689
690         // Recursively walk the type. Translate some possible errors to something nicer.
691         match self.walk_value(op) {
692             Ok(()) => {}
693             Err(err) => match err.kind {
694                 err_ub!(InvalidDiscriminant(val)) => {
695                     throw_validation_failure!(val, self.path, "a valid enum discriminant")
696                 }
697                 err_unsup!(ReadPointerAsBytes) => {
698                     throw_validation_failure!("a pointer", self.path, "plain (non-pointer) bytes")
699                 }
700                 // Propagate upwards (that will also check for unexpected errors).
701                 _ => return Err(err),
702             },
703         }
704
705         // *After* all of this, check the ABI.  We need to check the ABI to handle
706         // types like `NonNull` where the `Scalar` info is more restrictive than what
707         // the fields say (`rustc_layout_scalar_valid_range_start`).
708         // But in most cases, this will just propagate what the fields say,
709         // and then we want the error to point at the field -- so, first recurse,
710         // then check ABI.
711         //
712         // FIXME: We could avoid some redundant checks here. For newtypes wrapping
713         // scalars, we do the same check on every "level" (e.g., first we check
714         // MyNewtype and then the scalar in there).
715         match op.layout.abi {
716             Abi::Uninhabited => {
717                 throw_validation_failure!(
718                     format_args!("a value of uninhabited type {:?}", op.layout.ty),
719                     self.path
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                     "uninitialized or non-UTF-8 data in str",
750                     self.path
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                         match err.kind {
805                             err_ub!(InvalidUndefBytes(Some(ptr))) => {
806                                 // Some byte was uninitialized, determine which
807                                 // element that byte belongs to so we can
808                                 // provide an index.
809                                 let i = usize::try_from(ptr.offset.bytes() / layout.size.bytes())
810                                     .unwrap();
811                                 self.path.push(PathElem::ArrayElem(i));
812
813                                 throw_validation_failure!("uninitialized bytes", self.path)
814                             }
815                             // Propagate upwards (that will also check for unexpected errors).
816                             _ => return Err(err),
817                         }
818                     }
819                 }
820             }
821             // Fast path for arrays and slices of ZSTs. We only need to check a single ZST element
822             // of an array and not all of them, because there's only a single value of a specific
823             // ZST type, so either validation fails for all elements or none.
824             ty::Array(tys, ..) | ty::Slice(tys) if self.ecx.layout_of(tys)?.is_zst() => {
825                 // Validate just the first element
826                 self.walk_aggregate(op, fields.take(1))?
827             }
828             _ => {
829                 self.walk_aggregate(op, fields)? // default handler
830             }
831         }
832         Ok(())
833     }
834 }
835
836 impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
837     fn validate_operand_internal(
838         &self,
839         op: OpTy<'tcx, M::PointerTag>,
840         path: Vec<PathElem>,
841         ref_tracking_for_consts: Option<
842             &mut RefTracking<MPlaceTy<'tcx, M::PointerTag>, Vec<PathElem>>,
843         >,
844         may_ref_to_static: bool,
845     ) -> InterpResult<'tcx> {
846         trace!("validate_operand_internal: {:?}, {:?}", *op, op.layout.ty);
847
848         // Construct a visitor
849         let mut visitor =
850             ValidityVisitor { path, ref_tracking_for_consts, may_ref_to_static, ecx: self };
851
852         // Try to cast to ptr *once* instead of all the time.
853         let op = self.force_op_ptr(op).unwrap_or(op);
854
855         // Run it.
856         match visitor.visit_value(op) {
857             Ok(()) => Ok(()),
858             // Pass through validation failures.
859             Err(err) if matches!(err.kind, err_ub!(ValidationFailure { .. })) => Err(err),
860             // Also pass through InvalidProgram, those just indicate that we could not
861             // validate and each caller will know best what to do with them.
862             Err(err) if matches!(err.kind, InterpError::InvalidProgram(_)) => Err(err),
863             // Avoid other errors as those do not show *where* in the value the issue lies.
864             Err(err) => bug!("Unexpected error during validation: {}", err),
865         }
866     }
867
868     /// This function checks the data at `op` to be const-valid.
869     /// `op` is assumed to cover valid memory if it is an indirect operand.
870     /// It will error if the bits at the destination do not match the ones described by the layout.
871     ///
872     /// `ref_tracking` is used to record references that we encounter so that they
873     /// can be checked recursively by an outside driving loop.
874     ///
875     /// `may_ref_to_static` controls whether references are allowed to point to statics.
876     #[inline(always)]
877     pub fn const_validate_operand(
878         &self,
879         op: OpTy<'tcx, M::PointerTag>,
880         path: Vec<PathElem>,
881         ref_tracking: &mut RefTracking<MPlaceTy<'tcx, M::PointerTag>, Vec<PathElem>>,
882         may_ref_to_static: bool,
883     ) -> InterpResult<'tcx> {
884         self.validate_operand_internal(op, path, Some(ref_tracking), may_ref_to_static)
885     }
886
887     /// This function checks the data at `op` to be runtime-valid.
888     /// `op` is assumed to cover valid memory if it is an indirect operand.
889     /// It will error if the bits at the destination do not match the ones described by the layout.
890     #[inline(always)]
891     pub fn validate_operand(&self, op: OpTy<'tcx, M::PointerTag>) -> InterpResult<'tcx> {
892         self.validate_operand_internal(op, vec![], None, false)
893     }
894 }