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