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
7 use std::fmt::{Display, Write};
8 use std::num::NonZeroUsize;
10 use either::{Left, Right};
12 use rustc_ast::Mutability;
13 use rustc_data_structures::fx::FxHashSet;
15 use rustc_middle::mir::interpret::InterpError;
17 use rustc_middle::ty::layout::{LayoutOf, TyAndLayout};
18 use rustc_span::symbol::{sym, Symbol};
19 use rustc_target::abi::{Abi, Scalar as ScalarAbi, Size, VariantIdx, Variants, WrappingRange};
23 // for the validation errors
24 use super::UndefinedBehaviorInfo::*;
26 CheckInAllocMsg, GlobalAlloc, ImmTy, Immediate, InterpCx, InterpResult, MPlaceTy, Machine,
27 MemPlaceMeta, OpTy, Scalar, ValueVisitor,
30 macro_rules! throw_validation_failure {
31 ($where:expr, { $( $what_fmt:expr ),+ } $( expected { $( $expected_fmt:expr ),+ } )?) => {{
32 let mut msg = String::new();
33 msg.push_str("encountered ");
34 write!(&mut msg, $($what_fmt),+).unwrap();
36 msg.push_str(", but expected ");
37 write!(&mut msg, $($expected_fmt),+).unwrap();
39 let path = rustc_middle::ty::print::with_no_trimmed_paths!({
41 if !where_.is_empty() {
42 let mut path = String::new();
43 write_path(&mut path, where_);
49 throw_ub!(ValidationFailure { path, msg })
53 /// If $e throws an error matching the pattern, throw a validation failure.
54 /// Other errors are passed back to the caller, unchanged -- and if they reach the root of
55 /// the visitor, we make sure only validation errors and `InvalidProgram` errors are left.
56 /// This lets you use the patterns as a kind of validation list, asserting which errors
57 /// can possibly happen:
59 /// ```ignore(illustrative)
60 /// let v = try_validation!(some_fn(), some_path, {
61 /// Foo | Bar | Baz => { "some failure" },
65 /// The patterns must be of type `UndefinedBehaviorInfo`.
66 /// An additional expected parameter can also be added to the failure message:
68 /// ```ignore(illustrative)
69 /// let v = try_validation!(some_fn(), some_path, {
70 /// Foo | Bar | Baz => { "some failure" } expected { "something that wasn't a failure" },
74 /// An additional nicety is that both parameters actually take format args, so you can just write
75 /// the format string in directly:
77 /// ```ignore(illustrative)
78 /// let v = try_validation!(some_fn(), some_path, {
79 /// Foo | Bar | Baz => { "{:?}", some_failure } expected { "{}", expected_value },
83 macro_rules! try_validation {
84 ($e:expr, $where:expr,
85 $( $( $p:pat_param )|+ => { $( $what_fmt:expr ),+ } $( expected { $( $expected_fmt:expr ),+ } )? ),+ $(,)?
89 // We catch the error and turn it into a validation failure. We are okay with
90 // allocation here as this can only slow down builds that fail anyway.
91 Err(e) => match e.kind() {
93 InterpError::UndefinedBehavior($($p)|+) =>
94 throw_validation_failure!(
96 { $( $what_fmt ),+ } $( expected { $( $expected_fmt ),+ } )?
99 #[allow(unreachable_patterns)]
100 _ => Err::<!, _>(e)?,
106 /// We want to show a nice path to the invalid field for diagnostics,
107 /// but avoid string operations in the happy case where no error happens.
108 /// So we track a `Vec<PathElem>` where `PathElem` contains all the data we
109 /// need to later print something for the user.
110 #[derive(Copy, Clone, Debug)]
114 GeneratorState(VariantIdx),
124 /// Extra things to check for during validation of CTFE results.
125 pub enum CtfeValidationMode {
126 /// Regular validation, nothing special happening.
128 /// Validation of a `const`.
129 /// `inner` says if this is an inner, indirect allocation (as opposed to the top-level const
130 /// allocation). Being an inner allocation makes a difference because the top-level allocation
131 /// of a `const` is copied for each use, but the inner allocations are implicitly shared.
132 /// `allow_static_ptrs` says if pointers to statics are permitted (which is the case for promoteds in statics).
133 Const { inner: bool, allow_static_ptrs: bool },
136 /// State for tracking recursive validation of references
137 pub struct RefTracking<T, PATH = ()> {
138 pub seen: FxHashSet<T>,
139 pub todo: Vec<(T, PATH)>,
142 impl<T: Copy + Eq + Hash + std::fmt::Debug, PATH: Default> RefTracking<T, PATH> {
143 pub fn empty() -> Self {
144 RefTracking { seen: FxHashSet::default(), todo: vec![] }
146 pub fn new(op: T) -> Self {
147 let mut ref_tracking_for_consts =
148 RefTracking { seen: FxHashSet::default(), todo: vec![(op, PATH::default())] };
149 ref_tracking_for_consts.seen.insert(op);
150 ref_tracking_for_consts
153 pub fn track(&mut self, op: T, path: impl FnOnce() -> PATH) {
154 if self.seen.insert(op) {
155 trace!("Recursing below ptr {:#?}", op);
157 // Remember to come back to this later.
158 self.todo.push((op, path));
164 fn write_path(out: &mut String, path: &[PathElem]) {
165 use self::PathElem::*;
167 for elem in path.iter() {
169 Field(name) => write!(out, ".{}", name),
170 EnumTag => write!(out, ".<enum-tag>"),
171 Variant(name) => write!(out, ".<enum-variant({})>", name),
172 GeneratorTag => write!(out, ".<generator-tag>"),
173 GeneratorState(idx) => write!(out, ".<generator-state({})>", idx.index()),
174 CapturedVar(name) => write!(out, ".<captured-var({})>", name),
175 TupleElem(idx) => write!(out, ".{}", idx),
176 ArrayElem(idx) => write!(out, "[{}]", idx),
177 // `.<deref>` does not match Rust syntax, but it is more readable for long paths -- and
178 // some of the other items here also are not Rust syntax. Actually we can't
179 // even use the usual syntax because we are just showing the projections,
181 Deref => write!(out, ".<deref>"),
182 DynDowncast => write!(out, ".<dyn-downcast>"),
188 // Formats such that a sentence like "expected something {}" to mean
189 // "expected something <in the given range>" makes sense.
190 fn wrapping_range_format(r: WrappingRange, max_hi: u128) -> String {
191 let WrappingRange { start: lo, end: hi } = r;
192 assert!(hi <= max_hi);
194 format!("less or equal to {}, or greater or equal to {}", hi, lo)
196 format!("equal to {}", lo)
198 assert!(hi < max_hi, "should not be printing if the range covers everything");
199 format!("less or equal to {}", hi)
200 } else if hi == max_hi {
201 assert!(lo > 0, "should not be printing if the range covers everything");
202 format!("greater or equal to {}", lo)
204 format!("in the range {:?}", r)
208 struct ValidityVisitor<'rt, 'mir, 'tcx, M: Machine<'mir, 'tcx>> {
209 /// The `path` may be pushed to, but the part that is present when a function
210 /// starts must not be changed! `visit_fields` and `visit_array` rely on
211 /// this stack discipline.
213 ref_tracking: Option<&'rt mut RefTracking<MPlaceTy<'tcx, M::Provenance>, Vec<PathElem>>>,
214 /// `None` indicates this is not validating for CTFE (but for runtime).
215 ctfe_mode: Option<CtfeValidationMode>,
216 ecx: &'rt InterpCx<'mir, 'tcx, M>,
219 impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValidityVisitor<'rt, 'mir, 'tcx, M> {
220 fn aggregate_field_path_elem(&mut self, layout: TyAndLayout<'tcx>, field: usize) -> PathElem {
221 // First, check if we are projecting to a variant.
222 match layout.variants {
223 Variants::Multiple { tag_field, .. } => {
224 if tag_field == field {
225 return match layout.ty.kind() {
226 ty::Adt(def, ..) if def.is_enum() => PathElem::EnumTag,
227 ty::Generator(..) => PathElem::GeneratorTag,
228 _ => bug!("non-variant type {:?}", layout.ty),
232 Variants::Single { .. } => {}
235 // Now we know we are projecting to a field, so figure out which one.
236 match layout.ty.kind() {
237 // generators and closures.
238 ty::Closure(def_id, _) | ty::Generator(def_id, _, _) => {
240 // FIXME this should be more descriptive i.e. CapturePlace instead of CapturedVar
241 // https://github.com/rust-lang/project-rfc-2229/issues/46
242 if let Some(local_def_id) = def_id.as_local() {
243 let tables = self.ecx.tcx.typeck(local_def_id);
244 if let Some(captured_place) =
245 tables.closure_min_captures_flattened(local_def_id).nth(field)
247 // Sometimes the index is beyond the number of upvars (seen
249 let var_hir_id = captured_place.get_root_variable();
250 let node = self.ecx.tcx.hir().get(var_hir_id);
251 if let hir::Node::Pat(pat) = node {
252 if let hir::PatKind::Binding(_, _, ident, _) = pat.kind {
253 name = Some(ident.name);
259 PathElem::CapturedVar(name.unwrap_or_else(|| {
260 // Fall back to showing the field index.
266 ty::Tuple(_) => PathElem::TupleElem(field),
269 ty::Adt(def, ..) if def.is_enum() => {
270 // we might be projecting *to* a variant, or to a field *in* a variant.
271 match layout.variants {
272 Variants::Single { index } => {
274 PathElem::Field(def.variant(index).fields[field].name)
276 Variants::Multiple { .. } => bug!("we handled variants above"),
281 ty::Adt(def, _) => PathElem::Field(def.non_enum_variant().fields[field].name),
284 ty::Array(..) | ty::Slice(..) => PathElem::ArrayElem(field),
287 ty::Dynamic(..) => PathElem::DynDowncast,
289 // nothing else has an aggregate layout
290 _ => bug!("aggregate_field_path_elem: got non-aggregate type {:?}", layout.ty),
297 f: impl FnOnce(&mut Self) -> InterpResult<'tcx, R>,
298 ) -> InterpResult<'tcx, R> {
299 // Remember the old state
300 let path_len = self.path.len();
301 // Record new element
302 self.path.push(elem);
306 self.path.truncate(path_len);
313 op: &OpTy<'tcx, M::Provenance>,
314 expected: impl Display,
315 ) -> InterpResult<'tcx, ImmTy<'tcx, M::Provenance>> {
317 self.ecx.read_immediate(op),
319 InvalidUninitBytes(None) => { "uninitialized memory" } expected { "{expected}" }
325 op: &OpTy<'tcx, M::Provenance>,
326 expected: impl Display,
327 ) -> InterpResult<'tcx, Scalar<M::Provenance>> {
328 Ok(self.read_immediate(op, expected)?.to_scalar())
331 fn check_wide_ptr_meta(
333 meta: MemPlaceMeta<M::Provenance>,
334 pointee: TyAndLayout<'tcx>,
335 ) -> InterpResult<'tcx> {
336 let tail = self.ecx.tcx.struct_tail_erasing_lifetimes(pointee.ty, self.ecx.param_env);
339 let vtable = meta.unwrap_meta().to_pointer(self.ecx)?;
340 // Make sure it is a genuine vtable pointer.
341 let (_ty, _trait) = try_validation!(
342 self.ecx.get_ptr_vtable(vtable),
344 DanglingIntPointer(..) |
345 InvalidVTablePointer(..) =>
346 { "{vtable}" } expected { "a vtable pointer" },
348 // FIXME: check if the type/trait match what ty::Dynamic says?
350 ty::Slice(..) | ty::Str => {
351 let _len = meta.unwrap_meta().to_machine_usize(self.ecx)?;
352 // We do not check that `len * elem_size <= isize::MAX`:
353 // that is only required for references, and there it falls out of the
354 // "dereferenceable" check performed by Stacked Borrows.
357 // Unsized, but not wide.
359 _ => bug!("Unexpected unsized type tail: {:?}", tail),
365 /// Check a reference or `Box`.
366 fn check_safe_pointer(
368 value: &OpTy<'tcx, M::Provenance>,
370 ) -> InterpResult<'tcx> {
372 self.ecx.ref_to_mplace(&self.read_immediate(value, format_args!("a {kind}"))?)?;
373 // Handle wide pointers.
374 // Check metadata early, for better diagnostics
375 if place.layout.is_unsized() {
376 self.check_wide_ptr_meta(place.meta, place.layout)?;
378 // Make sure this is dereferenceable and all.
379 let size_and_align = try_validation!(
380 self.ecx.size_and_align_of_mplace(&place),
382 InvalidMeta(msg) => { "invalid {} metadata: {}", kind, msg },
384 let (size, align) = size_and_align
385 // for the purpose of validity, consider foreign types to have
386 // alignment and size determined by the layout (size will be 0,
387 // alignment should take attributes into account).
388 .unwrap_or_else(|| (place.layout.size, place.layout.align.abi));
389 // Direct call to `check_ptr_access_align` checks alignment even on CTFE machines.
391 self.ecx.check_ptr_access_align(
395 CheckInAllocMsg::InboundsTest, // will anyway be replaced by validity message
398 AlignmentCheckFailed { required, has } =>
400 "an unaligned {kind} (required {} byte alignment but found {})",
404 DanglingIntPointer(0, _) =>
406 DanglingIntPointer(i, _) =>
407 { "a dangling {kind} (address {i:#x} is unallocated)" },
408 PointerOutOfBounds { .. } =>
409 { "a dangling {kind} (going beyond the bounds of its allocation)" },
410 // This cannot happen during const-eval (because interning already detects
411 // dangling pointers), but it can happen in Miri.
412 PointerUseAfterFree(..) =>
413 { "a dangling {kind} (use-after-free)" },
415 // Do not allow pointers to uninhabited types.
416 if place.layout.abi.is_uninhabited() {
417 throw_validation_failure!(self.path,
418 { "a {kind} pointing to uninhabited type {}", place.layout.ty }
421 // Recursive checking
422 if let Some(ref_tracking) = self.ref_tracking.as_deref_mut() {
423 // Proceed recursively even for ZST, no reason to skip them!
424 // `!` is a ZST and we want to validate it.
425 if let Ok((alloc_id, _offset, _prov)) = self.ecx.ptr_try_get_alloc_id(place.ptr) {
426 // Let's see what kind of memory this points to.
427 let alloc_kind = self.ecx.tcx.try_get_global_alloc(alloc_id);
429 Some(GlobalAlloc::Static(did)) => {
430 // Special handling for pointers to statics (irrespective of their type).
431 assert!(!self.ecx.tcx.is_thread_local_static(did));
432 assert!(self.ecx.tcx.is_static(did));
435 Some(CtfeValidationMode::Const { allow_static_ptrs: false, .. })
437 // See const_eval::machine::MemoryExtra::can_access_statics for why
438 // this check is so important.
439 // This check is reachable when the const just referenced the static,
440 // but never read it (so we never entered `before_access_global`).
441 throw_validation_failure!(self.path,
442 { "a {} pointing to a static variable in a constant", kind }
445 // We skip recursively checking other statics. These statics must be sound by
446 // themselves, and the only way to get broken statics here is by using
448 // The reasons we don't check other statics is twofold. For one, in all
449 // sound cases, the static was already validated on its own, and second, we
450 // trigger cycle errors if we try to compute the value of the other static
451 // and that static refers back to us.
452 // We might miss const-invalid data,
453 // but things are still sound otherwise (in particular re: consts
454 // referring to statics).
457 Some(GlobalAlloc::Memory(alloc)) => {
458 if alloc.inner().mutability == Mutability::Mut
459 && matches!(self.ctfe_mode, Some(CtfeValidationMode::Const { .. }))
461 // This should be unreachable, but if someone manages to copy a pointer
462 // out of a `static`, then that pointer might point to mutable memory,
463 // and we would catch that here.
464 throw_validation_failure!(self.path,
465 { "a {} pointing to mutable memory in a constant", kind }
469 // Nothing to check for these.
470 None | Some(GlobalAlloc::Function(..) | GlobalAlloc::VTable(..)) => {}
473 let path = &self.path;
474 ref_tracking.track(place, || {
475 // We need to clone the path anyway, make sure it gets created
476 // with enough space for the additional `Deref`.
477 let mut new_path = Vec::with_capacity(path.len() + 1);
478 new_path.extend(path);
479 new_path.push(PathElem::Deref);
486 /// Check if this is a value of primitive type, and if yes check the validity of the value
487 /// at that type. Return `true` if the type is indeed primitive.
488 fn try_visit_primitive(
490 value: &OpTy<'tcx, M::Provenance>,
491 ) -> InterpResult<'tcx, bool> {
492 // Go over all the primitive types
493 let ty = value.layout.ty;
496 let value = self.read_scalar(value, "a boolean")?;
501 { "{:x}", value } expected { "a boolean" },
506 let value = self.read_scalar(value, "a unicode scalar value")?;
511 { "{:x}", value } expected { "a valid unicode scalar value (in `0..=0x10FFFF` but not in `0xD800..=0xDFFF`)" },
515 ty::Float(_) | ty::Int(_) | ty::Uint(_) => {
516 // NOTE: Keep this in sync with the array optimization for int/float
518 let value = self.read_scalar(
520 if matches!(ty.kind(), ty::Float(..)) {
521 "a floating point number"
526 // As a special exception we *do* match on a `Scalar` here, since we truly want
527 // to know its underlying representation (and *not* cast it to an integer).
528 if matches!(value, Scalar::Ptr(..)) {
529 throw_validation_failure!(self.path,
530 { "{:x}", value } expected { "plain (non-pointer) bytes" }
536 // We are conservative with uninit for integers, but try to
537 // actually enforce the strict rules for raw pointers (mostly because
538 // that lets us re-use `ref_to_mplace`).
540 self.ecx.ref_to_mplace(&self.read_immediate(value, "a raw pointer")?)?;
541 if place.layout.is_unsized() {
542 self.check_wide_ptr_meta(place.meta, place.layout)?;
546 ty::Ref(_, ty, mutbl) => {
547 if matches!(self.ctfe_mode, Some(CtfeValidationMode::Const { .. }))
548 && *mutbl == Mutability::Mut
550 // A mutable reference inside a const? That does not seem right (except if it is
552 let layout = self.ecx.layout_of(*ty)?;
553 if !layout.is_zst() {
554 throw_validation_failure!(self.path, { "mutable reference in a `const`" });
557 self.check_safe_pointer(value, "reference")?;
561 let value = self.read_scalar(value, "a function pointer")?;
563 // If we check references recursively, also check that this points to a function.
564 if let Some(_) = self.ref_tracking {
565 let ptr = value.to_pointer(self.ecx)?;
566 let _fn = try_validation!(
567 self.ecx.get_ptr_fn(ptr),
569 DanglingIntPointer(..) |
570 InvalidFunctionPointer(..) =>
571 { "{ptr}" } expected { "a function pointer" },
573 // FIXME: Check if the signature matches
575 // Otherwise (for standalone Miri), we have to still check it to be non-null.
576 if self.ecx.scalar_may_be_null(value)? {
577 throw_validation_failure!(self.path, { "a null function pointer" });
582 ty::Never => throw_validation_failure!(self.path, { "a value of the never type `!`" }),
583 ty::Foreign(..) | ty::FnDef(..) => {
587 // The above should be all the primitive types. The rest is compound, we
588 // check them by visiting their fields/variants.
596 | ty::Generator(..) => Ok(false),
597 // Some types only occur during typechecking, they have no layout.
598 // We should not see them here and we could not check them anyway.
601 | ty::Placeholder(..)
605 | ty::GeneratorWitness(..) => bug!("Encountered invalid type {:?}", ty),
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),
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" }
631 "something that cannot possibly fail to be {}",
632 wrapping_range_format(valid_range, max_value)
638 } else if scalar_layout.is_always_valid(self.ecx) {
639 // Easy. (This is reachable if `enforce_number_validity` is set.)
642 // Conservatively, we reject, because the pointer *could* have a bad
644 throw_validation_failure!(self.path,
647 "something that cannot possibly fail to be {}",
648 wrapping_range_format(valid_range, max_value)
655 if valid_range.contains(bits) {
658 throw_validation_failure!(self.path,
660 expected { "something {}", wrapping_range_format(valid_range, max_value) }
666 impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValueVisitor<'mir, 'tcx, M>
667 for ValidityVisitor<'rt, 'mir, 'tcx, M>
669 type V = OpTy<'tcx, M::Provenance>;
672 fn ecx(&self) -> &InterpCx<'mir, 'tcx, M> {
676 fn read_discriminant(
678 op: &OpTy<'tcx, M::Provenance>,
679 ) -> InterpResult<'tcx, VariantIdx> {
680 self.with_elem(PathElem::EnumTag, move |this| {
682 this.ecx.read_discriminant(op),
685 { "{:x}", val } expected { "a valid enum tag" },
686 InvalidUninitBytes(None) =>
687 { "uninitialized bytes" } expected { "a valid enum tag" },
696 old_op: &OpTy<'tcx, M::Provenance>,
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))
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),
717 self.with_elem(name, move |this| this.visit_value(new_op))
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`" });
736 fn visit_box(&mut self, op: &OpTy<'tcx, M::Provenance>) -> InterpResult<'tcx> {
737 self.check_safe_pointer(op, "box")?;
742 fn visit_value(&mut self, op: &OpTy<'tcx, M::Provenance>) -> InterpResult<'tcx> {
743 trace!("visit_value: {:?}, {:?}", *op, op.layout);
745 // Check primitive types -- the leaves of our recursive descent.
746 if self.try_visit_primitive(op)? {
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()
755 throw_validation_failure!(self.path, { "`UnsafeCell` in a `const`" });
759 // Recursively walk the value at its type.
760 self.walk_value(op)?;
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,
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 }
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)?;
785 Abi::ScalarPair(a_layout, b_layout) => {
786 // We can only proceed if *both* scalars need to be initialized.
787 // FIXME: find a way to also check ScalarPair when one side can be uninit but
788 // the other must be init.
789 if !a_layout.is_uninit_valid() && !b_layout.is_uninit_valid() {
791 self.read_immediate(op, "initiailized scalar value")?.to_scalar_pair();
792 self.visit_scalar(a, a_layout)?;
793 self.visit_scalar(b, b_layout)?;
796 Abi::Vector { .. } => {
797 // No checks here, we assume layout computation gets this right.
798 // (This is harder to check since Miri does not represent these as `Immediate`. We
799 // also cannot use field projections since this might be a newtype around a vector.)
801 Abi::Aggregate { .. } => {
811 op: &OpTy<'tcx, M::Provenance>,
812 fields: impl Iterator<Item = InterpResult<'tcx, Self::V>>,
813 ) -> InterpResult<'tcx> {
814 match op.layout.ty.kind() {
816 let mplace = op.assert_mem_place(); // strings are unsized and hence never immediate
817 let len = mplace.len(self.ecx)?;
819 self.ecx.read_bytes_ptr_strip_provenance(mplace.ptr, Size::from_bytes(len)),
821 InvalidUninitBytes(..) => { "uninitialized data in `str`" },
824 ty::Array(tys, ..) | ty::Slice(tys)
825 // This optimization applies for types that can hold arbitrary bytes (such as
826 // integer and floating point types) or for structs or tuples with no fields.
827 // FIXME(wesleywiser) This logic could be extended further to arbitrary structs
828 // or tuples made up of integer/floating point types or inhabited ZSTs with no
830 if matches!(tys.kind(), ty::Int(..) | ty::Uint(..) | ty::Float(..))
833 // Optimized handling for arrays of integer/float type.
835 // This is the length of the array/slice.
836 let len = op.len(self.ecx)?;
837 // This is the element type size.
838 let layout = self.ecx.layout_of(*tys)?;
839 // This is the size in bytes of the whole array. (This checks for overflow.)
840 let size = layout.size * len;
841 // If the size is 0, there is nothing to check.
842 // (`size` can only be 0 of `len` is 0, and empty arrays are always valid.)
843 if size == Size::ZERO {
846 // Now that we definitely have a non-ZST array, we know it lives in memory.
847 let mplace = match op.as_mplace_or_imm() {
848 Left(mplace) => mplace,
849 Right(imm) => match *imm {
851 throw_validation_failure!(self.path, { "uninitialized bytes" }),
852 Immediate::Scalar(..) | Immediate::ScalarPair(..) =>
853 bug!("arrays/slices can never have Scalar/ScalarPair layout"),
857 // Optimization: we just check the entire range at once.
858 // NOTE: Keep this in sync with the handling of integer and float
859 // types above, in `visit_primitive`.
860 // In run-time mode, we accept pointers in here. This is actually more
861 // permissive than a per-element check would be, e.g., we accept
862 // a &[u8] that contains a pointer even though bytewise checking would
863 // reject it. However, that's good: We don't inherently want
864 // to reject those pointers, we just do not have the machinery to
865 // talk about parts of a pointer.
866 // We also accept uninit, for consistency with the slow path.
867 let alloc = self.ecx.get_ptr_alloc(mplace.ptr, size, mplace.align)?.expect("we already excluded size 0");
869 match alloc.get_bytes_strip_provenance() {
870 // In the happy case, we needn't check anything else.
872 // Some error happened, try to provide a more detailed description.
874 // For some errors we might be able to provide extra information.
875 // (This custom logic does not fit the `try_validation!` macro.)
877 err_ub!(InvalidUninitBytes(Some((_alloc_id, access)))) => {
878 // Some byte was uninitialized, determine which
879 // element that byte belongs to so we can
881 let i = usize::try_from(
882 access.uninit.start.bytes() / layout.size.bytes(),
885 self.path.push(PathElem::ArrayElem(i));
887 throw_validation_failure!(self.path, { "uninitialized bytes" })
890 // Propagate upwards (that will also check for unexpected errors).
891 _ => return Err(err),
896 // Fast path for arrays and slices of ZSTs. We only need to check a single ZST element
897 // of an array and not all of them, because there's only a single value of a specific
898 // ZST type, so either validation fails for all elements or none.
899 ty::Array(tys, ..) | ty::Slice(tys) if self.ecx.layout_of(*tys)?.is_zst() => {
900 // Validate just the first element (if any).
901 self.walk_aggregate(op, fields.take(1))?
904 self.walk_aggregate(op, fields)? // default handler
911 impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
912 fn validate_operand_internal(
914 op: &OpTy<'tcx, M::Provenance>,
916 ref_tracking: Option<&mut RefTracking<MPlaceTy<'tcx, M::Provenance>, Vec<PathElem>>>,
917 ctfe_mode: Option<CtfeValidationMode>,
918 ) -> InterpResult<'tcx> {
919 trace!("validate_operand_internal: {:?}, {:?}", *op, op.layout.ty);
921 // Construct a visitor
922 let mut visitor = ValidityVisitor { path, ref_tracking, ctfe_mode, ecx: self };
925 match visitor.visit_value(&op) {
927 // Pass through validation failures.
928 Err(err) if matches!(err.kind(), err_ub!(ValidationFailure { .. })) => Err(err),
929 // Complain about any other kind of UB error -- those are bad because we'd like to
930 // report them in a way that shows *where* in the value the issue lies.
931 Err(err) if matches!(err.kind(), InterpError::UndefinedBehavior(_)) => {
932 err.print_backtrace();
933 bug!("Unexpected Undefined Behavior error during validation: {}", err);
935 // Pass through everything else.
936 Err(err) => Err(err),
940 /// This function checks the data at `op` to be const-valid.
941 /// `op` is assumed to cover valid memory if it is an indirect operand.
942 /// It will error if the bits at the destination do not match the ones described by the layout.
944 /// `ref_tracking` is used to record references that we encounter so that they
945 /// can be checked recursively by an outside driving loop.
947 /// `constant` controls whether this must satisfy the rules for constants:
948 /// - no pointers to statics.
949 /// - no `UnsafeCell` or non-ZST `&mut`.
951 pub fn const_validate_operand(
953 op: &OpTy<'tcx, M::Provenance>,
955 ref_tracking: &mut RefTracking<MPlaceTy<'tcx, M::Provenance>, Vec<PathElem>>,
956 ctfe_mode: CtfeValidationMode,
957 ) -> InterpResult<'tcx> {
958 self.validate_operand_internal(op, path, Some(ref_tracking), Some(ctfe_mode))
961 /// This function checks the data at `op` to be runtime-valid.
962 /// `op` is assumed to cover valid memory if it is an indirect operand.
963 /// It will error if the bits at the destination do not match the ones described by the layout.
965 pub fn validate_operand(&self, op: &OpTy<'tcx, M::Provenance>) -> InterpResult<'tcx> {
966 // Note that we *could* actually be in CTFE here with `-Zextra-const-ub-checks`, but it's
967 // still correct to not use `ctfe_mode`: that mode is for validation of the final constant
968 // value, it rules out things like `UnsafeCell` in awkward places. It also can make checking
969 // recurse through references which, for now, we don't want here, either.
970 self.validate_operand_internal(op, vec![], None, None)