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