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