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