2 use std::ops::RangeInclusive;
4 use syntax_pos::symbol::{sym, Symbol};
6 use rustc::ty::layout::{self, TyLayout, LayoutOf, VariantIdx};
8 use rustc_data_structures::fx::FxHashSet;
13 GlobalAlloc, InterpResult, InterpError,
14 OpTy, Machine, InterpCx, ValueVisitor, MPlaceTy, UnsupportedOpInfo,
17 macro_rules! validation_failure {
18 ($what:expr, $where:expr, $details:expr) => {{
19 let where_ = path_format(&$where);
20 let where_ = if where_.is_empty() {
23 format!(" at {}", where_)
25 throw_err!(ValidationFailure(format!(
26 "encountered {}{}, but expected {}",
27 $what, where_, $details,
30 ($what:expr, $where:expr) => {{
31 let where_ = path_format(&$where);
32 let where_ = if where_.is_empty() {
35 format!(" at {}", where_)
37 throw_err!(ValidationFailure(format!(
44 macro_rules! try_validation {
45 ($e:expr, $what:expr, $where:expr, $details:expr) => {{
48 Err(_) => return validation_failure!($what, $where, $details),
52 ($e:expr, $what:expr, $where:expr) => {{
55 Err(_) => return validation_failure!($what, $where),
60 /// We want to show a nice path to the invalid field for diagnostics,
61 /// but avoid string operations in the happy case where no error happens.
62 /// So we track a `Vec<PathElem>` where `PathElem` contains all the data we
63 /// need to later print something for the user.
64 #[derive(Copy, Clone, Debug)]
68 GeneratorState(VariantIdx),
77 /// State for tracking recursive validation of references
78 pub struct RefTracking<T, PATH = ()> {
79 pub seen: FxHashSet<T>,
80 pub todo: Vec<(T, PATH)>,
83 impl<T: Copy + Eq + Hash + std::fmt::Debug, PATH: Default> RefTracking<T, PATH> {
84 pub fn empty() -> Self {
86 seen: FxHashSet::default(),
90 pub fn new(op: T) -> Self {
91 let mut ref_tracking_for_consts = RefTracking {
92 seen: FxHashSet::default(),
93 todo: vec![(op, PATH::default())],
95 ref_tracking_for_consts.seen.insert(op);
96 ref_tracking_for_consts
99 pub fn track(&mut self, op: T, path: impl FnOnce() -> PATH) {
100 if self.seen.insert(op) {
101 trace!("Recursing below ptr {:#?}", op);
103 // Remember to come back to this later.
104 self.todo.push((op, path));
110 fn path_format(path: &Vec<PathElem>) -> String {
111 use self::PathElem::*;
113 let mut out = String::new();
114 for elem in path.iter() {
116 Field(name) => write!(out, ".{}", name),
117 Variant(name) => write!(out, ".<downcast-variant({})>", name),
118 GeneratorState(idx) => write!(out, ".<generator-state({})>", idx.index()),
119 ClosureVar(name) => write!(out, ".<closure-var({})>", name),
120 TupleElem(idx) => write!(out, ".{}", idx),
121 ArrayElem(idx) => write!(out, "[{}]", idx),
123 // This does not match Rust syntax, but it is more readable for long paths -- and
124 // some of the other items here also are not Rust syntax. Actually we can't
125 // even use the usual syntax because we are just showing the projections,
127 write!(out, ".<deref>"),
128 Tag => write!(out, ".<enum-tag>"),
129 DynDowncast => write!(out, ".<dyn-downcast>"),
135 // Test if a range that wraps at overflow contains `test`
136 fn wrapping_range_contains(r: &RangeInclusive<u128>, test: u128) -> bool {
137 let (lo, hi) = r.clone().into_inner();
140 (..=hi).contains(&test) || (lo..).contains(&test)
147 // Formats such that a sentence like "expected something {}" to mean
148 // "expected something <in the given range>" makes sense.
149 fn wrapping_range_format(r: &RangeInclusive<u128>, max_hi: u128) -> String {
150 let (lo, hi) = r.clone().into_inner();
151 debug_assert!(hi <= max_hi);
153 format!("less or equal to {}, or greater or equal to {}", hi, lo)
155 format!("equal to {}", lo)
157 debug_assert!(hi < max_hi, "should not be printing if the range covers everything");
158 format!("less or equal to {}", hi)
159 } else if hi == max_hi {
160 debug_assert!(lo > 0, "should not be printing if the range covers everything");
161 format!("greater or equal to {}", lo)
163 format!("in the range {:?}", r)
167 struct ValidityVisitor<'rt, 'mir, 'tcx, M: Machine<'mir, 'tcx>> {
168 /// The `path` may be pushed to, but the part that is present when a function
169 /// starts must not be changed! `visit_fields` and `visit_array` rely on
170 /// this stack discipline.
172 ref_tracking_for_consts: Option<&'rt mut RefTracking<
173 MPlaceTy<'tcx, M::PointerTag>,
176 ecx: &'rt InterpCx<'mir, 'tcx, M>,
179 impl<'rt, 'mir, 'tcx, M: Machine<'mir, 'tcx>> ValidityVisitor<'rt, 'mir, 'tcx, M> {
180 fn aggregate_field_path_elem(
182 layout: TyLayout<'tcx>,
185 match layout.ty.sty {
186 // generators and closures.
187 ty::Closure(def_id, _) | ty::Generator(def_id, _, _) => {
189 if def_id.is_local() {
190 let tables = self.ecx.tcx.typeck_tables_of(def_id);
191 if let Some(upvars) = tables.upvar_list.get(&def_id) {
192 // Sometimes the index is beyond the number of upvars (seen
194 if let Some((&var_hir_id, _)) = upvars.get_index(field) {
195 let node = self.ecx.tcx.hir().get(var_hir_id);
196 if let hir::Node::Binding(pat) = node {
197 if let hir::PatKind::Binding(_, _, ident, _) = pat.node {
198 name = Some(ident.name);
205 PathElem::ClosureVar(name.unwrap_or_else(|| {
206 // Fall back to showing the field index.
212 ty::Tuple(_) => PathElem::TupleElem(field),
215 ty::Adt(def, ..) if def.is_enum() => {
216 // we might be projecting *to* a variant, or to a field *in*a variant.
217 match layout.variants {
218 layout::Variants::Single { index } =>
220 PathElem::Field(def.variants[index].fields[field].ident.name),
226 ty::Adt(def, _) => PathElem::Field(def.non_enum_variant().fields[field].ident.name),
229 ty::Array(..) | ty::Slice(..) => PathElem::ArrayElem(field),
232 ty::Dynamic(..) => PathElem::DynDowncast,
234 // nothing else has an aggregate layout
235 _ => bug!("aggregate_field_path_elem: got non-aggregate type {:?}", layout.ty),
241 new_op: OpTy<'tcx, M::PointerTag>,
243 ) -> InterpResult<'tcx> {
244 // Remember the old state
245 let path_len = self.path.len();
247 self.path.push(elem);
248 self.visit_value(new_op)?;
250 self.path.truncate(path_len);
255 impl<'rt, 'mir, 'tcx, M: Machine<'mir, 'tcx>> ValueVisitor<'mir, 'tcx, M>
256 for ValidityVisitor<'rt, 'mir, 'tcx, M>
258 type V = OpTy<'tcx, M::PointerTag>;
261 fn ecx(&self) -> &InterpCx<'mir, 'tcx, M> {
268 old_op: OpTy<'tcx, M::PointerTag>,
270 new_op: OpTy<'tcx, M::PointerTag>
271 ) -> InterpResult<'tcx> {
272 let elem = self.aggregate_field_path_elem(old_op.layout, field);
273 self.visit_elem(new_op, elem)
279 old_op: OpTy<'tcx, M::PointerTag>,
280 variant_id: VariantIdx,
281 new_op: OpTy<'tcx, M::PointerTag>
282 ) -> InterpResult<'tcx> {
283 let name = match old_op.layout.ty.sty {
284 ty::Adt(adt, _) => PathElem::Variant(adt.variants[variant_id].ident.name),
285 // Generators also have variants
286 ty::Generator(..) => PathElem::GeneratorState(variant_id),
287 _ => bug!("Unexpected type with variant: {:?}", old_op.layout.ty),
289 self.visit_elem(new_op, name)
293 fn visit_value(&mut self, op: OpTy<'tcx, M::PointerTag>) -> InterpResult<'tcx>
295 trace!("visit_value: {:?}, {:?}", *op, op.layout);
296 // Translate some possible errors to something nicer.
297 match self.walk_value(op) {
299 Err(err) => match err.kind {
300 InterpError::Unsupported(UnsupportedOpInfo::InvalidDiscriminant(val)) =>
302 val, self.path, "a valid enum discriminant"
304 InterpError::Unsupported(UnsupportedOpInfo::ReadPointerAsBytes) =>
306 "a pointer", self.path, "plain (non-pointer) bytes"
313 fn visit_primitive(&mut self, value: OpTy<'tcx, M::PointerTag>) -> InterpResult<'tcx>
315 let value = self.ecx.read_immediate(value)?;
316 // Go over all the primitive types
317 let ty = value.layout.ty;
320 let value = value.to_scalar_or_undef();
321 try_validation!(value.to_bool(),
322 value, self.path, "a boolean");
325 let value = value.to_scalar_or_undef();
326 try_validation!(value.to_char(),
327 value, self.path, "a valid unicode codepoint");
329 ty::Float(_) | ty::Int(_) | ty::Uint(_) => {
330 // NOTE: Keep this in sync with the array optimization for int/float
332 let size = value.layout.size;
333 let value = value.to_scalar_or_undef();
334 if self.ref_tracking_for_consts.is_some() {
335 // Integers/floats in CTFE: Must be scalar bits, pointers are dangerous
336 try_validation!(value.to_bits(size),
337 value, self.path, "initialized plain (non-pointer) bytes");
339 // At run-time, for now, we accept *anything* for these types, including
340 // undef. We should fix that, but let's start low.
344 if self.ref_tracking_for_consts.is_some() {
345 // Integers/floats in CTFE: For consistency with integers, we do not
347 let _ptr = try_validation!(value.to_scalar_ptr(),
348 "undefined address in raw pointer", self.path);
349 let _meta = try_validation!(value.to_meta(),
350 "uninitialized data in raw fat pointer metadata", self.path);
352 // Remain consistent with `usize`: Accept anything.
355 _ if ty.is_box() || ty.is_region_ptr() => {
356 // Handle fat pointers.
357 // Check metadata early, for better diagnostics
358 let ptr = try_validation!(value.to_scalar_ptr(),
359 "undefined address in pointer", self.path);
360 let meta = try_validation!(value.to_meta(),
361 "uninitialized data in fat pointer metadata", self.path);
362 let layout = self.ecx.layout_of(value.layout.ty.builtin_deref(true).unwrap().ty)?;
363 if layout.is_unsized() {
364 let tail = self.ecx.tcx.struct_tail_erasing_lifetimes(layout.ty,
368 let vtable = meta.unwrap();
370 self.ecx.memory.check_ptr_access(
372 3*self.ecx.tcx.data_layout.pointer_size, // drop, size, align
373 self.ecx.tcx.data_layout.pointer_align.abi,
375 "dangling or unaligned vtable pointer or too small vtable",
378 try_validation!(self.ecx.read_drop_type_from_vtable(vtable),
379 "invalid drop fn in vtable", self.path);
380 try_validation!(self.ecx.read_size_and_align_from_vtable(vtable),
381 "invalid size or align in vtable", self.path);
382 // FIXME: More checks for the vtable.
384 ty::Slice(..) | ty::Str => {
385 try_validation!(meta.unwrap().to_usize(self.ecx),
386 "non-integer slice length in fat pointer", self.path);
389 // Unsized, but not fat.
392 bug!("Unexpected unsized type tail: {:?}", tail),
395 // Make sure this is dereferencable and all.
396 let (size, align) = self.ecx.size_and_align_of(meta, layout)?
397 // for the purpose of validity, consider foreign types to have
398 // alignment and size determined by the layout (size will be 0,
399 // alignment should take attributes into account).
400 .unwrap_or_else(|| (layout.size, layout.align.abi));
401 let ptr: Option<_> = match self.ecx.memory.check_ptr_access(ptr, size, align) {
405 "{:?} did not pass access check for size {:?}, align {:?}",
408 use super::UnsupportedOpInfo::*;
410 InterpError::Unsupported(InvalidNullPointerUsage) =>
411 return validation_failure!("NULL reference", self.path),
412 InterpError::Unsupported(AlignmentCheckFailed { required, has }) =>
413 return validation_failure!(format!("unaligned reference \
414 (required {} byte alignment but found {})",
415 required.bytes(), has.bytes()), self.path),
416 InterpError::Unsupported(ReadBytesAsPointer) =>
417 return validation_failure!(
418 "dangling reference (created from integer)",
422 return validation_failure!(
423 "dangling reference (not entirely in bounds)",
429 // Recursive checking
430 if let Some(ref mut ref_tracking) = self.ref_tracking_for_consts {
431 let place = self.ecx.ref_to_mplace(value)?;
432 if let Some(ptr) = ptr { // not a ZST
433 // Skip validation entirely for some external statics
434 let alloc_kind = self.ecx.tcx.alloc_map.lock().get(ptr.alloc_id);
435 if let Some(GlobalAlloc::Static(did)) = alloc_kind {
436 // `extern static` cannot be validated as they have no body.
437 // FIXME: Statics from other crates are also skipped.
438 // They might be checked at a different type, but for now we
439 // want to avoid recursing too deeply. This is not sound!
440 if !did.is_local() || self.ecx.tcx.is_foreign_item(did) {
445 // Proceed recursively even for ZST, no reason to skip them!
446 // `!` is a ZST and we want to validate it.
447 // Normalize before handing `place` to tracking because that will
448 // check for duplicates.
449 let place = if size.bytes() > 0 {
450 self.ecx.force_mplace_ptr(place)
451 .expect("we already bounds-checked")
455 let path = &self.path;
456 ref_tracking.track(place, || {
457 // We need to clone the path anyway, make sure it gets created
458 // with enough space for the additional `Deref`.
459 let mut new_path = Vec::with_capacity(path.len() + 1);
460 new_path.clone_from(path);
461 new_path.push(PathElem::Deref);
467 let value = value.to_scalar_or_undef();
468 let _fn = try_validation!(
469 value.not_undef().and_then(|ptr| self.ecx.memory.get_fn(ptr)),
470 value, self.path, "a function pointer"
472 // FIXME: Check if the signature matches
474 // This should be all the primitive types
475 _ => bug!("Unexpected primitive type {}", value.layout.ty)
480 fn visit_uninhabited(&mut self) -> InterpResult<'tcx>
482 validation_failure!("a value of an uninhabited type", self.path)
487 op: OpTy<'tcx, M::PointerTag>,
488 layout: &layout::Scalar,
489 ) -> InterpResult<'tcx> {
490 let value = self.ecx.read_scalar(op)?;
491 // Determine the allowed range
492 let (lo, hi) = layout.valid_range.clone().into_inner();
493 // `max_hi` is as big as the size fits
494 let max_hi = u128::max_value() >> (128 - op.layout.size.bits());
495 assert!(hi <= max_hi);
496 // We could also write `(hi + 1) % (max_hi + 1) == lo` but `max_hi + 1` overflows for `u128`
497 if (lo == 0 && hi == max_hi) || (hi + 1 == lo) {
501 // At least one value is excluded. Get the bits.
502 let value = try_validation!(value.not_undef(),
507 wrapping_range_format(&layout.valid_range, max_hi),
510 let bits = match value.to_bits_or_ptr(op.layout.size, self.ecx) {
512 if lo == 1 && hi == max_hi {
513 // Only NULL is the niche. So make sure the ptr is NOT NULL.
514 if self.ecx.memory.ptr_may_be_null(ptr) {
515 return validation_failure!(
516 "a potentially NULL pointer",
519 "something that cannot possibly fail to be {}",
520 wrapping_range_format(&layout.valid_range, max_hi)
526 // Conservatively, we reject, because the pointer *could* have a bad
528 return validation_failure!(
532 "something that cannot possibly fail to be {}",
533 wrapping_range_format(&layout.valid_range, max_hi)
541 // Now compare. This is slightly subtle because this is a special "wrap-around" range.
542 if wrapping_range_contains(&layout.valid_range, bits) {
548 format!("something {}", wrapping_range_format(&layout.valid_range, max_hi))
555 op: OpTy<'tcx, M::PointerTag>,
556 fields: impl Iterator<Item=InterpResult<'tcx, Self::V>>,
557 ) -> InterpResult<'tcx> {
558 match op.layout.ty.sty {
560 let mplace = op.assert_mem_place(); // strings are never immediate
561 try_validation!(self.ecx.read_str(mplace),
562 "uninitialized or non-UTF-8 data in str", self.path);
564 ty::Array(tys, ..) | ty::Slice(tys) if {
565 // This optimization applies only for integer and floating point types
566 // (i.e., types that can hold arbitrary bytes).
568 ty::Int(..) | ty::Uint(..) | ty::Float(..) => true,
572 // bailing out for zsts is ok, since the array element type can only be int/float
573 if op.layout.is_zst() {
576 // non-ZST array cannot be immediate, slices are never immediate
577 let mplace = op.assert_mem_place();
578 // This is the length of the array/slice.
579 let len = mplace.len(self.ecx)?;
580 // zero length slices have nothing to be checked
584 // This is the element type size.
585 let ty_size = self.ecx.layout_of(tys)?.size;
586 // This is the size in bytes of the whole array.
587 let size = ty_size * len;
588 // Size is not 0, get a pointer.
589 let ptr = self.ecx.force_ptr(mplace.ptr)?;
591 // NOTE: Keep this in sync with the handling of integer and float
592 // types above, in `visit_primitive`.
593 // In run-time mode, we accept pointers in here. This is actually more
594 // permissive than a per-element check would be, e.g., we accept
595 // an &[u8] that contains a pointer even though bytewise checking would
596 // reject it. However, that's good: We don't inherently want
597 // to reject those pointers, we just do not have the machinery to
598 // talk about parts of a pointer.
599 // We also accept undef, for consistency with the type-based checks.
600 match self.ecx.memory.get(ptr.alloc_id)?.check_bytes(
604 /*allow_ptr_and_undef*/ self.ref_tracking_for_consts.is_none(),
606 // In the happy case, we needn't check anything else.
608 // Some error happened, try to provide a more detailed description.
610 // For some errors we might be able to provide extra information
612 InterpError::Unsupported(UnsupportedOpInfo::ReadUndefBytes(offset)) => {
613 // Some byte was undefined, determine which
614 // element that byte belongs to so we can
616 let i = (offset.bytes() / ty_size.bytes()) as usize;
617 self.path.push(PathElem::ArrayElem(i));
619 return validation_failure!(
620 "undefined bytes", self.path
623 // Other errors shouldn't be possible
624 _ => return Err(err),
630 self.walk_aggregate(op, fields)? // default handler
637 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
638 /// This function checks the data at `op`. `op` is assumed to cover valid memory if it
639 /// is an indirect operand.
640 /// It will error if the bits at the destination do not match the ones described by the layout.
642 /// `ref_tracking_for_consts` can be `None` to avoid recursive checking below references.
643 /// This also toggles between "run-time" (no recursion) and "compile-time" (with recursion)
644 /// validation (e.g., pointer values are fine in integers at runtime) and various other const
645 /// specific validation checks.
646 pub fn validate_operand(
648 op: OpTy<'tcx, M::PointerTag>,
650 ref_tracking_for_consts: Option<&mut RefTracking<
651 MPlaceTy<'tcx, M::PointerTag>,
654 ) -> InterpResult<'tcx> {
655 trace!("validate_operand: {:?}, {:?}", *op, op.layout.ty);
657 // Construct a visitor
658 let mut visitor = ValidityVisitor {
660 ref_tracking_for_consts,
664 // Try to cast to ptr *once* instead of all the time.
665 let op = self.force_op_ptr(op).unwrap_or(op);
668 visitor.visit_value(op)