1//! Check the validity invariant of a given value, and tell the user
2//! where in the value it got violated.
3//! In const context, this goes even further and tries to approximate const safety.
4//! That's useful because it means other passes (e.g. promotion) can rely on `const`s
5//! to be const-safe.
67use std::borrow::Cow;
8use std::fmt::{self, Write};
9use std::hash::Hash;
10use std::num::NonZero;
1112use either::{Left, Right};
13use hir::def::DefKind;
14use rustc_abi::{
15BackendRepr, FieldIdx, FieldsShape, Scalaras ScalarAbi, Size, VariantIdx, Variants,
16WrappingRange,
17};
18use rustc_ast::Mutability;
19use rustc_data_structures::fx::FxHashSet;
20use rustc_hiras hir;
21use rustc_middle::mir::interpret::{
22InterpErrorKind, InvalidMetaKind, Misalignment, PointerArithmetic, Provenance, alloc_range,
23interp_ok,
24};
25use rustc_middle::ty::layout::{LayoutCx, TyAndLayout};
26use rustc_middle::ty::{self, Ty};
27use rustc_span::{Symbol, bug, sym};
28use tracing::trace;
2930use super::machine::AllocMap;
31use super::{
32AllocId, CheckInAllocMsg, GlobalAlloc, ImmTy, Immediate, InterpCx, InterpResult, MPlaceTy,
33Machine, MemPlaceMeta, PlaceTy, Pointer, Projectable, Scalar, ValueVisitor, err_ub,
34};
35use crate::enter_trace_span;
3637// for the validation errors
38#[rustfmt::skip]
39use super::InterpErrorKind::UndefinedBehavioras Ub;
40use super::InterpErrorKind::Unsupportedas Unsup;
41use super::UndefinedBehaviorInfo::*;
42use super::UnsupportedOpInfo::*;
4344macro_rules!err_validation_failure {
45 ($where:expr, $msg:expr ) => {{
46let where_ = &$where;
47let path = if !where_.projs.is_empty() {
48let mut path = String::new();
49 write_path(&mut path, &where_.projs);
50Some(path)
51 } else {
52None
53};
5455#[allow(unused)]
56use ValidationErrorKind::*;
57let msg = ValidationErrorKind::from($msg);
58err_ub!(ValidationError {
59 orig_ty: where_.orig_ty,
60 path,
61 ptr_bytes_warning: msg.ptr_bytes_warning(),
62 msg: msg.to_string(),
63 })
64 }};
65}
6667macro_rules!throw_validation_failure {
68 ($where:expr, $msg:expr ) => {
69do yeet err_validation_failure!($where, $msg)
70 };
71}
7273/// If $e throws an error matching the pattern, throw a validation failure.
74/// Other errors are passed back to the caller, unchanged -- and if they reach the root of
75/// the visitor, we make sure only validation errors and `InvalidProgram` errors are left.
76/// This lets you use the patterns as a kind of validation list, asserting which errors
77/// can possibly happen:
78///
79/// ```ignore(illustrative)
80/// let v = try_validation!(some_fn(x), some_path, {
81/// Foo | Bar | Baz => format!("some failure involving {x}"),
82/// });
83/// ```
84///
85/// The patterns must be of type `UndefinedBehaviorInfo`.
86macro_rules!try_validation {
87 ($e:expr, $where:expr,
88 $( $( $p:pat_param )|+ => $msg:expr ),+ $(,)?
89) => {{
90$e.map_err_kind(|e| {
91// We catch the error and turn it into a validation failure. We are okay with
92 // allocation here as this can only slow down builds that fail anyway.
93match e {
94 $(
95 $($p)|+ => {
96err_validation_failure!(
97$where,
98$msg
99)
100 }
101 ),+,
102 e => e,
103 }
104 })?
105}};
106}
107108#[derive(#[automatically_derived]impl ::core::fmt::Debug for PtrKind {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::Ref(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f, "Ref",
&__self_0),
Self::Box => ::core::fmt::Formatter::write_str(f, "Box"),
}
}
}Debug, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for PtrKind {
}
#[automatically_derived]impl ::core::clone::Clone for PtrKind {
#[inline]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<Mutability>;
*self
}
}Clone, #[automatically_derived]impl ::core::marker::Copy for PtrKind { }Copy, #[automatically_derived]impl ::core::marker::StructuralPartialEq for PtrKind {
}
#[automatically_derived]impl ::core::cmp::PartialEq for PtrKind {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other) &&
match (self, other) {
(Self::Ref(__self_0), Self::Ref(__arg1_0)) =>
__self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for PtrKind {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<Mutability>;
}
}Eq)]
109enum PtrKind {
110 Ref(Mutability),
111 Box,
112}
113114impl fmt::Displayfor PtrKind {
115fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
116let str = match self {
117 PtrKind::Ref(_) => "reference",
118 PtrKind::Box => "box",
119 };
120f.write_fmt(format_args!("{0}", str))write!(f, "{str}")121 }
122}
123124#[derive(#[automatically_derived]impl ::core::fmt::Debug for ExpectedKind {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_c_like_enum_write_str(f,
"Reference Box RawPtr Bool Char Float Int FnPtr Str",
match self {
ExpectedKind::Reference => 0usize,
ExpectedKind::Box => 10usize,
ExpectedKind::RawPtr => 14usize,
ExpectedKind::Bool => 21usize,
ExpectedKind::Char => 26usize,
ExpectedKind::Float => 31usize,
ExpectedKind::Int => 37usize,
ExpectedKind::FnPtr => 41usize,
ExpectedKind::Str => 47usize,
})
}
}Debug)]
125enum ExpectedKind {
126 Reference,
127 Box,
128 RawPtr,
129 Bool,
130 Char,
131 Float,
132 Int,
133 FnPtr,
134 Str,
135}
136137impl fmt::Displayfor ExpectedKind {
138fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
139let str = match self {
140 ExpectedKind::Reference => "expected a reference",
141 ExpectedKind::Box => "expected a box",
142 ExpectedKind::RawPtr => "expected a raw pointer",
143 ExpectedKind::Bool => "expected a boolean",
144 ExpectedKind::Char => "expected a unicode scalar value",
145 ExpectedKind::Float => "expected a floating point number",
146 ExpectedKind::Int => "expected an integer",
147 ExpectedKind::FnPtr => "expected a function pointer",
148 ExpectedKind::Str => "expected a string",
149 };
150f.write_fmt(format_args!("{0}", str))write!(f, "{str}")151 }
152}
153154impl From<PtrKind> for ExpectedKind {
155fn from(x: PtrKind) -> ExpectedKind {
156match x {
157 PtrKind::Box => ExpectedKind::Box,
158 PtrKind::Ref(_) => ExpectedKind::Reference,
159 }
160 }
161}
162163/// Validation errors that can be emitted in one than one place get a variant here so that
164/// we format them consistently. Everything else uses the `String` fallback.
165#[derive(#[automatically_derived]impl<'tcx> ::core::fmt::Debug for
ValidationErrorKind<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::Uninit { expected: __self_0 } =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Uninit expected", &__self_0),
Self::PointerAsInt { expected: __self_0 } =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"PointerAsInt expected", &__self_0),
Self::PartialPointer =>
::core::fmt::Formatter::write_str(f, "PartialPointer"),
Self::InvalidMetaWrongTrait {
vtable_dyn_type: __self_0, expected_dyn_type: __self_1 } =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"InvalidMetaWrongTrait vtable_dyn_type expected_dyn_type",
__self_0, &__self_1),
Self::GeneralError { msg: __self_0 } =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"GeneralError msg", &__self_0),
}
}
}Debug)]
166enum ValidationErrorKind<'tcx> {
167 Uninit {
168 expected: ExpectedKind,
169 },
170 PointerAsInt {
171 expected: ExpectedKind,
172 },
173 PartialPointer,
174 InvalidMetaWrongTrait {
175/// The vtable that was actually referenced by the wide pointer metadata.
176vtable_dyn_type: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
177/// The vtable that was expected at the point in MIR that it was accessed.
178expected_dyn_type: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
179 },
180 GeneralError {
181 msg: String,
182 },
183}
184185impl<'tcx> ValidationErrorKind<'tcx> {
186// We don't do this via `fmt::Display` to so that we can do a move in the `GeneralError` case.
187fn to_string(self) -> String {
188use ValidationErrorKind::*;
189match self {
190Uninit { expected } => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("encountered uninitialized memory, but {0}",
expected))
})format!("encountered uninitialized memory, but {expected}"),
191PointerAsInt { expected } => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("encountered a pointer, but {0}",
expected))
})format!("encountered a pointer, but {expected}"),
192PartialPointer => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("encountered a partial pointer or a mix of pointers"))
})format!("encountered a partial pointer or a mix of pointers"),
193InvalidMetaWrongTrait { vtable_dyn_type, expected_dyn_type } => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("wrong trait in wide pointer vtable: expected `{0}`, but encountered `{1}`",
expected_dyn_type, vtable_dyn_type))
})format!(
194"wrong trait in wide pointer vtable: expected `{expected_dyn_type}`, but encountered `{vtable_dyn_type}`"
195),
196GeneralError { msg } => msg,
197 }
198 }
199200fn ptr_bytes_warning(&self) -> bool {
201use ValidationErrorKind::*;
202#[allow(non_exhaustive_omitted_patterns)] match self {
PointerAsInt { .. } | PartialPointer => true,
_ => false,
}matches!(self, PointerAsInt { .. } | PartialPointer)203 }
204}
205206impl<'tcx> From<String> for ValidationErrorKind<'tcx> {
207fn from(msg: String) -> Self {
208 ValidationErrorKind::GeneralError { msg }
209 }
210}
211212fn fmt_range(r: WrappingRange, max_hi: u128) -> String {
213let WrappingRange { start: lo, end: hi } = r;
214if !(hi <= max_hi) {
::core::panicking::panic("assertion failed: hi <= max_hi")
};assert!(hi <= max_hi);
215if lo > hi {
216::alloc::__export::must_use({
::alloc::fmt::format(format_args!("less or equal to {0}, or greater or equal to {1}",
hi, lo))
})format!("less or equal to {hi}, or greater or equal to {lo}")217 } else if lo == hi {
218::alloc::__export::must_use({
::alloc::fmt::format(format_args!("equal to {0}", lo))
})format!("equal to {lo}")219 } else if lo == 0 {
220if !(hi < max_hi) {
{
::core::panicking::panic_fmt(format_args!("should not be printing if the range covers everything"));
}
};assert!(hi < max_hi, "should not be printing if the range covers everything");
221::alloc::__export::must_use({
::alloc::fmt::format(format_args!("less or equal to {0}", hi))
})format!("less or equal to {hi}")222 } else if hi == max_hi {
223if !(lo > 0) {
{
::core::panicking::panic_fmt(format_args!("should not be printing if the range covers everything"));
}
};assert!(lo > 0, "should not be printing if the range covers everything");
224::alloc::__export::must_use({
::alloc::fmt::format(format_args!("greater or equal to {0}", lo))
})format!("greater or equal to {lo}")225 } else {
226::alloc::__export::must_use({
::alloc::fmt::format(format_args!("in the range {0}..={1}", lo, hi))
})format!("in the range {lo}..={hi}")227 }
228}
229230/// We want to show a nice path to the invalid field for diagnostics,
231/// but avoid string operations in the happy case where no error happens.
232/// So we track a `Vec<PathElem>` where `PathElem` contains all the data we
233/// need to later print something for the user.
234#[derive(#[automatically_derived]impl<'tcx> ::core::marker::Copy for PathElem<'tcx> { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl<'tcx>
::core::clone::TrivialClone for PathElem<'tcx> {
}
#[automatically_derived]impl<'tcx> ::core::clone::Clone for PathElem<'tcx> {
#[inline]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<Symbol>;
let _: ::core::clone::AssertParamIsClone<VariantIdx>;
let _: ::core::clone::AssertParamIsClone<usize>;
let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
*self
}
}Clone, #[automatically_derived]impl<'tcx> ::core::fmt::Debug for PathElem<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::Field(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f, "Field",
&__self_0),
Self::Variant(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Variant", &__self_0),
Self::CoroutineState(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"CoroutineState", &__self_0),
Self::CapturedVar(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"CapturedVar", &__self_0),
Self::ArrayElem(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"ArrayElem", &__self_0),
Self::TupleElem(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"TupleElem", &__self_0),
Self::Deref => ::core::fmt::Formatter::write_str(f, "Deref"),
Self::EnumTag => ::core::fmt::Formatter::write_str(f, "EnumTag"),
Self::CoroutineTag =>
::core::fmt::Formatter::write_str(f, "CoroutineTag"),
Self::DynDowncast(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"DynDowncast", &__self_0),
Self::Vtable => ::core::fmt::Formatter::write_str(f, "Vtable"),
}
}
}Debug)]
235pub enum PathElem<'tcx> {
236 Field(Symbol),
237 Variant(Symbol),
238 CoroutineState(VariantIdx),
239 CapturedVar(Symbol),
240 ArrayElem(usize),
241 TupleElem(usize),
242 Deref,
243 EnumTag,
244 CoroutineTag,
245 DynDowncast(Ty<'tcx>),
246 Vtable,
247}
248249#[derive(#[automatically_derived]impl<'tcx> ::core::clone::Clone for Path<'tcx> {
#[inline]
fn clone(&self) -> Self {
Path {
orig_ty: ::core::clone::Clone::clone(&self.orig_ty),
projs: ::core::clone::Clone::clone(&self.projs),
}
}
}Clone, #[automatically_derived]impl<'tcx> ::core::fmt::Debug for Path<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f,
"Path orig_ty projs", &self.orig_ty, &&self.projs)
}
}Debug)]
250pub struct Path<'tcx> {
251 orig_ty: Ty<'tcx>,
252 projs: Vec<PathElem<'tcx>>,
253}
254255impl<'tcx> Path<'tcx> {
256fn new(ty: Ty<'tcx>) -> Self {
257Self { orig_ty: ty, projs: ::alloc::vec::Vec::new()vec![] }
258 }
259}
260261/// Extra things to check for during validation of CTFE results.
262#[derive(#[automatically_derived]impl ::core::marker::Copy for CtfeValidationMode { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for CtfeValidationMode {
}
#[automatically_derived]impl ::core::clone::Clone for CtfeValidationMode {
#[inline]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<Mutability>;
let _: ::core::clone::AssertParamIsClone<bool>;
*self
}
}Clone)]
263pub enum CtfeValidationMode {
264/// Validation of a `static`
265Static { mutbl: Mutability },
266/// Validation of a promoted.
267Promoted,
268/// Validation of a `const`.
269 /// `allow_immutable_unsafe_cell` says whether we allow `UnsafeCell` in immutable memory (which is the
270 /// case for the top-level allocation of a `const`, where this is fine because the allocation will be
271 /// copied at each use site).
272Const { allow_immutable_unsafe_cell: bool },
273}
274275impl CtfeValidationMode {
276fn allow_immutable_unsafe_cell(self) -> bool {
277match self {
278 CtfeValidationMode::Static { .. } => false,
279 CtfeValidationMode::Promoted { .. } => false,
280 CtfeValidationMode::Const { allow_immutable_unsafe_cell, .. } => {
281allow_immutable_unsafe_cell282 }
283 }
284 }
285}
286287/// State for tracking recursive validation of references
288pub struct RefTracking<T, PATH = ()> {
289 seen: FxHashSet<T>,
290 todo: Vec<(T, PATH)>,
291}
292293impl<T: Clone + Eq + Hash + std::fmt::Debug, PATH> RefTracking<T, PATH> {
294pub fn empty() -> Self {
295RefTracking { seen: FxHashSet::default(), todo: ::alloc::vec::Vec::new()vec![] }
296 }
297pub fn next(&mut self) -> Option<(T, PATH)> {
298self.todo.pop()
299 }
300301fn track(&mut self, val: T, path: impl FnOnce() -> PATH) {
302if self.seen.insert(val.clone()) {
303{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/f5cedb83a788ea9581097abc36a2a8503a7f541c/compiler/rustc_const_eval/src/interpret/validity.rs:303",
"rustc_const_eval::interpret::validity",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/f5cedb83a788ea9581097abc36a2a8503a7f541c/compiler/rustc_const_eval/src/interpret/validity.rs"),
::tracing_core::__macro_support::Option::Some(303u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::validity"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Recursing below ptr {0:#?}",
val) as &dyn ::tracing::field::Value))])
});
} else { ; }
};trace!("Recursing below ptr {:#?}", val);
304let path = path();
305// Remember to come back to this later.
306self.todo.push((val, path));
307 }
308 }
309}
310311impl<'tcx, T: Clone + Eq + Hash + std::fmt::Debug> RefTracking<T, Path<'tcx>> {
312pub fn new(val: T, ty: Ty<'tcx>) -> Self {
313let mut ref_tracking_for_consts =
314RefTracking { seen: FxHashSet::default(), todo: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(val.clone(), Path::new(ty))]))vec![(val.clone(), Path::new(ty))] };
315ref_tracking_for_consts.seen.insert(val);
316ref_tracking_for_consts317 }
318}
319320/// Format a path
321fn write_path(out: &mut String, path: &[PathElem<'_>]) {
322use self::PathElem::*;
323324for elem in path.iter() {
325match elem {
326 Field(name) => out.write_fmt(format_args!(".{0}", name))write!(out, ".{name}"),
327 EnumTag => out.write_fmt(format_args!(".<enum-tag>"))write!(out, ".<enum-tag>"),
328 Variant(name) => out.write_fmt(format_args!(".<enum-variant({0})>", name))write!(out, ".<enum-variant({name})>"),
329 CoroutineTag => out.write_fmt(format_args!(".<coroutine-tag>"))write!(out, ".<coroutine-tag>"),
330 CoroutineState(idx) => out.write_fmt(format_args!(".<coroutine-state({0})>", idx.index()))write!(out, ".<coroutine-state({})>", idx.index()),
331 CapturedVar(name) => out.write_fmt(format_args!(".<captured-var({0})>", name))write!(out, ".<captured-var({name})>"),
332 TupleElem(idx) => out.write_fmt(format_args!(".{0}", idx))write!(out, ".{idx}"),
333 ArrayElem(idx) => out.write_fmt(format_args!("[{0}]", idx))write!(out, "[{idx}]"),
334// `.<deref>` does not match Rust syntax, but it is more readable for long paths -- and
335 // some of the other items here also are not Rust syntax. Actually we can't
336 // even use the usual syntax because we are just showing the projections,
337 // not the root.
338 Deref => out.write_fmt(format_args!(".<deref>"))write!(out, ".<deref>"),
339 DynDowncast(ty) => out.write_fmt(format_args!(".<dyn-downcast({0})>", ty))write!(out, ".<dyn-downcast({ty})>"),
340 Vtable => out.write_fmt(format_args!(".<vtable>"))write!(out, ".<vtable>"),
341 }
342 .unwrap()
343 }
344}
345346pub type RangeSet = rustc_data_structures::range_set::RangeSet<Size>;
347348struct ValidityVisitor<'rt, 'tcx, M: Machine<'tcx>> {
349/// The `path` may be pushed to, but the part that is present when a function
350 /// starts must not be changed! `with_elem` relies on this stack discipline.
351path: Path<'tcx>,
352 ref_tracking: Option<&'rt mut RefTracking<MPlaceTy<'tcx, M::Provenance>, Path<'tcx>>>,
353/// `None` indicates this is not validating for CTFE (but for runtime).
354ctfe_mode: Option<CtfeValidationMode>,
355 ecx: &'rt mut InterpCx<'tcx, M>,
356/// Whether provenance should be reset outside of pointers (emulating the effect of a typed
357 /// copy).
358reset_provenance_and_padding: bool,
359/// This tracks which byte ranges in this value contain data; the remaining bytes are padding.
360 /// The ideal representation here would be pointer-length pairs, but to keep things more compact
361 /// we only store a (range) set of offsets -- the base pointer is the same throughout the entire
362 /// visit, after all.
363 /// If this is `Some`, then `reset_provenance_and_padding` must be true (but not vice versa:
364 /// we might not track data vs padding bytes if the place isn't stored in memory anyway).
365data_bytes: Option<RangeSet>,
366/// True if we are inside of `MaybeDangling`. This disables pointer access checks.
367may_dangle: bool,
368}
369370impl<'rt, 'tcx, M: Machine<'tcx>> ValidityVisitor<'rt, 'tcx, M> {
371fn aggregate_field_path_elem(
372&mut self,
373 layout: TyAndLayout<'tcx>,
374 field: usize,
375 field_ty: Ty<'tcx>,
376 ) -> PathElem<'tcx> {
377// First, check if we are projecting to a variant.
378match layout.variants {
379 Variants::Multiple { tag_field, .. } => {
380if tag_field.as_usize() == field {
381return match layout.ty.kind() {
382 ty::Adt(def, ..) if def.is_enum() => PathElem::EnumTag,
383 ty::Coroutine(..) => PathElem::CoroutineTag,
384_ => ::rustc_span::macros::bug_impl(None,
format_args!("non-variant type {0:?}", layout.ty), Location::caller())bug!("non-variant type {:?}", layout.ty),
385 };
386 }
387 }
388 Variants::Single { .. } | Variants::Empty => {}
389 }
390391// Now we know we are projecting to a field, so figure out which one.
392match layout.ty.kind() {
393// coroutines, closures, and coroutine-closures all have upvars that may be named.
394ty::Closure(def_id, _) | ty::Coroutine(def_id, _) | ty::CoroutineClosure(def_id, _) => {
395let mut name = None;
396// FIXME this should be more descriptive i.e. CapturePlace instead of CapturedVar
397 // https://github.com/rust-lang/project-rfc-2229/issues/46
398if let Some(local_def_id) = def_id.as_local() {
399let captures = self.ecx.tcx.closure_captures(local_def_id);
400if let Some(captured_place) = captures.get(field) {
401// Sometimes the index is beyond the number of upvars (seen
402 // for a coroutine).
403let var_hir_id = captured_place.get_root_variable();
404let node = self.ecx.tcx.hir_node(var_hir_id);
405if let hir::Node::Pat(pat) = node406 && let hir::PatKind::Binding(_, _, ident, _) = pat.kind
407 {
408name = Some(ident.name);
409 }
410 }
411 }
412413 PathElem::CapturedVar(name.unwrap_or_else(|| {
414// Fall back to showing the field index.
415sym::integer(field)
416 }))
417 }
418419// tuples
420ty::Tuple(_) => PathElem::TupleElem(field),
421422// enums
423ty::Adt(def, ..) if def.is_enum() => {
424// we might be projecting *to* a variant, or to a field *in* a variant.
425match layout.variants {
426 Variants::Single { index } => {
427// Inside a variant
428PathElem::Field(def.variant(index).fields[FieldIdx::from_usize(field)].name)
429 }
430 Variants::Empty => {
::core::panicking::panic_fmt(format_args!("there is no field in Variants::Empty types"));
}panic!("there is no field in Variants::Empty types"),
431 Variants::Multiple { .. } => ::rustc_span::macros::bug_impl(None,
format_args!("we handled variants above"), Location::caller())bug!("we handled variants above"),
432 }
433 }
434435// other ADTs
436ty::Adt(def, _) => {
437 PathElem::Field(def.non_enum_variant().fields[FieldIdx::from_usize(field)].name)
438 }
439440// arrays/slices
441ty::Array(..) | ty::Slice(..) => PathElem::ArrayElem(field),
442443// dyn traits
444ty::Dynamic(..) => {
445{
match (&field, &0) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(field, 0);
446 PathElem::DynDowncast(field_ty)
447 }
448449// nothing else has an aggregate layout
450_ => ::rustc_span::macros::bug_impl(None,
format_args!("aggregate_field_path_elem: got non-aggregate type {0:?}",
layout.ty), Location::caller())bug!("aggregate_field_path_elem: got non-aggregate type {:?}", layout.ty),
451 }
452 }
453454fn with_elem<R>(
455&mut self,
456 elem: PathElem<'tcx>,
457 f: impl FnOnce(&mut Self) -> InterpResult<'tcx, R>,
458 ) -> InterpResult<'tcx, R> {
459// Remember the old state
460let path_len = self.path.projs.len();
461// Record new element
462self.path.projs.push(elem);
463// Perform operation
464let r = f(self)?;
465// Undo changes
466self.path.projs.truncate(path_len);
467// Done
468interp_ok(r)
469 }
470471fn read_immediate(
472&self,
473 val: &PlaceTy<'tcx, M::Provenance>,
474 expected: ExpectedKind,
475 ) -> InterpResult<'tcx, ImmTy<'tcx, M::Provenance>> {
476interp_ok({
self.ecx.read_immediate(val).map_err_kind(|e|
{
match e {
Ub(InvalidUninitBytes(_)) => {
{
let where_ = &self.path;
let path =
if !where_.projs.is_empty() {
let mut path = String::new();
write_path(&mut path, &where_.projs);
Some(path)
} else { None };
#[allow(unused)]
use ValidationErrorKind::*;
let msg = ValidationErrorKind::from(Uninit { expected });
::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
orig_ty: where_.orig_ty,
path,
ptr_bytes_warning: msg.ptr_bytes_warning(),
msg: msg.to_string(),
})
}
}
Unsup(ReadPointerAsInt(_)) => {
{
let where_ = &self.path;
let path =
if !where_.projs.is_empty() {
let mut path = String::new();
write_path(&mut path, &where_.projs);
Some(path)
} else { None };
#[allow(unused)]
use ValidationErrorKind::*;
let msg =
ValidationErrorKind::from(PointerAsInt { expected });
::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
orig_ty: where_.orig_ty,
path,
ptr_bytes_warning: msg.ptr_bytes_warning(),
msg: msg.to_string(),
})
}
}
Unsup(ReadPartialPointer(_)) => {
{
let where_ = &self.path;
let path =
if !where_.projs.is_empty() {
let mut path = String::new();
write_path(&mut path, &where_.projs);
Some(path)
} else { None };
#[allow(unused)]
use ValidationErrorKind::*;
let msg = ValidationErrorKind::from(PartialPointer);
::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
orig_ty: where_.orig_ty,
path,
ptr_bytes_warning: msg.ptr_bytes_warning(),
msg: msg.to_string(),
})
}
}
e => e,
}
})?
}try_validation!(
477self.ecx.read_immediate(val),
478self.path,
479 Ub(InvalidUninitBytes(_)) =>
480 Uninit { expected },
481// The `Unsup` cases can only occur during CTFE
482Unsup(ReadPointerAsInt(_)) =>
483 PointerAsInt { expected },
484 Unsup(ReadPartialPointer(_)) =>
485 PartialPointer,
486 ))
487 }
488489fn read_scalar(
490&self,
491 val: &PlaceTy<'tcx, M::Provenance>,
492 expected: ExpectedKind,
493 ) -> InterpResult<'tcx, Scalar<M::Provenance>> {
494interp_ok(self.read_immediate(val, expected)?.to_scalar())
495 }
496497/// Given a place and a pointer loaded from that place, ensure that the place does
498 /// not store any more provenance than the pointer does. IOW, if any provenance
499 /// was discarded when loading the pointer, it will also get discarded in-memory.
500fn reset_pointer_provenance(
501&mut self,
502 place: &PlaceTy<'tcx, M::Provenance>,
503 ptr: &ImmTy<'tcx, M::Provenance>,
504 ) -> InterpResult<'tcx> {
505if #[allow(non_exhaustive_omitted_patterns)] match ptr.layout.backend_repr {
BackendRepr::Scalar(..) => true,
_ => false,
}matches!(ptr.layout.backend_repr, BackendRepr::Scalar(..)) {
506// A thin pointer. If it has provenance, we don't have to do anything.
507 // If it does not, ensure we clear the provenance in memory.
508if !#[allow(non_exhaustive_omitted_patterns)] match ptr.to_scalar() {
Scalar::Ptr(..) => true,
_ => false,
}matches!(ptr.to_scalar(), Scalar::Ptr(..)) {
509// The loaded pointer has no provenance. Some bytes of its representation still
510 // might have provenance, which we have to clear.
511self.ecx.clear_provenance(place)?;
512 }
513 } else {
514// A wide pointer. This means we have to worry both about the pointer itself and the
515 // metadata. We do the lazy thing and just write back the value we got. Just
516 // clearing provenance in a targeted manner would be more efficient, but unless this
517 // is a perf hotspot it's just not worth the effort.
518self.ecx.write_immediate_no_validate(**ptr, place)?;
519 }
520interp_ok(())
521 }
522523fn check_wide_ptr_meta(
524&mut self,
525 meta: MemPlaceMeta<M::Provenance>,
526 pointee: TyAndLayout<'tcx>,
527 ) -> InterpResult<'tcx> {
528let tail = self.ecx.tcx.struct_tail_for_codegen(pointee.ty, self.ecx.typing_env);
529match tail.kind() {
530 ty::Dynamic(data, _) => {
531let vtable = meta.unwrap_meta().to_pointer(self.ecx);
532// Make sure it is a genuine vtable pointer for the right trait.
533{
self.ecx.get_ptr_vtable_ty(vtable,
Some(data)).map_err_kind(|e|
{
match e {
Ub(DanglingIntPointer { .. } | InvalidVTablePointer(..)) =>
{
{
let where_ = &self.path;
let path =
if !where_.projs.is_empty() {
let mut path = String::new();
write_path(&mut path, &where_.projs);
Some(path)
} else { None };
#[allow(unused)]
use ValidationErrorKind::*;
let msg =
ValidationErrorKind::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("encountered {0}, but expected a vtable pointer",
vtable))
}));
::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
orig_ty: where_.orig_ty,
path,
ptr_bytes_warning: msg.ptr_bytes_warning(),
msg: msg.to_string(),
})
}
}
Ub(InvalidVTableTrait { vtable_dyn_type, expected_dyn_type
}) => {
{
let where_ = &self.path;
let path =
if !where_.projs.is_empty() {
let mut path = String::new();
write_path(&mut path, &where_.projs);
Some(path)
} else { None };
#[allow(unused)]
use ValidationErrorKind::*;
let msg =
ValidationErrorKind::from(InvalidMetaWrongTrait {
expected_dyn_type,
vtable_dyn_type,
});
::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
orig_ty: where_.orig_ty,
path,
ptr_bytes_warning: msg.ptr_bytes_warning(),
msg: msg.to_string(),
})
}
}
e => e,
}
})?
};try_validation!(
534self.ecx.get_ptr_vtable_ty(vtable, Some(data)),
535self.path,
536 Ub(DanglingIntPointer{ .. } | InvalidVTablePointer(..)) =>
537format!("encountered {vtable}, but expected a vtable pointer"),
538 Ub(InvalidVTableTrait { vtable_dyn_type, expected_dyn_type }) =>
539 InvalidMetaWrongTrait { expected_dyn_type, vtable_dyn_type },
540 );
541 }
542 ty::Slice(..) | ty::Str => {
543let _len = meta.unwrap_meta().to_target_usize(self.ecx)?;
544// We do not check that `len * elem_size <= isize::MAX`:
545 // that is only required for references, and there it falls out of the
546 // "dereferenceable" check performed by Stacked Borrows.
547}
548 ty::Foreign(..) => {
549// Unsized, but not wide.
550}
551_ => ::rustc_span::macros::bug_impl(None,
format_args!("Unexpected unsized type tail: {0:?}", tail),
Location::caller())bug!("Unexpected unsized type tail: {:?}", tail),
552 }
553554interp_ok(())
555 }
556557/// Check a reference or `Box`.
558 ///
559 /// `ty` is the actual type of `value`; for a Box, `value` will be just the inner raw pointer.
560fn check_safe_pointer(
561&mut self,
562 value: &PlaceTy<'tcx, M::Provenance>,
563 ty: Ty<'tcx>,
564 ptr_kind: PtrKind,
565 ) -> InterpResult<'tcx> {
566// Note that some of those checks (those that encode the basic validity invariant of
567 // pointers) are duplicated in `place_deref`, so changes here might need updates there.
568let ptr = self.read_immediate(value, ptr_kind.into())?;
569if self.reset_provenance_and_padding {
570// There's no padding in a pointer.
571self.add_data_range_place(value);
572// Resetting provenance is done below, together with retagging, to avoid
573 // redundant writes.
574}
575let place = self.ecx.imm_ptr_to_mplace(&ptr)?;
576// Handle wide pointers.
577 // Check metadata early, for better diagnostics
578if place.layout.is_unsized() {
579self.check_wide_ptr_meta(place.meta(), place.layout)?;
580 }
581582// Determine size and alignment of pointee.
583let size_and_align = {
self.ecx.size_and_align_of_val(&place).map_err_kind(|e|
{
match e {
Ub(InvalidMeta(msg)) => {
{
let where_ = &self.path;
let path =
if !where_.projs.is_empty() {
let mut path = String::new();
write_path(&mut path, &where_.projs);
Some(path)
} else { None };
#[allow(unused)]
use ValidationErrorKind::*;
let msg =
ValidationErrorKind::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("encountered invalid {1} metadata: {0}",
match msg {
InvalidMetaKind::SliceTooBig =>
"slice is bigger than largest supported object",
InvalidMetaKind::TooBig =>
"total size is bigger than largest supported object",
}, ptr_kind))
}));
::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
orig_ty: where_.orig_ty,
path,
ptr_bytes_warning: msg.ptr_bytes_warning(),
msg: msg.to_string(),
})
}
}
e => e,
}
})?
}try_validation!(
584self.ecx.size_and_align_of_val(&place),
585self.path,
586 Ub(InvalidMeta(msg)) => format!(
587"encountered invalid {ptr_kind} metadata: {}",
588match msg {
589 InvalidMetaKind::SliceTooBig => "slice is bigger than largest supported object",
590 InvalidMetaKind::TooBig => "total size is bigger than largest supported object",
591 }
592 )
593 );
594let (size, align) = size_and_align595// for the purpose of validity, consider foreign types to have
596 // alignment and size determined by the layout (size will be 0,
597 // alignment should take attributes into account).
598.unwrap_or_else(|| (place.layout.size, place.layout.align));
599600// If we're not allow to dangle, make sure this is dereferenceable and retag it for
601 // the aliasing model.
602let adjusted_ptr = if !self.may_dangle {
603{
self.ecx.check_ptr_access(place.ptr(), size,
CheckInAllocMsg::Dereferenceable("pointer")).map_err_kind(|e|
{
match e {
Ub(DanglingIntPointer { addr: 0, .. }) => {
{
let where_ = &self.path;
let path =
if !where_.projs.is_empty() {
let mut path = String::new();
write_path(&mut path, &where_.projs);
Some(path)
} else { None };
#[allow(unused)]
use ValidationErrorKind::*;
let msg =
ValidationErrorKind::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("encountered a null {0}",
ptr_kind))
}));
::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
orig_ty: where_.orig_ty,
path,
ptr_bytes_warning: msg.ptr_bytes_warning(),
msg: msg.to_string(),
})
}
}
Ub(DanglingIntPointer { addr: i, .. }) => {
{
let where_ = &self.path;
let path =
if !where_.projs.is_empty() {
let mut path = String::new();
write_path(&mut path, &where_.projs);
Some(path)
} else { None };
#[allow(unused)]
use ValidationErrorKind::*;
let msg =
ValidationErrorKind::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("encountered a dangling {1} ({0} has no provenance)",
Pointer::<Option<AllocId>>::without_provenance(i),
ptr_kind))
}));
::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
orig_ty: where_.orig_ty,
path,
ptr_bytes_warning: msg.ptr_bytes_warning(),
msg: msg.to_string(),
})
}
}
Ub(PointerOutOfBounds { .. }) => {
{
let where_ = &self.path;
let path =
if !where_.projs.is_empty() {
let mut path = String::new();
write_path(&mut path, &where_.projs);
Some(path)
} else { None };
#[allow(unused)]
use ValidationErrorKind::*;
let msg =
ValidationErrorKind::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("encountered a dangling {0} (going beyond the bounds of its allocation)",
ptr_kind))
}));
::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
orig_ty: where_.orig_ty,
path,
ptr_bytes_warning: msg.ptr_bytes_warning(),
msg: msg.to_string(),
})
}
}
Ub(PointerUseAfterFree(..)) => {
{
let where_ = &self.path;
let path =
if !where_.projs.is_empty() {
let mut path = String::new();
write_path(&mut path, &where_.projs);
Some(path)
} else { None };
#[allow(unused)]
use ValidationErrorKind::*;
let msg =
ValidationErrorKind::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("encountered a dangling {0} (use-after-free)",
ptr_kind))
}));
::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
orig_ty: where_.orig_ty,
path,
ptr_bytes_warning: msg.ptr_bytes_warning(),
msg: msg.to_string(),
})
}
}
e => e,
}
})?
};try_validation!(
604self.ecx.check_ptr_access(
605 place.ptr(),
606 size,
607 CheckInAllocMsg::Dereferenceable("pointer"), // will anyway be replaced by validity message
608),
609self.path,
610 Ub(DanglingIntPointer { addr: 0, .. }) =>
611format!("encountered a null {ptr_kind}"),
612 Ub(DanglingIntPointer { addr: i, .. }) =>
613format!(
614"encountered a dangling {ptr_kind} ({ptr} has no provenance)",
615 ptr = Pointer::<Option<AllocId>>::without_provenance(i)
616 ),
617 Ub(PointerOutOfBounds { .. }) =>
618format!("encountered a dangling {ptr_kind} (going beyond the bounds of its allocation)"),
619 Ub(PointerUseAfterFree(..)) =>
620format!("encountered a dangling {ptr_kind} (use-after-free)"),
621 );
622if self.reset_provenance_and_padding {
623 M::retag_ptr_value(self.ecx, &ptr, ty).map_err_kind(|e| match e {
624 Ub(WriteToReadOnly(_)) => {
625{
let where_ = &self.path;
let path =
if !where_.projs.is_empty() {
let mut path = String::new();
write_path(&mut path, &where_.projs);
Some(path)
} else { None };
#[allow(unused)]
use ValidationErrorKind::*;
let msg =
ValidationErrorKind::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("encountered {0} pointing to read-only memory",
if ptr_kind == PtrKind::Box {
"box"
} else { "mutable reference" }))
}));
::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
orig_ty: where_.orig_ty,
path,
ptr_bytes_warning: msg.ptr_bytes_warning(),
msg: msg.to_string(),
})
}err_validation_failure!(
626self.path,
627format!(
628"encountered {} pointing to read-only memory",
629if ptr_kind == PtrKind::Box { "box" } else { "mutable reference" },
630 )
631 )632 }
633 InterpErrorKind::MachineStop(mut machine_err) => {
634// Enhance the aliasing model error with the current path.
635if !self.path.projs.is_empty() {
636let mut path = String::new();
637 write_path(&mut path, &self.path.projs);
638 machine_err.with_validation_path(path);
639 }
640 InterpErrorKind::MachineStop(machine_err)
641 }
642 e => e,
643 })?
644} else {
645// We can't retag if we're not resetting provenance.
646None647 }
648 } else {
649// We are not checking dereferenceability, but we still want to ensure that the pointer
650 // *could* be dereferenceable in *some* memory: we have to be able to compute the
651 // address at the end of this range without overflowing..
652let scalar = Scalar::from_maybe_pointer(place.ptr(), self.ecx);
653// Skip this if we don't know the absolute address (during CTFE).
654if let Ok(addr) = scalar.try_to_scalar_int() {
655// Try to compute the end address. Cannot use `Size` addition as that also applies
656 // the "max obj size" bound.
657let addr = Size::from_bytes(addr.to_target_usize(*self.ecx.tcx)).bytes();
658// addr + size must fit into usize, i.e., `sum <= usize::MAX`.
659if !addr660 .checked_add(size.bytes())
661 .is_some_and(|result| result <= self.ecx.target_usize_max())
662 {
663do yeet {
let where_ = &self.path;
let path =
if !where_.projs.is_empty() {
let mut path = String::new();
write_path(&mut path, &where_.projs);
Some(path)
} else { None };
#[allow(unused)]
use ValidationErrorKind::*;
let msg =
ValidationErrorKind::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("encountered a {1} that is too close to the end of the address space for a pointee of {0} bytes",
size.bytes(), ptr_kind))
}));
::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
orig_ty: where_.orig_ty,
path,
ptr_bytes_warning: msg.ptr_bytes_warning(),
msg: msg.to_string(),
})
}throw_validation_failure!(
664self.path,
665format!(
666"encountered a {ptr_kind} that is too close to the end of the address space for a pointee of {} bytes",
667 size.bytes(),
668 )
669 )670 }
671 }
672673// Pointer remains unchanged.
674None675 };
676// If the pointer needs adjusting, write back adjusted pointer. This automatically
677 // also clears any excess provenance. Otherwise, just clear the provenance.
678if let Some(ptr) = adjusted_ptr {
679self.ecx.write_immediate_no_validate(*ptr, value)?;
680 } else if self.reset_provenance_and_padding {
681self.reset_pointer_provenance(value, &ptr)?;
682 }
683684// Make sure this is non-null. This is obviously needed when `may_dangle` is set,
685 // but even if we did check dereferenceability above that would still allow null
686 // pointers if `size` is zero.
687let scalar = Scalar::from_maybe_pointer(place.ptr(), self.ecx);
688if self.ecx.scalar_may_be_null(scalar)? {
689let maybe = !M::Provenance::OFFSET_IS_ADDR && #[allow(non_exhaustive_omitted_patterns)] match scalar {
Scalar::Ptr(..) => true,
_ => false,
}matches!(scalar, Scalar::Ptr(..));
690do yeet {
let where_ = &self.path;
let path =
if !where_.projs.is_empty() {
let mut path = String::new();
write_path(&mut path, &where_.projs);
Some(path)
} else { None };
#[allow(unused)]
use ValidationErrorKind::*;
let msg =
ValidationErrorKind::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("encountered a {0}null {1}",
if maybe { "maybe-" } else { "" }, ptr_kind))
}));
::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
orig_ty: where_.orig_ty,
path,
ptr_bytes_warning: msg.ptr_bytes_warning(),
msg: msg.to_string(),
})
}throw_validation_failure!(
691self.path,
692format!(
693"encountered a {maybe}null {ptr_kind}",
694 maybe = if maybe { "maybe-" } else { "" }
695 )
696 )697 }
698699// Do not allow references to uninhabited types.
700if !place.layout.ty.is_opsem_inhabited(*self.ecx.tcx, self.ecx.typing_env) {
701let ty = place.layout.ty;
702do yeet {
let where_ = &self.path;
let path =
if !where_.projs.is_empty() {
let mut path = String::new();
write_path(&mut path, &where_.projs);
Some(path)
} else { None };
#[allow(unused)]
use ValidationErrorKind::*;
let msg =
ValidationErrorKind::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("encountered a {0} pointing to uninhabited type `{1}`",
ptr_kind, ty))
}));
::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
orig_ty: where_.orig_ty,
path,
ptr_bytes_warning: msg.ptr_bytes_warning(),
msg: msg.to_string(),
})
}throw_validation_failure!(
703self.path,
704format!("encountered a {ptr_kind} pointing to uninhabited type `{ty}`")
705 )706 }
707708// Check alignment after dereferenceable (if both are violated, trigger the error above).
709{
self.ecx.check_ptr_align(place.ptr(),
align).map_err_kind(|e|
{
match e {
Ub(AlignmentCheckFailed(Misalignment { required, has },
_msg)) => {
{
let where_ = &self.path;
let path =
if !where_.projs.is_empty() {
let mut path = String::new();
write_path(&mut path, &where_.projs);
Some(path)
} else { None };
#[allow(unused)]
use ValidationErrorKind::*;
let msg =
ValidationErrorKind::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("encountered an unaligned {2} (required {0} byte alignment but found {1})",
required.bytes(), has.bytes(), ptr_kind))
}));
::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
orig_ty: where_.orig_ty,
path,
ptr_bytes_warning: msg.ptr_bytes_warning(),
msg: msg.to_string(),
})
}
}
e => e,
}
})?
};try_validation!(
710self.ecx.check_ptr_align(
711 place.ptr(),
712 align,
713 ),
714self.path,
715 Ub(AlignmentCheckFailed(Misalignment { required, has }, _msg)) => format!(
716"encountered an unaligned {ptr_kind} (required {required_bytes} byte alignment but found {found_bytes})",
717 required_bytes = required.bytes(),
718 found_bytes = has.bytes()
719 ),
720 );
721722// Recursive checking (but not inside `MaybeDangling` of course).
723if let Some(ref_tracking) = self.ref_tracking.as_deref_mut()
724 && !self.may_dangle
725 {
726// Proceed recursively even for ZST, no reason to skip them!
727 // `!` is a ZST and we want to validate it.
728if let Some(ctfe_mode) = self.ctfe_mode {
729let mut skip_recursive_check = false;
730// CTFE imposes restrictions on what references can point to.
731if let Ok((alloc_id, _offset, _prov)) =
732self.ecx.ptr_try_get_alloc_id(place.ptr(), 0)
733 {
734// Everything should be already interned.
735let Some(global_alloc) = self.ecx.tcx.try_get_global_alloc(alloc_id) else {
736if self.ecx.memory.alloc_map.contains_key(&alloc_id) {
737// This can happen when interning didn't complete due to, e.g.
738 // missing `make_global`. This must mean other errors are already
739 // being reported.
740self.ecx.tcx.dcx().delayed_bug(
741"interning did not complete, there should be an error",
742 );
743return interp_ok(());
744 }
745// We can't have *any* references to non-existing allocations in const-eval
746 // as the rest of rustc isn't happy with them... so we throw an error, even
747 // though for zero-sized references this isn't really UB.
748 // A potential future alternative would be to resurrect this as a zero-sized allocation
749 // (which codegen will then compile to an aligned dummy pointer anyway).
750do yeet {
let where_ = &self.path;
let path =
if !where_.projs.is_empty() {
let mut path = String::new();
write_path(&mut path, &where_.projs);
Some(path)
} else { None };
#[allow(unused)]
use ValidationErrorKind::*;
let msg =
ValidationErrorKind::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("encountered a dangling {0} (use-after-free)",
ptr_kind))
}));
::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
orig_ty: where_.orig_ty,
path,
ptr_bytes_warning: msg.ptr_bytes_warning(),
msg: msg.to_string(),
})
};throw_validation_failure!(
751self.path,
752format!("encountered a dangling {ptr_kind} (use-after-free)")
753 );
754 };
755let (size, _align) =
756global_alloc.size_and_align(*self.ecx.tcx, self.ecx.typing_env);
757let alloc_actual_mutbl =
758global_alloc.mutability(*self.ecx.tcx, self.ecx.typing_env);
759760match global_alloc {
761 GlobalAlloc::Static(did) => {
762let DefKind::Static { nested, .. } = self.ecx.tcx.def_kind(did) else {
763::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
Location::caller())bug!()764 };
765if !!self.ecx.tcx.is_thread_local_static(did) {
::core::panicking::panic("assertion failed: !self.ecx.tcx.is_thread_local_static(did)")
};assert!(!self.ecx.tcx.is_thread_local_static(did));
766if !self.ecx.tcx.is_static(did) {
::core::panicking::panic("assertion failed: self.ecx.tcx.is_static(did)")
};assert!(self.ecx.tcx.is_static(did));
767match ctfe_mode {
768 CtfeValidationMode::Static { .. }
769 | CtfeValidationMode::Promoted { .. } => {
770// We skip recursively checking other statics. These statics must be sound by
771 // themselves, and the only way to get broken statics here is by using
772 // unsafe code.
773 // The reasons we don't check other statics is twofold. For one, in all
774 // sound cases, the static was already validated on its own, and second, we
775 // trigger cycle errors if we try to compute the value of the other static
776 // and that static refers back to us (potentially through a promoted).
777 // This could miss some UB, but that's fine.
778 // We still walk nested allocations, as they are fundamentally part of this validation run.
779 // This means we will also recurse into nested statics of *other*
780 // statics, even though we do not recurse into other statics directly.
781 // That's somewhat inconsistent but harmless.
782skip_recursive_check = !nested;
783 }
784 CtfeValidationMode::Const { .. } => {
785// If this is mutable memory or an `extern static`, there's no point in checking it -- we'd
786 // just get errors trying to read the value.
787if alloc_actual_mutbl.is_mut()
788 || self.ecx.tcx.is_foreign_item(did)
789 {
790skip_recursive_check = true;
791 }
792 }
793 }
794 }
795_ => (),
796 }
797798// If this allocation has size zero, there is no actual mutability here.
799if size != Size::ZERO {
800// Determine whether this pointer expects to be pointing to something mutable.
801let ptr_expected_mutbl = match ptr_kind {
802 PtrKind::Box => Mutability::Mut,
803 PtrKind::Ref(mutbl) => {
804// We do not take into account interior mutability here since we cannot know if
805 // there really is an `UnsafeCell` inside `Option<UnsafeCell>` -- so we check
806 // that in the recursive descent behind this reference (controlled by
807 // `allow_immutable_unsafe_cell`).
808mutbl809 }
810 };
811// Mutable pointer to immutable memory is no good.
812if ptr_expected_mutbl == Mutability::Mut813 && alloc_actual_mutbl == Mutability::Not814 {
815// This can actually occur with transmutes.
816do yeet {
let where_ = &self.path;
let path =
if !where_.projs.is_empty() {
let mut path = String::new();
write_path(&mut path, &where_.projs);
Some(path)
} else { None };
#[allow(unused)]
use ValidationErrorKind::*;
let msg =
ValidationErrorKind::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("encountered mutable reference or box pointing to read-only memory"))
}));
::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
orig_ty: where_.orig_ty,
path,
ptr_bytes_warning: msg.ptr_bytes_warning(),
msg: msg.to_string(),
})
};throw_validation_failure!(
817self.path,
818format!(
819"encountered mutable reference or box pointing to read-only memory"
820)
821 );
822 }
823 }
824 }
825// Potentially skip recursive check.
826if skip_recursive_check {
827return interp_ok(());
828 }
829 } else {
830// This is not CTFE, so it's Miri with recursive checking.
831 // FIXME: should we skip `UnsafeCell` behind shared references? Currently that is
832 // not needed since validation reads bypass Stacked Borrows and data race checks,
833 // but is that really coherent?
834}
835let path = &self.path;
836ref_tracking.track(place, || {
837// We need to clone the path anyway, make sure it gets created
838 // with enough space for the additional `Deref`.
839let mut new_projs = Vec::with_capacity(path.projs.len() + 1);
840new_projs.extend(&path.projs);
841new_projs.push(PathElem::Deref);
842Path { projs: new_projs, orig_ty: path.orig_ty }
843 });
844 }
845interp_ok(())
846 }
847848/// Check if this is a value of primitive type, and if yes check the validity of the value
849 /// at that type. Return `true` if the type is indeed primitive.
850 ///
851 /// Note that not all of these have `FieldsShape::Primitive`, e.g. wide references.
852fn try_visit_primitive(
853&mut self,
854 value: &PlaceTy<'tcx, M::Provenance>,
855 ) -> InterpResult<'tcx, bool> {
856// Go over all the primitive types
857let ty = value.layout.ty;
858match ty.kind() {
859 ty::Bool => {
860let scalar = self.read_scalar(value, ExpectedKind::Bool)?;
861{
scalar.to_bool().map_err_kind(|e|
{
match e {
Ub(InvalidBool(..)) => {
{
let where_ = &self.path;
let path =
if !where_.projs.is_empty() {
let mut path = String::new();
write_path(&mut path, &where_.projs);
Some(path)
} else { None };
#[allow(unused)]
use ValidationErrorKind::*;
let msg =
ValidationErrorKind::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("encountered {0:x}, but expected a boolean",
scalar))
}));
::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
orig_ty: where_.orig_ty,
path,
ptr_bytes_warning: msg.ptr_bytes_warning(),
msg: msg.to_string(),
})
}
}
e => e,
}
})?
};try_validation!(
862 scalar.to_bool(),
863self.path,
864 Ub(InvalidBool(..)) =>
865format!("encountered {scalar:x}, but expected a boolean"),
866 );
867if self.reset_provenance_and_padding {
868self.ecx.clear_provenance(value)?;
869self.add_data_range_place(value);
870 }
871interp_ok(true)
872 }
873 ty::Char => {
874let scalar = self.read_scalar(value, ExpectedKind::Char)?;
875{
scalar.to_char().map_err_kind(|e|
{
match e {
Ub(InvalidChar(..)) => {
{
let where_ = &self.path;
let path =
if !where_.projs.is_empty() {
let mut path = String::new();
write_path(&mut path, &where_.projs);
Some(path)
} else { None };
#[allow(unused)]
use ValidationErrorKind::*;
let msg =
ValidationErrorKind::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("encountered {0:x}, but expected a valid unicode scalar value (in `0..=0x10FFFF` but not in `0xD800..=0xDFFF`)",
scalar))
}));
::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
orig_ty: where_.orig_ty,
path,
ptr_bytes_warning: msg.ptr_bytes_warning(),
msg: msg.to_string(),
})
}
}
e => e,
}
})?
};try_validation!(
876 scalar.to_char(),
877self.path,
878 Ub(InvalidChar(..)) =>
879format!("encountered {scalar:x}, but expected a valid unicode scalar value \
880 (in `0..=0x10FFFF` but not in `0xD800..=0xDFFF`)")
881 );
882if self.reset_provenance_and_padding {
883self.ecx.clear_provenance(value)?;
884self.add_data_range_place(value);
885 }
886interp_ok(true)
887 }
888 ty::Float(_) | ty::Int(_) | ty::Uint(_) => {
889// NOTE: Keep this in sync with the array optimization for int/float
890 // types below!
891self.read_scalar(
892 value,
893if #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
ty::Float(..) => true,
_ => false,
}matches!(ty.kind(), ty::Float(..)) {
894 ExpectedKind::Float
895 } else {
896 ExpectedKind::Int
897 },
898 )?;
899if self.reset_provenance_and_padding {
900self.ecx.clear_provenance(value)?;
901self.add_data_range_place(value);
902 }
903interp_ok(true)
904 }
905 ty::RawPtr(pointee, ..) => {
906let ptr = self.read_immediate(value, ExpectedKind::RawPtr)?;
907if self.reset_provenance_and_padding {
908self.reset_pointer_provenance(value, &ptr)?;
909// There's no padding in a pointer.
910self.add_data_range_place(value);
911 }
912913if !pointee.is_sized(*self.ecx.tcx, self.ecx.typing_env) {
914// Raw pointers to unsized types need to have their metadata checked.
915 // We avoid creating this place for sized types to match codegen: those types
916 // might actually be invalid (i.e., too big)!
917let place = self.ecx.imm_ptr_to_mplace(&ptr)?;
918if !place.layout.is_unsized() {
::core::panicking::panic("assertion failed: place.layout.is_unsized()")
};assert!(place.layout.is_unsized());
919self.check_wide_ptr_meta(place.meta(), place.layout)?;
920 }
921interp_ok(true)
922 }
923 ty::Ref(_, _ty, mutbl) => {
924self.check_safe_pointer(value, ty, PtrKind::Ref(*mutbl))?;
925interp_ok(true)
926 }
927 ty::FnPtr(..) => {
928let scalar = self.read_scalar(value, ExpectedKind::FnPtr)?;
929930// If we check references recursively, also check that this points to a function.
931if let Some(_) = self.ref_tracking {
932let ptr = scalar.to_pointer(self.ecx);
933let _fn = {
self.ecx.get_ptr_fn(ptr).map_err_kind(|e|
{
match e {
Ub(DanglingIntPointer { .. } | InvalidFunctionPointer(..))
=> {
{
let where_ = &self.path;
let path =
if !where_.projs.is_empty() {
let mut path = String::new();
write_path(&mut path, &where_.projs);
Some(path)
} else { None };
#[allow(unused)]
use ValidationErrorKind::*;
let msg =
ValidationErrorKind::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("encountered {0}, but expected a function pointer",
ptr))
}));
::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
orig_ty: where_.orig_ty,
path,
ptr_bytes_warning: msg.ptr_bytes_warning(),
msg: msg.to_string(),
})
}
}
e => e,
}
})?
}try_validation!(
934self.ecx.get_ptr_fn(ptr),
935self.path,
936 Ub(DanglingIntPointer{ .. } | InvalidFunctionPointer(..)) =>
937format!("encountered {ptr}, but expected a function pointer"),
938 );
939// FIXME: Check if the signature matches
940} else {
941// Otherwise (for standalone Miri and for `-Zextra-const-ub-checks`),
942 // we have to still check it to be non-null.
943if self.ecx.scalar_may_be_null(scalar)? {
944let maybe =
945 !M::Provenance::OFFSET_IS_ADDR && #[allow(non_exhaustive_omitted_patterns)] match scalar {
Scalar::Ptr(..) => true,
_ => false,
}matches!(scalar, Scalar::Ptr(..));
946do yeet {
let where_ = &self.path;
let path =
if !where_.projs.is_empty() {
let mut path = String::new();
write_path(&mut path, &where_.projs);
Some(path)
} else { None };
#[allow(unused)]
use ValidationErrorKind::*;
let msg =
ValidationErrorKind::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("encountered a {0}null function pointer",
if maybe { "maybe-" } else { "" }))
}));
::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
orig_ty: where_.orig_ty,
path,
ptr_bytes_warning: msg.ptr_bytes_warning(),
msg: msg.to_string(),
})
};throw_validation_failure!(
947self.path,
948format!(
949"encountered a {maybe}null function pointer",
950 maybe = if maybe { "maybe-" } else { "" }
951 )
952 );
953 }
954 }
955if self.reset_provenance_and_padding {
956// Make sure we do not preserve partial provenance. This matches the thin
957 // pointer handling in `deref_pointer`.
958if #[allow(non_exhaustive_omitted_patterns)] match scalar {
Scalar::Int(..) => true,
_ => false,
}matches!(scalar, Scalar::Int(..)) {
959self.ecx.clear_provenance(value)?;
960 }
961self.add_data_range_place(value);
962 }
963interp_ok(true)
964 }
965 ty::Never => {
966do yeet {
let where_ = &self.path;
let path =
if !where_.projs.is_empty() {
let mut path = String::new();
write_path(&mut path, &where_.projs);
Some(path)
} else { None };
#[allow(unused)]
use ValidationErrorKind::*;
let msg =
ValidationErrorKind::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("encountered a value of the never type `!`"))
}));
::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
orig_ty: where_.orig_ty,
path,
ptr_bytes_warning: msg.ptr_bytes_warning(),
msg: msg.to_string(),
})
}throw_validation_failure!(
967self.path,
968format!("encountered a value of the never type `!`")
969 )970 }
971 ty::Foreign(..) | ty::FnDef(..) => {
972// Nothing to check.
973interp_ok(true)
974 }
975 ty::UnsafeBinder(_) => {
::core::panicking::panic_fmt(format_args!("not implemented: {0}",
format_args!("FIXME(unsafe_binder)")));
}unimplemented!("FIXME(unsafe_binder)"),
976// The above should be all the primitive types. The rest is compound, we
977 // check them by visiting their fields/variants.
978ty::Adt(..)
979 | ty::Tuple(..)
980 | ty::Array(..)
981 | ty::Slice(..)
982 | ty::Str983 | ty::Dynamic(..)
984 | ty::Closure(..)
985 | ty::Pat(..)
986 | ty::CoroutineClosure(..)
987 | ty::Coroutine(..) => interp_ok(false),
988// Some types only occur during typechecking, they have no layout.
989 // We should not see them here and we could not check them anyway.
990ty::Error(_)
991 | ty::Infer(..)
992 | ty::Placeholder(..)
993 | ty::Bound(..)
994 | ty::Param(..)
995 | ty::Alias(..)
996 | ty::CoroutineWitness(..) => ::rustc_span::macros::bug_impl(None,
format_args!("Encountered invalid type {0:?}", ty), Location::caller())bug!("Encountered invalid type {:?}", ty),
997 }
998 }
9991000fn visit_scalar(
1001&mut self,
1002 scalar: Scalar<M::Provenance>,
1003 scalar_layout: ScalarAbi,
1004 ) -> InterpResult<'tcx> {
1005let size = scalar_layout.size(self.ecx);
1006let valid_range = scalar_layout.valid_range(self.ecx);
1007let WrappingRange { start, end } = valid_range;
1008let max_value = size.unsigned_int_max();
1009if !(end <= max_value) {
::core::panicking::panic("assertion failed: end <= max_value")
};assert!(end <= max_value);
1010let bits = match scalar.try_to_scalar_int() {
1011Ok(int) => int.to_bits(size),
1012Err(_) => {
1013// So this is a pointer then, and casting to an int failed.
1014 // Can only happen during CTFE.
1015 // We support 2 kinds of ranges here: full range, and excluding zero.
1016if start == 1 && end == max_value {
1017// Only null is the niche. So make sure the ptr is NOT null.
1018if self.ecx.scalar_may_be_null(scalar)? {
1019do yeet {
let where_ = &self.path;
let path =
if !where_.projs.is_empty() {
let mut path = String::new();
write_path(&mut path, &where_.projs);
Some(path)
} else { None };
#[allow(unused)]
use ValidationErrorKind::*;
let msg =
ValidationErrorKind::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("encountered a maybe-null pointer, but expected something that is definitely non-zero"))
}));
::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
orig_ty: where_.orig_ty,
path,
ptr_bytes_warning: msg.ptr_bytes_warning(),
msg: msg.to_string(),
})
}throw_validation_failure!(
1020self.path,
1021format!(
1022"encountered a maybe-null pointer, but expected something that is definitely non-zero"
1023)
1024 )1025 } else {
1026return interp_ok(());
1027 }
1028 } else if scalar_layout.is_always_valid(self.ecx) {
1029// Easy. (This is reachable if `enforce_number_validity` is set.)
1030return interp_ok(());
1031 } else {
1032// Conservatively, we reject, because the pointer *could* have a bad value.
1033do yeet {
let where_ = &self.path;
let path =
if !where_.projs.is_empty() {
let mut path = String::new();
write_path(&mut path, &where_.projs);
Some(path)
} else { None };
#[allow(unused)]
use ValidationErrorKind::*;
let msg =
ValidationErrorKind::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("encountered a pointer with unknown absolute address, but expected something that is definitely {0}",
fmt_range(valid_range, max_value)))
}));
::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
orig_ty: where_.orig_ty,
path,
ptr_bytes_warning: msg.ptr_bytes_warning(),
msg: msg.to_string(),
})
}throw_validation_failure!(
1034self.path,
1035format!(
1036"encountered a pointer with unknown absolute address, but expected something that is definitely {in_range}",
1037 in_range = fmt_range(valid_range, max_value)
1038 )
1039 )1040 }
1041 }
1042 };
1043// Now compare.
1044if valid_range.contains(bits) {
1045interp_ok(())
1046 } else {
1047do yeet {
let where_ = &self.path;
let path =
if !where_.projs.is_empty() {
let mut path = String::new();
write_path(&mut path, &where_.projs);
Some(path)
} else { None };
#[allow(unused)]
use ValidationErrorKind::*;
let msg =
ValidationErrorKind::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("encountered {1}, but expected something {0}",
fmt_range(valid_range, max_value), bits))
}));
::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
orig_ty: where_.orig_ty,
path,
ptr_bytes_warning: msg.ptr_bytes_warning(),
msg: msg.to_string(),
})
}throw_validation_failure!(
1048self.path,
1049format!(
1050"encountered {bits}, but expected something {in_range}",
1051 in_range = fmt_range(valid_range, max_value)
1052 )
1053 )1054 }
1055 }
10561057fn in_mutable_memory(&self, val: &PlaceTy<'tcx, M::Provenance>) -> bool {
1058if true {
if !self.ctfe_mode.is_some() {
::core::panicking::panic("assertion failed: self.ctfe_mode.is_some()")
};
};debug_assert!(self.ctfe_mode.is_some());
1059if let Some(mplace) = val.as_mplace_or_local().left() {
1060if let Some(alloc_id) = mplace.ptr().provenance.and_then(|p| p.get_alloc_id()) {
1061let tcx = *self.ecx.tcx;
1062// Everything must be already interned.
1063let mutbl = tcx.global_alloc(alloc_id).mutability(tcx, self.ecx.typing_env);
1064if let Some((_, alloc)) = self.ecx.memory.alloc_map.get(alloc_id) {
1065{
match (&alloc.mutability, &mutbl) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(alloc.mutability, mutbl);
1066 }
1067mutbl.is_mut()
1068 } else {
1069// No memory at all.
1070false
1071}
1072 } else {
1073// A local variable -- definitely mutable.
1074true
1075}
1076 }
10771078/// Add the given pointer-length pair to the "data" range of this visit.
1079fn add_data_range(&mut self, ptr: Pointer<Option<M::Provenance>>, size: Size) {
1080if let Some(data_bytes) = self.data_bytes.as_mut() {
1081// We only have to store the offset, the rest is the same for all pointers here.
1082 // The logic is agnostic to whether the offset is relative or absolute as long as
1083 // it is consistent.
1084let (_prov, offset) = ptr.into_raw_parts();
1085// Add this.
1086data_bytes.add_range(offset, size);
1087 };
1088 }
10891090/// Add the entire given place to the "data" range of this visit.
1091fn add_data_range_place(&mut self, place: &PlaceTy<'tcx, M::Provenance>) {
1092// Only sized places can be added this way.
1093if true {
if !place.layout.is_sized() {
::core::panicking::panic("assertion failed: place.layout.is_sized()")
};
};debug_assert!(place.layout.is_sized());
1094if let Some(data_bytes) = self.data_bytes.as_mut() {
1095let offset = Self::data_range_offset(self.ecx, place);
1096data_bytes.add_range(offset, place.layout.size);
1097 }
1098 }
10991100/// Convert a place into the offset it starts at, for the purpose of data_range tracking.
1101 /// Must only be called if `data_bytes` is `Some(_)`.
1102fn data_range_offset(ecx: &InterpCx<'tcx, M>, place: &PlaceTy<'tcx, M::Provenance>) -> Size {
1103// The presence of `data_bytes` implies that our place is in memory.
1104let ptr = ecx1105 .place_to_op(place)
1106 .expect("place must be in memory")
1107 .as_mplace_or_imm()
1108 .expect_left("place must be in memory")
1109 .ptr();
1110let (_prov, offset) = ptr.into_raw_parts();
1111offset1112 }
11131114fn reset_padding(&mut self, place: &PlaceTy<'tcx, M::Provenance>) -> InterpResult<'tcx> {
1115let Some(data_bytes) = self.data_bytes.as_mut() else { return interp_ok(()) };
1116// Our value must be in memory, otherwise we would not have set up `data_bytes`.
1117let mplace = self.ecx.force_allocation(place)?;
1118// Determine starting offset and size.
1119let (_prov, start_offset) = mplace.ptr().into_raw_parts();
1120let (size, _align) = self
1121.ecx
1122 .size_and_align_of_val(&mplace)?
1123.unwrap_or((mplace.layout.size, mplace.layout.align));
1124// If there is no padding at all, we can skip the rest: check for
1125 // a single data range covering the entire value.
1126if data_bytes.0 == &[(start_offset, size)] {
1127return interp_ok(());
1128 }
1129// Get a handle for the allocation. Do this only once, to avoid looking up the same
1130 // allocation over and over again. (Though to be fair, iterating the value already does
1131 // exactly that.)
1132let Some(mut alloc) = self.ecx.get_ptr_alloc_mut(mplace.ptr(), size)? else {
1133// A ZST, no padding to clear.
1134return interp_ok(());
1135 };
1136// Add a "finalizer" data range at the end, so that the iteration below finds all gaps
1137 // between ranges.
1138data_bytes.0.push((start_offset + size, Size::ZERO));
1139// Iterate, and reset gaps.
1140let mut padding_cleared_until = start_offset;
1141for &(offset, size) in data_bytes.0.iter() {
1142if !(offset >= padding_cleared_until) {
{
::core::panicking::panic_fmt(format_args!("reset_padding on {0}: previous field ended at offset {1}, next field starts at {2} (and has a size of {3} bytes)",
mplace.layout.ty,
(padding_cleared_until - start_offset).bytes(),
(offset - start_offset).bytes(), size.bytes()));
}
};assert!(
1143 offset >= padding_cleared_until,
1144"reset_padding on {}: previous field ended at offset {}, next field starts at {} (and has a size of {} bytes)",
1145 mplace.layout.ty,
1146 (padding_cleared_until - start_offset).bytes(),
1147 (offset - start_offset).bytes(),
1148 size.bytes(),
1149 );
1150if offset > padding_cleared_until {
1151// We found padding. Adjust the range to be relative to `alloc`, and make it uninit.
1152let padding_start = padding_cleared_until - start_offset;
1153let padding_size = offset - padding_cleared_until;
1154let range = alloc_range(padding_start, padding_size);
1155{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/f5cedb83a788ea9581097abc36a2a8503a7f541c/compiler/rustc_const_eval/src/interpret/validity.rs:1155",
"rustc_const_eval::interpret::validity",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/f5cedb83a788ea9581097abc36a2a8503a7f541c/compiler/rustc_const_eval/src/interpret/validity.rs"),
::tracing_core::__macro_support::Option::Some(1155u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::validity"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("reset_padding on {0}: resetting padding range {1:?}",
mplace.layout.ty, range) as &dyn ::tracing::field::Value))])
});
} else { ; }
};trace!("reset_padding on {}: resetting padding range {range:?}", mplace.layout.ty);
1156 alloc.write_uninit(range);
1157 }
1158 padding_cleared_until = offset + size;
1159 }
1160if !(padding_cleared_until == start_offset + size) {
::core::panicking::panic("assertion failed: padding_cleared_until == start_offset + size")
};assert!(padding_cleared_until == start_offset + size);
1161interp_ok(())
1162 }
11631164/// Computes the data range of this union type:
1165 /// which bytes are inside a field (i.e., not padding.)
1166fn union_data_range<'e>(
1167 ecx: &'e mut InterpCx<'tcx, M>,
1168 layout: TyAndLayout<'tcx>,
1169 ) -> Cow<'e, RangeSet> {
1170if !layout.ty.is_union() {
::core::panicking::panic("assertion failed: layout.ty.is_union()")
};assert!(layout.ty.is_union());
1171if !layout.is_sized() {
{
::core::panicking::panic_fmt(format_args!("there are no unsized unions"));
}
};assert!(layout.is_sized(), "there are no unsized unions");
1172let layout_cx = LayoutCx::new(*ecx.tcx, ecx.typing_env);
1173return M::cached_union_data_range(ecx, layout.ty, || {
1174let mut out = RangeSet::new();
1175union_data_range_uncached(&layout_cx, layout, Size::ZERO, &mut out);
1176out1177 });
11781179/// Helper for recursive traversal: add data ranges of the given type to `out`.
1180fn union_data_range_uncached<'tcx>(
1181 cx: &LayoutCx<'tcx>,
1182 layout: TyAndLayout<'tcx>,
1183 base_offset: Size,
1184 out: &mut RangeSet,
1185 ) {
1186// If this is a ZST, we don't contain any data. In particular, this helps us to quickly
1187 // skip over huge arrays of ZST.
1188if layout.is_zst() {
1189return;
1190 }
1191// Just recursively add all the fields of everything to the output.
1192match &layout.fields {
1193 FieldsShape::Primitive => {
1194out.add_range(base_offset, layout.size);
1195 }
1196&FieldsShape::Union(fields) => {
1197// Currently, all fields start at offset 0 (relative to `base_offset`).
1198for field in 0..fields.get() {
1199let field = layout.field(cx, field);
1200 union_data_range_uncached(cx, field, base_offset, out);
1201 }
1202 }
1203&FieldsShape::Array { stride, count } => {
1204let elem = layout.field(cx, 0);
12051206// Fast-path for large arrays of simple types that do not contain any padding.
1207if elem.backend_repr.is_scalar() {
1208out.add_range(base_offset, elem.size * count);
1209 } else {
1210for idx in 0..count {
1211// This repeats the same computation for every array element... but the alternative
1212 // is to allocate temporary storage for a dedicated `out` set for the array element,
1213 // and replicating that N times. Is that better?
1214union_data_range_uncached(cx, elem, base_offset + idx * stride, out);
1215 }
1216 }
1217 }
1218 FieldsShape::Arbitrary { offsets, .. } => {
1219for (field, &offset) in offsets.iter_enumerated() {
1220let field = layout.field(cx, field.as_usize());
1221 union_data_range_uncached(cx, field, base_offset + offset, out);
1222 }
1223 }
1224 }
1225// Don't forget potential other variants.
1226match &layout.variants {
1227 Variants::Single { .. } | Variants::Empty => {
1228// Fully handled above.
1229}
1230 Variants::Multiple { variants, .. } => {
1231for variant in variants.indices() {
1232let variant = layout.for_variant(cx, variant);
1233 union_data_range_uncached(cx, variant, base_offset, out);
1234 }
1235 }
1236 }
1237 }
1238 }
1239}
12401241impl<'rt, 'tcx, M: Machine<'tcx>> ValueVisitor<'tcx, M> for ValidityVisitor<'rt, 'tcx, M> {
1242type V = PlaceTy<'tcx, M::Provenance>;
12431244#[inline(always)]
1245fn ecx(&self) -> &InterpCx<'tcx, M> {
1246self.ecx
1247 }
12481249fn read_discriminant(
1250&mut self,
1251 val: &PlaceTy<'tcx, M::Provenance>,
1252 ) -> InterpResult<'tcx, VariantIdx> {
1253self.with_elem(PathElem::EnumTag, move |this| {
1254interp_ok({
this.ecx.read_discriminant(val).map_err_kind(|e|
{
match e {
Ub(InvalidTag(val)) => {
{
let where_ = &this.path;
let path =
if !where_.projs.is_empty() {
let mut path = String::new();
write_path(&mut path, &where_.projs);
Some(path)
} else { None };
#[allow(unused)]
use ValidationErrorKind::*;
let msg =
ValidationErrorKind::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("encountered {0:x}, but expected a valid enum tag",
val))
}));
::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
orig_ty: where_.orig_ty,
path,
ptr_bytes_warning: msg.ptr_bytes_warning(),
msg: msg.to_string(),
})
}
}
Ub(UninhabitedEnumVariantRead(_)) => {
{
let where_ = &this.path;
let path =
if !where_.projs.is_empty() {
let mut path = String::new();
write_path(&mut path, &where_.projs);
Some(path)
} else { None };
#[allow(unused)]
use ValidationErrorKind::*;
let msg =
ValidationErrorKind::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("encountered an uninhabited enum variant"))
}));
::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
orig_ty: where_.orig_ty,
path,
ptr_bytes_warning: msg.ptr_bytes_warning(),
msg: msg.to_string(),
})
}
}
e => e,
}
})?
}try_validation!(
1255 this.ecx.read_discriminant(val),
1256 this.path,
1257 Ub(InvalidTag(val)) =>
1258format!("encountered {val:x}, but expected a valid enum tag"),
1259 Ub(UninhabitedEnumVariantRead(_)) =>
1260format!("encountered an uninhabited enum variant"),
1261// Uninit / bad provenance are not possible since the field was already previously
1262 // checked at its integer type.
1263))
1264 })
1265 }
12661267#[inline]
1268fn visit_field(
1269&mut self,
1270 old_val: &PlaceTy<'tcx, M::Provenance>,
1271 field: usize,
1272 new_val: &PlaceTy<'tcx, M::Provenance>,
1273 ) -> InterpResult<'tcx> {
1274let elem = self.aggregate_field_path_elem(old_val.layout, field, new_val.layout.ty);
1275self.with_elem(elem, move |this| this.visit_value(new_val))
1276 }
12771278#[inline]
1279fn visit_variant(
1280&mut self,
1281 old_val: &PlaceTy<'tcx, M::Provenance>,
1282 variant_id: VariantIdx,
1283 new_val: &PlaceTy<'tcx, M::Provenance>,
1284 ) -> InterpResult<'tcx> {
1285let name = match old_val.layout.ty.kind() {
1286 ty::Adt(adt, _) => PathElem::Variant(adt.variant(variant_id).name),
1287// Coroutines also have variants
1288ty::Coroutine(..) => PathElem::CoroutineState(variant_id),
1289_ => ::rustc_span::macros::bug_impl(None,
format_args!("Unexpected type with variant: {0:?}", old_val.layout.ty),
Location::caller())bug!("Unexpected type with variant: {:?}", old_val.layout.ty),
1290 };
1291self.with_elem(name, move |this| this.visit_value(new_val))
1292 }
12931294#[inline(always)]
1295fn visit_union(
1296&mut self,
1297 val: &PlaceTy<'tcx, M::Provenance>,
1298 _fields: NonZero<usize>,
1299 ) -> InterpResult<'tcx> {
1300// Special check for CTFE validation, preventing `UnsafeCell` inside unions in immutable memory.
1301if self.ctfe_mode.is_some_and(|c| !c.allow_immutable_unsafe_cell()) {
1302// Unsized unions are currently not a thing, but let's keep this code consistent with
1303 // the check in `visit_value`.
1304let zst = self.ecx.size_and_align_of_val(val)?.is_some_and(|(s, _a)| s.bytes() == 0);
1305if !zst && !val.layout.ty.is_freeze(*self.ecx.tcx, self.ecx.typing_env) {
1306if !self.in_mutable_memory(val) {
1307do yeet {
let where_ = &self.path;
let path =
if !where_.projs.is_empty() {
let mut path = String::new();
write_path(&mut path, &where_.projs);
Some(path)
} else { None };
#[allow(unused)]
use ValidationErrorKind::*;
let msg =
ValidationErrorKind::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("encountered `UnsafeCell` in read-only memory"))
}));
::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
orig_ty: where_.orig_ty,
path,
ptr_bytes_warning: msg.ptr_bytes_warning(),
msg: msg.to_string(),
})
};throw_validation_failure!(
1308self.path,
1309format!("encountered `UnsafeCell` in read-only memory")
1310 );
1311 }
1312 }
1313 }
1314if self.reset_provenance_and_padding
1315 && let Some(data_bytes) = self.data_bytes.as_mut()
1316 {
1317let base_offset = Self::data_range_offset(self.ecx, val);
1318// Determine and add data range for this union.
1319let union_data_range = Self::union_data_range(self.ecx, val.layout);
1320for &(offset, size) in union_data_range.0.iter() {
1321 data_bytes.add_range(base_offset + offset, size);
1322 }
1323 }
1324interp_ok(())
1325 }
13261327#[inline]
1328fn visit_box(
1329&mut self,
1330 box_ty: Ty<'tcx>,
1331 val: &PlaceTy<'tcx, M::Provenance>,
1332 ) -> InterpResult<'tcx> {
1333self.check_safe_pointer(&val, box_ty, PtrKind::Box)?;
1334interp_ok(())
1335 }
13361337#[inline]
1338fn visit_variantless(&mut self, val: &PlaceTy<'tcx, M::Provenance>) -> InterpResult<'tcx> {
1339let ty = val.layout.ty;
1340if !ty.is_enum() {
{
::core::panicking::panic_fmt(format_args!("encountered non-enum variantless type `{0}`",
ty));
}
};assert!(ty.is_enum(), "encountered non-enum variantless type `{ty}`");
1341do yeet {
let where_ = &self.path;
let path =
if !where_.projs.is_empty() {
let mut path = String::new();
write_path(&mut path, &where_.projs);
Some(path)
} else { None };
#[allow(unused)]
use ValidationErrorKind::*;
let msg =
ValidationErrorKind::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("encountered a value of zero-variant enum `{0}`",
ty))
}));
::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
orig_ty: where_.orig_ty,
path,
ptr_bytes_warning: msg.ptr_bytes_warning(),
msg: msg.to_string(),
})
};throw_validation_failure!(
1342self.path,
1343format!("encountered a value of zero-variant enum `{ty}`")
1344 );
1345 }
13461347#[inline]
1348fn visit_value(&mut self, val: &PlaceTy<'tcx, M::Provenance>) -> InterpResult<'tcx> {
1349{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/f5cedb83a788ea9581097abc36a2a8503a7f541c/compiler/rustc_const_eval/src/interpret/validity.rs:1349",
"rustc_const_eval::interpret::validity",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/f5cedb83a788ea9581097abc36a2a8503a7f541c/compiler/rustc_const_eval/src/interpret/validity.rs"),
::tracing_core::__macro_support::Option::Some(1349u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::validity"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("visit_value: {0:?}, {1:?}",
*val, val.layout) as &dyn ::tracing::field::Value))])
});
} else { ; }
};trace!("visit_value: {:?}, {:?}", *val, val.layout);
13501351// Check primitive types -- the leaves of our recursive descent.
1352 // This is called even for enum discriminants (which are "fields" of their enum),
1353 // so for integer-typed discriminants the provenance reset will happen here.
1354 // We assume that the Scalar validity range does not restrict these values
1355 // any further than `try_visit_primitive` does!
1356if self.try_visit_primitive(val)? {
1357return interp_ok(());
1358 }
13591360// Special check preventing `UnsafeCell` in the inner part of constants
1361if self.ctfe_mode.is_some_and(|c| !c.allow_immutable_unsafe_cell()) {
1362// Exclude ZST values. We need to compute the dynamic size/align to properly
1363 // handle slices and trait objects.
1364let zst = self.ecx.size_and_align_of_val(val)?.is_some_and(|(s, _a)| s.bytes() == 0);
1365if !zst1366 && let Some(def) = val.layout.ty.ty_adt_def()
1367 && def.is_unsafe_cell()
1368 {
1369if !self.in_mutable_memory(val) {
1370do yeet {
let where_ = &self.path;
let path =
if !where_.projs.is_empty() {
let mut path = String::new();
write_path(&mut path, &where_.projs);
Some(path)
} else { None };
#[allow(unused)]
use ValidationErrorKind::*;
let msg =
ValidationErrorKind::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("encountered `UnsafeCell` in read-only memory"))
}));
::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
orig_ty: where_.orig_ty,
path,
ptr_bytes_warning: msg.ptr_bytes_warning(),
msg: msg.to_string(),
})
};throw_validation_failure!(
1371self.path,
1372format!("encountered `UnsafeCell` in read-only memory")
1373 );
1374 }
1375 }
1376 }
13771378// Recursively walk the value at its type. Apply optimizations for some large types.
1379match val.layout.ty.kind() {
1380 ty::Str => {
1381let mplace = val.assert_mem_place(); // strings are unsized and hence never immediate
1382let len = mplace.len(self.ecx)?;
1383let expected = ExpectedKind::Str;
1384{
self.ecx.read_bytes_ptr_strip_provenance(mplace.ptr(),
Size::from_bytes(len)).map_err_kind(|e|
{
match e {
Ub(InvalidUninitBytes(..)) => {
{
let where_ = &self.path;
let path =
if !where_.projs.is_empty() {
let mut path = String::new();
write_path(&mut path, &where_.projs);
Some(path)
} else { None };
#[allow(unused)]
use ValidationErrorKind::*;
let msg = ValidationErrorKind::from(Uninit { expected });
::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
orig_ty: where_.orig_ty,
path,
ptr_bytes_warning: msg.ptr_bytes_warning(),
msg: msg.to_string(),
})
}
}
Unsup(ReadPointerAsInt(_)) => {
{
let where_ = &self.path;
let path =
if !where_.projs.is_empty() {
let mut path = String::new();
write_path(&mut path, &where_.projs);
Some(path)
} else { None };
#[allow(unused)]
use ValidationErrorKind::*;
let msg =
ValidationErrorKind::from(PointerAsInt { expected });
::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
orig_ty: where_.orig_ty,
path,
ptr_bytes_warning: msg.ptr_bytes_warning(),
msg: msg.to_string(),
})
}
}
e => e,
}
})?
};try_validation!(
1385self.ecx.read_bytes_ptr_strip_provenance(mplace.ptr(), Size::from_bytes(len)),
1386self.path,
1387 Ub(InvalidUninitBytes(..)) =>
1388 Uninit { expected },
1389 Unsup(ReadPointerAsInt(_)) =>
1390 PointerAsInt { expected },
1391 );
1392 }
1393 ty::Array(tys, ..) | ty::Slice(tys)
1394// This optimization applies for types that can hold arbitrary non-provenance bytes (such as
1395 // integer and floating point types).
1396 // FIXME(wesleywiser) This logic could be extended further to arbitrary structs or
1397 // tuples made up of integer/floating point types or inhabited ZSTs with no padding.
1398if #[allow(non_exhaustive_omitted_patterns)] match tys.kind() {
ty::Int(..) | ty::Uint(..) | ty::Float(..) => true,
_ => false,
}matches!(tys.kind(), ty::Int(..) | ty::Uint(..) | ty::Float(..))1399 =>
1400 {
1401let expected = if tys.is_integral() { ExpectedKind::Int } else { ExpectedKind::Float };
1402// Optimized handling for arrays of integer/float type.
14031404 // This is the length of the array/slice.
1405let len = val.len(self.ecx)?;
1406// This is the element type size.
1407let layout = self.ecx.layout_of(*tys)?;
1408// This is the size in bytes of the whole array. (This checks for overflow.)
1409let size = layout.size * len;
1410// If the size is 0, there is nothing to check.
1411 // (`size` can only be 0 if `len` is 0, and empty arrays are always valid.)
1412if size == Size::ZERO {
1413return interp_ok(());
1414 }
1415// Now that we definitely have a non-ZST array, we know it lives in memory -- except it may
1416 // be an uninitialized local variable, those are also "immediate".
1417let mplace = match val.to_op(self.ecx)?.as_mplace_or_imm() {
1418Left(mplace) => mplace,
1419Right(imm) => match *imm {
1420 Immediate::Uninit =>
1421do yeet {
let where_ = &self.path;
let path =
if !where_.projs.is_empty() {
let mut path = String::new();
write_path(&mut path, &where_.projs);
Some(path)
} else { None };
#[allow(unused)]
use ValidationErrorKind::*;
let msg = ValidationErrorKind::from(Uninit { expected });
::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
orig_ty: where_.orig_ty,
path,
ptr_bytes_warning: msg.ptr_bytes_warning(),
msg: msg.to_string(),
})
}throw_validation_failure!(
1422self.path,
1423 Uninit { expected }
1424 ),
1425 Immediate::Scalar(..) | Immediate::ScalarPair { .. } =>
1426::rustc_span::macros::bug_impl(None,
format_args!("arrays/slices can never have Scalar/ScalarPair layout"),
Location::caller())bug!("arrays/slices can never have Scalar/ScalarPair layout"),
1427 }
1428 };
14291430// Optimization: we just check the entire range at once.
1431 // NOTE: Keep this in sync with the handling of integer and float
1432 // types above, in `visit_primitive`.
1433 // No need for an alignment check here, this is not an actual memory access.
1434let alloc = self.ecx.get_ptr_alloc(mplace.ptr(), size)?.expect("we already excluded size 0");
14351436 alloc.get_bytes_strip_provenance().map_err_kind(|kind| {
1437// Some error happened, try to provide a more detailed description.
1438 // For some errors we might be able to provide extra information.
1439 // (This custom logic does not fit the `try_validation!` macro.)
1440match kind {
1441 Ub(InvalidUninitBytes(Some((_alloc_id, access)))) | Unsup(ReadPointerAsInt(Some((_alloc_id, access)))) => {
1442// Some byte was uninitialized, determine which
1443 // element that byte belongs to so we can
1444 // provide an index.
1445let i = usize::try_from(
1446 access.bad.start.bytes() / layout.size.bytes(),
1447 )
1448 .unwrap();
1449self.path.projs.push(PathElem::ArrayElem(i));
14501451if #[allow(non_exhaustive_omitted_patterns)] match kind {
Ub(InvalidUninitBytes(_)) => true,
_ => false,
}matches!(kind, Ub(InvalidUninitBytes(_))) {
1452{
let where_ = &self.path;
let path =
if !where_.projs.is_empty() {
let mut path = String::new();
write_path(&mut path, &where_.projs);
Some(path)
} else { None };
#[allow(unused)]
use ValidationErrorKind::*;
let msg = ValidationErrorKind::from(Uninit { expected });
::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
orig_ty: where_.orig_ty,
path,
ptr_bytes_warning: msg.ptr_bytes_warning(),
msg: msg.to_string(),
})
}err_validation_failure!(self.path, Uninit { expected })1453 } else {
1454{
let where_ = &self.path;
let path =
if !where_.projs.is_empty() {
let mut path = String::new();
write_path(&mut path, &where_.projs);
Some(path)
} else { None };
#[allow(unused)]
use ValidationErrorKind::*;
let msg = ValidationErrorKind::from(PointerAsInt { expected });
::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
orig_ty: where_.orig_ty,
path,
ptr_bytes_warning: msg.ptr_bytes_warning(),
msg: msg.to_string(),
})
}err_validation_failure!(self.path, PointerAsInt {expected})1455 }
1456 }
14571458// Propagate upwards (that will also check for unexpected errors).
1459err => err,
1460 }
1461 })?;
14621463// Don't forget that these are all non-pointer types, and thus do not preserve
1464 // provenance.
1465if self.reset_provenance_and_padding {
1466// We can't share this with above as above, we might be looking at read-only memory.
1467let mut alloc = self.ecx.get_ptr_alloc_mut(mplace.ptr(), size)?.expect("we already excluded size 0");
1468alloc.clear_provenance();
1469// Also, mark this as containing data, not padding.
1470self.add_data_range(mplace.ptr(), size);
1471 }
1472 }
1473// Fast path for arrays and slices of ZSTs. We only need to check a single ZST element
1474 // of an array and not all of them, because there's only a single value of a specific
1475 // ZST type, so either validation fails for all elements or none.
1476ty::Array(tys, ..) | ty::Slice(tys) if self.ecx.layout_of(*tys)?.is_zst() => {
1477// Validate just the first element (if any).
1478if val.len(self.ecx)? > 0 {
1479self.visit_field(val, 0, &self.ecx.project_index(val, 0)?)?;
1480 }
1481 }
1482 ty::Pat(base, pat) => {
1483// First check that the base type is valid
1484self.visit_value(&val.transmute(self.ecx.layout_of(*base)?, self.ecx)?)?;
1485// When you extend this match, make sure to also add tests to
1486 // tests/ui/type/pattern_types/validity.rs
1487match **pat {
1488// Range and non-null patterns are precisely reflected into `valid_range` and thus
1489 // handled fully by `visit_scalar` (called below).
1490ty::PatternKind::Range { .. } => {},
1491 ty::PatternKind::NotNull => {},
14921493// FIXME(pattern_types): check that the value is covered by one of the variants.
1494 // For now, we rely on layout computation setting the scalar's `valid_range` to
1495 // match the pattern. However, this cannot always work; the layout may
1496 // pessimistically cover actually illegal ranges and Miri would miss that UB.
1497 // The consolation here is that codegen also will miss that UB, so at least
1498 // we won't see optimizations actually breaking such programs.
1499ty::PatternKind::Or(_patterns) => {}
1500 }
1501// FIXME(pattern_types): handle everything based on the pattern, not on the layout.
1502 // it's ok to run scalar validation even if the pattern type is `u8 is 0..=255` and thus
1503 // allows uninit values, because that's rare and so not a perf issue.
1504match val.layout.backend_repr {
1505 BackendRepr::Scalar(scalar_layout) => {
1506if !scalar_layout.is_uninit_valid() {
1507// There is something to check here.
1508 // We read directly via `ecx` since the read cannot fail -- we already read
1509 // this field above when recursing into the field.
1510let scalar = self.ecx.read_scalar(val)?;
1511self.visit_scalar(scalar, scalar_layout)?;
1512 }
1513 }
1514 BackendRepr::ScalarPair { a: a_layout, b: b_layout, b_offset: _ } => {
1515// We can only proceed if *both* scalars need to be initialized.
1516 // FIXME: find a way to also check ScalarPair when one side can be uninit but
1517 // the other must be init.
1518if !a_layout.is_uninit_valid() && !b_layout.is_uninit_valid() {
1519// We read directly via `ecx` since the read cannot fail -- we already read
1520 // this field above when recursing into the field.
1521let (a, b) = self.ecx.read_immediate(val)?.to_scalar_pair();
1522self.visit_scalar(a, a_layout)?;
1523self.visit_scalar(b, b_layout)?;
1524 }
1525 }
1526 BackendRepr::SimdVector { .. } | BackendRepr::SimdScalableVector { .. } => ::core::panicking::unreachable_default_msg()unreachable!(),
1527 BackendRepr::Memory { .. } => ::core::panicking::unreachable_default_msg()unreachable!()1528 }
1529 }
1530_ => {
1531let old_may_dangle = self.may_dangle;
1532self.may_dangle |= val.layout.ty.is_like_maybe_dangling();
15331534// default handler
1535{
self.walk_value(val).map_err_kind(|e|
{
match e {
Ub(InvalidVTableTrait { vtable_dyn_type, expected_dyn_type
}) => {
{
let where_ = &self.path;
let path =
if !where_.projs.is_empty() {
let mut path = String::new();
write_path(&mut path, &where_.projs);
Some(path)
} else { None };
#[allow(unused)]
use ValidationErrorKind::*;
let msg =
ValidationErrorKind::from(InvalidMetaWrongTrait {
expected_dyn_type,
vtable_dyn_type,
});
::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
orig_ty: where_.orig_ty,
path,
ptr_bytes_warning: msg.ptr_bytes_warning(),
msg: msg.to_string(),
})
}
}
e => e,
}
})?
};try_validation!(
1536self.walk_value(val),
1537self.path,
1538// It's not great to catch errors here, since we can't give a very good path,
1539 // but it's better than ICEing.
1540Ub(InvalidVTableTrait { vtable_dyn_type, expected_dyn_type }) =>
1541 InvalidMetaWrongTrait { expected_dyn_type, vtable_dyn_type },
1542 );
15431544self.may_dangle = old_may_dangle;
1545 }
1546 }
15471548// Assert that we checked everything there is to check about this type.
1549 // `is_opsem_inhabited` implies that the layout is inhabited (checked by layout invariants).
1550if !val.layout.ty.is_opsem_inhabited(*self.ecx.tcx, self.ecx.typing_env) {
{
::core::panicking::panic_fmt(format_args!("a value of type `{0}` passed validation but that type is uninhabited",
val.layout.ty));
}
};assert!(
1551 val.layout.ty.is_opsem_inhabited(*self.ecx.tcx, self.ecx.typing_env),
1552"a value of type `{}` passed validation but that type is uninhabited",
1553 val.layout.ty
1554 );
1555if truecfg!(debug_assertions) {
1556// Only run expensive checks when debug assertions are enabled.
1557match val.layout.backend_repr {
1558 BackendRepr::Scalar(scalar_layout) => {
1559if !scalar_layout.is_uninit_valid() {
1560// There is something to check here.
1561 // We read directly via `ecx` since the read cannot fail -- we already read
1562 // this field above when recursing into the field.
1563let scalar = self1564 .ecx
1565 .read_scalar(val)
1566 .expect("the above checks should have fully handled this situation");
1567self.visit_scalar(scalar, scalar_layout)
1568 .expect("the above checks should have fully handled this situation");
1569 }
1570 }
1571 BackendRepr::ScalarPair { a: a_layout, b: b_layout, b_offset: _ } => {
1572// We can only proceed if *both* scalars need to be initialized.
1573 // FIXME: find a way to also check ScalarPair when one side can be uninit but
1574 // the other must be init.
1575if !a_layout.is_uninit_valid() && !b_layout.is_uninit_valid() {
1576let (a, b) = self1577 .ecx
1578 .read_immediate(val)
1579 .expect("the above checks should have fully handled this situation")
1580 .to_scalar_pair();
1581self.visit_scalar(a, a_layout)
1582 .expect("the above checks should have fully handled this situation");
1583self.visit_scalar(b, b_layout)
1584 .expect("the above checks should have fully handled this situation");
1585 }
1586 }
1587 BackendRepr::SimdVector { .. } | BackendRepr::SimdScalableVector { .. } => {}
1588 BackendRepr::Memory { .. } => {}
1589 }
1590 }
15911592interp_ok(())
1593 }
1594}
15951596impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
1597/// The internal core entry point for all validation operations.
1598fn validate_place_internal(
1599&mut self,
1600 val: &PlaceTy<'tcx, M::Provenance>,
1601 path: Path<'tcx>,
1602 ref_tracking: Option<&mut RefTracking<MPlaceTy<'tcx, M::Provenance>, Path<'tcx>>>,
1603 ctfe_mode: Option<CtfeValidationMode>,
1604 reset_provenance_and_padding: bool,
1605 start_in_may_dangle: bool,
1606 ) -> InterpResult<'tcx> {
1607{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/f5cedb83a788ea9581097abc36a2a8503a7f541c/compiler/rustc_const_eval/src/interpret/validity.rs:1607",
"rustc_const_eval::interpret::validity",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/f5cedb83a788ea9581097abc36a2a8503a7f541c/compiler/rustc_const_eval/src/interpret/validity.rs"),
::tracing_core::__macro_support::Option::Some(1607u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::validity"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("validate_place_internal: {0:?}, {1:?}",
*val, val.layout.ty) as &dyn ::tracing::field::Value))])
});
} else { ; }
};trace!("validate_place_internal: {:?}, {:?}", *val, val.layout.ty);
16081609// Run the visitor.
1610self.ghost_run_mut(|ecx| {
1611let reset_padding = reset_provenance_and_padding && {
1612// Check if `val` is actually stored in memory. If not, padding is not even
1613 // represented and we need not reset it.
1614ecx.place_to_op(val)?.as_mplace_or_imm().is_left()
1615 };
1616let mut v = ValidityVisitor {
1617path,
1618ref_tracking,
1619ctfe_mode,
1620ecx,
1621reset_provenance_and_padding,
1622 data_bytes: reset_padding.then_some(RangeSet::new()),
1623 may_dangle: start_in_may_dangle,
1624 };
1625 v.visit_value(val)?;
1626 v.reset_padding(val)?;
1627interp_ok(())
1628 })
1629 .inspect_err_info(|err| {
1630if !#[allow(non_exhaustive_omitted_patterns)] match err.kind() {
InterpErrorKind::UndefinedBehavior(ValidationError { .. }) |
InterpErrorKind::InvalidProgram(_) | InterpErrorKind::Unsupported(_) |
InterpErrorKind::MachineStop(_) => true,
_ => false,
}matches!(
1631 err.kind(),
1632 InterpErrorKind::UndefinedBehavior(ValidationError { .. })
1633 | InterpErrorKind::InvalidProgram(_)
1634 | InterpErrorKind::Unsupported(_)
1635// We have to also ignore machine-specific errors since we do retagging
1636 // during validation.
1637| InterpErrorKind::MachineStop(_)
1638 ) {
1639::rustc_span::macros::bug_impl(None,
format_args!("Unexpected error during validation: {0}", err.to_string()),
Location::caller());bug!("Unexpected error during validation: {}", err.to_string());
1640 }
1641 })
1642 }
16431644/// This function checks the data at `val` to be const-valid.
1645 /// `val` is assumed to cover valid memory.
1646 /// It will error if the bits at the destination do not match the ones described by the layout.
1647 ///
1648 /// `ref_tracking` is used to record references that we encounter so that they
1649 /// can be checked recursively by an outside driving loop.
1650 ///
1651 /// `constant` controls whether this must satisfy the rules for constants:
1652 /// - no pointers to statics.
1653 /// - no `UnsafeCell` or non-ZST `&mut`.
1654#[inline(always)]
1655pub(crate) fn const_validate_place(
1656&mut self,
1657 val: &PlaceTy<'tcx, M::Provenance>,
1658 path: Path<'tcx>,
1659 ref_tracking: &mut RefTracking<MPlaceTy<'tcx, M::Provenance>, Path<'tcx>>,
1660 ctfe_mode: CtfeValidationMode,
1661 ) -> InterpResult<'tcx> {
1662self.validate_place_internal(
1663val,
1664path,
1665Some(ref_tracking),
1666Some(ctfe_mode),
1667/*reset_provenance*/ false,
1668/*start_in_may_dangle*/ false,
1669 )
1670 }
16711672/// This function checks the data at `val` to be runtime-valid.
1673 /// `val` is assumed to cover valid memory.
1674 /// It will error if the bits at the destination do not match the ones described by the layout.
1675#[inline(always)]
1676pub fn validate_place(
1677&mut self,
1678 val: &PlaceTy<'tcx, M::Provenance>,
1679 recursive: bool,
1680 reset_provenance_and_padding: bool,
1681 ) -> InterpResult<'tcx> {
1682let _trace =
1683<M as
crate::interpret::Machine>::enter_trace_span(||
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("validate_place",
"rustc_const_eval::interpret::validity",
::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/f5cedb83a788ea9581097abc36a2a8503a7f541c/compiler/rustc_const_eval/src/interpret/validity.rs"),
::tracing_core::__macro_support::Option::Some(1683u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::validity"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("recursive")
}> =
::tracing::__macro_support::FieldName::new("recursive");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("reset_provenance_and_padding")
}> =
::tracing::__macro_support::FieldName::new("reset_provenance_and_padding");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("val")
}> =
::tracing::__macro_support::FieldName::new("val");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::INFO <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&recursive
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&reset_provenance_and_padding
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&val)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
})enter_trace_span!(M, "validate_place", recursive, reset_provenance_and_padding, ?val,);
1684// Note that we *could* actually be in CTFE here with `-Zextra-const-ub-checks`, but it's
1685 // still correct to not use `ctfe_mode`: that mode is for validation of the final constant
1686 // value, it rules out things like `UnsafeCell` in awkward places.
1687if !recursive {
1688return self.validate_place_internal(
1689val,
1690Path::new(val.layout.ty),
1691None,
1692None,
1693reset_provenance_and_padding,
1694/*start_in_may_dangle*/ false,
1695 );
1696 }
1697// Do a recursive check.
1698let mut ref_tracking = RefTracking::empty();
1699self.validate_place_internal(
1700 val,
1701 Path::new(val.layout.ty),
1702Some(&mut ref_tracking),
1703None,
1704 reset_provenance_and_padding,
1705/*start_in_may_dangle*/ false,
1706 )?;
1707while let Some((mplace, path)) = ref_tracking.todo.pop() {
1708// Things behind reference do *not* have the provenance reset. In fact
1709 // we treat the entire thing as being inside MaybeDangling, i.e., references
1710 // do not have to be dereferenceable.
1711self.validate_place_internal(
1712&mplace.into(),
1713 path,
1714None, // no further recursion
1715None,
1716/*reset_provenance_and_padding*/ false,
1717/*start_in_may_dangle*/ true,
1718 )?;
1719 }
1720interp_ok(())
1721 }
1722}