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