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::convert::TryFrom;
9 use std::num::NonZeroUsize;
10 use std::ops::RangeInclusive;
12 use rustc_data_structures::fx::FxHashSet;
14 use rustc_middle::mir::interpret::{InterpError, InterpErrorInfo};
16 use rustc_middle::ty::layout::TyAndLayout;
17 use rustc_span::symbol::{sym, Symbol};
18 use rustc_target::abi::{Abi, LayoutOf, Scalar, VariantIdx, Variants};
23 CheckInAllocMsg, GlobalAlloc, InterpCx, InterpResult, MPlaceTy, Machine, MemPlaceMeta, OpTy,
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();
33 if !where_.is_empty() {
35 write_path(&mut msg, where_);
38 msg.push_str(", but expected ");
39 write!(&mut msg, $($expected_fmt),+).unwrap();
41 throw_ub!(ValidationFailure(msg))
45 /// If $e throws an error matching the pattern, throw a validation failure.
46 /// Other errors are passed back to the caller, unchanged -- and if they reach the root of
47 /// the visitor, we make sure only validation errors and `InvalidProgram` errors are left.
48 /// This lets you use the patterns as a kind of validation whitelist, asserting which errors
49 /// can possibly happen:
52 /// let v = try_validation!(some_fn(), some_path, {
53 /// Foo | Bar | Baz => { "some failure" },
57 /// An additional expected parameter can also be added to the failure message:
60 /// let v = try_validation!(some_fn(), some_path, {
61 /// Foo | Bar | Baz => { "some failure" } expected { "something that wasn't a failure" },
65 /// An additional nicety is that both parameters actually take format args, so you can just write
66 /// the format string in directly:
69 /// let v = try_validation!(some_fn(), some_path, {
70 /// Foo | Bar | Baz => { "{:?}", some_failure } expected { "{}", expected_value },
74 macro_rules! try_validation {
75 ($e:expr, $where:expr,
76 $( $( $p:pat )|+ => { $( $what_fmt:expr ),+ } $( expected { $( $expected_fmt:expr ),+ } )? ),+ $(,)?
80 // We catch the error and turn it into a validation failure. We are okay with
81 // allocation here as this can only slow down builds that fail anyway.
82 $( $( Err(InterpErrorInfo { kind: $p, .. }) )|+ =>
83 throw_validation_failure!(
85 { $( $what_fmt ),+ } $( expected { $( $expected_fmt ),+ } )?
88 #[allow(unreachable_patterns)]
89 Err(e) => Err::<!, _>(e)?,
94 /// We want to show a nice path to the invalid field for diagnostics,
95 /// but avoid string operations in the happy case where no error happens.
96 /// So we track a `Vec<PathElem>` where `PathElem` contains all the data we
97 /// need to later print something for the user.
98 #[derive(Copy, Clone, Debug)]
102 GeneratorState(VariantIdx),
112 /// State for tracking recursive validation of references
113 pub struct RefTracking<T, PATH = ()> {
114 pub seen: FxHashSet<T>,
115 pub todo: Vec<(T, PATH)>,
118 impl<T: Copy + Eq + Hash + std::fmt::Debug, PATH: Default> RefTracking<T, PATH> {
119 pub fn empty() -> Self {
120 RefTracking { seen: FxHashSet::default(), todo: vec![] }
122 pub fn new(op: T) -> Self {
123 let mut ref_tracking_for_consts =
124 RefTracking { seen: FxHashSet::default(), todo: vec![(op, PATH::default())] };
125 ref_tracking_for_consts.seen.insert(op);
126 ref_tracking_for_consts
129 pub fn track(&mut self, op: T, path: impl FnOnce() -> PATH) {
130 if self.seen.insert(op) {
131 trace!("Recursing below ptr {:#?}", op);
133 // Remember to come back to this later.
134 self.todo.push((op, path));
140 fn write_path(out: &mut String, path: &Vec<PathElem>) {
141 use self::PathElem::*;
143 for elem in path.iter() {
145 Field(name) => write!(out, ".{}", name),
146 EnumTag => write!(out, ".<enum-tag>"),
147 Variant(name) => write!(out, ".<enum-variant({})>", name),
148 GeneratorTag => write!(out, ".<generator-tag>"),
149 GeneratorState(idx) => write!(out, ".<generator-state({})>", idx.index()),
150 CapturedVar(name) => write!(out, ".<captured-var({})>", name),
151 TupleElem(idx) => write!(out, ".{}", idx),
152 ArrayElem(idx) => write!(out, "[{}]", idx),
153 // `.<deref>` does not match Rust syntax, but it is more readable for long paths -- and
154 // some of the other items here also are not Rust syntax. Actually we can't
155 // even use the usual syntax because we are just showing the projections,
157 Deref => write!(out, ".<deref>"),
158 DynDowncast => write!(out, ".<dyn-downcast>"),
164 // Test if a range that wraps at overflow contains `test`
165 fn wrapping_range_contains(r: &RangeInclusive<u128>, test: u128) -> bool {
166 let (lo, hi) = r.clone().into_inner();
169 (..=hi).contains(&test) || (lo..).contains(&test)
176 // Formats such that a sentence like "expected something {}" to mean
177 // "expected something <in the given range>" makes sense.
178 fn wrapping_range_format(r: &RangeInclusive<u128>, max_hi: u128) -> String {
179 let (lo, hi) = r.clone().into_inner();
180 assert!(hi <= max_hi);
182 format!("less or equal to {}, or greater or equal to {}", hi, lo)
184 format!("equal to {}", lo)
186 assert!(hi < max_hi, "should not be printing if the range covers everything");
187 format!("less or equal to {}", hi)
188 } else if hi == max_hi {
189 assert!(lo > 0, "should not be printing if the range covers everything");
190 format!("greater or equal to {}", lo)
192 format!("in the range {:?}", r)
196 struct ValidityVisitor<'rt, 'mir, 'tcx, M: Machine<'mir, 'tcx>> {
197 /// The `path` may be pushed to, but the part that is present when a function
198 /// starts must not be changed! `visit_fields` and `visit_array` rely on
199 /// this stack discipline.
201 ref_tracking_for_consts:
202 Option<&'rt mut RefTracking<MPlaceTy<'tcx, M::PointerTag>, Vec<PathElem>>>,
203 may_ref_to_static: bool,
204 ecx: &'rt InterpCx<'mir, 'tcx, M>,
207 impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValidityVisitor<'rt, 'mir, 'tcx, M> {
208 fn aggregate_field_path_elem(&mut self, layout: TyAndLayout<'tcx>, field: usize) -> PathElem {
209 // First, check if we are projecting to a variant.
210 match layout.variants {
211 Variants::Multiple { discr_index, .. } => {
212 if discr_index == field {
213 return match layout.ty.kind {
214 ty::Adt(def, ..) if def.is_enum() => PathElem::EnumTag,
215 ty::Generator(..) => PathElem::GeneratorTag,
216 _ => bug!("non-variant type {:?}", layout.ty),
220 Variants::Single { .. } => {}
223 // Now we know we are projecting to a field, so figure out which one.
224 match layout.ty.kind {
225 // generators and closures.
226 ty::Closure(def_id, _) | ty::Generator(def_id, _, _) => {
228 if let Some(def_id) = def_id.as_local() {
229 let tables = self.ecx.tcx.typeck_tables_of(def_id);
230 if let Some(upvars) = tables.upvar_list.get(&def_id.to_def_id()) {
231 // Sometimes the index is beyond the number of upvars (seen
233 if let Some((&var_hir_id, _)) = upvars.get_index(field) {
234 let node = self.ecx.tcx.hir().get(var_hir_id);
235 if let hir::Node::Binding(pat) = node {
236 if let hir::PatKind::Binding(_, _, ident, _) = pat.kind {
237 name = Some(ident.name);
244 PathElem::CapturedVar(name.unwrap_or_else(|| {
245 // Fall back to showing the field index.
251 ty::Tuple(_) => PathElem::TupleElem(field),
254 ty::Adt(def, ..) if def.is_enum() => {
255 // we might be projecting *to* a variant, or to a field *in* a variant.
256 match layout.variants {
257 Variants::Single { index } => {
259 PathElem::Field(def.variants[index].fields[field].ident.name)
261 Variants::Multiple { .. } => bug!("we handled variants above"),
266 ty::Adt(def, _) => PathElem::Field(def.non_enum_variant().fields[field].ident.name),
269 ty::Array(..) | ty::Slice(..) => PathElem::ArrayElem(field),
272 ty::Dynamic(..) => PathElem::DynDowncast,
274 // nothing else has an aggregate layout
275 _ => bug!("aggregate_field_path_elem: got non-aggregate type {:?}", layout.ty),
281 new_op: OpTy<'tcx, M::PointerTag>,
283 ) -> InterpResult<'tcx> {
284 // Remember the old state
285 let path_len = self.path.len();
287 self.path.push(elem);
288 self.visit_value(new_op)?;
290 self.path.truncate(path_len);
294 fn check_wide_ptr_meta(
296 meta: MemPlaceMeta<M::PointerTag>,
297 pointee: TyAndLayout<'tcx>,
298 ) -> InterpResult<'tcx> {
299 let tail = self.ecx.tcx.struct_tail_erasing_lifetimes(pointee.ty, self.ecx.param_env);
302 let vtable = meta.unwrap_meta();
303 // Direct call to `check_ptr_access_align` checks alignment even on CTFE machines.
305 self.ecx.memory.check_ptr_access_align(
307 3 * self.ecx.tcx.data_layout.pointer_size, // drop, size, align
308 Some(self.ecx.tcx.data_layout.pointer_align.abi),
309 CheckInAllocMsg::InboundsTest,
312 err_ub!(DanglingIntPointer(..)) |
313 err_ub!(PointerUseAfterFree(..)) |
314 err_unsup!(ReadBytesAsPointer) =>
315 { "dangling vtable pointer in wide pointer" },
316 err_ub!(AlignmentCheckFailed { .. }) =>
317 { "unaligned vtable pointer in wide pointer" },
318 err_ub!(PointerOutOfBounds { .. }) =>
319 { "too small vtable" },
322 self.ecx.read_drop_type_from_vtable(vtable),
324 err_ub!(DanglingIntPointer(..)) |
325 err_ub!(InvalidFunctionPointer(..)) |
326 err_unsup!(ReadBytesAsPointer) =>
327 { "invalid drop function pointer in vtable (not pointing to a function)" },
328 err_ub!(InvalidDropFn(..)) =>
329 { "invalid drop function pointer in vtable (function has incompatible signature)" },
332 self.ecx.read_size_and_align_from_vtable(vtable),
334 err_unsup!(ReadPointerAsBytes) => { "invalid size or align in vtable" },
336 // FIXME: More checks for the vtable.
338 ty::Slice(..) | ty::Str => {
339 let _len = try_validation!(
340 meta.unwrap_meta().to_machine_usize(self.ecx),
342 err_unsup!(ReadPointerAsBytes) => { "non-integer slice length in wide pointer" },
344 // We do not check that `len * elem_size <= isize::MAX`:
345 // that is only required for references, and there it falls out of the
346 // "dereferenceable" check performed by Stacked Borrows.
349 // Unsized, but not wide.
351 _ => bug!("Unexpected unsized type tail: {:?}", tail),
357 /// Check a reference or `Box`.
358 fn check_safe_pointer(
360 value: OpTy<'tcx, M::PointerTag>,
362 ) -> InterpResult<'tcx> {
363 let value = self.ecx.read_immediate(value)?;
364 // Handle wide pointers.
365 // Check metadata early, for better diagnostics
366 let place = try_validation!(
367 self.ecx.ref_to_mplace(value),
369 err_ub!(InvalidUninitBytes(..)) => { "uninitialized {}", kind },
371 if place.layout.is_unsized() {
372 self.check_wide_ptr_meta(place.meta, place.layout)?;
374 // Make sure this is dereferenceable and all.
375 let size_and_align = try_validation!(
376 self.ecx.size_and_align_of(place.meta, place.layout),
378 err_ub!(InvalidMeta(msg)) => { "invalid {} metadata: {}", kind, msg },
380 let (size, align) = size_and_align
381 // for the purpose of validity, consider foreign types to have
382 // alignment and size determined by the layout (size will be 0,
383 // alignment should take attributes into account).
384 .unwrap_or_else(|| (place.layout.size, place.layout.align.abi));
385 // Direct call to `check_ptr_access_align` checks alignment even on CTFE machines.
386 let ptr: Option<_> = try_validation!(
387 self.ecx.memory.check_ptr_access_align(
391 CheckInAllocMsg::InboundsTest,
394 err_ub!(AlignmentCheckFailed { required, has }) =>
396 "an unaligned {} (required {} byte alignment but found {})",
401 err_ub!(DanglingIntPointer(0, _)) =>
402 { "a NULL {}", kind },
403 err_ub!(DanglingIntPointer(i, _)) =>
404 { "a dangling {} (address 0x{:x} is unallocated)", kind, i },
405 err_ub!(PointerOutOfBounds { .. }) =>
406 { "a dangling {} (going beyond the bounds of its allocation)", kind },
407 err_unsup!(ReadBytesAsPointer) =>
408 { "a dangling {} (created from integer)", kind },
409 // This cannot happen during const-eval (because interning already detects
410 // dangling pointers), but it can happen in Miri.
411 err_ub!(PointerUseAfterFree(..)) =>
412 { "a dangling {} (use-after-free)", kind },
414 // Recursive checking
415 if let Some(ref mut ref_tracking) = self.ref_tracking_for_consts {
416 if let Some(ptr) = ptr {
418 // Skip validation entirely for some external statics
419 let alloc_kind = self.ecx.tcx.alloc_map.lock().get(ptr.alloc_id);
420 if let Some(GlobalAlloc::Static(did)) = alloc_kind {
421 // See const_eval::machine::MemoryExtra::can_access_statics for why
422 // this check is so important.
423 // This check is reachable when the const just referenced the static,
424 // but never read it (so we never entered `before_access_global`).
425 // We also need to do it here instead of going on to avoid running
426 // into the `before_access_global` check during validation.
427 if !self.may_ref_to_static && self.ecx.tcx.is_static(did) {
428 throw_validation_failure!(self.path,
429 { "a {} pointing to a static variable", kind }
432 // `extern static` cannot be validated as they have no body.
433 // FIXME: Statics from other crates are also skipped.
434 // They might be checked at a different type, but for now we
435 // want to avoid recursing too deeply. We might miss const-invalid data,
436 // but things are still sound otherwise (in particular re: consts
437 // referring to statics).
438 if !did.is_local() || self.ecx.tcx.is_foreign_item(did) {
443 // Proceed recursively even for ZST, no reason to skip them!
444 // `!` is a ZST and we want to validate it.
445 // Normalize before handing `place` to tracking because that will
446 // check for duplicates.
447 let place = if size.bytes() > 0 {
448 self.ecx.force_mplace_ptr(place).expect("we already bounds-checked")
452 let path = &self.path;
453 ref_tracking.track(place, || {
454 // We need to clone the path anyway, make sure it gets created
455 // with enough space for the additional `Deref`.
456 let mut new_path = Vec::with_capacity(path.len() + 1);
457 new_path.clone_from(path);
458 new_path.push(PathElem::Deref);
465 /// Check if this is a value of primitive type, and if yes check the validity of the value
466 /// at that type. Return `true` if the type is indeed primitive.
467 fn try_visit_primitive(
469 value: OpTy<'tcx, M::PointerTag>,
470 ) -> InterpResult<'tcx, bool> {
471 // Go over all the primitive types
472 let ty = value.layout.ty;
475 let value = self.ecx.read_scalar(value)?;
479 err_ub!(InvalidBool(..)) => { "{}", value } expected { "a boolean" },
484 let value = self.ecx.read_scalar(value)?;
488 err_ub!(InvalidChar(..)) => { "{}", value } expected { "a valid unicode codepoint" },
492 ty::Float(_) | ty::Int(_) | ty::Uint(_) => {
493 let value = self.ecx.read_scalar(value)?;
494 // NOTE: Keep this in sync with the array optimization for int/float
496 if self.ref_tracking_for_consts.is_some() {
497 // Integers/floats in CTFE: Must be scalar bits, pointers are dangerous
498 let is_bits = value.not_undef().map_or(false, |v| v.is_bits());
500 throw_validation_failure!(self.path,
501 { "{}", value } expected { "initialized plain (non-pointer) bytes" }
505 // At run-time, for now, we accept *anything* for these types, including
506 // undef. We should fix that, but let's start low.
511 // We are conservative with undef for integers, but try to
512 // actually enforce the strict rules for raw pointers (mostly because
513 // that lets us re-use `ref_to_mplace`).
514 let place = try_validation!(
515 self.ecx.ref_to_mplace(self.ecx.read_immediate(value)?),
517 err_ub!(InvalidUninitBytes(..)) => { "uninitialized raw pointer" },
519 if place.layout.is_unsized() {
520 self.check_wide_ptr_meta(place.meta, place.layout)?;
525 self.check_safe_pointer(value, "reference")?;
528 ty::Adt(def, ..) if def.is_box() => {
529 self.check_safe_pointer(value, "box")?;
533 let value = self.ecx.read_scalar(value)?;
534 let _fn = try_validation!(
535 value.not_undef().and_then(|ptr| self.ecx.memory.get_fn(ptr)),
537 err_ub!(DanglingIntPointer(..)) |
538 err_ub!(InvalidFunctionPointer(..)) |
539 err_unsup!(ReadBytesAsPointer) =>
540 { "{}", value } expected { "a function pointer" },
542 // FIXME: Check if the signature matches
545 ty::Never => throw_validation_failure!(self.path, { "a value of the never type `!`" }),
546 ty::Foreign(..) | ty::FnDef(..) => {
550 // The above should be all the (inhabited) primitive types. The rest is compound, we
551 // check them by visiting their fields/variants.
552 // (`Str` UTF-8 check happens in `visit_aggregate`, too.)
560 | ty::Generator(..) => Ok(false),
561 // Some types only occur during typechecking, they have no layout.
562 // We should not see them here and we could not check them anyway.
565 | ty::Placeholder(..)
569 | ty::UnnormalizedProjection(..)
571 | ty::GeneratorWitness(..) => bug!("Encountered invalid type {:?}", ty),
577 op: OpTy<'tcx, M::PointerTag>,
578 scalar_layout: &Scalar,
579 ) -> InterpResult<'tcx> {
580 let value = self.ecx.read_scalar(op)?;
581 let valid_range = &scalar_layout.valid_range;
582 let (lo, hi) = valid_range.clone().into_inner();
583 // Determine the allowed range
584 // `max_hi` is as big as the size fits
585 let max_hi = u128::MAX >> (128 - op.layout.size.bits());
586 assert!(hi <= max_hi);
587 // We could also write `(hi + 1) % (max_hi + 1) == lo` but `max_hi + 1` overflows for `u128`
588 if (lo == 0 && hi == max_hi) || (hi + 1 == lo) {
592 // At least one value is excluded. Get the bits.
593 let value = try_validation!(
596 err_ub!(InvalidUninitBytes(..)) => { "{}", value }
597 expected { "something {}", wrapping_range_format(valid_range, max_hi) },
599 let bits = match value.to_bits_or_ptr(op.layout.size, self.ecx) {
601 if lo == 1 && hi == max_hi {
602 // Only NULL is the niche. So make sure the ptr is NOT NULL.
603 if self.ecx.memory.ptr_may_be_null(ptr) {
604 throw_validation_failure!(self.path,
605 { "a potentially NULL pointer" }
607 "something that cannot possibly fail to be {}",
608 wrapping_range_format(valid_range, max_hi)
614 // Conservatively, we reject, because the pointer *could* have a bad
616 throw_validation_failure!(self.path,
619 "something that cannot possibly fail to be {}",
620 wrapping_range_format(valid_range, max_hi)
627 // Now compare. This is slightly subtle because this is a special "wrap-around" range.
628 if wrapping_range_contains(&valid_range, bits) {
631 throw_validation_failure!(self.path,
633 expected { "something {}", wrapping_range_format(valid_range, max_hi) }
639 impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValueVisitor<'mir, 'tcx, M>
640 for ValidityVisitor<'rt, 'mir, 'tcx, M>
642 type V = OpTy<'tcx, M::PointerTag>;
645 fn ecx(&self) -> &InterpCx<'mir, 'tcx, M> {
652 old_op: OpTy<'tcx, M::PointerTag>,
654 new_op: OpTy<'tcx, M::PointerTag>,
655 ) -> InterpResult<'tcx> {
656 let elem = self.aggregate_field_path_elem(old_op.layout, field);
657 self.visit_elem(new_op, elem)
663 old_op: OpTy<'tcx, M::PointerTag>,
664 variant_id: VariantIdx,
665 new_op: OpTy<'tcx, M::PointerTag>,
666 ) -> InterpResult<'tcx> {
667 let name = match old_op.layout.ty.kind {
668 ty::Adt(adt, _) => PathElem::Variant(adt.variants[variant_id].ident.name),
669 // Generators also have variants
670 ty::Generator(..) => PathElem::GeneratorState(variant_id),
671 _ => bug!("Unexpected type with variant: {:?}", old_op.layout.ty),
673 self.visit_elem(new_op, name)
679 _op: OpTy<'tcx, M::PointerTag>,
680 _fields: NonZeroUsize,
681 ) -> InterpResult<'tcx> {
686 fn visit_value(&mut self, op: OpTy<'tcx, M::PointerTag>) -> InterpResult<'tcx> {
687 trace!("visit_value: {:?}, {:?}", *op, op.layout);
689 // Check primitive types -- the leafs of our recursive descend.
690 if self.try_visit_primitive(op)? {
693 // Sanity check: `builtin_deref` does not know any pointers that are not primitive.
694 assert!(op.layout.ty.builtin_deref(true).is_none());
696 // Recursively walk the type. Translate some possible errors to something nicer.
700 err_ub!(InvalidDiscriminant(val)) =>
701 { "{}", val } expected { "a valid enum discriminant" },
702 err_unsup!(ReadPointerAsBytes) =>
703 { "a pointer" } expected { "plain (non-pointer) bytes" },
706 // *After* all of this, check the ABI. We need to check the ABI to handle
707 // types like `NonNull` where the `Scalar` info is more restrictive than what
708 // the fields say (`rustc_layout_scalar_valid_range_start`).
709 // But in most cases, this will just propagate what the fields say,
710 // and then we want the error to point at the field -- so, first recurse,
713 // FIXME: We could avoid some redundant checks here. For newtypes wrapping
714 // scalars, we do the same check on every "level" (e.g., first we check
715 // MyNewtype and then the scalar in there).
716 match op.layout.abi {
717 Abi::Uninhabited => {
718 throw_validation_failure!(self.path,
719 { "a value of uninhabited type {:?}", op.layout.ty }
722 Abi::Scalar(ref scalar_layout) => {
723 self.visit_scalar(op, scalar_layout)?;
725 Abi::ScalarPair { .. } | Abi::Vector { .. } => {
726 // These have fields that we already visited above, so we already checked
727 // all their scalar-level restrictions.
728 // There is also no equivalent to `rustc_layout_scalar_valid_range_start`
729 // that would make skipping them here an issue.
731 Abi::Aggregate { .. } => {
741 op: OpTy<'tcx, M::PointerTag>,
742 fields: impl Iterator<Item = InterpResult<'tcx, Self::V>>,
743 ) -> InterpResult<'tcx> {
744 match op.layout.ty.kind {
746 let mplace = op.assert_mem_place(self.ecx); // strings are never immediate
748 self.ecx.read_str(mplace),
750 err_ub!(InvalidStr(..)) => { "uninitialized or non-UTF-8 data in str" },
753 ty::Array(tys, ..) | ty::Slice(tys)
755 // This optimization applies for types that can hold arbitrary bytes (such as
756 // integer and floating point types) or for structs or tuples with no fields.
757 // FIXME(wesleywiser) This logic could be extended further to arbitrary structs
758 // or tuples made up of integer/floating point types or inhabited ZSTs with no
761 ty::Int(..) | ty::Uint(..) | ty::Float(..) => true,
766 // Optimized handling for arrays of integer/float type.
768 // Arrays cannot be immediate, slices are never immediate.
769 let mplace = op.assert_mem_place(self.ecx);
770 // This is the length of the array/slice.
771 let len = mplace.len(self.ecx)?;
772 // Zero length slices have nothing to be checked.
776 // This is the element type size.
777 let layout = self.ecx.layout_of(tys)?;
778 // This is the size in bytes of the whole array. (This checks for overflow.)
779 let size = layout.size * len;
780 // Size is not 0, get a pointer.
781 let ptr = self.ecx.force_ptr(mplace.ptr)?;
783 // Optimization: we just check the entire range at once.
784 // NOTE: Keep this in sync with the handling of integer and float
785 // types above, in `visit_primitive`.
786 // In run-time mode, we accept pointers in here. This is actually more
787 // permissive than a per-element check would be, e.g., we accept
788 // an &[u8] that contains a pointer even though bytewise checking would
789 // reject it. However, that's good: We don't inherently want
790 // to reject those pointers, we just do not have the machinery to
791 // talk about parts of a pointer.
792 // We also accept undef, for consistency with the slow path.
793 match self.ecx.memory.get_raw(ptr.alloc_id)?.check_bytes(
797 /*allow_ptr_and_undef*/ self.ref_tracking_for_consts.is_none(),
799 // In the happy case, we needn't check anything else.
801 // Some error happened, try to provide a more detailed description.
803 // For some errors we might be able to provide extra information.
804 // (This custom logic does not fit the `try_validation!` macro.)
806 err_ub!(InvalidUninitBytes(Some(ptr))) => {
807 // Some byte was uninitialized, determine which
808 // element that byte belongs to so we can
810 let i = usize::try_from(ptr.offset.bytes() / layout.size.bytes())
812 self.path.push(PathElem::ArrayElem(i));
814 throw_validation_failure!(self.path, { "uninitialized bytes" })
816 // Propagate upwards (that will also check for unexpected errors).
817 _ => return Err(err),
822 // Fast path for arrays and slices of ZSTs. We only need to check a single ZST element
823 // of an array and not all of them, because there's only a single value of a specific
824 // ZST type, so either validation fails for all elements or none.
825 ty::Array(tys, ..) | ty::Slice(tys) if self.ecx.layout_of(tys)?.is_zst() => {
826 // Validate just the first element
827 self.walk_aggregate(op, fields.take(1))?
830 self.walk_aggregate(op, fields)? // default handler
837 impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
838 fn validate_operand_internal(
840 op: OpTy<'tcx, M::PointerTag>,
842 ref_tracking_for_consts: Option<
843 &mut RefTracking<MPlaceTy<'tcx, M::PointerTag>, Vec<PathElem>>,
845 may_ref_to_static: bool,
846 ) -> InterpResult<'tcx> {
847 trace!("validate_operand_internal: {:?}, {:?}", *op, op.layout.ty);
849 // Construct a visitor
851 ValidityVisitor { path, ref_tracking_for_consts, may_ref_to_static, ecx: self };
853 // Try to cast to ptr *once* instead of all the time.
854 let op = self.force_op_ptr(op).unwrap_or(op);
857 match visitor.visit_value(op) {
859 // Pass through validation failures.
860 Err(err) if matches!(err.kind, err_ub!(ValidationFailure { .. })) => Err(err),
861 // Also pass through InvalidProgram, those just indicate that we could not
862 // validate and each caller will know best what to do with them.
863 Err(err) if matches!(err.kind, InterpError::InvalidProgram(_)) => Err(err),
864 // Avoid other errors as those do not show *where* in the value the issue lies.
866 err.print_backtrace();
867 bug!("Unexpected error during validation: {}", err);
872 /// This function checks the data at `op` to be const-valid.
873 /// `op` is assumed to cover valid memory if it is an indirect operand.
874 /// It will error if the bits at the destination do not match the ones described by the layout.
876 /// `ref_tracking` is used to record references that we encounter so that they
877 /// can be checked recursively by an outside driving loop.
879 /// `may_ref_to_static` controls whether references are allowed to point to statics.
881 pub fn const_validate_operand(
883 op: OpTy<'tcx, M::PointerTag>,
885 ref_tracking: &mut RefTracking<MPlaceTy<'tcx, M::PointerTag>, Vec<PathElem>>,
886 may_ref_to_static: bool,
887 ) -> InterpResult<'tcx> {
888 self.validate_operand_internal(op, path, Some(ref_tracking), may_ref_to_static)
891 /// This function checks the data at `op` to be runtime-valid.
892 /// `op` is assumed to cover valid memory if it is an indirect operand.
893 /// It will error if the bits at the destination do not match the ones described by the layout.
895 pub fn validate_operand(&self, op: OpTy<'tcx, M::PointerTag>) -> InterpResult<'tcx> {
896 self.validate_operand_internal(op, vec![], None, false)