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,
35};
36use crate::enter_trace_span;
3738// for the validation errors
39#[rustfmt::skip]
40use super::InterpErrorKind::UndefinedBehavioras Ub;
41use super::InterpErrorKind::Unsupportedas Unsup;
42use super::UndefinedBehaviorInfo::*;
43use super::UnsupportedOpInfo::*;
4445macro_rules!err_validation_failure {
46 ($where:expr, $msg:expr ) => {{
47let where_ = &$where;
48let path = if !where_.projs.is_empty() {
49let mut path = String::new();
50 write_path(&mut path, &where_.projs);
51Some(path)
52 } else {
53None
54};
5556#[allow(unused)]
57use ValidationErrorKind::*;
58let msg = ValidationErrorKind::from($msg);
59err_ub!(ValidationError {
60 orig_ty: where_.orig_ty,
61 path,
62 ptr_bytes_warning: msg.ptr_bytes_warning(),
63 msg: msg.to_string(),
64 })
65 }};
66}
6768macro_rules!throw_validation_failure {
69 ($where:expr, $msg:expr ) => {
70do yeet err_validation_failure!($where, $msg)
71 };
72}
7374/// If $e throws an error matching the pattern, throw a validation failure.
75/// Other errors are passed back to the caller, unchanged -- and if they reach the root of
76/// the visitor, we make sure only validation errors and `InvalidProgram` errors are left.
77/// This lets you use the patterns as a kind of validation list, asserting which errors
78/// can possibly happen:
79///
80/// ```ignore(illustrative)
81/// let v = try_validation!(some_fn(x), some_path, {
82/// Foo | Bar | Baz => format!("some failure involving {x}"),
83/// });
84/// ```
85///
86/// The patterns must be of type `UndefinedBehaviorInfo`.
87macro_rules!try_validation {
88 ($e:expr, $where:expr,
89 $( $( $p:pat_param )|+ => $msg:expr ),+ $(,)?
90) => {{
91$e.map_err_kind(|e| {
92// We catch the error and turn it into a validation failure. We are okay with
93 // allocation here as this can only slow down builds that fail anyway.
94match e {
95 $(
96 $($p)|+ => {
97err_validation_failure!(
98$where,
99$msg
100)
101 }
102 ),+,
103 e => e,
104 }
105 })?
106}};
107}
108109#[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)]
110enum PtrKind {
111 Ref(Mutability),
112 Box,
113}
114115impl fmt::Displayfor PtrKind {
116fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
117let str = match self {
118 PtrKind::Ref(_) => "reference",
119 PtrKind::Box => "box",
120 };
121f.write_fmt(format_args!("{0}", str))write!(f, "{str}")122 }
123}
124125#[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)]
126enum ExpectedKind {
127 Reference,
128 Box,
129 RawPtr,
130 Bool,
131 Char,
132 Float,
133 Int,
134 FnPtr,
135 Str,
136}
137138impl fmt::Displayfor ExpectedKind {
139fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
140let str = match self {
141 ExpectedKind::Reference => "expected a reference",
142 ExpectedKind::Box => "expected a box",
143 ExpectedKind::RawPtr => "expected a raw pointer",
144 ExpectedKind::Bool => "expected a boolean",
145 ExpectedKind::Char => "expected a unicode scalar value",
146 ExpectedKind::Float => "expected a floating point number",
147 ExpectedKind::Int => "expected an integer",
148 ExpectedKind::FnPtr => "expected a function pointer",
149 ExpectedKind::Str => "expected a string",
150 };
151f.write_fmt(format_args!("{0}", str))write!(f, "{str}")152 }
153}
154155impl From<PtrKind> for ExpectedKind {
156fn from(x: PtrKind) -> ExpectedKind {
157match x {
158 PtrKind::Box => ExpectedKind::Box,
159 PtrKind::Ref(_) => ExpectedKind::Reference,
160 }
161 }
162}
163164/// Validation errors that can be emitted in one than one place get a variant here so that
165/// we format them consistently. Everything else uses the `String` fallback.
166#[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)]
167enum ValidationErrorKind<'tcx> {
168 Uninit {
169 expected: ExpectedKind,
170 },
171 PointerAsInt {
172 expected: ExpectedKind,
173 },
174 PartialPointer,
175 InvalidMetaWrongTrait {
176/// The vtable that was actually referenced by the wide pointer metadata.
177vtable_dyn_type: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
178/// The vtable that was expected at the point in MIR that it was accessed.
179expected_dyn_type: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
180 },
181 GeneralError {
182 msg: String,
183 },
184}
185186impl<'tcx> ValidationErrorKind<'tcx> {
187// We don't do this via `fmt::Display` to so that we can do a move in the `GeneralError` case.
188fn to_string(self) -> String {
189use ValidationErrorKind::*;
190match self {
191Uninit { expected } => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("encountered uninitialized memory, but {0}",
expected))
})format!("encountered uninitialized memory, but {expected}"),
192PointerAsInt { expected } => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("encountered a pointer, but {0}",
expected))
})format!("encountered a pointer, but {expected}"),
193PartialPointer => ::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"),
194InvalidMetaWrongTrait { 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!(
195"wrong trait in wide pointer vtable: expected `{expected_dyn_type}`, but encountered `{vtable_dyn_type}`"
196),
197GeneralError { msg } => msg,
198 }
199 }
200201fn ptr_bytes_warning(&self) -> bool {
202use ValidationErrorKind::*;
203#[allow(non_exhaustive_omitted_patterns)] match self {
PointerAsInt { .. } | PartialPointer => true,
_ => false,
}matches!(self, PointerAsInt { .. } | PartialPointer)204 }
205}
206207impl<'tcx> From<String> for ValidationErrorKind<'tcx> {
208fn from(msg: String) -> Self {
209 ValidationErrorKind::GeneralError { msg }
210 }
211}
212213fn fmt_range(r: WrappingRange, max_hi: u128) -> String {
214let WrappingRange { start: lo, end: hi } = r;
215if !(hi <= max_hi) {
::core::panicking::panic("assertion failed: hi <= max_hi")
};assert!(hi <= max_hi);
216if lo > hi {
217::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}")218 } else if lo == hi {
219::alloc::__export::must_use({
::alloc::fmt::format(format_args!("equal to {0}", lo))
})format!("equal to {lo}")220 } else if lo == 0 {
221if !(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");
222::alloc::__export::must_use({
::alloc::fmt::format(format_args!("less or equal to {0}", hi))
})format!("less or equal to {hi}")223 } else if hi == max_hi {
224if !(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");
225::alloc::__export::must_use({
::alloc::fmt::format(format_args!("greater or equal to {0}", lo))
})format!("greater or equal to {lo}")226 } else {
227::alloc::__export::must_use({
::alloc::fmt::format(format_args!("in the range {0}..={1}", lo, hi))
})format!("in the range {lo}..={hi}")228 }
229}
230231/// We want to show a nice path to the invalid field for diagnostics,
232/// but avoid string operations in the happy case where no error happens.
233/// So we track a `Vec<PathElem>` where `PathElem` contains all the data we
234/// need to later print something for the user.
235#[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)]
236pub enum PathElem<'tcx> {
237 Field(Symbol),
238 Variant(Symbol),
239 CoroutineState(VariantIdx),
240 CapturedVar(Symbol),
241 ArrayElem(usize),
242 TupleElem(usize),
243 Deref,
244 EnumTag,
245 CoroutineTag,
246 DynDowncast(Ty<'tcx>),
247 Vtable,
248}
249250#[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)]
251pub struct Path<'tcx> {
252 orig_ty: Ty<'tcx>,
253 projs: Vec<PathElem<'tcx>>,
254}
255256impl<'tcx> Path<'tcx> {
257fn new(ty: Ty<'tcx>) -> Self {
258Self { orig_ty: ty, projs: ::alloc::vec::Vec::new()vec![] }
259 }
260}
261262/// Extra things to check for during validation of CTFE results.
263#[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)]
264pub enum CtfeValidationMode {
265/// Validation of a `static`
266Static { mutbl: Mutability },
267/// Validation of a promoted.
268Promoted,
269/// Validation of a `const`.
270 /// `allow_immutable_unsafe_cell` says whether we allow `UnsafeCell` in immutable memory (which is the
271 /// case for the top-level allocation of a `const`, where this is fine because the allocation will be
272 /// copied at each use site).
273Const { allow_immutable_unsafe_cell: bool },
274}
275276impl CtfeValidationMode {
277fn allow_immutable_unsafe_cell(self) -> bool {
278match self {
279 CtfeValidationMode::Static { .. } => false,
280 CtfeValidationMode::Promoted { .. } => false,
281 CtfeValidationMode::Const { allow_immutable_unsafe_cell, .. } => {
282allow_immutable_unsafe_cell283 }
284 }
285 }
286}
287288/// State for tracking recursive validation of references
289pub struct RefTracking<T, PATH = ()> {
290 seen: FxHashSet<T>,
291 todo: Vec<(T, PATH)>,
292}
293294impl<T: Clone + Eq + Hash + std::fmt::Debug, PATH> RefTracking<T, PATH> {
295pub fn empty() -> Self {
296RefTracking { seen: FxHashSet::default(), todo: ::alloc::vec::Vec::new()vec![] }
297 }
298pub fn next(&mut self) -> Option<(T, PATH)> {
299self.todo.pop()
300 }
301302fn track(&mut self, val: T, path: impl FnOnce() -> PATH) {
303if self.seen.insert(val.clone()) {
304{
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:304",
"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(304u32),
::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);
305let path = path();
306// Remember to come back to this later.
307self.todo.push((val, path));
308 }
309 }
310}
311312impl<'tcx, T: Clone + Eq + Hash + std::fmt::Debug> RefTracking<T, Path<'tcx>> {
313pub fn new(val: T, ty: Ty<'tcx>) -> Self {
314let mut ref_tracking_for_consts =
315RefTracking { 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))] };
316ref_tracking_for_consts.seen.insert(val);
317ref_tracking_for_consts318 }
319}
320321/// Format a path
322fn write_path(out: &mut String, path: &[PathElem<'_>]) {
323use self::PathElem::*;
324325for elem in path.iter() {
326match elem {
327 Field(name) => out.write_fmt(format_args!(".{0}", name))write!(out, ".{name}"),
328 EnumTag => out.write_fmt(format_args!(".<enum-tag>"))write!(out, ".<enum-tag>"),
329 Variant(name) => out.write_fmt(format_args!(".<enum-variant({0})>", name))write!(out, ".<enum-variant({name})>"),
330 CoroutineTag => out.write_fmt(format_args!(".<coroutine-tag>"))write!(out, ".<coroutine-tag>"),
331 CoroutineState(idx) => out.write_fmt(format_args!(".<coroutine-state({0})>", idx.index()))write!(out, ".<coroutine-state({})>", idx.index()),
332 CapturedVar(name) => out.write_fmt(format_args!(".<captured-var({0})>", name))write!(out, ".<captured-var({name})>"),
333 TupleElem(idx) => out.write_fmt(format_args!(".{0}", idx))write!(out, ".{idx}"),
334 ArrayElem(idx) => out.write_fmt(format_args!("[{0}]", idx))write!(out, "[{idx}]"),
335// `.<deref>` does not match Rust syntax, but it is more readable for long paths -- and
336 // some of the other items here also are not Rust syntax. Actually we can't
337 // even use the usual syntax because we are just showing the projections,
338 // not the root.
339 Deref => out.write_fmt(format_args!(".<deref>"))write!(out, ".<deref>"),
340 DynDowncast(ty) => out.write_fmt(format_args!(".<dyn-downcast({0})>", ty))write!(out, ".<dyn-downcast({ty})>"),
341 Vtable => out.write_fmt(format_args!(".<vtable>"))write!(out, ".<vtable>"),
342 }
343 .unwrap()
344 }
345}
346347pub type RangeSet = rustc_data_structures::range_set::RangeSet<Size>;
348349struct ValidityVisitor<'rt, 'tcx, M: Machine<'tcx>> {
350/// The `path` may be pushed to, but the part that is present when a function
351 /// starts must not be changed! `with_elem` relies on this stack discipline.
352path: Path<'tcx>,
353 ref_tracking: Option<&'rt mut RefTracking<MPlaceTy<'tcx, M::Provenance>, Path<'tcx>>>,
354/// `None` indicates this is not validating for CTFE (but for runtime).
355ctfe_mode: Option<CtfeValidationMode>,
356 ecx: &'rt mut InterpCx<'tcx, M>,
357/// Whether provenance should be reset outside of pointers (emulating the effect of a typed
358 /// copy).
359reset_provenance_and_padding: bool,
360/// This tracks which byte ranges in this value contain data; the remaining bytes are padding.
361 /// The ideal representation here would be pointer-length pairs, but to keep things more compact
362 /// we only store a (range) set of offsets -- the base pointer is the same throughout the entire
363 /// visit, after all.
364 /// If this is `Some`, then `reset_provenance_and_padding` must be true (but not vice versa:
365 /// we might not track data vs padding bytes if the place isn't stored in memory anyway).
366data_bytes: Option<RangeSet>,
367/// True if we are inside of `MaybeDangling`. This disables pointer access checks.
368may_dangle: bool,
369}
370371impl<'rt, 'tcx, M: Machine<'tcx>> ValidityVisitor<'rt, 'tcx, M> {
372fn aggregate_field_path_elem(
373&mut self,
374 layout: TyAndLayout<'tcx>,
375 field: usize,
376 field_ty: Ty<'tcx>,
377 ) -> PathElem<'tcx> {
378// First, check if we are projecting to a variant.
379match layout.variants {
380 Variants::Multiple { tag_field, .. } => {
381if tag_field.as_usize() == field {
382return match layout.ty.kind() {
383 ty::Adt(def, ..) if def.is_enum() => PathElem::EnumTag,
384 ty::Coroutine(..) => PathElem::CoroutineTag,
385_ => ::rustc_middle::util::bug::bug_fmt(format_args!("non-variant type {0:?}",
layout.ty))bug!("non-variant type {:?}", layout.ty),
386 };
387 }
388 }
389 Variants::Single { .. } | Variants::Empty => {}
390 }
391392// Now we know we are projecting to a field, so figure out which one.
393match layout.ty.kind() {
394// coroutines, closures, and coroutine-closures all have upvars that may be named.
395ty::Closure(def_id, _) | ty::Coroutine(def_id, _) | ty::CoroutineClosure(def_id, _) => {
396let mut name = None;
397// FIXME this should be more descriptive i.e. CapturePlace instead of CapturedVar
398 // https://github.com/rust-lang/project-rfc-2229/issues/46
399if let Some(local_def_id) = def_id.as_local() {
400let captures = self.ecx.tcx.closure_captures(local_def_id);
401if let Some(captured_place) = captures.get(field) {
402// Sometimes the index is beyond the number of upvars (seen
403 // for a coroutine).
404let var_hir_id = captured_place.get_root_variable();
405let node = self.ecx.tcx.hir_node(var_hir_id);
406if let hir::Node::Pat(pat) = node407 && let hir::PatKind::Binding(_, _, ident, _) = pat.kind
408 {
409name = Some(ident.name);
410 }
411 }
412 }
413414 PathElem::CapturedVar(name.unwrap_or_else(|| {
415// Fall back to showing the field index.
416sym::integer(field)
417 }))
418 }
419420// tuples
421ty::Tuple(_) => PathElem::TupleElem(field),
422423// enums
424ty::Adt(def, ..) if def.is_enum() => {
425// we might be projecting *to* a variant, or to a field *in* a variant.
426match layout.variants {
427 Variants::Single { index } => {
428// Inside a variant
429PathElem::Field(def.variant(index).fields[FieldIdx::from_usize(field)].name)
430 }
431 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"),
432 Variants::Multiple { .. } => ::rustc_middle::util::bug::bug_fmt(format_args!("we handled variants above"))bug!("we handled variants above"),
433 }
434 }
435436// other ADTs
437ty::Adt(def, _) => {
438 PathElem::Field(def.non_enum_variant().fields[FieldIdx::from_usize(field)].name)
439 }
440441// arrays/slices
442ty::Array(..) | ty::Slice(..) => PathElem::ArrayElem(field),
443444// dyn traits
445ty::Dynamic(..) => {
446{
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);
447 PathElem::DynDowncast(field_ty)
448 }
449450// nothing else has an aggregate layout
451_ => ::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),
452 }
453 }
454455fn with_elem<R>(
456&mut self,
457 elem: PathElem<'tcx>,
458 f: impl FnOnce(&mut Self) -> InterpResult<'tcx, R>,
459 ) -> InterpResult<'tcx, R> {
460// Remember the old state
461let path_len = self.path.projs.len();
462// Record new element
463self.path.projs.push(elem);
464// Perform operation
465let r = f(self)?;
466// Undo changes
467self.path.projs.truncate(path_len);
468// Done
469interp_ok(r)
470 }
471472fn read_immediate(
473&self,
474 val: &PlaceTy<'tcx, M::Provenance>,
475 expected: ExpectedKind,
476 ) -> InterpResult<'tcx, ImmTy<'tcx, M::Provenance>> {
477interp_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!(
478self.ecx.read_immediate(val),
479self.path,
480 Ub(InvalidUninitBytes(_)) =>
481 Uninit { expected },
482// The `Unsup` cases can only occur during CTFE
483Unsup(ReadPointerAsInt(_)) =>
484 PointerAsInt { expected },
485 Unsup(ReadPartialPointer(_)) =>
486 PartialPointer,
487 ))
488 }
489490fn read_scalar(
491&self,
492 val: &PlaceTy<'tcx, M::Provenance>,
493 expected: ExpectedKind,
494 ) -> InterpResult<'tcx, Scalar<M::Provenance>> {
495interp_ok(self.read_immediate(val, expected)?.to_scalar())
496 }
497498/// Given a place and a pointer loaded from that place, ensure that the place does
499 /// not store any more provenance than the pointer does. IOW, if any provenance
500 /// was discarded when loading the pointer, it will also get discarded in-memory.
501fn reset_pointer_provenance(
502&mut self,
503 place: &PlaceTy<'tcx, M::Provenance>,
504 ptr: &ImmTy<'tcx, M::Provenance>,
505 ) -> InterpResult<'tcx> {
506if #[allow(non_exhaustive_omitted_patterns)] match ptr.layout.backend_repr {
BackendRepr::Scalar(..) => true,
_ => false,
}matches!(ptr.layout.backend_repr, BackendRepr::Scalar(..)) {
507// A thin pointer. If it has provenance, we don't have to do anything.
508 // If it does not, ensure we clear the provenance in memory.
509if !#[allow(non_exhaustive_omitted_patterns)] match ptr.to_scalar() {
Scalar::Ptr(..) => true,
_ => false,
}matches!(ptr.to_scalar(), Scalar::Ptr(..)) {
510// The loaded pointer has no provenance. Some bytes of its representation still
511 // might have provenance, which we have to clear.
512self.ecx.clear_provenance(place)?;
513 }
514 } else {
515// A wide pointer. This means we have to worry both about the pointer itself and the
516 // metadata. We do the lazy thing and just write back the value we got. Just
517 // clearing provenance in a targeted manner would be more efficient, but unless this
518 // is a perf hotspot it's just not worth the effort.
519self.ecx.write_immediate_no_validate(**ptr, place)?;
520 }
521interp_ok(())
522 }
523524fn check_wide_ptr_meta(
525&mut self,
526 meta: MemPlaceMeta<M::Provenance>,
527 pointee: TyAndLayout<'tcx>,
528 ) -> InterpResult<'tcx> {
529let tail = self.ecx.tcx.struct_tail_for_codegen(pointee.ty, self.ecx.typing_env);
530match tail.kind() {
531 ty::Dynamic(data, _) => {
532let vtable = meta.unwrap_meta().to_pointer(self.ecx)?;
533// Make sure it is a genuine vtable pointer for the right trait.
534{
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!(
535self.ecx.get_ptr_vtable_ty(vtable, Some(data)),
536self.path,
537 Ub(DanglingIntPointer{ .. } | InvalidVTablePointer(..)) =>
538format!("encountered {vtable}, but expected a vtable pointer"),
539 Ub(InvalidVTableTrait { vtable_dyn_type, expected_dyn_type }) =>
540 InvalidMetaWrongTrait { expected_dyn_type, vtable_dyn_type },
541 );
542 }
543 ty::Slice(..) | ty::Str => {
544let _len = meta.unwrap_meta().to_target_usize(self.ecx)?;
545// We do not check that `len * elem_size <= isize::MAX`:
546 // that is only required for references, and there it falls out of the
547 // "dereferenceable" check performed by Stacked Borrows.
548}
549 ty::Foreign(..) => {
550// Unsized, but not wide.
551}
552_ => ::rustc_middle::util::bug::bug_fmt(format_args!("Unexpected unsized type tail: {0:?}",
tail))bug!("Unexpected unsized type tail: {:?}", tail),
553 }
554555interp_ok(())
556 }
557558/// Check a reference or `Box`.
559 ///
560 /// `ty` is the actual type of `value`; for a Box, `value` will be just the inner raw pointer.
561fn check_safe_pointer(
562&mut self,
563 value: &PlaceTy<'tcx, M::Provenance>,
564 ty: Ty<'tcx>,
565 ptr_kind: PtrKind,
566 ) -> InterpResult<'tcx> {
567// Note that some of those checks (those that encode the basic validity invariant of
568 // pointers) are duplicated in `place_deref`, so changes here might need updates there.
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("pointer")).map_err_kind(|e|
{
match e {
Ub(DanglingIntPointer { addr: 0, .. }) => {
{
let where_ = &self.path;
let path =
if !where_.projs.is_empty() {
let mut path = String::new();
write_path(&mut path, &where_.projs);
Some(path)
} else { None };
#[allow(unused)]
use ValidationErrorKind::*;
let msg =
ValidationErrorKind::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("encountered a null {0}",
ptr_kind))
}));
::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
orig_ty: where_.orig_ty,
path,
ptr_bytes_warning: msg.ptr_bytes_warning(),
msg: msg.to_string(),
})
}
}
Ub(DanglingIntPointer { addr: i, .. }) => {
{
let where_ = &self.path;
let path =
if !where_.projs.is_empty() {
let mut path = String::new();
write_path(&mut path, &where_.projs);
Some(path)
} else { None };
#[allow(unused)]
use ValidationErrorKind::*;
let msg =
ValidationErrorKind::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("encountered a dangling {1} ({0} has no provenance)",
Pointer::<Option<AllocId>>::without_provenance(i),
ptr_kind))
}));
::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
orig_ty: where_.orig_ty,
path,
ptr_bytes_warning: msg.ptr_bytes_warning(),
msg: msg.to_string(),
})
}
}
Ub(PointerOutOfBounds { .. }) => {
{
let where_ = &self.path;
let path =
if !where_.projs.is_empty() {
let mut path = String::new();
write_path(&mut path, &where_.projs);
Some(path)
} else { None };
#[allow(unused)]
use ValidationErrorKind::*;
let msg =
ValidationErrorKind::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("encountered a dangling {0} (going beyond the bounds of its allocation)",
ptr_kind))
}));
::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
orig_ty: where_.orig_ty,
path,
ptr_bytes_warning: msg.ptr_bytes_warning(),
msg: msg.to_string(),
})
}
}
Ub(PointerUseAfterFree(..)) => {
{
let where_ = &self.path;
let path =
if !where_.projs.is_empty() {
let mut path = String::new();
write_path(&mut path, &where_.projs);
Some(path)
} else { None };
#[allow(unused)]
use ValidationErrorKind::*;
let msg =
ValidationErrorKind::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("encountered a dangling {0} (use-after-free)",
ptr_kind))
}));
::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
orig_ty: where_.orig_ty,
path,
ptr_bytes_warning: msg.ptr_bytes_warning(),
msg: msg.to_string(),
})
}
}
e => e,
}
})?
};try_validation!(
605self.ecx.check_ptr_access(
606 place.ptr(),
607 size,
608 CheckInAllocMsg::Dereferenceable("pointer"), // 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// We are not checking dereferenceability, but we still want to ensure that the pointer
651 // *could* be dereferenceable in *some* memory: we have to be able to compute the
652 // address at the end of this range without overflowing..
653let scalar = Scalar::from_maybe_pointer(place.ptr(), self.ecx);
654// Skip this if we don't know the absolute address (during CTFE).
655if let Ok(addr) = scalar.try_to_scalar_int() {
656// Try to compute the end address.
657let addr = Size::from_bytes(addr.to_target_usize(*self.ecx.tcx));
658if addr.checked_add(size, self.ecx).is_none() {
659do yeet {
let where_ = &self.path;
let path =
if !where_.projs.is_empty() {
let mut path = String::new();
write_path(&mut path, &where_.projs);
Some(path)
} else { None };
#[allow(unused)]
use ValidationErrorKind::*;
let msg =
ValidationErrorKind::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("encountered a {1} that is too close to the end of the address space for a pointee of {0} bytes",
size.bytes(), ptr_kind))
}));
::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::ValidationError {
orig_ty: where_.orig_ty,
path,
ptr_bytes_warning: msg.ptr_bytes_warning(),
msg: msg.to_string(),
})
}throw_validation_failure!(
660self.path,
661format!(
662"encountered a {ptr_kind} that is too close to the end of the address space for a pointee of {} bytes",
663 size.bytes(),
664 )
665 )666 }
667 }
668669// Pointer remains unchanged.
670None671 };
672// If the pointer needs adjusting, write back adjusted pointer. This automatically
673 // also clears any excess provenance. Otherwise, just clear the provenance.
674if let Some(ptr) = adjusted_ptr {
675self.ecx.write_immediate_no_validate(*ptr, value)?;
676 } else if self.reset_provenance_and_padding {
677self.reset_pointer_provenance(value, &ptr)?;
678 }
679680// Make sure this is non-null. This is obviously needed when `may_dangle` is set,
681 // but even if we did check dereferenceability above that would still allow null
682 // pointers if `size` is zero.
683let scalar = Scalar::from_maybe_pointer(place.ptr(), self.ecx);
684if self.ecx.scalar_may_be_null(scalar)? {
685let maybe = !M::Provenance::OFFSET_IS_ADDR && #[allow(non_exhaustive_omitted_patterns)] match scalar {
Scalar::Ptr(..) => true,
_ => false,
}matches!(scalar, Scalar::Ptr(..));
686do 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!(
687self.path,
688format!(
689"encountered a {maybe}null {ptr_kind}",
690 maybe = if maybe { "maybe-" } else { "" }
691 )
692 )693 }
694695// Do not allow references to uninhabited types.
696if !place.layout.ty.is_opsem_inhabited(*self.ecx.tcx, self.ecx.typing_env) {
697let ty = place.layout.ty;
698do 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!(
699self.path,
700format!("encountered a {ptr_kind} pointing to uninhabited type `{ty}`")
701 )702 }
703704// Check alignment after dereferenceable (if both are violated, trigger the error above).
705{
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!(
706self.ecx.check_ptr_align(
707 place.ptr(),
708 align,
709 ),
710self.path,
711 Ub(AlignmentCheckFailed(Misalignment { required, has }, _msg)) => format!(
712"encountered an unaligned {ptr_kind} (required {required_bytes} byte alignment but found {found_bytes})",
713 required_bytes = required.bytes(),
714 found_bytes = has.bytes()
715 ),
716 );
717718// Recursive checking (but not inside `MaybeDangling` of course).
719if let Some(ref_tracking) = self.ref_tracking.as_deref_mut()
720 && !self.may_dangle
721 {
722// Proceed recursively even for ZST, no reason to skip them!
723 // `!` is a ZST and we want to validate it.
724if let Some(ctfe_mode) = self.ctfe_mode {
725let mut skip_recursive_check = false;
726// CTFE imposes restrictions on what references can point to.
727if let Ok((alloc_id, _offset, _prov)) =
728self.ecx.ptr_try_get_alloc_id(place.ptr(), 0)
729 {
730// Everything should be already interned.
731let Some(global_alloc) = self.ecx.tcx.try_get_global_alloc(alloc_id) else {
732if self.ecx.memory.alloc_map.contains_key(&alloc_id) {
733// This can happen when interning didn't complete due to, e.g.
734 // missing `make_global`. This must mean other errors are already
735 // being reported.
736self.ecx.tcx.dcx().delayed_bug(
737"interning did not complete, there should be an error",
738 );
739return interp_ok(());
740 }
741// We can't have *any* references to non-existing allocations in const-eval
742 // as the rest of rustc isn't happy with them... so we throw an error, even
743 // though for zero-sized references this isn't really UB.
744 // A potential future alternative would be to resurrect this as a zero-sized allocation
745 // (which codegen will then compile to an aligned dummy pointer anyway).
746do 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!(
747self.path,
748format!("encountered a dangling {ptr_kind} (use-after-free)")
749 );
750 };
751let (size, _align) =
752global_alloc.size_and_align(*self.ecx.tcx, self.ecx.typing_env);
753let alloc_actual_mutbl =
754global_alloc.mutability(*self.ecx.tcx, self.ecx.typing_env);
755756match global_alloc {
757 GlobalAlloc::Static(did) => {
758let DefKind::Static { nested, .. } = self.ecx.tcx.def_kind(did) else {
759::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!()760 };
761if !!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));
762if !self.ecx.tcx.is_static(did) {
::core::panicking::panic("assertion failed: self.ecx.tcx.is_static(did)")
};assert!(self.ecx.tcx.is_static(did));
763match ctfe_mode {
764 CtfeValidationMode::Static { .. }
765 | CtfeValidationMode::Promoted { .. } => {
766// We skip recursively checking other statics. These statics must be sound by
767 // themselves, and the only way to get broken statics here is by using
768 // unsafe code.
769 // The reasons we don't check other statics is twofold. For one, in all
770 // sound cases, the static was already validated on its own, and second, we
771 // trigger cycle errors if we try to compute the value of the other static
772 // and that static refers back to us (potentially through a promoted).
773 // This could miss some UB, but that's fine.
774 // We still walk nested allocations, as they are fundamentally part of this validation run.
775 // This means we will also recurse into nested statics of *other*
776 // statics, even though we do not recurse into other statics directly.
777 // That's somewhat inconsistent but harmless.
778skip_recursive_check = !nested;
779 }
780 CtfeValidationMode::Const { .. } => {
781// If this is mutable memory or an `extern static`, there's no point in checking it -- we'd
782 // just get errors trying to read the value.
783if alloc_actual_mutbl.is_mut()
784 || self.ecx.tcx.is_foreign_item(did)
785 {
786skip_recursive_check = true;
787 }
788 }
789 }
790 }
791_ => (),
792 }
793794// If this allocation has size zero, there is no actual mutability here.
795if size != Size::ZERO {
796// Determine whether this pointer expects to be pointing to something mutable.
797let ptr_expected_mutbl = match ptr_kind {
798 PtrKind::Box => Mutability::Mut,
799 PtrKind::Ref(mutbl) => {
800// We do not take into account interior mutability here since we cannot know if
801 // there really is an `UnsafeCell` inside `Option<UnsafeCell>` -- so we check
802 // that in the recursive descent behind this reference (controlled by
803 // `allow_immutable_unsafe_cell`).
804mutbl805 }
806 };
807// Mutable pointer to immutable memory is no good.
808if ptr_expected_mutbl == Mutability::Mut809 && alloc_actual_mutbl == Mutability::Not810 {
811// This can actually occur with transmutes.
812do 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!(
813self.path,
814format!(
815"encountered mutable reference or box pointing to read-only memory"
816)
817 );
818 }
819 }
820 }
821// Potentially skip recursive check.
822if skip_recursive_check {
823return interp_ok(());
824 }
825 } else {
826// This is not CTFE, so it's Miri with recursive checking.
827 // FIXME: should we skip `UnsafeCell` behind shared references? Currently that is
828 // not needed since validation reads bypass Stacked Borrows and data race checks,
829 // but is that really coherent?
830}
831let path = &self.path;
832ref_tracking.track(place, || {
833// We need to clone the path anyway, make sure it gets created
834 // with enough space for the additional `Deref`.
835let mut new_projs = Vec::with_capacity(path.projs.len() + 1);
836new_projs.extend(&path.projs);
837new_projs.push(PathElem::Deref);
838Path { projs: new_projs, orig_ty: path.orig_ty }
839 });
840 }
841interp_ok(())
842 }
843844/// Check if this is a value of primitive type, and if yes check the validity of the value
845 /// at that type. Return `true` if the type is indeed primitive.
846 ///
847 /// Note that not all of these have `FieldsShape::Primitive`, e.g. wide references.
848fn try_visit_primitive(
849&mut self,
850 value: &PlaceTy<'tcx, M::Provenance>,
851 ) -> InterpResult<'tcx, bool> {
852// Go over all the primitive types
853let ty = value.layout.ty;
854match ty.kind() {
855 ty::Bool => {
856let scalar = self.read_scalar(value, ExpectedKind::Bool)?;
857{
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!(
858 scalar.to_bool(),
859self.path,
860 Ub(InvalidBool(..)) =>
861format!("encountered {scalar:x}, but expected a boolean"),
862 );
863if self.reset_provenance_and_padding {
864self.ecx.clear_provenance(value)?;
865self.add_data_range_place(value);
866 }
867interp_ok(true)
868 }
869 ty::Char => {
870let scalar = self.read_scalar(value, ExpectedKind::Char)?;
871{
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!(
872 scalar.to_char(),
873self.path,
874 Ub(InvalidChar(..)) =>
875format!("encountered {scalar:x}, but expected a valid unicode scalar value \
876 (in `0..=0x10FFFF` but not in `0xD800..=0xDFFF`)")
877 );
878if self.reset_provenance_and_padding {
879self.ecx.clear_provenance(value)?;
880self.add_data_range_place(value);
881 }
882interp_ok(true)
883 }
884 ty::Float(_) | ty::Int(_) | ty::Uint(_) => {
885// NOTE: Keep this in sync with the array optimization for int/float
886 // types below!
887self.read_scalar(
888 value,
889if #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
ty::Float(..) => true,
_ => false,
}matches!(ty.kind(), ty::Float(..)) {
890 ExpectedKind::Float
891 } else {
892 ExpectedKind::Int
893 },
894 )?;
895if self.reset_provenance_and_padding {
896self.ecx.clear_provenance(value)?;
897self.add_data_range_place(value);
898 }
899interp_ok(true)
900 }
901 ty::RawPtr(pointee, ..) => {
902let ptr = self.read_immediate(value, ExpectedKind::RawPtr)?;
903if self.reset_provenance_and_padding {
904self.reset_pointer_provenance(value, &ptr)?;
905// There's no padding in a pointer.
906self.add_data_range_place(value);
907 }
908909if !pointee.is_sized(*self.ecx.tcx, self.ecx.typing_env) {
910// Raw pointers to unsized types need to have their metadata checked.
911 // We avoid creating this place for sized types to match codegen: those types
912 // might actually be invalid (i.e., too big)!
913let place = self.ecx.imm_ptr_to_mplace(&ptr)?;
914if !place.layout.is_unsized() {
::core::panicking::panic("assertion failed: place.layout.is_unsized()")
};assert!(place.layout.is_unsized());
915self.check_wide_ptr_meta(place.meta(), place.layout)?;
916 }
917interp_ok(true)
918 }
919 ty::Ref(_, _ty, mutbl) => {
920self.check_safe_pointer(value, ty, PtrKind::Ref(*mutbl))?;
921interp_ok(true)
922 }
923 ty::FnPtr(..) => {
924let scalar = self.read_scalar(value, ExpectedKind::FnPtr)?;
925926// If we check references recursively, also check that this points to a function.
927if let Some(_) = self.ref_tracking {
928let ptr = scalar.to_pointer(self.ecx)?;
929let _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!(
930self.ecx.get_ptr_fn(ptr),
931self.path,
932 Ub(DanglingIntPointer{ .. } | InvalidFunctionPointer(..)) =>
933format!("encountered {ptr}, but expected a function pointer"),
934 );
935// FIXME: Check if the signature matches
936} else {
937// Otherwise (for standalone Miri and for `-Zextra-const-ub-checks`),
938 // we have to still check it to be non-null.
939if self.ecx.scalar_may_be_null(scalar)? {
940let maybe =
941 !M::Provenance::OFFSET_IS_ADDR && #[allow(non_exhaustive_omitted_patterns)] match scalar {
Scalar::Ptr(..) => true,
_ => false,
}matches!(scalar, Scalar::Ptr(..));
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 {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!(
943self.path,
944format!(
945"encountered a {maybe}null function pointer",
946 maybe = if maybe { "maybe-" } else { "" }
947 )
948 );
949 }
950 }
951if self.reset_provenance_and_padding {
952// Make sure we do not preserve partial provenance. This matches the thin
953 // pointer handling in `deref_pointer`.
954if #[allow(non_exhaustive_omitted_patterns)] match scalar {
Scalar::Int(..) => true,
_ => false,
}matches!(scalar, Scalar::Int(..)) {
955self.ecx.clear_provenance(value)?;
956 }
957self.add_data_range_place(value);
958 }
959interp_ok(true)
960 }
961 ty::Never => {
962do 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!(
963self.path,
964format!("encountered a value of the never type `!`")
965 )966 }
967 ty::Foreign(..) | ty::FnDef(..) => {
968// Nothing to check.
969interp_ok(true)
970 }
971 ty::UnsafeBinder(_) => {
::core::panicking::panic_fmt(format_args!("not implemented: {0}",
format_args!("FIXME(unsafe_binder)")));
}unimplemented!("FIXME(unsafe_binder)"),
972// The above should be all the primitive types. The rest is compound, we
973 // check them by visiting their fields/variants.
974ty::Adt(..)
975 | ty::Tuple(..)
976 | ty::Array(..)
977 | ty::Slice(..)
978 | ty::Str979 | ty::Dynamic(..)
980 | ty::Closure(..)
981 | ty::Pat(..)
982 | ty::CoroutineClosure(..)
983 | ty::Coroutine(..) => interp_ok(false),
984// Some types only occur during typechecking, they have no layout.
985 // We should not see them here and we could not check them anyway.
986ty::Error(_)
987 | ty::Infer(..)
988 | ty::Placeholder(..)
989 | ty::Bound(..)
990 | ty::Param(..)
991 | ty::Alias(..)
992 | ty::CoroutineWitness(..) => ::rustc_middle::util::bug::bug_fmt(format_args!("Encountered invalid type {0:?}",
ty))bug!("Encountered invalid type {:?}", ty),
993 }
994 }
995996fn visit_scalar(
997&mut self,
998 scalar: Scalar<M::Provenance>,
999 scalar_layout: ScalarAbi,
1000 ) -> InterpResult<'tcx> {
1001let size = scalar_layout.size(self.ecx);
1002let valid_range = scalar_layout.valid_range(self.ecx);
1003let WrappingRange { start, end } = valid_range;
1004let max_value = size.unsigned_int_max();
1005if !(end <= max_value) {
::core::panicking::panic("assertion failed: end <= max_value")
};assert!(end <= max_value);
1006let bits = match scalar.try_to_scalar_int() {
1007Ok(int) => int.to_bits(size),
1008Err(_) => {
1009// So this is a pointer then, and casting to an int failed.
1010 // Can only happen during CTFE.
1011 // We support 2 kinds of ranges here: full range, and excluding zero.
1012if start == 1 && end == max_value {
1013// Only null is the niche. So make sure the ptr is NOT null.
1014if self.ecx.scalar_may_be_null(scalar)? {
1015do 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!(
1016self.path,
1017format!(
1018"encountered a maybe-null pointer, but expected something that is definitely non-zero"
1019)
1020 )1021 } else {
1022return interp_ok(());
1023 }
1024 } else if scalar_layout.is_always_valid(self.ecx) {
1025// Easy. (This is reachable if `enforce_number_validity` is set.)
1026return interp_ok(());
1027 } else {
1028// Conservatively, we reject, because the pointer *could* have a bad value.
1029do 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!(
1030self.path,
1031format!(
1032"encountered a pointer with unknown absolute address, but expected something that is definitely {in_range}",
1033 in_range = fmt_range(valid_range, max_value)
1034 )
1035 )1036 }
1037 }
1038 };
1039// Now compare.
1040if valid_range.contains(bits) {
1041interp_ok(())
1042 } else {
1043do 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!(
1044self.path,
1045format!(
1046"encountered {bits}, but expected something {in_range}",
1047 in_range = fmt_range(valid_range, max_value)
1048 )
1049 )1050 }
1051 }
10521053fn in_mutable_memory(&self, val: &PlaceTy<'tcx, M::Provenance>) -> bool {
1054if true {
if !self.ctfe_mode.is_some() {
::core::panicking::panic("assertion failed: self.ctfe_mode.is_some()")
};
};debug_assert!(self.ctfe_mode.is_some());
1055if let Some(mplace) = val.as_mplace_or_local().left() {
1056if let Some(alloc_id) = mplace.ptr().provenance.and_then(|p| p.get_alloc_id()) {
1057let tcx = *self.ecx.tcx;
1058// Everything must be already interned.
1059let mutbl = tcx.global_alloc(alloc_id).mutability(tcx, self.ecx.typing_env);
1060if let Some((_, alloc)) = self.ecx.memory.alloc_map.get(alloc_id) {
1061{
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);
1062 }
1063mutbl.is_mut()
1064 } else {
1065// No memory at all.
1066false
1067}
1068 } else {
1069// A local variable -- definitely mutable.
1070true
1071}
1072 }
10731074/// Add the given pointer-length pair to the "data" range of this visit.
1075fn add_data_range(&mut self, ptr: Pointer<Option<M::Provenance>>, size: Size) {
1076if let Some(data_bytes) = self.data_bytes.as_mut() {
1077// We only have to store the offset, the rest is the same for all pointers here.
1078 // The logic is agnostic to whether the offset is relative or absolute as long as
1079 // it is consistent.
1080let (_prov, offset) = ptr.into_raw_parts();
1081// Add this.
1082data_bytes.add_range(offset, size);
1083 };
1084 }
10851086/// Add the entire given place to the "data" range of this visit.
1087fn add_data_range_place(&mut self, place: &PlaceTy<'tcx, M::Provenance>) {
1088// Only sized places can be added this way.
1089if true {
if !place.layout.is_sized() {
::core::panicking::panic("assertion failed: place.layout.is_sized()")
};
};debug_assert!(place.layout.is_sized());
1090if let Some(data_bytes) = self.data_bytes.as_mut() {
1091let offset = Self::data_range_offset(self.ecx, place);
1092data_bytes.add_range(offset, place.layout.size);
1093 }
1094 }
10951096/// Convert a place into the offset it starts at, for the purpose of data_range tracking.
1097 /// Must only be called if `data_bytes` is `Some(_)`.
1098fn data_range_offset(ecx: &InterpCx<'tcx, M>, place: &PlaceTy<'tcx, M::Provenance>) -> Size {
1099// The presence of `data_bytes` implies that our place is in memory.
1100let ptr = ecx1101 .place_to_op(place)
1102 .expect("place must be in memory")
1103 .as_mplace_or_imm()
1104 .expect_left("place must be in memory")
1105 .ptr();
1106let (_prov, offset) = ptr.into_raw_parts();
1107offset1108 }
11091110fn reset_padding(&mut self, place: &PlaceTy<'tcx, M::Provenance>) -> InterpResult<'tcx> {
1111let Some(data_bytes) = self.data_bytes.as_mut() else { return interp_ok(()) };
1112// Our value must be in memory, otherwise we would not have set up `data_bytes`.
1113let mplace = self.ecx.force_allocation(place)?;
1114// Determine starting offset and size.
1115let (_prov, start_offset) = mplace.ptr().into_raw_parts();
1116let (size, _align) = self
1117.ecx
1118 .size_and_align_of_val(&mplace)?
1119.unwrap_or((mplace.layout.size, mplace.layout.align.abi));
1120// If there is no padding at all, we can skip the rest: check for
1121 // a single data range covering the entire value.
1122if data_bytes.0 == &[(start_offset, size)] {
1123return interp_ok(());
1124 }
1125// Get a handle for the allocation. Do this only once, to avoid looking up the same
1126 // allocation over and over again. (Though to be fair, iterating the value already does
1127 // exactly that.)
1128let Some(mut alloc) = self.ecx.get_ptr_alloc_mut(mplace.ptr(), size)? else {
1129// A ZST, no padding to clear.
1130return interp_ok(());
1131 };
1132// Add a "finalizer" data range at the end, so that the iteration below finds all gaps
1133 // between ranges.
1134data_bytes.0.push((start_offset + size, Size::ZERO));
1135// Iterate, and reset gaps.
1136let mut padding_cleared_until = start_offset;
1137for &(offset, size) in data_bytes.0.iter() {
1138if !(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!(
1139 offset >= padding_cleared_until,
1140"reset_padding on {}: previous field ended at offset {}, next field starts at {} (and has a size of {} bytes)",
1141 mplace.layout.ty,
1142 (padding_cleared_until - start_offset).bytes(),
1143 (offset - start_offset).bytes(),
1144 size.bytes(),
1145 );
1146if offset > padding_cleared_until {
1147// We found padding. Adjust the range to be relative to `alloc`, and make it uninit.
1148let padding_start = padding_cleared_until - start_offset;
1149let padding_size = offset - padding_cleared_until;
1150let range = alloc_range(padding_start, padding_size);
1151{
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:1151",
"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(1151u32),
::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);
1152 alloc.write_uninit(range);
1153 }
1154 padding_cleared_until = offset + size;
1155 }
1156if !(padding_cleared_until == start_offset + size) {
::core::panicking::panic("assertion failed: padding_cleared_until == start_offset + size")
};assert!(padding_cleared_until == start_offset + size);
1157interp_ok(())
1158 }
11591160/// Computes the data range of this union type:
1161 /// which bytes are inside a field (i.e., not padding.)
1162fn union_data_range<'e>(
1163 ecx: &'e mut InterpCx<'tcx, M>,
1164 layout: TyAndLayout<'tcx>,
1165 ) -> Cow<'e, RangeSet> {
1166if !layout.ty.is_union() {
::core::panicking::panic("assertion failed: layout.ty.is_union()")
};assert!(layout.ty.is_union());
1167if !layout.is_sized() {
{
::core::panicking::panic_fmt(format_args!("there are no unsized unions"));
}
};assert!(layout.is_sized(), "there are no unsized unions");
1168let layout_cx = LayoutCx::new(*ecx.tcx, ecx.typing_env);
1169return M::cached_union_data_range(ecx, layout.ty, || {
1170let mut out = RangeSet::new();
1171union_data_range_uncached(&layout_cx, layout, Size::ZERO, &mut out);
1172out1173 });
11741175/// Helper for recursive traversal: add data ranges of the given type to `out`.
1176fn union_data_range_uncached<'tcx>(
1177 cx: &LayoutCx<'tcx>,
1178 layout: TyAndLayout<'tcx>,
1179 base_offset: Size,
1180 out: &mut RangeSet,
1181 ) {
1182// If this is a ZST, we don't contain any data. In particular, this helps us to quickly
1183 // skip over huge arrays of ZST.
1184if layout.is_zst() {
1185return;
1186 }
1187// Just recursively add all the fields of everything to the output.
1188match &layout.fields {
1189 FieldsShape::Primitive => {
1190out.add_range(base_offset, layout.size);
1191 }
1192&FieldsShape::Union(fields) => {
1193// Currently, all fields start at offset 0 (relative to `base_offset`).
1194for field in 0..fields.get() {
1195let field = layout.field(cx, field);
1196 union_data_range_uncached(cx, field, base_offset, out);
1197 }
1198 }
1199&FieldsShape::Array { stride, count } => {
1200let elem = layout.field(cx, 0);
12011202// Fast-path for large arrays of simple types that do not contain any padding.
1203if elem.backend_repr.is_scalar() {
1204out.add_range(base_offset, elem.size * count);
1205 } else {
1206for idx in 0..count {
1207// This repeats the same computation for every array element... but the alternative
1208 // is to allocate temporary storage for a dedicated `out` set for the array element,
1209 // and replicating that N times. Is that better?
1210union_data_range_uncached(cx, elem, base_offset + idx * stride, out);
1211 }
1212 }
1213 }
1214 FieldsShape::Arbitrary { offsets, .. } => {
1215for (field, &offset) in offsets.iter_enumerated() {
1216let field = layout.field(cx, field.as_usize());
1217 union_data_range_uncached(cx, field, base_offset + offset, out);
1218 }
1219 }
1220 }
1221// Don't forget potential other variants.
1222match &layout.variants {
1223 Variants::Single { .. } | Variants::Empty => {
1224// Fully handled above.
1225}
1226 Variants::Multiple { variants, .. } => {
1227for variant in variants.indices() {
1228let variant = layout.for_variant(cx, variant);
1229 union_data_range_uncached(cx, variant, base_offset, out);
1230 }
1231 }
1232 }
1233 }
1234 }
1235}
12361237impl<'rt, 'tcx, M: Machine<'tcx>> ValueVisitor<'tcx, M> for ValidityVisitor<'rt, 'tcx, M> {
1238type V = PlaceTy<'tcx, M::Provenance>;
12391240#[inline(always)]
1241fn ecx(&self) -> &InterpCx<'tcx, M> {
1242self.ecx
1243 }
12441245fn read_discriminant(
1246&mut self,
1247 val: &PlaceTy<'tcx, M::Provenance>,
1248 ) -> InterpResult<'tcx, VariantIdx> {
1249self.with_elem(PathElem::EnumTag, move |this| {
1250interp_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!(
1251 this.ecx.read_discriminant(val),
1252 this.path,
1253 Ub(InvalidTag(val)) =>
1254format!("encountered {val:x}, but expected a valid enum tag"),
1255 Ub(UninhabitedEnumVariantRead(_)) =>
1256format!("encountered an uninhabited enum variant"),
1257// Uninit / bad provenance are not possible since the field was already previously
1258 // checked at its integer type.
1259))
1260 })
1261 }
12621263#[inline]
1264fn visit_field(
1265&mut self,
1266 old_val: &PlaceTy<'tcx, M::Provenance>,
1267 field: usize,
1268 new_val: &PlaceTy<'tcx, M::Provenance>,
1269 ) -> InterpResult<'tcx> {
1270let elem = self.aggregate_field_path_elem(old_val.layout, field, new_val.layout.ty);
1271self.with_elem(elem, move |this| this.visit_value(new_val))
1272 }
12731274#[inline]
1275fn visit_variant(
1276&mut self,
1277 old_val: &PlaceTy<'tcx, M::Provenance>,
1278 variant_id: VariantIdx,
1279 new_val: &PlaceTy<'tcx, M::Provenance>,
1280 ) -> InterpResult<'tcx> {
1281let name = match old_val.layout.ty.kind() {
1282 ty::Adt(adt, _) => PathElem::Variant(adt.variant(variant_id).name),
1283// Coroutines also have variants
1284ty::Coroutine(..) => PathElem::CoroutineState(variant_id),
1285_ => ::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),
1286 };
1287self.with_elem(name, move |this| this.visit_value(new_val))
1288 }
12891290#[inline(always)]
1291fn visit_union(
1292&mut self,
1293 val: &PlaceTy<'tcx, M::Provenance>,
1294 _fields: NonZero<usize>,
1295 ) -> InterpResult<'tcx> {
1296// Special check for CTFE validation, preventing `UnsafeCell` inside unions in immutable memory.
1297if self.ctfe_mode.is_some_and(|c| !c.allow_immutable_unsafe_cell()) {
1298// Unsized unions are currently not a thing, but let's keep this code consistent with
1299 // the check in `visit_value`.
1300let zst = self.ecx.size_and_align_of_val(val)?.is_some_and(|(s, _a)| s.bytes() == 0);
1301if !zst && !val.layout.ty.is_freeze(*self.ecx.tcx, self.ecx.typing_env) {
1302if !self.in_mutable_memory(val) {
1303do 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!(
1304self.path,
1305format!("encountered `UnsafeCell` in read-only memory")
1306 );
1307 }
1308 }
1309 }
1310if self.reset_provenance_and_padding
1311 && let Some(data_bytes) = self.data_bytes.as_mut()
1312 {
1313let base_offset = Self::data_range_offset(self.ecx, val);
1314// Determine and add data range for this union.
1315let union_data_range = Self::union_data_range(self.ecx, val.layout);
1316for &(offset, size) in union_data_range.0.iter() {
1317 data_bytes.add_range(base_offset + offset, size);
1318 }
1319 }
1320interp_ok(())
1321 }
13221323#[inline]
1324fn visit_box(
1325&mut self,
1326 box_ty: Ty<'tcx>,
1327 val: &PlaceTy<'tcx, M::Provenance>,
1328 ) -> InterpResult<'tcx> {
1329self.check_safe_pointer(&val, box_ty, PtrKind::Box)?;
1330interp_ok(())
1331 }
13321333#[inline]
1334fn visit_variantless(&mut self, val: &PlaceTy<'tcx, M::Provenance>) -> InterpResult<'tcx> {
1335let ty = val.layout.ty;
1336if !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}`");
1337do 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!(
1338self.path,
1339format!("encountered a value of zero-variant enum `{ty}`")
1340 );
1341 }
13421343#[inline]
1344fn visit_value(&mut self, val: &PlaceTy<'tcx, M::Provenance>) -> InterpResult<'tcx> {
1345{
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:1345",
"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(1345u32),
::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);
13461347// Check primitive types -- the leaves of our recursive descent.
1348 // This is called even for enum discriminants (which are "fields" of their enum),
1349 // so for integer-typed discriminants the provenance reset will happen here.
1350 // We assume that the Scalar validity range does not restrict these values
1351 // any further than `try_visit_primitive` does!
1352if self.try_visit_primitive(val)? {
1353return interp_ok(());
1354 }
13551356// Special check preventing `UnsafeCell` in the inner part of constants
1357if self.ctfe_mode.is_some_and(|c| !c.allow_immutable_unsafe_cell()) {
1358// Exclude ZST values. We need to compute the dynamic size/align to properly
1359 // handle slices and trait objects.
1360let zst = self.ecx.size_and_align_of_val(val)?.is_some_and(|(s, _a)| s.bytes() == 0);
1361if !zst1362 && let Some(def) = val.layout.ty.ty_adt_def()
1363 && def.is_unsafe_cell()
1364 {
1365if !self.in_mutable_memory(val) {
1366do 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!(
1367self.path,
1368format!("encountered `UnsafeCell` in read-only memory")
1369 );
1370 }
1371 }
1372 }
13731374// Recursively walk the value at its type. Apply optimizations for some large types.
1375match val.layout.ty.kind() {
1376 ty::Str => {
1377let mplace = val.assert_mem_place(); // strings are unsized and hence never immediate
1378let len = mplace.len(self.ecx)?;
1379let expected = ExpectedKind::Str;
1380{
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!(
1381self.ecx.read_bytes_ptr_strip_provenance(mplace.ptr(), Size::from_bytes(len)),
1382self.path,
1383 Ub(InvalidUninitBytes(..)) =>
1384 Uninit { expected },
1385 Unsup(ReadPointerAsInt(_)) =>
1386 PointerAsInt { expected },
1387 );
1388 }
1389 ty::Array(tys, ..) | ty::Slice(tys)
1390// This optimization applies for types that can hold arbitrary non-provenance bytes (such as
1391 // integer and floating point types).
1392 // FIXME(wesleywiser) This logic could be extended further to arbitrary structs or
1393 // tuples made up of integer/floating point types or inhabited ZSTs with no padding.
1394if #[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(..))1395 =>
1396 {
1397let expected = if tys.is_integral() { ExpectedKind::Int } else { ExpectedKind::Float };
1398// Optimized handling for arrays of integer/float type.
13991400 // This is the length of the array/slice.
1401let len = val.len(self.ecx)?;
1402// This is the element type size.
1403let layout = self.ecx.layout_of(*tys)?;
1404// This is the size in bytes of the whole array. (This checks for overflow.)
1405let size = layout.size * len;
1406// If the size is 0, there is nothing to check.
1407 // (`size` can only be 0 if `len` is 0, and empty arrays are always valid.)
1408if size == Size::ZERO {
1409return interp_ok(());
1410 }
1411// Now that we definitely have a non-ZST array, we know it lives in memory -- except it may
1412 // be an uninitialized local variable, those are also "immediate".
1413let mplace = match val.to_op(self.ecx)?.as_mplace_or_imm() {
1414Left(mplace) => mplace,
1415Right(imm) => match *imm {
1416 Immediate::Uninit =>
1417do 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!(
1418self.path,
1419 Uninit { expected }
1420 ),
1421 Immediate::Scalar(..) | Immediate::ScalarPair { .. } =>
1422::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"),
1423 }
1424 };
14251426// Optimization: we just check the entire range at once.
1427 // NOTE: Keep this in sync with the handling of integer and float
1428 // types above, in `visit_primitive`.
1429 // No need for an alignment check here, this is not an actual memory access.
1430let alloc = self.ecx.get_ptr_alloc(mplace.ptr(), size)?.expect("we already excluded size 0");
14311432 alloc.get_bytes_strip_provenance().map_err_kind(|kind| {
1433// Some error happened, try to provide a more detailed description.
1434 // For some errors we might be able to provide extra information.
1435 // (This custom logic does not fit the `try_validation!` macro.)
1436match kind {
1437 Ub(InvalidUninitBytes(Some((_alloc_id, access)))) | Unsup(ReadPointerAsInt(Some((_alloc_id, access)))) => {
1438// Some byte was uninitialized, determine which
1439 // element that byte belongs to so we can
1440 // provide an index.
1441let i = usize::try_from(
1442 access.bad.start.bytes() / layout.size.bytes(),
1443 )
1444 .unwrap();
1445self.path.projs.push(PathElem::ArrayElem(i));
14461447if #[allow(non_exhaustive_omitted_patterns)] match kind {
Ub(InvalidUninitBytes(_)) => true,
_ => false,
}matches!(kind, Ub(InvalidUninitBytes(_))) {
1448{
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 })1449 } else {
1450{
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})1451 }
1452 }
14531454// Propagate upwards (that will also check for unexpected errors).
1455err => err,
1456 }
1457 })?;
14581459// Don't forget that these are all non-pointer types, and thus do not preserve
1460 // provenance.
1461if self.reset_provenance_and_padding {
1462// We can't share this with above as above, we might be looking at read-only memory.
1463let mut alloc = self.ecx.get_ptr_alloc_mut(mplace.ptr(), size)?.expect("we already excluded size 0");
1464alloc.clear_provenance();
1465// Also, mark this as containing data, not padding.
1466self.add_data_range(mplace.ptr(), size);
1467 }
1468 }
1469// Fast path for arrays and slices of ZSTs. We only need to check a single ZST element
1470 // of an array and not all of them, because there's only a single value of a specific
1471 // ZST type, so either validation fails for all elements or none.
1472ty::Array(tys, ..) | ty::Slice(tys) if self.ecx.layout_of(*tys)?.is_zst() => {
1473// Validate just the first element (if any).
1474if val.len(self.ecx)? > 0 {
1475self.visit_field(val, 0, &self.ecx.project_index(val, 0)?)?;
1476 }
1477 }
1478 ty::Pat(base, pat) => {
1479// First check that the base type is valid
1480self.visit_value(&val.transmute(self.ecx.layout_of(*base)?, self.ecx)?)?;
1481// When you extend this match, make sure to also add tests to
1482 // tests/ui/type/pattern_types/validity.rs
1483match **pat {
1484// Range and non-null patterns are precisely reflected into `valid_range` and thus
1485 // handled fully by `visit_scalar` (called below).
1486ty::PatternKind::Range { .. } => {},
1487 ty::PatternKind::NotNull => {},
14881489// FIXME(pattern_types): check that the value is covered by one of the variants.
1490 // For now, we rely on layout computation setting the scalar's `valid_range` to
1491 // match the pattern. However, this cannot always work; the layout may
1492 // pessimistically cover actually illegal ranges and Miri would miss that UB.
1493 // The consolation here is that codegen also will miss that UB, so at least
1494 // we won't see optimizations actually breaking such programs.
1495ty::PatternKind::Or(_patterns) => {}
1496 }
1497// FIXME(pattern_types): handle everything based on the pattern, not on the layout.
1498 // it's ok to run scalar validation even if the pattern type is `u8 is 0..=255` and thus
1499 // allows uninit values, because that's rare and so not a perf issue.
1500match val.layout.backend_repr {
1501 BackendRepr::Scalar(scalar_layout) => {
1502if !scalar_layout.is_uninit_valid() {
1503// There is something to check here.
1504 // We read directly via `ecx` since the read cannot fail -- we already read
1505 // this field above when recursing into the field.
1506let scalar = self.ecx.read_scalar(val)?;
1507self.visit_scalar(scalar, scalar_layout)?;
1508 }
1509 }
1510 BackendRepr::ScalarPair { a: a_layout, b: b_layout, b_offset: _ } => {
1511// We can only proceed if *both* scalars need to be initialized.
1512 // FIXME: find a way to also check ScalarPair when one side can be uninit but
1513 // the other must be init.
1514if !a_layout.is_uninit_valid() && !b_layout.is_uninit_valid() {
1515// We read directly via `ecx` since the read cannot fail -- we already read
1516 // this field above when recursing into the field.
1517let (a, b) = self.ecx.read_immediate(val)?.to_scalar_pair();
1518self.visit_scalar(a, a_layout)?;
1519self.visit_scalar(b, b_layout)?;
1520 }
1521 }
1522 BackendRepr::SimdVector { .. } | BackendRepr::SimdScalableVector { .. } => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1523 BackendRepr::Memory { .. } => ::core::panicking::panic("internal error: entered unreachable code")unreachable!()1524 }
1525 }
1526 ty::Adt(adt, _) if adt.is_maybe_dangling() => {
1527let old_may_dangle = mem::replace(&mut self.may_dangle, true);
15281529let inner = self.ecx.project_field(val, FieldIdx::ZERO)?;
1530self.visit_value(&inner)?;
15311532self.may_dangle = old_may_dangle;
1533 }
1534_ => {
1535// default handler
1536{
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!(
1537self.walk_value(val),
1538self.path,
1539// It's not great to catch errors here, since we can't give a very good path,
1540 // but it's better than ICEing.
1541Ub(InvalidVTableTrait { vtable_dyn_type, expected_dyn_type }) =>
1542 InvalidMetaWrongTrait { expected_dyn_type, vtable_dyn_type },
1543 );
1544 }
1545 }
15461547// Assert that we checked everything there is to check about this type.
1548 // `is_opsem_inhabited` implies that the layout is inhabited (checked by layout invariants).
1549if !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!(
1550 val.layout.ty.is_opsem_inhabited(*self.ecx.tcx, self.ecx.typing_env),
1551"a value of type `{}` passed validation but that type is uninhabited",
1552 val.layout.ty
1553 );
1554if truecfg!(debug_assertions) {
1555// Only run expensive checks when debug assertions are enabled.
1556match val.layout.backend_repr {
1557 BackendRepr::Scalar(scalar_layout) => {
1558if !scalar_layout.is_uninit_valid() {
1559// There is something to check here.
1560 // We read directly via `ecx` since the read cannot fail -- we already read
1561 // this field above when recursing into the field.
1562let scalar = self1563 .ecx
1564 .read_scalar(val)
1565 .expect("the above checks should have fully handled this situation");
1566self.visit_scalar(scalar, scalar_layout)
1567 .expect("the above checks should have fully handled this situation");
1568 }
1569 }
1570 BackendRepr::ScalarPair { a: a_layout, b: b_layout, b_offset: _ } => {
1571// We can only proceed if *both* scalars need to be initialized.
1572 // FIXME: find a way to also check ScalarPair when one side can be uninit but
1573 // the other must be init.
1574if !a_layout.is_uninit_valid() && !b_layout.is_uninit_valid() {
1575let (a, b) = self1576 .ecx
1577 .read_immediate(val)
1578 .expect("the above checks should have fully handled this situation")
1579 .to_scalar_pair();
1580self.visit_scalar(a, a_layout)
1581 .expect("the above checks should have fully handled this situation");
1582self.visit_scalar(b, b_layout)
1583 .expect("the above checks should have fully handled this situation");
1584 }
1585 }
1586 BackendRepr::SimdVector { .. } | BackendRepr::SimdScalableVector { .. } => {}
1587 BackendRepr::Memory { .. } => {}
1588 }
1589 }
15901591interp_ok(())
1592 }
1593}
15941595impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
1596/// The internal core entry point for all validation operations.
1597fn validate_place_internal(
1598&mut self,
1599 val: &PlaceTy<'tcx, M::Provenance>,
1600 path: Path<'tcx>,
1601 ref_tracking: Option<&mut RefTracking<MPlaceTy<'tcx, M::Provenance>, Path<'tcx>>>,
1602 ctfe_mode: Option<CtfeValidationMode>,
1603 reset_provenance_and_padding: bool,
1604 start_in_may_dangle: bool,
1605 ) -> InterpResult<'tcx> {
1606{
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:1606",
"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(1606u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::validity"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("validate_place_internal: {0:?}, {1:?}",
*val, val.layout.ty) as &dyn ::tracing::field::Value))])
});
} else { ; }
};trace!("validate_place_internal: {:?}, {:?}", *val, val.layout.ty);
16071608// Run the visitor.
1609self.run_for_validation_mut(|ecx| {
1610let reset_padding = reset_provenance_and_padding && {
1611// Check if `val` is actually stored in memory. If not, padding is not even
1612 // represented and we need not reset it.
1613ecx.place_to_op(val)?.as_mplace_or_imm().is_left()
1614 };
1615let mut v = ValidityVisitor {
1616path,
1617ref_tracking,
1618ctfe_mode,
1619ecx,
1620reset_provenance_and_padding,
1621 data_bytes: reset_padding.then_some(RangeSet::new()),
1622 may_dangle: start_in_may_dangle,
1623 };
1624 v.visit_value(val)?;
1625 v.reset_padding(val)?;
1626interp_ok(())
1627 })
1628 .inspect_err_info(|err| {
1629if !#[allow(non_exhaustive_omitted_patterns)] match err.kind() {
InterpErrorKind::UndefinedBehavior(ValidationError { .. }) |
InterpErrorKind::InvalidProgram(_) | InterpErrorKind::Unsupported(_) |
InterpErrorKind::MachineStop(_) => true,
_ => false,
}matches!(
1630 err.kind(),
1631 InterpErrorKind::UndefinedBehavior(ValidationError { .. })
1632 | InterpErrorKind::InvalidProgram(_)
1633 | InterpErrorKind::Unsupported(_)
1634// We have to also ignore machine-specific errors since we do retagging
1635 // during validation.
1636| InterpErrorKind::MachineStop(_)
1637 ) {
1638::rustc_middle::util::bug::bug_fmt(format_args!("Unexpected error during validation: {0}",
err.to_string()));bug!("Unexpected error during validation: {}", err.to_string());
1639 }
1640 })
1641 }
16421643/// This function checks the data at `val` to be const-valid.
1644 /// `val` is assumed to cover valid memory.
1645 /// It will error if the bits at the destination do not match the ones described by the layout.
1646 ///
1647 /// `ref_tracking` is used to record references that we encounter so that they
1648 /// can be checked recursively by an outside driving loop.
1649 ///
1650 /// `constant` controls whether this must satisfy the rules for constants:
1651 /// - no pointers to statics.
1652 /// - no `UnsafeCell` or non-ZST `&mut`.
1653#[inline(always)]
1654pub(crate) fn const_validate_place(
1655&mut self,
1656 val: &PlaceTy<'tcx, M::Provenance>,
1657 path: Path<'tcx>,
1658 ref_tracking: &mut RefTracking<MPlaceTy<'tcx, M::Provenance>, Path<'tcx>>,
1659 ctfe_mode: CtfeValidationMode,
1660 ) -> InterpResult<'tcx> {
1661self.validate_place_internal(
1662val,
1663path,
1664Some(ref_tracking),
1665Some(ctfe_mode),
1666/*reset_provenance*/ false,
1667/*start_in_may_dangle*/ false,
1668 )
1669 }
16701671/// This function checks the data at `val` to be runtime-valid.
1672 /// `val` is assumed to cover valid memory.
1673 /// It will error if the bits at the destination do not match the ones described by the layout.
1674#[inline(always)]
1675pub fn validate_place(
1676&mut self,
1677 val: &PlaceTy<'tcx, M::Provenance>,
1678 recursive: bool,
1679 reset_provenance_and_padding: bool,
1680 ) -> InterpResult<'tcx> {
1681let _trace =
1682<M as
crate::interpret::Machine>::enter_trace_span(||
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("validate_place",
"rustc_const_eval::interpret::validity",
::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/validity.rs"),
::tracing_core::__macro_support::Option::Some(1682u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::validity"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("recursive")
}> =
::tracing::__macro_support::FieldName::new("recursive");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("reset_provenance_and_padding")
}> =
::tracing::__macro_support::FieldName::new("reset_provenance_and_padding");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("val")
}> =
::tracing::__macro_support::FieldName::new("val");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::INFO <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&recursive
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&reset_provenance_and_padding
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&val)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
})enter_trace_span!(M, "validate_place", recursive, reset_provenance_and_padding, ?val,);
1683// Note that we *could* actually be in CTFE here with `-Zextra-const-ub-checks`, but it's
1684 // still correct to not use `ctfe_mode`: that mode is for validation of the final constant
1685 // value, it rules out things like `UnsafeCell` in awkward places.
1686if !recursive {
1687return self.validate_place_internal(
1688val,
1689Path::new(val.layout.ty),
1690None,
1691None,
1692reset_provenance_and_padding,
1693/*start_in_may_dangle*/ false,
1694 );
1695 }
1696// Do a recursive check.
1697let mut ref_tracking = RefTracking::empty();
1698self.validate_place_internal(
1699 val,
1700 Path::new(val.layout.ty),
1701Some(&mut ref_tracking),
1702None,
1703 reset_provenance_and_padding,
1704/*start_in_may_dangle*/ false,
1705 )?;
1706while let Some((mplace, path)) = ref_tracking.todo.pop() {
1707// Things behind reference do *not* have the provenance reset. In fact
1708 // we treat the entire thing as being inside MaybeDangling, i.e., references
1709 // do not have to be dereferenceable.
1710self.validate_place_internal(
1711&mplace.into(),
1712 path,
1713None, // no further recursion
1714None,
1715/*reset_provenance_and_padding*/ false,
1716/*start_in_may_dangle*/ true,
1717 )?;
1718 }
1719interp_ok(())
1720 }
1721}