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