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