]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_const_eval/src/interpret/validity.rs
Auto merge of #99182 - RalfJung:mitigate-uninit, r=scottmcm
[rust.git] / compiler / rustc_const_eval / src / 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
11 use rustc_data_structures::fx::FxHashSet;
12 use rustc_hir as hir;
13 use rustc_middle::mir::interpret::InterpError;
14 use rustc_middle::ty;
15 use rustc_middle::ty::layout::{LayoutOf, TyAndLayout};
16 use rustc_span::symbol::{sym, Symbol};
17 use rustc_span::DUMMY_SP;
18 use rustc_target::abi::{Abi, Scalar as ScalarAbi, Size, VariantIdx, Variants, WrappingRange};
19
20 use std::hash::Hash;
21
22 use super::{
23     alloc_range, CheckInAllocMsg, GlobalAlloc, Immediate, InterpCx, InterpResult, MPlaceTy,
24     Machine, MemPlaceMeta, OpTy, Scalar, ScalarMaybeUninit, ValueVisitor,
25 };
26
27 macro_rules! throw_validation_failure {
28     ($where:expr, { $( $what_fmt:expr ),+ } $( expected { $( $expected_fmt:expr ),+ } )?) => {{
29         let mut msg = String::new();
30         msg.push_str("encountered ");
31         write!(&mut msg, $($what_fmt),+).unwrap();
32         $(
33             msg.push_str(", but expected ");
34             write!(&mut msg, $($expected_fmt),+).unwrap();
35         )?
36         let path = rustc_middle::ty::print::with_no_trimmed_paths!({
37             let where_ = &$where;
38             if !where_.is_empty() {
39                 let mut path = String::new();
40                 write_path(&mut path, where_);
41                 Some(path)
42             } else {
43                 None
44             }
45         });
46         throw_ub!(ValidationFailure { path, msg })
47     }};
48 }
49
50 /// If $e throws an error matching the pattern, throw a validation failure.
51 /// Other errors are passed back to the caller, unchanged -- and if they reach the root of
52 /// the visitor, we make sure only validation errors and `InvalidProgram` errors are left.
53 /// This lets you use the patterns as a kind of validation list, asserting which errors
54 /// can possibly happen:
55 ///
56 /// ```
57 /// let v = try_validation!(some_fn(), some_path, {
58 ///     Foo | Bar | Baz => { "some failure" },
59 /// });
60 /// ```
61 ///
62 /// An additional expected parameter can also be added to the failure message:
63 ///
64 /// ```
65 /// let v = try_validation!(some_fn(), some_path, {
66 ///     Foo | Bar | Baz => { "some failure" } expected { "something that wasn't a failure" },
67 /// });
68 /// ```
69 ///
70 /// An additional nicety is that both parameters actually take format args, so you can just write
71 /// the format string in directly:
72 ///
73 /// ```
74 /// let v = try_validation!(some_fn(), some_path, {
75 ///     Foo | Bar | Baz => { "{:?}", some_failure } expected { "{}", expected_value },
76 /// });
77 /// ```
78 ///
79 macro_rules! try_validation {
80     ($e:expr, $where:expr,
81     $( $( $p:pat_param )|+ => { $( $what_fmt:expr ),+ } $( expected { $( $expected_fmt:expr ),+ } )? ),+ $(,)?
82     ) => {{
83         match $e {
84             Ok(x) => x,
85             // We catch the error and turn it into a validation failure. We are okay with
86             // allocation here as this can only slow down builds that fail anyway.
87             Err(e) => match e.kind() {
88                 $(
89                     $($p)|+ =>
90                        throw_validation_failure!(
91                             $where,
92                             { $( $what_fmt ),+ } $( expected { $( $expected_fmt ),+ } )?
93                         )
94                 ),+,
95                 #[allow(unreachable_patterns)]
96                 _ => Err::<!, _>(e)?,
97             }
98         }
99     }};
100 }
101
102 /// We want to show a nice path to the invalid field for diagnostics,
103 /// but avoid string operations in the happy case where no error happens.
104 /// So we track a `Vec<PathElem>` where `PathElem` contains all the data we
105 /// need to later print something for the user.
106 #[derive(Copy, Clone, Debug)]
107 pub enum PathElem {
108     Field(Symbol),
109     Variant(Symbol),
110     GeneratorState(VariantIdx),
111     CapturedVar(Symbol),
112     ArrayElem(usize),
113     TupleElem(usize),
114     Deref,
115     EnumTag,
116     GeneratorTag,
117     DynDowncast,
118 }
119
120 /// Extra things to check for during validation of CTFE results.
121 pub enum CtfeValidationMode {
122     /// Regular validation, nothing special happening.
123     Regular,
124     /// Validation of a `const`.
125     /// `inner` says if this is an inner, indirect allocation (as opposed to the top-level const
126     /// allocation). Being an inner allocation makes a difference because the top-level allocation
127     /// of a `const` is copied for each use, but the inner allocations are implicitly shared.
128     /// `allow_static_ptrs` says if pointers to statics are permitted (which is the case for promoteds in statics).
129     Const { inner: bool, allow_static_ptrs: bool },
130 }
131
132 /// State for tracking recursive validation of references
133 pub struct RefTracking<T, PATH = ()> {
134     pub seen: FxHashSet<T>,
135     pub todo: Vec<(T, PATH)>,
136 }
137
138 impl<T: Copy + Eq + Hash + std::fmt::Debug, PATH: Default> RefTracking<T, PATH> {
139     pub fn empty() -> Self {
140         RefTracking { seen: FxHashSet::default(), todo: vec![] }
141     }
142     pub fn new(op: T) -> Self {
143         let mut ref_tracking_for_consts =
144             RefTracking { seen: FxHashSet::default(), todo: vec![(op, PATH::default())] };
145         ref_tracking_for_consts.seen.insert(op);
146         ref_tracking_for_consts
147     }
148
149     pub fn track(&mut self, op: T, path: impl FnOnce() -> PATH) {
150         if self.seen.insert(op) {
151             trace!("Recursing below ptr {:#?}", op);
152             let path = path();
153             // Remember to come back to this later.
154             self.todo.push((op, path));
155         }
156     }
157 }
158
159 /// Format a path
160 fn write_path(out: &mut String, path: &[PathElem]) {
161     use self::PathElem::*;
162
163     for elem in path.iter() {
164         match elem {
165             Field(name) => write!(out, ".{}", name),
166             EnumTag => write!(out, ".<enum-tag>"),
167             Variant(name) => write!(out, ".<enum-variant({})>", name),
168             GeneratorTag => write!(out, ".<generator-tag>"),
169             GeneratorState(idx) => write!(out, ".<generator-state({})>", idx.index()),
170             CapturedVar(name) => write!(out, ".<captured-var({})>", name),
171             TupleElem(idx) => write!(out, ".{}", idx),
172             ArrayElem(idx) => write!(out, "[{}]", idx),
173             // `.<deref>` does not match Rust syntax, but it is more readable for long paths -- and
174             // some of the other items here also are not Rust syntax.  Actually we can't
175             // even use the usual syntax because we are just showing the projections,
176             // not the root.
177             Deref => write!(out, ".<deref>"),
178             DynDowncast => write!(out, ".<dyn-downcast>"),
179         }
180         .unwrap()
181     }
182 }
183
184 // Formats such that a sentence like "expected something {}" to mean
185 // "expected something <in the given range>" makes sense.
186 fn wrapping_range_format(r: WrappingRange, max_hi: u128) -> String {
187     let WrappingRange { start: lo, end: hi } = r;
188     assert!(hi <= max_hi);
189     if lo > hi {
190         format!("less or equal to {}, or greater or equal to {}", hi, lo)
191     } else if lo == hi {
192         format!("equal to {}", lo)
193     } else if lo == 0 {
194         assert!(hi < max_hi, "should not be printing if the range covers everything");
195         format!("less or equal to {}", hi)
196     } else if hi == max_hi {
197         assert!(lo > 0, "should not be printing if the range covers everything");
198         format!("greater or equal to {}", lo)
199     } else {
200         format!("in the range {:?}", r)
201     }
202 }
203
204 struct ValidityVisitor<'rt, 'mir, 'tcx, M: Machine<'mir, 'tcx>> {
205     /// The `path` may be pushed to, but the part that is present when a function
206     /// starts must not be changed!  `visit_fields` and `visit_array` rely on
207     /// this stack discipline.
208     path: Vec<PathElem>,
209     ref_tracking: Option<&'rt mut RefTracking<MPlaceTy<'tcx, M::Provenance>, Vec<PathElem>>>,
210     /// `None` indicates this is not validating for CTFE (but for runtime).
211     ctfe_mode: Option<CtfeValidationMode>,
212     ecx: &'rt InterpCx<'mir, 'tcx, M>,
213 }
214
215 impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValidityVisitor<'rt, 'mir, 'tcx, M> {
216     fn aggregate_field_path_elem(&mut self, layout: TyAndLayout<'tcx>, field: usize) -> PathElem {
217         // First, check if we are projecting to a variant.
218         match layout.variants {
219             Variants::Multiple { tag_field, .. } => {
220                 if tag_field == field {
221                     return match layout.ty.kind() {
222                         ty::Adt(def, ..) if def.is_enum() => PathElem::EnumTag,
223                         ty::Generator(..) => PathElem::GeneratorTag,
224                         _ => bug!("non-variant type {:?}", layout.ty),
225                     };
226                 }
227             }
228             Variants::Single { .. } => {}
229         }
230
231         // Now we know we are projecting to a field, so figure out which one.
232         match layout.ty.kind() {
233             // generators and closures.
234             ty::Closure(def_id, _) | ty::Generator(def_id, _, _) => {
235                 let mut name = None;
236                 // FIXME this should be more descriptive i.e. CapturePlace instead of CapturedVar
237                 // https://github.com/rust-lang/project-rfc-2229/issues/46
238                 if let Some(local_def_id) = def_id.as_local() {
239                     let tables = self.ecx.tcx.typeck(local_def_id);
240                     if let Some(captured_place) =
241                         tables.closure_min_captures_flattened(*def_id).nth(field)
242                     {
243                         // Sometimes the index is beyond the number of upvars (seen
244                         // for a generator).
245                         let var_hir_id = captured_place.get_root_variable();
246                         let node = self.ecx.tcx.hir().get(var_hir_id);
247                         if let hir::Node::Pat(pat) = node {
248                             if let hir::PatKind::Binding(_, _, ident, _) = pat.kind {
249                                 name = Some(ident.name);
250                             }
251                         }
252                     }
253                 }
254
255                 PathElem::CapturedVar(name.unwrap_or_else(|| {
256                     // Fall back to showing the field index.
257                     sym::integer(field)
258                 }))
259             }
260
261             // tuples
262             ty::Tuple(_) => PathElem::TupleElem(field),
263
264             // enums
265             ty::Adt(def, ..) if def.is_enum() => {
266                 // we might be projecting *to* a variant, or to a field *in* a variant.
267                 match layout.variants {
268                     Variants::Single { index } => {
269                         // Inside a variant
270                         PathElem::Field(def.variant(index).fields[field].name)
271                     }
272                     Variants::Multiple { .. } => bug!("we handled variants above"),
273                 }
274             }
275
276             // other ADTs
277             ty::Adt(def, _) => PathElem::Field(def.non_enum_variant().fields[field].name),
278
279             // arrays/slices
280             ty::Array(..) | ty::Slice(..) => PathElem::ArrayElem(field),
281
282             // dyn traits
283             ty::Dynamic(..) => PathElem::DynDowncast,
284
285             // nothing else has an aggregate layout
286             _ => bug!("aggregate_field_path_elem: got non-aggregate type {:?}", layout.ty),
287         }
288     }
289
290     fn with_elem<R>(
291         &mut self,
292         elem: PathElem,
293         f: impl FnOnce(&mut Self) -> InterpResult<'tcx, R>,
294     ) -> InterpResult<'tcx, R> {
295         // Remember the old state
296         let path_len = self.path.len();
297         // Record new element
298         self.path.push(elem);
299         // Perform operation
300         let r = f(self)?;
301         // Undo changes
302         self.path.truncate(path_len);
303         // Done
304         Ok(r)
305     }
306
307     fn check_wide_ptr_meta(
308         &mut self,
309         meta: MemPlaceMeta<M::Provenance>,
310         pointee: TyAndLayout<'tcx>,
311     ) -> InterpResult<'tcx> {
312         let tail = self.ecx.tcx.struct_tail_erasing_lifetimes(pointee.ty, self.ecx.param_env);
313         match tail.kind() {
314             ty::Dynamic(..) => {
315                 let vtable = meta.unwrap_meta().to_pointer(self.ecx)?;
316                 // Make sure it is a genuine vtable pointer.
317                 let (_ty, _trait) = try_validation!(
318                     self.ecx.get_ptr_vtable(vtable),
319                     self.path,
320                     err_ub!(DanglingIntPointer(..)) |
321                     err_ub!(InvalidVTablePointer(..)) =>
322                         { "{vtable}" } expected { "a vtable pointer" },
323                 );
324                 // FIXME: check if the type/trait match what ty::Dynamic says?
325             }
326             ty::Slice(..) | ty::Str => {
327                 let _len = try_validation!(
328                     meta.unwrap_meta().to_machine_usize(self.ecx),
329                     self.path,
330                     err_unsup!(ReadPointerAsBytes) => { "non-integer slice length in wide pointer" },
331                 );
332                 // We do not check that `len * elem_size <= isize::MAX`:
333                 // that is only required for references, and there it falls out of the
334                 // "dereferenceable" check performed by Stacked Borrows.
335             }
336             ty::Foreign(..) => {
337                 // Unsized, but not wide.
338             }
339             _ => bug!("Unexpected unsized type tail: {:?}", tail),
340         }
341
342         Ok(())
343     }
344
345     /// Check a reference or `Box`.
346     fn check_safe_pointer(
347         &mut self,
348         value: &OpTy<'tcx, M::Provenance>,
349         kind: &str,
350     ) -> InterpResult<'tcx> {
351         let value = try_validation!(
352             self.ecx.read_immediate(value),
353             self.path,
354             err_unsup!(ReadPointerAsBytes) => { "part of a pointer" } expected { "a proper pointer or integer value" },
355         );
356         // Handle wide pointers.
357         // Check metadata early, for better diagnostics
358         let place = try_validation!(
359             self.ecx.ref_to_mplace(&value),
360             self.path,
361             err_ub!(InvalidUninitBytes(None)) => { "uninitialized {}", kind },
362         );
363         if place.layout.is_unsized() {
364             self.check_wide_ptr_meta(place.meta, place.layout)?;
365         }
366         // Make sure this is dereferenceable and all.
367         let size_and_align = try_validation!(
368             self.ecx.size_and_align_of_mplace(&place),
369             self.path,
370             err_ub!(InvalidMeta(msg)) => { "invalid {} metadata: {}", kind, msg },
371         );
372         let (size, align) = size_and_align
373             // for the purpose of validity, consider foreign types to have
374             // alignment and size determined by the layout (size will be 0,
375             // alignment should take attributes into account).
376             .unwrap_or_else(|| (place.layout.size, place.layout.align.abi));
377         // Direct call to `check_ptr_access_align` checks alignment even on CTFE machines.
378         try_validation!(
379             self.ecx.check_ptr_access_align(
380                 place.ptr,
381                 size,
382                 align,
383                 CheckInAllocMsg::InboundsTest, // will anyway be replaced by validity message
384             ),
385             self.path,
386             err_ub!(AlignmentCheckFailed { required, has }) =>
387                 {
388                     "an unaligned {kind} (required {} byte alignment but found {})",
389                     required.bytes(),
390                     has.bytes()
391                 },
392             err_ub!(DanglingIntPointer(0, _)) =>
393                 { "a null {kind}" },
394             err_ub!(DanglingIntPointer(i, _)) =>
395                 { "a dangling {kind} (address {i:#x} is unallocated)" },
396             err_ub!(PointerOutOfBounds { .. }) =>
397                 { "a dangling {kind} (going beyond the bounds of its allocation)" },
398             // This cannot happen during const-eval (because interning already detects
399             // dangling pointers), but it can happen in Miri.
400             err_ub!(PointerUseAfterFree(..)) =>
401                 { "a dangling {kind} (use-after-free)" },
402         );
403         // Do not allow pointers to uninhabited types.
404         if place.layout.abi.is_uninhabited() {
405             throw_validation_failure!(self.path,
406                 { "a {kind} pointing to uninhabited type {}", place.layout.ty }
407             )
408         }
409         // Recursive checking
410         if let Some(ref mut ref_tracking) = self.ref_tracking {
411             // Proceed recursively even for ZST, no reason to skip them!
412             // `!` is a ZST and we want to validate it.
413             if let Ok((alloc_id, _offset, _prov)) = self.ecx.ptr_try_get_alloc_id(place.ptr) {
414                 // Special handling for pointers to statics (irrespective of their type).
415                 let alloc_kind = self.ecx.tcx.try_get_global_alloc(alloc_id);
416                 if let Some(GlobalAlloc::Static(did)) = alloc_kind {
417                     assert!(!self.ecx.tcx.is_thread_local_static(did));
418                     assert!(self.ecx.tcx.is_static(did));
419                     if matches!(
420                         self.ctfe_mode,
421                         Some(CtfeValidationMode::Const { allow_static_ptrs: false, .. })
422                     ) {
423                         // See const_eval::machine::MemoryExtra::can_access_statics for why
424                         // this check is so important.
425                         // This check is reachable when the const just referenced the static,
426                         // but never read it (so we never entered `before_access_global`).
427                         throw_validation_failure!(self.path,
428                             { "a {} pointing to a static variable", kind }
429                         );
430                     }
431                     // We skip checking other statics. These statics must be sound by
432                     // themselves, and the only way to get broken statics here is by using
433                     // unsafe code.
434                     // The reasons we don't check other statics is twofold. For one, in all
435                     // sound cases, the static was already validated on its own, and second, we
436                     // trigger cycle errors if we try to compute the value of the other static
437                     // and that static refers back to us.
438                     // We might miss const-invalid data,
439                     // but things are still sound otherwise (in particular re: consts
440                     // referring to statics).
441                     return Ok(());
442                 }
443             }
444             let path = &self.path;
445             ref_tracking.track(place, || {
446                 // We need to clone the path anyway, make sure it gets created
447                 // with enough space for the additional `Deref`.
448                 let mut new_path = Vec::with_capacity(path.len() + 1);
449                 new_path.extend(path);
450                 new_path.push(PathElem::Deref);
451                 new_path
452             });
453         }
454         Ok(())
455     }
456
457     fn read_scalar(
458         &self,
459         op: &OpTy<'tcx, M::Provenance>,
460     ) -> InterpResult<'tcx, ScalarMaybeUninit<M::Provenance>> {
461         Ok(try_validation!(
462             self.ecx.read_scalar(op),
463             self.path,
464             err_unsup!(ReadPointerAsBytes) => { "(potentially part of) a pointer" } expected { "plain (non-pointer) bytes" },
465         ))
466     }
467
468     fn read_immediate_forced(
469         &self,
470         op: &OpTy<'tcx, M::Provenance>,
471     ) -> InterpResult<'tcx, Immediate<M::Provenance>> {
472         Ok(*try_validation!(
473             self.ecx.read_immediate_raw(op, /*force*/ true),
474             self.path,
475             err_unsup!(ReadPointerAsBytes) => { "(potentially part of) a pointer" } expected { "plain (non-pointer) bytes" },
476         ).unwrap())
477     }
478
479     /// Check if this is a value of primitive type, and if yes check the validity of the value
480     /// at that type.  Return `true` if the type is indeed primitive.
481     fn try_visit_primitive(
482         &mut self,
483         value: &OpTy<'tcx, M::Provenance>,
484     ) -> InterpResult<'tcx, bool> {
485         // Go over all the primitive types
486         let ty = value.layout.ty;
487         match ty.kind() {
488             ty::Bool => {
489                 let value = self.read_scalar(value)?;
490                 try_validation!(
491                     value.to_bool(),
492                     self.path,
493                     err_ub!(InvalidBool(..)) | err_ub!(InvalidUninitBytes(None)) =>
494                         { "{:x}", value } expected { "a boolean" },
495                 );
496                 Ok(true)
497             }
498             ty::Char => {
499                 let value = self.read_scalar(value)?;
500                 try_validation!(
501                     value.to_char(),
502                     self.path,
503                     err_ub!(InvalidChar(..)) | err_ub!(InvalidUninitBytes(None)) =>
504                         { "{:x}", value } expected { "a valid unicode scalar value (in `0..=0x10FFFF` but not in `0xD800..=0xDFFF`)" },
505                 );
506                 Ok(true)
507             }
508             ty::Float(_) | ty::Int(_) | ty::Uint(_) => {
509                 let value = self.read_scalar(value)?;
510                 // NOTE: Keep this in sync with the array optimization for int/float
511                 // types below!
512                 if M::enforce_number_init(self.ecx) {
513                     try_validation!(
514                         value.check_init(),
515                         self.path,
516                         err_ub!(InvalidUninitBytes(..)) =>
517                             { "{:x}", value } expected { "initialized bytes" }
518                     );
519                 }
520                 // As a special exception we *do* match on a `Scalar` here, since we truly want
521                 // to know its underlying representation (and *not* cast it to an integer).
522                 let is_ptr = value.check_init().map_or(false, |v| matches!(v, Scalar::Ptr(..)));
523                 if is_ptr {
524                     throw_validation_failure!(self.path,
525                         { "{:x}", value } expected { "plain (non-pointer) bytes" }
526                     )
527                 }
528                 Ok(true)
529             }
530             ty::RawPtr(..) => {
531                 // We are conservative with uninit for integers, but try to
532                 // actually enforce the strict rules for raw pointers (mostly because
533                 // that lets us re-use `ref_to_mplace`).
534                 let place = try_validation!(
535                     self.ecx.read_immediate(value).and_then(|ref i| self.ecx.ref_to_mplace(i)),
536                     self.path,
537                     err_ub!(InvalidUninitBytes(None)) => { "uninitialized raw pointer" },
538                     err_unsup!(ReadPointerAsBytes) => { "part of a pointer" } expected { "a proper pointer or integer value" },
539                 );
540                 if place.layout.is_unsized() {
541                     self.check_wide_ptr_meta(place.meta, place.layout)?;
542                 }
543                 Ok(true)
544             }
545             ty::Ref(_, ty, mutbl) => {
546                 if matches!(self.ctfe_mode, Some(CtfeValidationMode::Const { .. }))
547                     && *mutbl == hir::Mutability::Mut
548                 {
549                     // A mutable reference inside a const? That does not seem right (except if it is
550                     // a ZST).
551                     let layout = self.ecx.layout_of(*ty)?;
552                     if !layout.is_zst() {
553                         throw_validation_failure!(self.path, { "mutable reference in a `const`" });
554                     }
555                 }
556                 self.check_safe_pointer(value, "reference")?;
557                 Ok(true)
558             }
559             ty::FnPtr(_sig) => {
560                 let value = try_validation!(
561                     self.ecx.read_scalar(value).and_then(|v| v.check_init()),
562                     self.path,
563                     err_unsup!(ReadPointerAsBytes) => { "part of a pointer" } expected { "a proper pointer or integer value" },
564                     err_ub!(InvalidUninitBytes(None)) => { "uninitialized bytes" } expected { "a proper pointer or integer value" },
565                 );
566
567                 // If we check references recursively, also check that this points to a function.
568                 if let Some(_) = self.ref_tracking {
569                     let ptr = value.to_pointer(self.ecx)?;
570                     let _fn = try_validation!(
571                         self.ecx.get_ptr_fn(ptr),
572                         self.path,
573                         err_ub!(DanglingIntPointer(..)) |
574                         err_ub!(InvalidFunctionPointer(..)) =>
575                             { "{ptr}" } expected { "a function pointer" },
576                     );
577                     // FIXME: Check if the signature matches
578                 } else {
579                     // Otherwise (for standalone Miri), we have to still check it to be non-null.
580                     if self.ecx.scalar_may_be_null(value)? {
581                         throw_validation_failure!(self.path, { "a null function pointer" });
582                     }
583                 }
584                 Ok(true)
585             }
586             ty::Never => throw_validation_failure!(self.path, { "a value of the never type `!`" }),
587             ty::Foreign(..) | ty::FnDef(..) => {
588                 // Nothing to check.
589                 Ok(true)
590             }
591             // The above should be all the primitive types. The rest is compound, we
592             // check them by visiting their fields/variants.
593             ty::Adt(..)
594             | ty::Tuple(..)
595             | ty::Array(..)
596             | ty::Slice(..)
597             | ty::Str
598             | ty::Dynamic(..)
599             | ty::Closure(..)
600             | ty::Generator(..) => Ok(false),
601             // Some types only occur during typechecking, they have no layout.
602             // We should not see them here and we could not check them anyway.
603             ty::Error(_)
604             | ty::Infer(..)
605             | ty::Placeholder(..)
606             | ty::Bound(..)
607             | ty::Param(..)
608             | ty::Opaque(..)
609             | ty::Projection(..)
610             | ty::GeneratorWitness(..) => bug!("Encountered invalid type {:?}", ty),
611         }
612     }
613
614     fn visit_scalar(
615         &mut self,
616         scalar: ScalarMaybeUninit<M::Provenance>,
617         scalar_layout: ScalarAbi,
618     ) -> InterpResult<'tcx> {
619         // We check `is_full_range` in a slightly complicated way because *if* we are checking
620         // number validity, then we want to ensure that `Scalar::Initialized` is indeed initialized,
621         // i.e. that we go over the `check_init` below.
622         let size = scalar_layout.size(self.ecx);
623         let is_full_range = match scalar_layout {
624             ScalarAbi::Initialized { .. } => {
625                 if M::enforce_number_init(self.ecx) {
626                     false // not "full" since uninit is not accepted
627                 } else {
628                     scalar_layout.is_always_valid(self.ecx)
629                 }
630             }
631             ScalarAbi::Union { .. } => true,
632         };
633         if is_full_range {
634             // Nothing to check. Cruciall we don't even `read_scalar` until here, since that would
635             // fail for `Union` scalars!
636             return Ok(());
637         }
638         // We have something to check: it must at least be initialized.
639         let valid_range = scalar_layout.valid_range(self.ecx);
640         let WrappingRange { start, end } = valid_range;
641         let max_value = size.unsigned_int_max();
642         assert!(end <= max_value);
643         let value = try_validation!(
644             scalar.check_init(),
645             self.path,
646             err_ub!(InvalidUninitBytes(None)) => { "{:x}", scalar }
647                 expected { "something {}", wrapping_range_format(valid_range, max_value) },
648         );
649         let bits = match value.try_to_int() {
650             Ok(int) => int.assert_bits(size),
651             Err(_) => {
652                 // So this is a pointer then, and casting to an int failed.
653                 // Can only happen during CTFE.
654                 // We support 2 kinds of ranges here: full range, and excluding zero.
655                 if start == 1 && end == max_value {
656                     // Only null is the niche.  So make sure the ptr is NOT null.
657                     if self.ecx.scalar_may_be_null(value)? {
658                         throw_validation_failure!(self.path,
659                             { "a potentially null pointer" }
660                             expected {
661                                 "something that cannot possibly fail to be {}",
662                                 wrapping_range_format(valid_range, max_value)
663                             }
664                         )
665                     } else {
666                         return Ok(());
667                     }
668                 } else if scalar_layout.is_always_valid(self.ecx) {
669                     // Easy. (This is reachable if `enforce_number_validity` is set.)
670                     return Ok(());
671                 } else {
672                     // Conservatively, we reject, because the pointer *could* have a bad
673                     // value.
674                     throw_validation_failure!(self.path,
675                         { "a pointer" }
676                         expected {
677                             "something that cannot possibly fail to be {}",
678                             wrapping_range_format(valid_range, max_value)
679                         }
680                     )
681                 }
682             }
683         };
684         // Now compare.
685         if valid_range.contains(bits) {
686             Ok(())
687         } else {
688             throw_validation_failure!(self.path,
689                 { "{}", bits }
690                 expected { "something {}", wrapping_range_format(valid_range, max_value) }
691             )
692         }
693     }
694 }
695
696 impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValueVisitor<'mir, 'tcx, M>
697     for ValidityVisitor<'rt, 'mir, 'tcx, M>
698 {
699     type V = OpTy<'tcx, M::Provenance>;
700
701     #[inline(always)]
702     fn ecx(&self) -> &InterpCx<'mir, 'tcx, M> {
703         &self.ecx
704     }
705
706     fn read_discriminant(
707         &mut self,
708         op: &OpTy<'tcx, M::Provenance>,
709     ) -> InterpResult<'tcx, VariantIdx> {
710         self.with_elem(PathElem::EnumTag, move |this| {
711             Ok(try_validation!(
712                 this.ecx.read_discriminant(op),
713                 this.path,
714                 err_ub!(InvalidTag(val)) =>
715                     { "{:x}", val } expected { "a valid enum tag" },
716                 err_ub!(InvalidUninitBytes(None)) =>
717                     { "uninitialized bytes" } expected { "a valid enum tag" },
718                 err_unsup!(ReadPointerAsBytes) =>
719                     { "a pointer" } expected { "a valid enum tag" },
720             )
721             .1)
722         })
723     }
724
725     #[inline]
726     fn visit_field(
727         &mut self,
728         old_op: &OpTy<'tcx, M::Provenance>,
729         field: usize,
730         new_op: &OpTy<'tcx, M::Provenance>,
731     ) -> InterpResult<'tcx> {
732         let elem = self.aggregate_field_path_elem(old_op.layout, field);
733         self.with_elem(elem, move |this| this.visit_value(new_op))
734     }
735
736     #[inline]
737     fn visit_variant(
738         &mut self,
739         old_op: &OpTy<'tcx, M::Provenance>,
740         variant_id: VariantIdx,
741         new_op: &OpTy<'tcx, M::Provenance>,
742     ) -> InterpResult<'tcx> {
743         let name = match old_op.layout.ty.kind() {
744             ty::Adt(adt, _) => PathElem::Variant(adt.variant(variant_id).name),
745             // Generators also have variants
746             ty::Generator(..) => PathElem::GeneratorState(variant_id),
747             _ => bug!("Unexpected type with variant: {:?}", old_op.layout.ty),
748         };
749         self.with_elem(name, move |this| this.visit_value(new_op))
750     }
751
752     #[inline(always)]
753     fn visit_union(
754         &mut self,
755         op: &OpTy<'tcx, M::Provenance>,
756         _fields: NonZeroUsize,
757     ) -> InterpResult<'tcx> {
758         // Special check preventing `UnsafeCell` inside unions in the inner part of constants.
759         if matches!(self.ctfe_mode, Some(CtfeValidationMode::Const { inner: true, .. })) {
760             if !op.layout.ty.is_freeze(self.ecx.tcx.at(DUMMY_SP), self.ecx.param_env) {
761                 throw_validation_failure!(self.path, { "`UnsafeCell` in a `const`" });
762             }
763         }
764         Ok(())
765     }
766
767     #[inline]
768     fn visit_box(&mut self, op: &OpTy<'tcx, M::Provenance>) -> InterpResult<'tcx> {
769         self.check_safe_pointer(op, "box")?;
770         Ok(())
771     }
772
773     #[inline]
774     fn visit_value(&mut self, op: &OpTy<'tcx, M::Provenance>) -> InterpResult<'tcx> {
775         trace!("visit_value: {:?}, {:?}", *op, op.layout);
776
777         // Check primitive types -- the leaves of our recursive descent.
778         if self.try_visit_primitive(op)? {
779             return Ok(());
780         }
781
782         // Special check preventing `UnsafeCell` in the inner part of constants
783         if let Some(def) = op.layout.ty.ty_adt_def() {
784             if matches!(self.ctfe_mode, Some(CtfeValidationMode::Const { inner: true, .. }))
785                 && def.is_unsafe_cell()
786             {
787                 throw_validation_failure!(self.path, { "`UnsafeCell` in a `const`" });
788             }
789         }
790
791         // Recursively walk the value at its type.
792         self.walk_value(op)?;
793
794         // *After* all of this, check the ABI.  We need to check the ABI to handle
795         // types like `NonNull` where the `Scalar` info is more restrictive than what
796         // the fields say (`rustc_layout_scalar_valid_range_start`).
797         // But in most cases, this will just propagate what the fields say,
798         // and then we want the error to point at the field -- so, first recurse,
799         // then check ABI.
800         //
801         // FIXME: We could avoid some redundant checks here. For newtypes wrapping
802         // scalars, we do the same check on every "level" (e.g., first we check
803         // MyNewtype and then the scalar in there).
804         match op.layout.abi {
805             Abi::Uninhabited => {
806                 throw_validation_failure!(self.path,
807                     { "a value of uninhabited type {:?}", op.layout.ty }
808                 );
809             }
810             Abi::Scalar(scalar_layout) => {
811                 // We use a 'forced' read because we always need a `Immediate` here
812                 // and treating "partially uninit" as "fully uninit" is fine for us.
813                 let scalar = self.read_immediate_forced(op)?.to_scalar_or_uninit();
814                 self.visit_scalar(scalar, scalar_layout)?;
815             }
816             Abi::ScalarPair(a_layout, b_layout) => {
817                 // There is no `rustc_layout_scalar_valid_range_start` for pairs, so
818                 // we would validate these things as we descend into the fields,
819                 // but that can miss bugs in layout computation. Layout computation
820                 // is subtle due to enums having ScalarPair layout, where one field
821                 // is the discriminant.
822                 if cfg!(debug_assertions) {
823                     // We use a 'forced' read because we always need a `Immediate` here
824                     // and treating "partially uninit" as "fully uninit" is fine for us.
825                     let (a, b) = self.read_immediate_forced(op)?.to_scalar_or_uninit_pair();
826                     self.visit_scalar(a, a_layout)?;
827                     self.visit_scalar(b, b_layout)?;
828                 }
829             }
830             Abi::Vector { .. } => {
831                 // No checks here, we assume layout computation gets this right.
832                 // (This is harder to check since Miri does not represent these as `Immediate`. We
833                 // also cannot use field projections since this might be a newtype around a vector.)
834             }
835             Abi::Aggregate { .. } => {
836                 // Nothing to do.
837             }
838         }
839
840         Ok(())
841     }
842
843     fn visit_aggregate(
844         &mut self,
845         op: &OpTy<'tcx, M::Provenance>,
846         fields: impl Iterator<Item = InterpResult<'tcx, Self::V>>,
847     ) -> InterpResult<'tcx> {
848         match op.layout.ty.kind() {
849             ty::Str => {
850                 let mplace = op.assert_mem_place(); // strings are unsized and hence never immediate
851                 let len = mplace.len(self.ecx)?;
852                 try_validation!(
853                     self.ecx.read_bytes_ptr(mplace.ptr, Size::from_bytes(len)),
854                     self.path,
855                     err_ub!(InvalidUninitBytes(..)) => { "uninitialized data in `str`" },
856                     err_unsup!(ReadPointerAsBytes) => { "a pointer in `str`" },
857                 );
858             }
859             ty::Array(tys, ..) | ty::Slice(tys)
860                 // This optimization applies for types that can hold arbitrary bytes (such as
861                 // integer and floating point types) or for structs or tuples with no fields.
862                 // FIXME(wesleywiser) This logic could be extended further to arbitrary structs
863                 // or tuples made up of integer/floating point types or inhabited ZSTs with no
864                 // padding.
865                 if matches!(tys.kind(), ty::Int(..) | ty::Uint(..) | ty::Float(..))
866                 =>
867             {
868                 // Optimized handling for arrays of integer/float type.
869
870                 // This is the length of the array/slice.
871                 let len = op.len(self.ecx)?;
872                 // This is the element type size.
873                 let layout = self.ecx.layout_of(*tys)?;
874                 // This is the size in bytes of the whole array. (This checks for overflow.)
875                 let size = layout.size * len;
876                 // If the size is 0, there is nothing to check.
877                 // (`size` can only be 0 of `len` is 0, and empty arrays are always valid.)
878                 if size == Size::ZERO {
879                     return Ok(());
880                 }
881                 // Now that we definitely have a non-ZST array, we know it lives in memory.
882                 let mplace = match op.try_as_mplace() {
883                     Ok(mplace) => mplace,
884                     Err(imm) => match *imm {
885                         Immediate::Uninit =>
886                             throw_validation_failure!(self.path, { "uninitialized bytes" }),
887                         Immediate::Scalar(..) | Immediate::ScalarPair(..) =>
888                             bug!("arrays/slices can never have Scalar/ScalarPair layout"),
889                     }
890                 };
891
892                 // Optimization: we just check the entire range at once.
893                 // NOTE: Keep this in sync with the handling of integer and float
894                 // types above, in `visit_primitive`.
895                 // In run-time mode, we accept pointers in here.  This is actually more
896                 // permissive than a per-element check would be, e.g., we accept
897                 // a &[u8] that contains a pointer even though bytewise checking would
898                 // reject it.  However, that's good: We don't inherently want
899                 // to reject those pointers, we just do not have the machinery to
900                 // talk about parts of a pointer.
901                 // We also accept uninit, for consistency with the slow path.
902                 let alloc = self.ecx.get_ptr_alloc(mplace.ptr, size, mplace.align)?.expect("we already excluded size 0");
903
904                 match alloc.check_bytes(
905                     alloc_range(Size::ZERO, size),
906                     /*allow_uninit*/ !M::enforce_number_init(self.ecx),
907                     /*allow_ptr*/ false,
908                 ) {
909                     // In the happy case, we needn't check anything else.
910                     Ok(()) => {}
911                     // Some error happened, try to provide a more detailed description.
912                     Err(err) => {
913                         // For some errors we might be able to provide extra information.
914                         // (This custom logic does not fit the `try_validation!` macro.)
915                         match err.kind() {
916                             err_ub!(InvalidUninitBytes(Some((_alloc_id, access)))) => {
917                                 // Some byte was uninitialized, determine which
918                                 // element that byte belongs to so we can
919                                 // provide an index.
920                                 let i = usize::try_from(
921                                     access.uninit.start.bytes() / layout.size.bytes(),
922                                 )
923                                 .unwrap();
924                                 self.path.push(PathElem::ArrayElem(i));
925
926                                 throw_validation_failure!(self.path, { "uninitialized bytes" })
927                             }
928                             err_unsup!(ReadPointerAsBytes) => {
929                                 throw_validation_failure!(self.path, { "a pointer" } expected { "plain (non-pointer) bytes" })
930                             }
931
932                             // Propagate upwards (that will also check for unexpected errors).
933                             _ => return Err(err),
934                         }
935                     }
936                 }
937             }
938             // Fast path for arrays and slices of ZSTs. We only need to check a single ZST element
939             // of an array and not all of them, because there's only a single value of a specific
940             // ZST type, so either validation fails for all elements or none.
941             ty::Array(tys, ..) | ty::Slice(tys) if self.ecx.layout_of(*tys)?.is_zst() => {
942                 // Validate just the first element (if any).
943                 self.walk_aggregate(op, fields.take(1))?
944             }
945             _ => {
946                 self.walk_aggregate(op, fields)? // default handler
947             }
948         }
949         Ok(())
950     }
951 }
952
953 impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
954     fn validate_operand_internal(
955         &self,
956         op: &OpTy<'tcx, M::Provenance>,
957         path: Vec<PathElem>,
958         ref_tracking: Option<&mut RefTracking<MPlaceTy<'tcx, M::Provenance>, Vec<PathElem>>>,
959         ctfe_mode: Option<CtfeValidationMode>,
960     ) -> InterpResult<'tcx> {
961         trace!("validate_operand_internal: {:?}, {:?}", *op, op.layout.ty);
962
963         // Construct a visitor
964         let mut visitor = ValidityVisitor { path, ref_tracking, ctfe_mode, ecx: self };
965
966         // Run it.
967         match visitor.visit_value(&op) {
968             Ok(()) => Ok(()),
969             // Pass through validation failures.
970             Err(err) if matches!(err.kind(), err_ub!(ValidationFailure { .. })) => Err(err),
971             // Also pass through InvalidProgram, those just indicate that we could not
972             // validate and each caller will know best what to do with them.
973             Err(err) if matches!(err.kind(), InterpError::InvalidProgram(_)) => Err(err),
974             // Avoid other errors as those do not show *where* in the value the issue lies.
975             Err(err) => {
976                 err.print_backtrace();
977                 bug!("Unexpected error during validation: {}", err);
978             }
979         }
980     }
981
982     /// This function checks the data at `op` to be const-valid.
983     /// `op` is assumed to cover valid memory if it is an indirect operand.
984     /// It will error if the bits at the destination do not match the ones described by the layout.
985     ///
986     /// `ref_tracking` is used to record references that we encounter so that they
987     /// can be checked recursively by an outside driving loop.
988     ///
989     /// `constant` controls whether this must satisfy the rules for constants:
990     /// - no pointers to statics.
991     /// - no `UnsafeCell` or non-ZST `&mut`.
992     #[inline(always)]
993     pub fn const_validate_operand(
994         &self,
995         op: &OpTy<'tcx, M::Provenance>,
996         path: Vec<PathElem>,
997         ref_tracking: &mut RefTracking<MPlaceTy<'tcx, M::Provenance>, Vec<PathElem>>,
998         ctfe_mode: CtfeValidationMode,
999     ) -> InterpResult<'tcx> {
1000         self.validate_operand_internal(op, path, Some(ref_tracking), Some(ctfe_mode))
1001     }
1002
1003     /// This function checks the data at `op` to be runtime-valid.
1004     /// `op` is assumed to cover valid memory if it is an indirect operand.
1005     /// It will error if the bits at the destination do not match the ones described by the layout.
1006     #[inline(always)]
1007     pub fn validate_operand(&self, op: &OpTy<'tcx, M::Provenance>) -> InterpResult<'tcx> {
1008         self.validate_operand_internal(op, vec![], None, None)
1009     }
1010 }