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
8 use std::ops::RangeInclusive;
11 use rustc::ty::layout::{self, LayoutOf, TyLayout, VariantIdx};
12 use rustc_data_structures::fx::FxHashSet;
14 use rustc_span::symbol::{sym, Symbol};
19 CheckInAllocMsg, GlobalAlloc, InterpCx, InterpResult, MPlaceTy, Machine, MemPlaceMeta, OpTy,
23 macro_rules! throw_validation_failure {
24 ($what:expr, $where:expr, $details:expr) => {{
25 let mut msg = format!("encountered {}", $what);
27 if !where_.is_empty() {
29 write_path(&mut msg, where_);
31 write!(&mut msg, ", but expected {}", $details).unwrap();
32 throw_unsup!(ValidationFailure(msg))
34 ($what:expr, $where:expr) => {{
35 let mut msg = format!("encountered {}", $what);
37 if !where_.is_empty() {
39 write_path(&mut msg, where_);
41 throw_unsup!(ValidationFailure(msg))
45 macro_rules! try_validation {
46 ($e:expr, $what:expr, $where:expr, $details:expr) => {{
49 Err(_) => throw_validation_failure!($what, $where, $details),
53 ($e:expr, $what:expr, $where:expr) => {{
56 Err(_) => throw_validation_failure!($what, $where),
61 /// We want to show a nice path to the invalid field for diagnostics,
62 /// but avoid string operations in the happy case where no error happens.
63 /// So we track a `Vec<PathElem>` where `PathElem` contains all the data we
64 /// need to later print something for the user.
65 #[derive(Copy, Clone, Debug)]
69 GeneratorState(VariantIdx),
78 /// State for tracking recursive validation of references
79 pub struct RefTracking<T, PATH = ()> {
80 pub seen: FxHashSet<T>,
81 pub todo: Vec<(T, PATH)>,
84 impl<T: Copy + Eq + Hash + std::fmt::Debug, PATH: Default> RefTracking<T, PATH> {
85 pub fn empty() -> Self {
86 RefTracking { seen: FxHashSet::default(), todo: vec![] }
88 pub fn new(op: T) -> Self {
89 let mut ref_tracking_for_consts =
90 RefTracking { seen: FxHashSet::default(), todo: vec![(op, PATH::default())] };
91 ref_tracking_for_consts.seen.insert(op);
92 ref_tracking_for_consts
95 pub fn track(&mut self, op: T, path: impl FnOnce() -> PATH) {
96 if self.seen.insert(op) {
97 trace!("Recursing below ptr {:#?}", op);
99 // Remember to come back to this later.
100 self.todo.push((op, path));
106 fn write_path(out: &mut String, path: &Vec<PathElem>) {
107 use self::PathElem::*;
109 for elem in path.iter() {
111 Field(name) => write!(out, ".{}", name),
112 Variant(name) => write!(out, ".<downcast-variant({})>", name),
113 GeneratorState(idx) => write!(out, ".<generator-state({})>", idx.index()),
114 ClosureVar(name) => write!(out, ".<closure-var({})>", name),
115 TupleElem(idx) => write!(out, ".{}", idx),
116 ArrayElem(idx) => write!(out, "[{}]", idx),
117 // `.<deref>` does not match Rust syntax, but it is more readable for long paths -- and
118 // some of the other items here also are not Rust syntax. Actually we can't
119 // even use the usual syntax because we are just showing the projections,
121 Deref => write!(out, ".<deref>"),
122 Tag => write!(out, ".<enum-tag>"),
123 DynDowncast => write!(out, ".<dyn-downcast>"),
129 // Test if a range that wraps at overflow contains `test`
130 fn wrapping_range_contains(r: &RangeInclusive<u128>, test: u128) -> bool {
131 let (lo, hi) = r.clone().into_inner();
134 (..=hi).contains(&test) || (lo..).contains(&test)
141 // Formats such that a sentence like "expected something {}" to mean
142 // "expected something <in the given range>" makes sense.
143 fn wrapping_range_format(r: &RangeInclusive<u128>, max_hi: u128) -> String {
144 let (lo, hi) = r.clone().into_inner();
145 debug_assert!(hi <= max_hi);
147 format!("less or equal to {}, or greater or equal to {}", hi, lo)
149 format!("equal to {}", lo)
151 debug_assert!(hi < max_hi, "should not be printing if the range covers everything");
152 format!("less or equal to {}", hi)
153 } else if hi == max_hi {
154 debug_assert!(lo > 0, "should not be printing if the range covers everything");
155 format!("greater or equal to {}", lo)
157 format!("in the range {:?}", r)
161 struct ValidityVisitor<'rt, 'mir, 'tcx, M: Machine<'mir, 'tcx>> {
162 /// The `path` may be pushed to, but the part that is present when a function
163 /// starts must not be changed! `visit_fields` and `visit_array` rely on
164 /// this stack discipline.
166 ref_tracking_for_consts:
167 Option<&'rt mut RefTracking<MPlaceTy<'tcx, M::PointerTag>, Vec<PathElem>>>,
168 ecx: &'rt InterpCx<'mir, 'tcx, M>,
171 impl<'rt, 'mir, 'tcx, M: Machine<'mir, 'tcx>> ValidityVisitor<'rt, 'mir, 'tcx, M> {
172 fn aggregate_field_path_elem(&mut self, layout: TyLayout<'tcx>, field: usize) -> PathElem {
173 match layout.ty.kind {
174 // generators and closures.
175 ty::Closure(def_id, _) | ty::Generator(def_id, _, _) => {
177 if def_id.is_local() {
178 let tables = self.ecx.tcx.typeck_tables_of(def_id);
179 if let Some(upvars) = tables.upvar_list.get(&def_id) {
180 // Sometimes the index is beyond the number of upvars (seen
182 if let Some((&var_hir_id, _)) = upvars.get_index(field) {
183 let node = self.ecx.tcx.hir().get(var_hir_id);
184 if let hir::Node::Binding(pat) = node {
185 if let hir::PatKind::Binding(_, _, ident, _) = pat.kind {
186 name = Some(ident.name);
193 PathElem::ClosureVar(name.unwrap_or_else(|| {
194 // Fall back to showing the field index.
200 ty::Tuple(_) => PathElem::TupleElem(field),
203 ty::Adt(def, ..) if def.is_enum() => {
204 // we might be projecting *to* a variant, or to a field *in*a variant.
205 match layout.variants {
206 layout::Variants::Single { index } => {
208 PathElem::Field(def.variants[index].fields[field].ident.name)
215 ty::Adt(def, _) => PathElem::Field(def.non_enum_variant().fields[field].ident.name),
218 ty::Array(..) | ty::Slice(..) => PathElem::ArrayElem(field),
221 ty::Dynamic(..) => PathElem::DynDowncast,
223 // nothing else has an aggregate layout
224 _ => bug!("aggregate_field_path_elem: got non-aggregate type {:?}", layout.ty),
230 new_op: OpTy<'tcx, M::PointerTag>,
232 ) -> InterpResult<'tcx> {
233 // Remember the old state
234 let path_len = self.path.len();
236 self.path.push(elem);
237 self.visit_value(new_op)?;
239 self.path.truncate(path_len);
243 fn check_wide_ptr_meta(
245 meta: MemPlaceMeta<M::PointerTag>,
246 pointee: TyLayout<'tcx>,
247 ) -> InterpResult<'tcx> {
248 let tail = self.ecx.tcx.struct_tail_erasing_lifetimes(pointee.ty, self.ecx.param_env);
251 let vtable = meta.unwrap_meta();
253 self.ecx.memory.check_ptr_access(
255 3 * self.ecx.tcx.data_layout.pointer_size, // drop, size, align
256 self.ecx.tcx.data_layout.pointer_align.abi,
258 "dangling or unaligned vtable pointer in wide pointer or too small vtable",
262 self.ecx.read_drop_type_from_vtable(vtable),
263 "invalid drop fn in vtable",
267 self.ecx.read_size_and_align_from_vtable(vtable),
268 "invalid size or align in vtable",
271 // FIXME: More checks for the vtable.
273 ty::Slice(..) | ty::Str => {
274 let _len = try_validation!(
275 meta.unwrap_meta().to_machine_usize(self.ecx),
276 "non-integer slice length in wide pointer",
279 // We do not check that `len * elem_size <= isize::MAX`:
280 // that is only required for references, and there it falls out of the
281 // "dereferenceable" check performed by Stacked Borrows.
284 // Unsized, but not wide.
286 _ => bug!("Unexpected unsized type tail: {:?}", tail),
293 impl<'rt, 'mir, 'tcx, M: Machine<'mir, 'tcx>> ValueVisitor<'mir, 'tcx, M>
294 for ValidityVisitor<'rt, 'mir, 'tcx, M>
296 type V = OpTy<'tcx, M::PointerTag>;
299 fn ecx(&self) -> &InterpCx<'mir, 'tcx, M> {
306 old_op: OpTy<'tcx, M::PointerTag>,
308 new_op: OpTy<'tcx, M::PointerTag>,
309 ) -> InterpResult<'tcx> {
310 let elem = self.aggregate_field_path_elem(old_op.layout, field);
311 self.visit_elem(new_op, elem)
317 old_op: OpTy<'tcx, M::PointerTag>,
318 variant_id: VariantIdx,
319 new_op: OpTy<'tcx, M::PointerTag>,
320 ) -> InterpResult<'tcx> {
321 let name = match old_op.layout.ty.kind {
322 ty::Adt(adt, _) => PathElem::Variant(adt.variants[variant_id].ident.name),
323 // Generators also have variants
324 ty::Generator(..) => PathElem::GeneratorState(variant_id),
325 _ => bug!("Unexpected type with variant: {:?}", old_op.layout.ty),
327 self.visit_elem(new_op, name)
331 fn visit_value(&mut self, op: OpTy<'tcx, M::PointerTag>) -> InterpResult<'tcx> {
332 trace!("visit_value: {:?}, {:?}", *op, op.layout);
333 // Translate some possible errors to something nicer.
334 match self.walk_value(op) {
336 Err(err) => match err.kind {
337 err_ub!(InvalidDiscriminant(val)) => {
338 throw_validation_failure!(val, self.path, "a valid enum discriminant")
340 err_unsup!(ReadPointerAsBytes) => {
341 throw_validation_failure!("a pointer", self.path, "plain (non-pointer) bytes")
348 fn visit_primitive(&mut self, value: OpTy<'tcx, M::PointerTag>) -> InterpResult<'tcx> {
349 let value = self.ecx.read_immediate(value)?;
350 // Go over all the primitive types
351 let ty = value.layout.ty;
354 let value = value.to_scalar_or_undef();
355 try_validation!(value.to_bool(), value, self.path, "a boolean");
358 let value = value.to_scalar_or_undef();
359 try_validation!(value.to_char(), value, self.path, "a valid unicode codepoint");
361 ty::Float(_) | ty::Int(_) | ty::Uint(_) => {
362 // NOTE: Keep this in sync with the array optimization for int/float
364 let size = value.layout.size;
365 let value = value.to_scalar_or_undef();
366 if self.ref_tracking_for_consts.is_some() {
367 // Integers/floats in CTFE: Must be scalar bits, pointers are dangerous
372 "initialized plain (non-pointer) bytes"
375 // At run-time, for now, we accept *anything* for these types, including
376 // undef. We should fix that, but let's start low.
380 // We are conservative with undef for integers, but try to
381 // actually enforce our current rules for raw pointers.
383 try_validation!(self.ecx.ref_to_mplace(value), "undefined pointer", self.path);
384 if place.layout.is_unsized() {
385 self.check_wide_ptr_meta(place.meta, place.layout)?;
388 _ if ty.is_box() || ty.is_region_ptr() => {
389 // Handle wide pointers.
390 // Check metadata early, for better diagnostics
392 try_validation!(self.ecx.ref_to_mplace(value), "undefined pointer", self.path);
393 if place.layout.is_unsized() {
394 self.check_wide_ptr_meta(place.meta, place.layout)?;
396 // Make sure this is dereferenceable and all.
397 let (size, align) = self
399 .size_and_align_of(place.meta, place.layout)?
400 // for the purpose of validity, consider foreign types to have
401 // alignment and size determined by the layout (size will be 0,
402 // alignment should take attributes into account).
403 .unwrap_or_else(|| (place.layout.size, place.layout.align.abi));
404 let ptr: Option<_> = match self.ecx.memory.check_ptr_access_align(
408 CheckInAllocMsg::InboundsTest,
413 "{:?} did not pass access check for size {:?}, align {:?}",
414 place.ptr, size, align
417 err_unsup!(InvalidNullPointerUsage) => {
418 throw_validation_failure!("NULL reference", self.path)
420 err_unsup!(AlignmentCheckFailed { required, has }) => {
421 throw_validation_failure!(
423 "unaligned reference \
424 (required {} byte alignment but found {})",
431 err_unsup!(ReadBytesAsPointer) => throw_validation_failure!(
432 "dangling reference (created from integer)",
435 _ => throw_validation_failure!(
436 "dangling reference (not entirely in bounds)",
442 // Recursive checking
443 if let Some(ref mut ref_tracking) = self.ref_tracking_for_consts {
444 if let Some(ptr) = ptr {
446 // Skip validation entirely for some external statics
447 let alloc_kind = self.ecx.tcx.alloc_map.lock().get(ptr.alloc_id);
448 if let Some(GlobalAlloc::Static(did)) = alloc_kind {
449 // `extern static` cannot be validated as they have no body.
450 // FIXME: Statics from other crates are also skipped.
451 // They might be checked at a different type, but for now we
452 // want to avoid recursing too deeply. This is not sound!
453 if !did.is_local() || self.ecx.tcx.is_foreign_item(did) {
458 // Proceed recursively even for ZST, no reason to skip them!
459 // `!` is a ZST and we want to validate it.
460 // Normalize before handing `place` to tracking because that will
461 // check for duplicates.
462 let place = if size.bytes() > 0 {
463 self.ecx.force_mplace_ptr(place).expect("we already bounds-checked")
467 let path = &self.path;
468 ref_tracking.track(place, || {
469 // We need to clone the path anyway, make sure it gets created
470 // with enough space for the additional `Deref`.
471 let mut new_path = Vec::with_capacity(path.len() + 1);
472 new_path.clone_from(path);
473 new_path.push(PathElem::Deref);
479 let value = value.to_scalar_or_undef();
480 let _fn = try_validation!(
481 value.not_undef().and_then(|ptr| self.ecx.memory.get_fn(ptr)),
486 // FIXME: Check if the signature matches
488 // This should be all the primitive types
489 _ => bug!("Unexpected primitive type {}", value.layout.ty),
494 fn visit_uninhabited(&mut self) -> InterpResult<'tcx> {
495 throw_validation_failure!("a value of an uninhabited type", self.path)
500 op: OpTy<'tcx, M::PointerTag>,
501 layout: &layout::Scalar,
502 ) -> InterpResult<'tcx> {
503 let value = self.ecx.read_scalar(op)?;
504 // Determine the allowed range
505 let (lo, hi) = layout.valid_range.clone().into_inner();
506 // `max_hi` is as big as the size fits
507 let max_hi = u128::max_value() >> (128 - op.layout.size.bits());
508 assert!(hi <= max_hi);
509 // We could also write `(hi + 1) % (max_hi + 1) == lo` but `max_hi + 1` overflows for `u128`
510 if (lo == 0 && hi == max_hi) || (hi + 1 == lo) {
514 // At least one value is excluded. Get the bits.
515 let value = try_validation!(
519 format_args!("something {}", wrapping_range_format(&layout.valid_range, max_hi),)
521 let bits = match value.to_bits_or_ptr(op.layout.size, self.ecx) {
523 if lo == 1 && hi == max_hi {
524 // Only NULL is the niche. So make sure the ptr is NOT NULL.
525 if self.ecx.memory.ptr_may_be_null(ptr) {
526 throw_validation_failure!(
527 "a potentially NULL pointer",
530 "something that cannot possibly fail to be {}",
531 wrapping_range_format(&layout.valid_range, max_hi)
537 // Conservatively, we reject, because the pointer *could* have a bad
539 throw_validation_failure!(
543 "something that cannot possibly fail to be {}",
544 wrapping_range_format(&layout.valid_range, max_hi)
551 // Now compare. This is slightly subtle because this is a special "wrap-around" range.
552 if wrapping_range_contains(&layout.valid_range, bits) {
555 throw_validation_failure!(
558 format_args!("something {}", wrapping_range_format(&layout.valid_range, max_hi))
565 op: OpTy<'tcx, M::PointerTag>,
566 fields: impl Iterator<Item = InterpResult<'tcx, Self::V>>,
567 ) -> InterpResult<'tcx> {
568 match op.layout.ty.kind {
570 let mplace = op.assert_mem_place(self.ecx); // strings are never immediate
572 self.ecx.read_str(mplace),
573 "uninitialized or non-UTF-8 data in str",
577 ty::Array(tys, ..) | ty::Slice(tys)
579 // This optimization applies for types that can hold arbitrary bytes (such as
580 // integer and floating point types) or for structs or tuples with no fields.
581 // FIXME(wesleywiser) This logic could be extended further to arbitrary structs
582 // or tuples made up of integer/floating point types or inhabited ZSTs with no
585 ty::Int(..) | ty::Uint(..) | ty::Float(..) => true,
586 ty::Tuple(tys) if tys.len() == 0 => true,
588 if adt_def.is_struct() && adt_def.all_fields().next().is_none() =>
596 // Optimized handling for arrays of integer/float type.
598 // Arrays cannot be immediate, slices are never immediate.
599 let mplace = op.assert_mem_place(self.ecx);
600 // This is the length of the array/slice.
601 let len = mplace.len(self.ecx)?;
602 // Zero length slices have nothing to be checked.
606 // This is the element type size.
607 let layout = self.ecx.layout_of(tys)?;
608 // Empty tuples and fieldless structs (the only ZSTs that allow reaching this code)
609 // have no data to be checked.
613 // This is the size in bytes of the whole array.
614 let size = layout.size * len;
615 // Size is not 0, get a pointer.
616 let ptr = self.ecx.force_ptr(mplace.ptr)?;
618 // Optimization: we just check the entire range at once.
619 // NOTE: Keep this in sync with the handling of integer and float
620 // types above, in `visit_primitive`.
621 // In run-time mode, we accept pointers in here. This is actually more
622 // permissive than a per-element check would be, e.g., we accept
623 // an &[u8] that contains a pointer even though bytewise checking would
624 // reject it. However, that's good: We don't inherently want
625 // to reject those pointers, we just do not have the machinery to
626 // talk about parts of a pointer.
627 // We also accept undef, for consistency with the slow path.
628 match self.ecx.memory.get_raw(ptr.alloc_id)?.check_bytes(
632 /*allow_ptr_and_undef*/ self.ref_tracking_for_consts.is_none(),
634 // In the happy case, we needn't check anything else.
636 // Some error happened, try to provide a more detailed description.
638 // For some errors we might be able to provide extra information
640 err_unsup!(ReadUndefBytes(offset)) => {
641 // Some byte was undefined, determine which
642 // element that byte belongs to so we can
644 let i = (offset.bytes() / layout.size.bytes()) as usize;
645 self.path.push(PathElem::ArrayElem(i));
647 throw_validation_failure!("undefined bytes", self.path)
649 // Other errors shouldn't be possible
650 _ => return Err(err),
656 self.walk_aggregate(op, fields)? // default handler
663 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
664 /// This function checks the data at `op`. `op` is assumed to cover valid memory if it
665 /// is an indirect operand.
666 /// It will error if the bits at the destination do not match the ones described by the layout.
668 /// `ref_tracking_for_consts` can be `None` to avoid recursive checking below references.
669 /// This also toggles between "run-time" (no recursion) and "compile-time" (with recursion)
670 /// validation (e.g., pointer values are fine in integers at runtime) and various other const
671 /// specific validation checks.
672 pub fn validate_operand(
674 op: OpTy<'tcx, M::PointerTag>,
676 ref_tracking_for_consts: Option<
677 &mut RefTracking<MPlaceTy<'tcx, M::PointerTag>, Vec<PathElem>>,
679 ) -> InterpResult<'tcx> {
680 trace!("validate_operand: {:?}, {:?}", *op, op.layout.ty);
682 // Construct a visitor
683 let mut visitor = ValidityVisitor { path, ref_tracking_for_consts, ecx: self };
685 // Try to cast to ptr *once* instead of all the time.
686 let op = self.force_op_ptr(op).unwrap_or(op);
689 visitor.visit_value(op)