2019-08-30 08:37:02 +02:00
|
|
|
//! Check the validity invariant of a given value, and tell the user
|
|
|
|
//! where in the value it got violated.
|
|
|
|
//! In const context, this goes even further and tries to approximate const safety.
|
|
|
|
//! That's useful because it means other passes (e.g. promotion) can rely on `const`s
|
|
|
|
//! to be const-safe.
|
|
|
|
|
2020-03-21 13:49:02 +01:00
|
|
|
use std::convert::TryFrom;
|
2018-11-02 09:33:26 +01:00
|
|
|
use std::fmt::Write;
|
2020-04-16 15:15:46 +00:00
|
|
|
use std::num::NonZeroUsize;
|
2018-08-17 12:18:02 +02:00
|
|
|
|
|
|
|
use rustc_data_structures::fx::FxHashSet;
|
2020-01-05 02:37:57 +01:00
|
|
|
use rustc_hir as hir;
|
2021-02-14 00:00:00 +00:00
|
|
|
use rustc_middle::mir::interpret::InterpError;
|
2020-03-29 16:41:09 +02:00
|
|
|
use rustc_middle::ty;
|
2021-08-30 17:38:27 +03:00
|
|
|
use rustc_middle::ty::layout::{LayoutOf, TyAndLayout};
|
2019-12-31 20:15:40 +03:00
|
|
|
use rustc_span::symbol::{sym, Symbol};
|
2021-10-28 00:00:00 +00:00
|
|
|
use rustc_span::DUMMY_SP;
|
2021-08-30 17:38:27 +03:00
|
|
|
use rustc_target::abi::{Abi, Scalar as ScalarAbi, Size, VariantIdx, Variants, WrappingRange};
|
2018-08-17 12:18:02 +02:00
|
|
|
|
2019-02-10 14:59:13 +01:00
|
|
|
use std::hash::Hash;
|
|
|
|
|
2018-08-17 12:18:02 +02:00
|
|
|
use super::{
|
2022-05-04 22:47:46 +02:00
|
|
|
alloc_range, CheckInAllocMsg, GlobalAlloc, Immediate, InterpCx, InterpResult, MPlaceTy,
|
|
|
|
Machine, MemPlaceMeta, OpTy, Scalar, ScalarMaybeUninit, ValueVisitor,
|
2018-08-17 12:18:02 +02:00
|
|
|
};
|
|
|
|
|
2019-07-31 12:48:54 +05:30
|
|
|
macro_rules! throw_validation_failure {
|
2020-05-06 11:42:18 +02:00
|
|
|
($where:expr, { $( $what_fmt:expr ),+ } $( expected { $( $expected_fmt:expr ),+ } )?) => {{
|
2021-06-14 18:57:53 +02:00
|
|
|
let mut msg = String::new();
|
|
|
|
msg.push_str("encountered ");
|
|
|
|
write!(&mut msg, $($what_fmt),+).unwrap();
|
|
|
|
$(
|
|
|
|
msg.push_str(", but expected ");
|
|
|
|
write!(&mut msg, $($expected_fmt),+).unwrap();
|
|
|
|
)?
|
2022-02-16 13:04:48 -05:00
|
|
|
let path = rustc_middle::ty::print::with_no_trimmed_paths!({
|
2021-06-13 22:40:42 +02:00
|
|
|
let where_ = &$where;
|
2021-06-14 18:57:53 +02:00
|
|
|
if !where_.is_empty() {
|
2021-06-13 22:40:42 +02:00
|
|
|
let mut path = String::new();
|
|
|
|
write_path(&mut path, where_);
|
|
|
|
Some(path)
|
|
|
|
} else {
|
|
|
|
None
|
2021-06-14 18:57:53 +02:00
|
|
|
}
|
2020-09-02 10:40:56 +03:00
|
|
|
});
|
2021-06-13 22:40:42 +02:00
|
|
|
throw_ub!(ValidationFailure { path, msg })
|
2018-08-17 12:18:02 +02:00
|
|
|
}};
|
|
|
|
}
|
|
|
|
|
2020-05-06 09:22:52 +02:00
|
|
|
/// If $e throws an error matching the pattern, throw a validation failure.
|
|
|
|
/// Other errors are passed back to the caller, unchanged -- and if they reach the root of
|
|
|
|
/// the visitor, we make sure only validation errors and `InvalidProgram` errors are left.
|
2020-07-07 11:12:44 -04:00
|
|
|
/// This lets you use the patterns as a kind of validation list, asserting which errors
|
2020-05-06 09:22:52 +02:00
|
|
|
/// can possibly happen:
|
2020-04-23 22:00:06 +10:00
|
|
|
///
|
2020-05-01 17:52:42 +10:00
|
|
|
/// ```
|
2020-05-06 00:07:53 +02:00
|
|
|
/// let v = try_validation!(some_fn(), some_path, {
|
2020-05-01 17:52:42 +10:00
|
|
|
/// Foo | Bar | Baz => { "some failure" },
|
|
|
|
/// });
|
2020-04-23 22:00:06 +10:00
|
|
|
/// ```
|
2020-05-01 17:52:42 +10:00
|
|
|
///
|
|
|
|
/// An additional expected parameter can also be added to the failure message:
|
|
|
|
///
|
|
|
|
/// ```
|
2020-05-06 00:07:53 +02:00
|
|
|
/// let v = try_validation!(some_fn(), some_path, {
|
2020-05-01 17:52:42 +10:00
|
|
|
/// Foo | Bar | Baz => { "some failure" } expected { "something that wasn't a failure" },
|
|
|
|
/// });
|
|
|
|
/// ```
|
|
|
|
///
|
2020-05-01 21:49:42 +10:00
|
|
|
/// An additional nicety is that both parameters actually take format args, so you can just write
|
|
|
|
/// the format string in directly:
|
|
|
|
///
|
|
|
|
/// ```
|
2020-05-06 00:07:53 +02:00
|
|
|
/// let v = try_validation!(some_fn(), some_path, {
|
2020-05-01 21:49:42 +10:00
|
|
|
/// Foo | Bar | Baz => { "{:?}", some_failure } expected { "{}", expected_value },
|
|
|
|
/// });
|
|
|
|
/// ```
|
|
|
|
///
|
2020-05-06 00:07:53 +02:00
|
|
|
macro_rules! try_validation {
|
|
|
|
($e:expr, $where:expr,
|
2021-09-18 17:37:24 -04:00
|
|
|
$( $( $p:pat_param )|+ => { $( $what_fmt:expr ),+ } $( expected { $( $expected_fmt:expr ),+ } )? ),+ $(,)?
|
2020-05-06 00:07:53 +02:00
|
|
|
) => {{
|
2018-10-02 17:02:58 +02:00
|
|
|
match $e {
|
|
|
|
Ok(x) => x,
|
2020-04-23 22:52:27 +10:00
|
|
|
// We catch the error and turn it into a validation failure. We are okay with
|
|
|
|
// allocation here as this can only slow down builds that fail anyway.
|
2021-02-14 00:00:00 +00:00
|
|
|
Err(e) => match e.kind() {
|
|
|
|
$(
|
|
|
|
$($p)|+ =>
|
|
|
|
throw_validation_failure!(
|
|
|
|
$where,
|
|
|
|
{ $( $what_fmt ),+ } $( expected { $( $expected_fmt ),+ } )?
|
|
|
|
)
|
|
|
|
),+,
|
|
|
|
#[allow(unreachable_patterns)]
|
|
|
|
_ => Err::<!, _>(e)?,
|
|
|
|
}
|
2018-10-02 17:02:58 +02:00
|
|
|
}
|
2019-12-12 15:23:46 +01:00
|
|
|
}};
|
2018-10-02 17:02:58 +02:00
|
|
|
}
|
|
|
|
|
2018-11-12 13:05:20 -05:00
|
|
|
/// We want to show a nice path to the invalid field for diagnostics,
|
2018-08-18 13:46:52 +02:00
|
|
|
/// but avoid string operations in the happy case where no error happens.
|
|
|
|
/// So we track a `Vec<PathElem>` where `PathElem` contains all the data we
|
|
|
|
/// need to later print something for the user.
|
|
|
|
#[derive(Copy, Clone, Debug)]
|
|
|
|
pub enum PathElem {
|
|
|
|
Field(Symbol),
|
2018-11-07 16:45:07 +01:00
|
|
|
Variant(Symbol),
|
2019-05-05 22:53:56 +02:00
|
|
|
GeneratorState(VariantIdx),
|
2020-02-26 12:00:33 +01:00
|
|
|
CapturedVar(Symbol),
|
2018-08-18 13:46:52 +02:00
|
|
|
ArrayElem(usize),
|
|
|
|
TupleElem(usize),
|
|
|
|
Deref,
|
2020-02-26 12:00:33 +01:00
|
|
|
EnumTag,
|
|
|
|
GeneratorTag,
|
2018-10-31 18:44:00 +01:00
|
|
|
DynDowncast,
|
2018-08-18 13:46:52 +02:00
|
|
|
}
|
|
|
|
|
2020-10-24 20:49:17 +02:00
|
|
|
/// Extra things to check for during validation of CTFE results.
|
|
|
|
pub enum CtfeValidationMode {
|
|
|
|
/// Regular validation, nothing special happening.
|
|
|
|
Regular,
|
2020-12-20 19:34:29 +01:00
|
|
|
/// Validation of a `const`.
|
|
|
|
/// `inner` says if this is an inner, indirect allocation (as opposed to the top-level const
|
|
|
|
/// allocation). Being an inner allocation makes a difference because the top-level allocation
|
|
|
|
/// of a `const` is copied for each use, but the inner allocations are implicitly shared.
|
|
|
|
/// `allow_static_ptrs` says if pointers to statics are permitted (which is the case for promoteds in statics).
|
|
|
|
Const { inner: bool, allow_static_ptrs: bool },
|
2020-10-24 20:49:17 +02:00
|
|
|
}
|
|
|
|
|
2018-10-02 16:06:50 +02:00
|
|
|
/// State for tracking recursive validation of references
|
2019-02-10 14:59:13 +01:00
|
|
|
pub struct RefTracking<T, PATH = ()> {
|
2019-02-15 21:05:47 +01:00
|
|
|
pub seen: FxHashSet<T>,
|
2019-02-10 14:59:13 +01:00
|
|
|
pub todo: Vec<(T, PATH)>,
|
2018-10-02 16:06:50 +02:00
|
|
|
}
|
|
|
|
|
2019-02-10 14:59:13 +01:00
|
|
|
impl<T: Copy + Eq + Hash + std::fmt::Debug, PATH: Default> RefTracking<T, PATH> {
|
|
|
|
pub fn empty() -> Self {
|
|
|
|
RefTracking { seen: FxHashSet::default(), todo: vec![] }
|
|
|
|
}
|
2019-02-15 21:05:47 +01:00
|
|
|
pub fn new(op: T) -> Self {
|
2019-02-10 14:59:13 +01:00
|
|
|
let mut ref_tracking_for_consts =
|
|
|
|
RefTracking { seen: FxHashSet::default(), todo: vec![(op, PATH::default())] };
|
|
|
|
ref_tracking_for_consts.seen.insert(op);
|
|
|
|
ref_tracking_for_consts
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn track(&mut self, op: T, path: impl FnOnce() -> PATH) {
|
|
|
|
if self.seen.insert(op) {
|
|
|
|
trace!("Recursing below ptr {:#?}", op);
|
|
|
|
let path = path();
|
|
|
|
// Remember to come back to this later.
|
|
|
|
self.todo.push((op, path));
|
|
|
|
}
|
2018-10-02 16:06:50 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-08-18 13:46:52 +02:00
|
|
|
/// Format a path
|
2020-12-30 12:59:07 +01:00
|
|
|
fn write_path(out: &mut String, path: &[PathElem]) {
|
2018-08-18 13:46:52 +02:00
|
|
|
use self::PathElem::*;
|
|
|
|
|
|
|
|
for elem in path.iter() {
|
|
|
|
match elem {
|
2018-10-31 18:44:00 +01:00
|
|
|
Field(name) => write!(out, ".{}", name),
|
2020-02-26 12:00:33 +01:00
|
|
|
EnumTag => write!(out, ".<enum-tag>"),
|
|
|
|
Variant(name) => write!(out, ".<enum-variant({})>", name),
|
|
|
|
GeneratorTag => write!(out, ".<generator-tag>"),
|
2019-05-05 22:53:56 +02:00
|
|
|
GeneratorState(idx) => write!(out, ".<generator-state({})>", idx.index()),
|
2020-02-26 12:00:33 +01:00
|
|
|
CapturedVar(name) => write!(out, ".<captured-var({})>", name),
|
2018-10-31 18:44:00 +01:00
|
|
|
TupleElem(idx) => write!(out, ".{}", idx),
|
|
|
|
ArrayElem(idx) => write!(out, "[{}]", idx),
|
2020-01-06 11:35:55 +01:00
|
|
|
// `.<deref>` does not match Rust syntax, but it is more readable for long paths -- and
|
2018-08-18 13:46:52 +02:00
|
|
|
// some of the other items here also are not Rust syntax. Actually we can't
|
|
|
|
// even use the usual syntax because we are just showing the projections,
|
|
|
|
// not the root.
|
2020-01-06 11:35:55 +01:00
|
|
|
Deref => write!(out, ".<deref>"),
|
2018-10-31 18:44:00 +01:00
|
|
|
DynDowncast => write!(out, ".<dyn-downcast>"),
|
|
|
|
}
|
|
|
|
.unwrap()
|
2018-08-18 13:46:52 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-11-03 12:44:10 +01:00
|
|
|
// Formats such that a sentence like "expected something {}" to mean
|
|
|
|
// "expected something <in the given range>" makes sense.
|
2021-08-23 14:24:34 +02:00
|
|
|
fn wrapping_range_format(r: WrappingRange, max_hi: u128) -> String {
|
|
|
|
let WrappingRange { start: lo, end: hi } = r;
|
2020-02-28 22:54:10 +01:00
|
|
|
assert!(hi <= max_hi);
|
2018-11-03 12:44:10 +01:00
|
|
|
if lo > hi {
|
|
|
|
format!("less or equal to {}, or greater or equal to {}", hi, lo)
|
2019-07-01 19:19:19 +02:00
|
|
|
} else if lo == hi {
|
|
|
|
format!("equal to {}", lo)
|
|
|
|
} else if lo == 0 {
|
2020-02-28 22:54:10 +01:00
|
|
|
assert!(hi < max_hi, "should not be printing if the range covers everything");
|
2019-07-01 19:19:19 +02:00
|
|
|
format!("less or equal to {}", hi)
|
|
|
|
} else if hi == max_hi {
|
2020-02-28 22:54:10 +01:00
|
|
|
assert!(lo > 0, "should not be printing if the range covers everything");
|
2019-07-01 19:19:19 +02:00
|
|
|
format!("greater or equal to {}", lo)
|
2018-11-03 12:44:10 +01:00
|
|
|
} else {
|
2019-07-01 19:19:19 +02:00
|
|
|
format!("in the range {:?}", r)
|
2018-11-03 12:44:10 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-06-11 22:03:44 +03:00
|
|
|
struct ValidityVisitor<'rt, 'mir, 'tcx, M: Machine<'mir, 'tcx>> {
|
2018-10-31 16:46:33 +01:00
|
|
|
/// The `path` may be pushed to, but the part that is present when a function
|
|
|
|
/// starts must not be changed! `visit_fields` and `visit_array` rely on
|
|
|
|
/// this stack discipline.
|
|
|
|
path: Vec<PathElem>,
|
2022-07-18 18:47:31 -04:00
|
|
|
ref_tracking: Option<&'rt mut RefTracking<MPlaceTy<'tcx, M::Provenance>, Vec<PathElem>>>,
|
2020-10-24 20:49:17 +02:00
|
|
|
/// `None` indicates this is not validating for CTFE (but for runtime).
|
|
|
|
ctfe_mode: Option<CtfeValidationMode>,
|
2019-06-27 11:36:01 +02:00
|
|
|
ecx: &'rt InterpCx<'mir, 'tcx, M>,
|
2018-10-31 16:46:33 +01:00
|
|
|
}
|
|
|
|
|
2020-03-16 15:12:42 -07:00
|
|
|
impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValidityVisitor<'rt, 'mir, 'tcx, M> {
|
2020-03-04 14:50:21 +00:00
|
|
|
fn aggregate_field_path_elem(&mut self, layout: TyAndLayout<'tcx>, field: usize) -> PathElem {
|
2020-02-26 12:00:33 +01:00
|
|
|
// First, check if we are projecting to a variant.
|
|
|
|
match layout.variants {
|
2020-05-23 13:22:45 +02:00
|
|
|
Variants::Multiple { tag_field, .. } => {
|
|
|
|
if tag_field == field {
|
2020-08-03 00:49:11 +02:00
|
|
|
return match layout.ty.kind() {
|
2020-02-26 12:00:33 +01:00
|
|
|
ty::Adt(def, ..) if def.is_enum() => PathElem::EnumTag,
|
|
|
|
ty::Generator(..) => PathElem::GeneratorTag,
|
|
|
|
_ => bug!("non-variant type {:?}", layout.ty),
|
|
|
|
};
|
|
|
|
}
|
|
|
|
}
|
2020-03-31 18:16:47 +02:00
|
|
|
Variants::Single { .. } => {}
|
2020-02-26 12:00:33 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// Now we know we are projecting to a field, so figure out which one.
|
2020-08-03 00:49:11 +02:00
|
|
|
match layout.ty.kind() {
|
2018-10-31 18:44:00 +01:00
|
|
|
// generators and closures.
|
|
|
|
ty::Closure(def_id, _) | ty::Generator(def_id, _, _) => {
|
2018-11-26 20:58:59 +02:00
|
|
|
let mut name = None;
|
2020-12-23 15:38:22 -05:00
|
|
|
// FIXME this should be more descriptive i.e. CapturePlace instead of CapturedVar
|
|
|
|
// https://github.com/rust-lang/project-rfc-2229/issues/46
|
|
|
|
if let Some(local_def_id) = def_id.as_local() {
|
|
|
|
let tables = self.ecx.tcx.typeck(local_def_id);
|
|
|
|
if let Some(captured_place) =
|
|
|
|
tables.closure_min_captures_flattened(*def_id).nth(field)
|
|
|
|
{
|
2019-05-04 03:57:46 +03:00
|
|
|
// Sometimes the index is beyond the number of upvars (seen
|
2018-11-26 20:58:59 +02:00
|
|
|
// for a generator).
|
2020-12-23 15:38:22 -05:00
|
|
|
let var_hir_id = captured_place.get_root_variable();
|
|
|
|
let node = self.ecx.tcx.hir().get(var_hir_id);
|
2022-06-28 13:15:30 -05:00
|
|
|
if let hir::Node::Pat(pat) = node {
|
2020-12-23 15:38:22 -05:00
|
|
|
if let hir::PatKind::Binding(_, _, ident, _) = pat.kind {
|
|
|
|
name = Some(ident.name);
|
2018-11-26 20:58:59 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2018-10-31 18:44:00 +01:00
|
|
|
}
|
2018-11-26 20:58:59 +02:00
|
|
|
|
2020-02-26 12:00:33 +01:00
|
|
|
PathElem::CapturedVar(name.unwrap_or_else(|| {
|
2018-11-26 20:58:59 +02:00
|
|
|
// Fall back to showing the field index.
|
2019-05-22 19:25:39 +10:00
|
|
|
sym::integer(field)
|
2018-11-26 20:58:59 +02:00
|
|
|
}))
|
2018-10-31 18:44:00 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// tuples
|
|
|
|
ty::Tuple(_) => PathElem::TupleElem(field),
|
|
|
|
|
|
|
|
// enums
|
|
|
|
ty::Adt(def, ..) if def.is_enum() => {
|
2020-02-17 22:59:16 +01:00
|
|
|
// we might be projecting *to* a variant, or to a field *in* a variant.
|
2018-11-01 13:53:21 +01:00
|
|
|
match layout.variants {
|
2020-03-31 18:16:47 +02:00
|
|
|
Variants::Single { index } => {
|
2020-01-03 13:31:56 +01:00
|
|
|
// Inside a variant
|
2022-03-05 07:28:41 +11:00
|
|
|
PathElem::Field(def.variant(index).fields[field].name)
|
2019-12-22 17:42:04 -05:00
|
|
|
}
|
2020-03-31 18:16:47 +02:00
|
|
|
Variants::Multiple { .. } => bug!("we handled variants above"),
|
2018-11-01 13:53:21 +01:00
|
|
|
}
|
2018-10-31 18:44:00 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// other ADTs
|
2022-01-02 22:37:05 -05:00
|
|
|
ty::Adt(def, _) => PathElem::Field(def.non_enum_variant().fields[field].name),
|
2018-10-31 18:44:00 +01:00
|
|
|
|
|
|
|
// arrays/slices
|
|
|
|
ty::Array(..) | ty::Slice(..) => PathElem::ArrayElem(field),
|
|
|
|
|
|
|
|
// dyn traits
|
|
|
|
ty::Dynamic(..) => PathElem::DynDowncast,
|
|
|
|
|
|
|
|
// nothing else has an aggregate layout
|
|
|
|
_ => bug!("aggregate_field_path_elem: got non-aggregate type {:?}", layout.ty),
|
2018-11-08 17:06:27 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-07-05 13:40:27 +02:00
|
|
|
fn with_elem<R>(
|
2018-11-08 17:06:27 +01:00
|
|
|
&mut self,
|
|
|
|
elem: PathElem,
|
2020-07-05 13:40:27 +02:00
|
|
|
f: impl FnOnce(&mut Self) -> InterpResult<'tcx, R>,
|
|
|
|
) -> InterpResult<'tcx, R> {
|
2018-11-08 17:06:27 +01:00
|
|
|
// Remember the old state
|
|
|
|
let path_len = self.path.len();
|
2020-07-05 13:40:27 +02:00
|
|
|
// Record new element
|
2018-10-31 18:44:00 +01:00
|
|
|
self.path.push(elem);
|
2020-07-05 13:40:27 +02:00
|
|
|
// Perform operation
|
|
|
|
let r = f(self)?;
|
2018-11-08 17:06:27 +01:00
|
|
|
// Undo changes
|
|
|
|
self.path.truncate(path_len);
|
2020-07-05 13:40:27 +02:00
|
|
|
// Done
|
|
|
|
Ok(r)
|
2018-10-31 16:46:33 +01:00
|
|
|
}
|
2019-08-25 13:57:46 +02:00
|
|
|
|
|
|
|
fn check_wide_ptr_meta(
|
|
|
|
&mut self,
|
2022-07-18 18:47:31 -04:00
|
|
|
meta: MemPlaceMeta<M::Provenance>,
|
2020-03-04 14:50:21 +00:00
|
|
|
pointee: TyAndLayout<'tcx>,
|
2019-08-25 13:57:46 +02:00
|
|
|
) -> InterpResult<'tcx> {
|
|
|
|
let tail = self.ecx.tcx.struct_tail_erasing_lifetimes(pointee.ty, self.ecx.param_env);
|
2020-08-03 00:49:11 +02:00
|
|
|
match tail.kind() {
|
2019-08-25 13:57:46 +02:00
|
|
|
ty::Dynamic(..) => {
|
2022-04-07 16:22:09 -04:00
|
|
|
let vtable = self.ecx.scalar_to_ptr(meta.unwrap_meta())?;
|
2022-07-17 16:02:49 -04:00
|
|
|
// Make sure it is a genuine vtable pointer.
|
|
|
|
let (_ty, _trait) = try_validation!(
|
|
|
|
self.ecx.get_ptr_vtable(vtable),
|
2020-05-06 09:22:52 +02:00
|
|
|
self.path,
|
|
|
|
err_ub!(DanglingIntPointer(..)) |
|
2022-07-19 19:57:44 -04:00
|
|
|
err_ub!(InvalidVTablePointer(..)) =>
|
2022-07-17 16:02:49 -04:00
|
|
|
{ "{vtable}" } expected { "a vtable pointer" },
|
2019-08-25 13:57:46 +02:00
|
|
|
);
|
2022-07-17 16:02:49 -04:00
|
|
|
// FIXME: check if the type/trait match what ty::Dynamic says?
|
2019-08-25 13:57:46 +02:00
|
|
|
}
|
|
|
|
ty::Slice(..) | ty::Str => {
|
2019-11-06 13:00:14 +01:00
|
|
|
let _len = try_validation!(
|
2020-01-09 12:02:44 +01:00
|
|
|
meta.unwrap_meta().to_machine_usize(self.ecx),
|
2020-05-06 00:07:53 +02:00
|
|
|
self.path,
|
|
|
|
err_unsup!(ReadPointerAsBytes) => { "non-integer slice length in wide pointer" },
|
2019-08-25 13:57:46 +02:00
|
|
|
);
|
2019-08-26 19:48:56 +02:00
|
|
|
// We do not check that `len * elem_size <= isize::MAX`:
|
|
|
|
// that is only required for references, and there it falls out of the
|
2019-11-22 18:11:28 +01:00
|
|
|
// "dereferenceable" check performed by Stacked Borrows.
|
2019-08-25 13:57:46 +02:00
|
|
|
}
|
|
|
|
ty::Foreign(..) => {
|
|
|
|
// Unsized, but not wide.
|
|
|
|
}
|
|
|
|
_ => bug!("Unexpected unsized type tail: {:?}", tail),
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
2018-10-31 16:46:33 +01:00
|
|
|
|
2020-03-02 13:09:13 +01:00
|
|
|
/// Check a reference or `Box`.
|
2020-03-02 21:17:34 +01:00
|
|
|
fn check_safe_pointer(
|
|
|
|
&mut self,
|
2022-07-18 18:47:31 -04:00
|
|
|
value: &OpTy<'tcx, M::Provenance>,
|
2020-03-02 21:17:34 +01:00
|
|
|
kind: &str,
|
|
|
|
) -> InterpResult<'tcx> {
|
2021-02-13 14:58:31 +01:00
|
|
|
let value = try_validation!(
|
|
|
|
self.ecx.read_immediate(value),
|
|
|
|
self.path,
|
|
|
|
err_unsup!(ReadPointerAsBytes) => { "part of a pointer" } expected { "a proper pointer or integer value" },
|
|
|
|
);
|
2020-03-02 13:09:13 +01:00
|
|
|
// Handle wide pointers.
|
|
|
|
// Check metadata early, for better diagnostics
|
2020-04-15 12:18:20 +02:00
|
|
|
let place = try_validation!(
|
2021-02-15 00:00:00 +00:00
|
|
|
self.ecx.ref_to_mplace(&value),
|
2020-05-06 00:07:53 +02:00
|
|
|
self.path,
|
2020-07-05 12:14:12 +02:00
|
|
|
err_ub!(InvalidUninitBytes(None)) => { "uninitialized {}", kind },
|
2020-04-15 12:18:20 +02:00
|
|
|
);
|
2020-03-02 13:09:13 +01:00
|
|
|
if place.layout.is_unsized() {
|
|
|
|
self.check_wide_ptr_meta(place.meta, place.layout)?;
|
|
|
|
}
|
|
|
|
// Make sure this is dereferenceable and all.
|
2020-05-06 13:26:24 +02:00
|
|
|
let size_and_align = try_validation!(
|
2021-02-15 00:00:00 +00:00
|
|
|
self.ecx.size_and_align_of_mplace(&place),
|
2020-05-06 13:26:24 +02:00
|
|
|
self.path,
|
|
|
|
err_ub!(InvalidMeta(msg)) => { "invalid {} metadata: {}", kind, msg },
|
|
|
|
);
|
2020-03-05 23:31:39 +01:00
|
|
|
let (size, align) = size_and_align
|
2020-03-02 13:09:13 +01:00
|
|
|
// for the purpose of validity, consider foreign types to have
|
|
|
|
// alignment and size determined by the layout (size will be 0,
|
|
|
|
// alignment should take attributes into account).
|
|
|
|
.unwrap_or_else(|| (place.layout.size, place.layout.align.abi));
|
2020-05-06 00:07:53 +02:00
|
|
|
// Direct call to `check_ptr_access_align` checks alignment even on CTFE machines.
|
2021-05-16 18:53:20 +02:00
|
|
|
try_validation!(
|
2022-04-03 13:05:49 -04:00
|
|
|
self.ecx.check_ptr_access_align(
|
2020-05-06 13:26:24 +02:00
|
|
|
place.ptr,
|
|
|
|
size,
|
2021-05-17 13:08:12 +02:00
|
|
|
align,
|
2021-05-06 00:16:27 +02:00
|
|
|
CheckInAllocMsg::InboundsTest, // will anyway be replaced by validity message
|
2020-05-06 13:26:24 +02:00
|
|
|
),
|
|
|
|
self.path,
|
|
|
|
err_ub!(AlignmentCheckFailed { required, has }) =>
|
|
|
|
{
|
2022-05-17 17:32:36 +02:00
|
|
|
"an unaligned {kind} (required {} byte alignment but found {})",
|
2020-05-06 13:26:24 +02:00
|
|
|
required.bytes(),
|
|
|
|
has.bytes()
|
|
|
|
},
|
2020-05-06 13:46:01 +02:00
|
|
|
err_ub!(DanglingIntPointer(0, _)) =>
|
2022-05-17 17:32:36 +02:00
|
|
|
{ "a null {kind}" },
|
2020-05-06 13:46:01 +02:00
|
|
|
err_ub!(DanglingIntPointer(i, _)) =>
|
2022-07-06 10:52:20 -04:00
|
|
|
{ "a dangling {kind} (address {i:#x} is unallocated)" },
|
2020-05-06 13:26:24 +02:00
|
|
|
err_ub!(PointerOutOfBounds { .. }) =>
|
2022-05-17 17:32:36 +02:00
|
|
|
{ "a dangling {kind} (going beyond the bounds of its allocation)" },
|
2020-05-06 13:26:24 +02:00
|
|
|
// This cannot happen during const-eval (because interning already detects
|
|
|
|
// dangling pointers), but it can happen in Miri.
|
2020-05-06 13:46:01 +02:00
|
|
|
err_ub!(PointerUseAfterFree(..)) =>
|
2022-05-17 17:32:36 +02:00
|
|
|
{ "a dangling {kind} (use-after-free)" },
|
2020-05-06 13:26:24 +02:00
|
|
|
);
|
2022-05-17 17:32:36 +02:00
|
|
|
// Do not allow pointers to uninhabited types.
|
|
|
|
if place.layout.abi.is_uninhabited() {
|
|
|
|
throw_validation_failure!(self.path,
|
|
|
|
{ "a {kind} pointing to uninhabited type {}", place.layout.ty }
|
|
|
|
)
|
|
|
|
}
|
2020-03-02 13:09:13 +01:00
|
|
|
// Recursive checking
|
2020-10-24 20:49:17 +02:00
|
|
|
if let Some(ref mut ref_tracking) = self.ref_tracking {
|
2021-05-16 18:53:20 +02:00
|
|
|
// Proceed recursively even for ZST, no reason to skip them!
|
|
|
|
// `!` is a ZST and we want to validate it.
|
2022-07-18 18:47:31 -04:00
|
|
|
if let Ok((alloc_id, _offset, _prov)) = self.ecx.ptr_try_get_alloc_id(place.ptr) {
|
2022-03-22 18:58:23 -04:00
|
|
|
// Special handling for pointers to statics (irrespective of their type).
|
2022-07-17 11:40:34 -04:00
|
|
|
let alloc_kind = self.ecx.tcx.try_get_global_alloc(alloc_id);
|
2020-03-02 13:09:13 +01:00
|
|
|
if let Some(GlobalAlloc::Static(did)) = alloc_kind {
|
2020-05-02 21:44:25 +02:00
|
|
|
assert!(!self.ecx.tcx.is_thread_local_static(did));
|
2020-07-30 17:58:39 +02:00
|
|
|
assert!(self.ecx.tcx.is_static(did));
|
2020-12-20 19:34:29 +01:00
|
|
|
if matches!(
|
|
|
|
self.ctfe_mode,
|
|
|
|
Some(CtfeValidationMode::Const { allow_static_ptrs: false, .. })
|
|
|
|
) {
|
2020-09-07 17:30:38 +02:00
|
|
|
// See const_eval::machine::MemoryExtra::can_access_statics for why
|
|
|
|
// this check is so important.
|
|
|
|
// This check is reachable when the const just referenced the static,
|
|
|
|
// but never read it (so we never entered `before_access_global`).
|
2020-05-06 11:42:18 +02:00
|
|
|
throw_validation_failure!(self.path,
|
|
|
|
{ "a {} pointing to a static variable", kind }
|
2020-03-05 23:31:39 +01:00
|
|
|
);
|
|
|
|
}
|
2020-10-24 20:49:17 +02:00
|
|
|
// We skip checking other statics. These statics must be sound by
|
|
|
|
// themselves, and the only way to get broken statics here is by using
|
|
|
|
// unsafe code.
|
|
|
|
// The reasons we don't check other statics is twofold. For one, in all
|
|
|
|
// sound cases, the static was already validated on its own, and second, we
|
|
|
|
// trigger cycle errors if we try to compute the value of the other static
|
|
|
|
// and that static refers back to us.
|
|
|
|
// We might miss const-invalid data,
|
|
|
|
// but things are still sound otherwise (in particular re: consts
|
|
|
|
// referring to statics).
|
|
|
|
return Ok(());
|
2020-03-02 13:09:13 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
let path = &self.path;
|
|
|
|
ref_tracking.track(place, || {
|
|
|
|
// We need to clone the path anyway, make sure it gets created
|
|
|
|
// with enough space for the additional `Deref`.
|
|
|
|
let mut new_path = Vec::with_capacity(path.len() + 1);
|
2022-03-22 18:58:23 -04:00
|
|
|
new_path.extend(path);
|
2020-03-02 13:09:13 +01:00
|
|
|
new_path.push(PathElem::Deref);
|
|
|
|
new_path
|
|
|
|
});
|
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2021-02-13 14:58:31 +01:00
|
|
|
fn read_scalar(
|
|
|
|
&self,
|
2022-07-18 18:47:31 -04:00
|
|
|
op: &OpTy<'tcx, M::Provenance>,
|
|
|
|
) -> InterpResult<'tcx, ScalarMaybeUninit<M::Provenance>> {
|
2021-02-13 14:58:31 +01:00
|
|
|
Ok(try_validation!(
|
|
|
|
self.ecx.read_scalar(op),
|
|
|
|
self.path,
|
|
|
|
err_unsup!(ReadPointerAsBytes) => { "(potentially part of) a pointer" } expected { "plain (non-pointer) bytes" },
|
|
|
|
))
|
|
|
|
}
|
|
|
|
|
2022-05-04 22:47:46 +02:00
|
|
|
fn read_immediate_forced(
|
|
|
|
&self,
|
2022-07-18 18:47:31 -04:00
|
|
|
op: &OpTy<'tcx, M::Provenance>,
|
|
|
|
) -> InterpResult<'tcx, Immediate<M::Provenance>> {
|
2022-05-04 22:47:46 +02:00
|
|
|
Ok(*try_validation!(
|
2022-05-05 09:55:38 +02:00
|
|
|
self.ecx.read_immediate_raw(op, /*force*/ true),
|
2022-05-04 22:47:46 +02:00
|
|
|
self.path,
|
|
|
|
err_unsup!(ReadPointerAsBytes) => { "(potentially part of) a pointer" } expected { "plain (non-pointer) bytes" },
|
|
|
|
).unwrap())
|
|
|
|
}
|
|
|
|
|
2020-03-02 13:09:13 +01:00
|
|
|
/// Check if this is a value of primitive type, and if yes check the validity of the value
|
|
|
|
/// at that type. Return `true` if the type is indeed primitive.
|
2020-03-02 22:47:28 +01:00
|
|
|
fn try_visit_primitive(
|
|
|
|
&mut self,
|
2022-07-18 18:47:31 -04:00
|
|
|
value: &OpTy<'tcx, M::Provenance>,
|
2020-03-02 22:47:28 +01:00
|
|
|
) -> InterpResult<'tcx, bool> {
|
2018-10-02 18:07:40 +02:00
|
|
|
// Go over all the primitive types
|
2018-10-08 13:41:16 +02:00
|
|
|
let ty = value.layout.ty;
|
2020-08-03 00:49:11 +02:00
|
|
|
match ty.kind() {
|
2018-10-02 18:07:40 +02:00
|
|
|
ty::Bool => {
|
2021-02-13 14:58:31 +01:00
|
|
|
let value = self.read_scalar(value)?;
|
2020-05-06 00:07:53 +02:00
|
|
|
try_validation!(
|
|
|
|
value.to_bool(),
|
|
|
|
self.path,
|
2020-07-05 12:14:12 +02:00
|
|
|
err_ub!(InvalidBool(..)) | err_ub!(InvalidUninitBytes(None)) =>
|
2022-02-21 21:46:51 -05:00
|
|
|
{ "{:x}", value } expected { "a boolean" },
|
2020-05-06 00:07:53 +02:00
|
|
|
);
|
2020-03-02 13:09:13 +01:00
|
|
|
Ok(true)
|
2018-10-02 18:07:40 +02:00
|
|
|
}
|
2018-08-22 11:54:46 +01:00
|
|
|
ty::Char => {
|
2021-02-13 14:58:31 +01:00
|
|
|
let value = self.read_scalar(value)?;
|
2020-05-06 00:07:53 +02:00
|
|
|
try_validation!(
|
|
|
|
value.to_char(),
|
|
|
|
self.path,
|
2020-07-05 12:14:12 +02:00
|
|
|
err_ub!(InvalidChar(..)) | err_ub!(InvalidUninitBytes(None)) =>
|
2022-02-21 21:46:51 -05:00
|
|
|
{ "{:x}", value } expected { "a valid unicode scalar value (in `0..=0x10FFFF` but not in `0xD800..=0xDFFF`)" },
|
2020-05-06 00:07:53 +02:00
|
|
|
);
|
2020-03-02 13:09:13 +01:00
|
|
|
Ok(true)
|
2018-10-02 18:07:40 +02:00
|
|
|
}
|
2018-10-03 11:38:16 +02:00
|
|
|
ty::Float(_) | ty::Int(_) | ty::Uint(_) => {
|
2021-02-13 14:58:31 +01:00
|
|
|
let value = self.read_scalar(value)?;
|
2018-10-16 08:37:27 +02:00
|
|
|
// NOTE: Keep this in sync with the array optimization for int/float
|
|
|
|
// types below!
|
2022-05-19 20:16:25 +02:00
|
|
|
if M::enforce_number_init(self.ecx) {
|
|
|
|
try_validation!(
|
|
|
|
value.check_init(),
|
|
|
|
self.path,
|
|
|
|
err_ub!(InvalidUninitBytes(..)) =>
|
|
|
|
{ "{:x}", value } expected { "initialized bytes" }
|
|
|
|
);
|
|
|
|
}
|
2022-07-23 10:15:37 -04:00
|
|
|
// As a special exception we *do* match on a `Scalar` here, since we truly want
|
|
|
|
// to know its underlying representation (and *not* cast it to an integer).
|
|
|
|
let is_ptr = value.check_init().map_or(false, |v| matches!(v, Scalar::Ptr(..)));
|
|
|
|
if is_ptr {
|
|
|
|
throw_validation_failure!(self.path,
|
|
|
|
{ "{:x}", value } expected { "plain (non-pointer) bytes" }
|
|
|
|
)
|
2018-10-03 11:38:16 +02:00
|
|
|
}
|
2020-03-02 13:09:13 +01:00
|
|
|
Ok(true)
|
2018-10-03 11:38:16 +02:00
|
|
|
}
|
2018-10-19 17:11:23 +02:00
|
|
|
ty::RawPtr(..) => {
|
2020-08-08 07:53:47 -06:00
|
|
|
// We are conservative with uninit for integers, but try to
|
2020-04-15 12:18:20 +02:00
|
|
|
// actually enforce the strict rules for raw pointers (mostly because
|
|
|
|
// that lets us re-use `ref_to_mplace`).
|
2020-05-06 00:07:53 +02:00
|
|
|
let place = try_validation!(
|
2021-02-15 00:00:00 +00:00
|
|
|
self.ecx.read_immediate(value).and_then(|ref i| self.ecx.ref_to_mplace(i)),
|
2020-05-06 00:07:53 +02:00
|
|
|
self.path,
|
2020-07-05 12:14:12 +02:00
|
|
|
err_ub!(InvalidUninitBytes(None)) => { "uninitialized raw pointer" },
|
2021-02-13 14:58:31 +01:00
|
|
|
err_unsup!(ReadPointerAsBytes) => { "part of a pointer" } expected { "a proper pointer or integer value" },
|
2020-05-06 00:07:53 +02:00
|
|
|
);
|
2019-11-06 08:44:15 +01:00
|
|
|
if place.layout.is_unsized() {
|
|
|
|
self.check_wide_ptr_meta(place.meta, place.layout)?;
|
2019-08-25 14:26:56 +02:00
|
|
|
}
|
2020-03-02 13:09:13 +01:00
|
|
|
Ok(true)
|
2018-10-19 17:11:23 +02:00
|
|
|
}
|
2020-10-25 10:22:56 +01:00
|
|
|
ty::Ref(_, ty, mutbl) => {
|
2020-10-25 11:12:19 +01:00
|
|
|
if matches!(self.ctfe_mode, Some(CtfeValidationMode::Const { .. }))
|
|
|
|
&& *mutbl == hir::Mutability::Mut
|
|
|
|
{
|
|
|
|
// A mutable reference inside a const? That does not seem right (except if it is
|
2020-10-25 10:22:56 +01:00
|
|
|
// a ZST).
|
Overhaul `TyS` and `Ty`.
Specifically, change `Ty` from this:
```
pub type Ty<'tcx> = &'tcx TyS<'tcx>;
```
to this
```
pub struct Ty<'tcx>(Interned<'tcx, TyS<'tcx>>);
```
There are two benefits to this.
- It's now a first class type, so we can define methods on it. This
means we can move a lot of methods away from `TyS`, leaving `TyS` as a
barely-used type, which is appropriate given that it's not meant to
be used directly.
- The uniqueness requirement is now explicit, via the `Interned` type.
E.g. the pointer-based `Eq` and `Hash` comes from `Interned`, rather
than via `TyS`, which wasn't obvious at all.
Much of this commit is boring churn. The interesting changes are in
these files:
- compiler/rustc_middle/src/arena.rs
- compiler/rustc_middle/src/mir/visit.rs
- compiler/rustc_middle/src/ty/context.rs
- compiler/rustc_middle/src/ty/mod.rs
Specifically:
- Most mentions of `TyS` are removed. It's very much a dumb struct now;
`Ty` has all the smarts.
- `TyS` now has `crate` visibility instead of `pub`.
- `TyS::make_for_test` is removed in favour of the static `BOOL_TY`,
which just works better with the new structure.
- The `Eq`/`Ord`/`Hash` impls are removed from `TyS`. `Interned`s impls
of `Eq`/`Hash` now suffice. `Ord` is now partly on `Interned`
(pointer-based, for the `Equal` case) and partly on `TyS`
(contents-based, for the other cases).
- There are many tedious sigil adjustments, i.e. adding or removing `*`
or `&`. They seem to be unavoidable.
2022-01-25 14:13:38 +11:00
|
|
|
let layout = self.ecx.layout_of(*ty)?;
|
2020-10-25 10:22:56 +01:00
|
|
|
if !layout.is_zst() {
|
|
|
|
throw_validation_failure!(self.path, { "mutable reference in a `const`" });
|
|
|
|
}
|
|
|
|
}
|
2020-03-02 21:17:34 +01:00
|
|
|
self.check_safe_pointer(value, "reference")?;
|
2020-03-02 13:09:13 +01:00
|
|
|
Ok(true)
|
|
|
|
}
|
2018-10-02 18:07:40 +02:00
|
|
|
ty::FnPtr(_sig) => {
|
2021-02-13 14:58:31 +01:00
|
|
|
let value = try_validation!(
|
2022-02-22 18:49:12 -05:00
|
|
|
self.ecx.read_scalar(value).and_then(|v| v.check_init()),
|
2021-02-13 14:58:31 +01:00
|
|
|
self.path,
|
|
|
|
err_unsup!(ReadPointerAsBytes) => { "part of a pointer" } expected { "a proper pointer or integer value" },
|
2022-02-22 18:49:12 -05:00
|
|
|
err_ub!(InvalidUninitBytes(None)) => { "uninitialized bytes" } expected { "a proper pointer or integer value" },
|
2021-02-13 14:58:31 +01:00
|
|
|
);
|
2022-02-24 19:38:37 -05:00
|
|
|
|
2022-02-22 18:49:12 -05:00
|
|
|
// If we check references recursively, also check that this points to a function.
|
|
|
|
if let Some(_) = self.ref_tracking {
|
2022-04-07 16:22:09 -04:00
|
|
|
let ptr = self.ecx.scalar_to_ptr(value)?;
|
2022-02-22 18:49:12 -05:00
|
|
|
let _fn = try_validation!(
|
2022-04-03 13:05:49 -04:00
|
|
|
self.ecx.get_ptr_fn(ptr),
|
2022-02-22 18:49:12 -05:00
|
|
|
self.path,
|
|
|
|
err_ub!(DanglingIntPointer(..)) |
|
|
|
|
err_ub!(InvalidFunctionPointer(..)) =>
|
2022-07-17 16:02:49 -04:00
|
|
|
{ "{ptr}" } expected { "a function pointer" },
|
2022-02-22 18:49:12 -05:00
|
|
|
);
|
|
|
|
// FIXME: Check if the signature matches
|
2022-02-24 19:38:37 -05:00
|
|
|
} else {
|
|
|
|
// Otherwise (for standalone Miri), we have to still check it to be non-null.
|
2022-04-07 16:22:09 -04:00
|
|
|
if self.ecx.scalar_may_be_null(value)? {
|
2022-02-24 19:38:37 -05:00
|
|
|
throw_validation_failure!(self.path, { "a null function pointer" });
|
|
|
|
}
|
2022-02-22 18:49:12 -05:00
|
|
|
}
|
2020-03-02 13:09:13 +01:00
|
|
|
Ok(true)
|
|
|
|
}
|
2020-05-06 11:42:18 +02:00
|
|
|
ty::Never => throw_validation_failure!(self.path, { "a value of the never type `!`" }),
|
2020-03-02 13:09:13 +01:00
|
|
|
ty::Foreign(..) | ty::FnDef(..) => {
|
|
|
|
// Nothing to check.
|
|
|
|
Ok(true)
|
2018-10-02 18:07:40 +02:00
|
|
|
}
|
2020-10-28 10:39:21 +01:00
|
|
|
// The above should be all the primitive types. The rest is compound, we
|
2020-03-02 13:09:13 +01:00
|
|
|
// check them by visiting their fields/variants.
|
|
|
|
ty::Adt(..)
|
|
|
|
| ty::Tuple(..)
|
|
|
|
| ty::Array(..)
|
|
|
|
| ty::Slice(..)
|
|
|
|
| ty::Str
|
|
|
|
| ty::Dynamic(..)
|
|
|
|
| ty::Closure(..)
|
2020-03-02 22:47:28 +01:00
|
|
|
| ty::Generator(..) => Ok(false),
|
2020-03-02 22:24:23 +01:00
|
|
|
// Some types only occur during typechecking, they have no layout.
|
|
|
|
// We should not see them here and we could not check them anyway.
|
2020-05-05 23:02:09 -05:00
|
|
|
ty::Error(_)
|
2020-03-02 13:09:13 +01:00
|
|
|
| ty::Infer(..)
|
|
|
|
| ty::Placeholder(..)
|
|
|
|
| ty::Bound(..)
|
|
|
|
| ty::Param(..)
|
|
|
|
| ty::Opaque(..)
|
2020-03-02 22:47:28 +01:00
|
|
|
| ty::Projection(..)
|
|
|
|
| ty::GeneratorWitness(..) => bug!("Encountered invalid type {:?}", ty),
|
2018-08-17 12:18:02 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-11-02 09:33:26 +01:00
|
|
|
fn visit_scalar(
|
|
|
|
&mut self,
|
2022-07-18 18:47:31 -04:00
|
|
|
scalar: ScalarMaybeUninit<M::Provenance>,
|
2021-08-29 11:06:55 +02:00
|
|
|
scalar_layout: ScalarAbi,
|
2019-06-07 18:56:27 +02:00
|
|
|
) -> InterpResult<'tcx> {
|
2022-04-05 19:14:35 -04:00
|
|
|
// We check `is_full_range` in a slightly complicated way because *if* we are checking
|
|
|
|
// number validity, then we want to ensure that `Scalar::Initialized` is indeed initialized,
|
|
|
|
// i.e. that we go over the `check_init` below.
|
2022-05-04 22:47:46 +02:00
|
|
|
let size = scalar_layout.size(self.ecx);
|
2022-04-05 19:14:35 -04:00
|
|
|
let is_full_range = match scalar_layout {
|
2022-04-19 14:12:21 -04:00
|
|
|
ScalarAbi::Initialized { .. } => {
|
2022-05-19 20:16:25 +02:00
|
|
|
if M::enforce_number_init(self.ecx) {
|
2022-04-05 19:14:35 -04:00
|
|
|
false // not "full" since uninit is not accepted
|
|
|
|
} else {
|
2022-04-19 14:12:21 -04:00
|
|
|
scalar_layout.is_always_valid(self.ecx)
|
2022-04-05 19:14:35 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
ScalarAbi::Union { .. } => true,
|
|
|
|
};
|
|
|
|
if is_full_range {
|
2022-04-19 14:12:21 -04:00
|
|
|
// Nothing to check. Cruciall we don't even `read_scalar` until here, since that would
|
|
|
|
// fail for `Union` scalars!
|
2018-10-02 20:05:12 +02:00
|
|
|
return Ok(());
|
|
|
|
}
|
2022-05-04 22:47:46 +02:00
|
|
|
// We have something to check: it must at least be initialized.
|
2022-03-03 12:02:12 +00:00
|
|
|
let valid_range = scalar_layout.valid_range(self.ecx);
|
2021-08-25 15:21:45 +02:00
|
|
|
let WrappingRange { start, end } = valid_range;
|
2022-05-04 22:47:46 +02:00
|
|
|
let max_value = size.unsigned_int_max();
|
2021-08-25 15:21:45 +02:00
|
|
|
assert!(end <= max_value);
|
2018-10-02 20:05:12 +02:00
|
|
|
let value = try_validation!(
|
2022-05-04 22:47:46 +02:00
|
|
|
scalar.check_init(),
|
2019-01-21 14:48:07 +00:00
|
|
|
self.path,
|
2022-05-04 22:47:46 +02:00
|
|
|
err_ub!(InvalidUninitBytes(None)) => { "{:x}", scalar }
|
2021-08-25 15:21:45 +02:00
|
|
|
expected { "something {}", wrapping_range_format(valid_range, max_value) },
|
2019-01-21 14:48:07 +00:00
|
|
|
);
|
2021-07-16 09:39:35 +02:00
|
|
|
let bits = match value.try_to_int() {
|
2022-05-04 22:47:46 +02:00
|
|
|
Ok(int) => int.assert_bits(size),
|
2021-07-16 09:39:35 +02:00
|
|
|
Err(_) => {
|
|
|
|
// So this is a pointer then, and casting to an int failed.
|
|
|
|
// Can only happen during CTFE.
|
2022-04-05 19:14:35 -04:00
|
|
|
// We support 2 kinds of ranges here: full range, and excluding zero.
|
2021-08-25 15:21:45 +02:00
|
|
|
if start == 1 && end == max_value {
|
2021-05-02 15:55:22 -06:00
|
|
|
// Only null is the niche. So make sure the ptr is NOT null.
|
2022-04-07 16:22:09 -04:00
|
|
|
if self.ecx.scalar_may_be_null(value)? {
|
2020-05-06 11:42:18 +02:00
|
|
|
throw_validation_failure!(self.path,
|
2021-05-02 15:55:22 -06:00
|
|
|
{ "a potentially null pointer" }
|
2020-05-06 11:42:18 +02:00
|
|
|
expected {
|
2019-07-01 19:11:32 +02:00
|
|
|
"something that cannot possibly fail to be {}",
|
2021-08-25 15:21:45 +02:00
|
|
|
wrapping_range_format(valid_range, max_value)
|
2020-05-06 11:42:18 +02:00
|
|
|
}
|
2019-07-30 20:18:50 +05:30
|
|
|
)
|
2022-04-05 19:14:35 -04:00
|
|
|
} else {
|
|
|
|
return Ok(());
|
2018-10-03 11:38:16 +02:00
|
|
|
}
|
2022-04-19 14:12:21 -04:00
|
|
|
} else if scalar_layout.is_always_valid(self.ecx) {
|
2022-04-05 19:14:35 -04:00
|
|
|
// Easy. (This is reachable if `enforce_number_validity` is set.)
|
2018-10-03 11:38:16 +02:00
|
|
|
return Ok(());
|
|
|
|
} else {
|
2019-07-01 11:26:28 +02:00
|
|
|
// Conservatively, we reject, because the pointer *could* have a bad
|
2018-10-03 11:38:16 +02:00
|
|
|
// value.
|
2020-05-06 11:42:18 +02:00
|
|
|
throw_validation_failure!(self.path,
|
|
|
|
{ "a pointer" }
|
|
|
|
expected {
|
2018-11-03 12:44:10 +01:00
|
|
|
"something that cannot possibly fail to be {}",
|
2021-08-25 15:21:45 +02:00
|
|
|
wrapping_range_format(valid_range, max_value)
|
2020-05-06 11:42:18 +02:00
|
|
|
}
|
2019-07-30 20:18:50 +05:30
|
|
|
)
|
2018-10-03 11:38:16 +02:00
|
|
|
}
|
2018-10-02 20:05:12 +02:00
|
|
|
}
|
|
|
|
};
|
2022-04-05 19:14:35 -04:00
|
|
|
// Now compare.
|
2021-08-22 21:46:03 +02:00
|
|
|
if valid_range.contains(bits) {
|
2018-11-03 12:44:10 +01:00
|
|
|
Ok(())
|
2018-10-02 20:05:12 +02:00
|
|
|
} else {
|
2020-05-06 11:42:18 +02:00
|
|
|
throw_validation_failure!(self.path,
|
|
|
|
{ "{}", bits }
|
2021-08-25 15:21:45 +02:00
|
|
|
expected { "something {}", wrapping_range_format(valid_range, max_value) }
|
2018-11-03 12:44:10 +01:00
|
|
|
)
|
2018-10-02 16:06:50 +02:00
|
|
|
}
|
|
|
|
}
|
2020-02-17 22:59:16 +01:00
|
|
|
}
|
|
|
|
|
2020-03-16 15:12:42 -07:00
|
|
|
impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValueVisitor<'mir, 'tcx, M>
|
2020-02-17 22:59:16 +01:00
|
|
|
for ValidityVisitor<'rt, 'mir, 'tcx, M>
|
|
|
|
{
|
2022-07-18 18:47:31 -04:00
|
|
|
type V = OpTy<'tcx, M::Provenance>;
|
2020-02-17 22:59:16 +01:00
|
|
|
|
|
|
|
#[inline(always)]
|
|
|
|
fn ecx(&self) -> &InterpCx<'mir, 'tcx, M> {
|
|
|
|
&self.ecx
|
|
|
|
}
|
|
|
|
|
2020-07-05 16:01:18 +02:00
|
|
|
fn read_discriminant(
|
|
|
|
&mut self,
|
2022-07-18 18:47:31 -04:00
|
|
|
op: &OpTy<'tcx, M::Provenance>,
|
2020-07-05 16:01:18 +02:00
|
|
|
) -> InterpResult<'tcx, VariantIdx> {
|
2020-07-05 13:40:27 +02:00
|
|
|
self.with_elem(PathElem::EnumTag, move |this| {
|
|
|
|
Ok(try_validation!(
|
|
|
|
this.ecx.read_discriminant(op),
|
|
|
|
this.path,
|
|
|
|
err_ub!(InvalidTag(val)) =>
|
2022-02-20 16:43:21 +01:00
|
|
|
{ "{:x}", val } expected { "a valid enum tag" },
|
2020-07-05 13:40:27 +02:00
|
|
|
err_ub!(InvalidUninitBytes(None)) =>
|
|
|
|
{ "uninitialized bytes" } expected { "a valid enum tag" },
|
|
|
|
err_unsup!(ReadPointerAsBytes) =>
|
|
|
|
{ "a pointer" } expected { "a valid enum tag" },
|
2020-07-05 16:01:18 +02:00
|
|
|
)
|
|
|
|
.1)
|
2020-07-05 13:40:27 +02:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2020-02-17 22:59:16 +01:00
|
|
|
#[inline]
|
|
|
|
fn visit_field(
|
|
|
|
&mut self,
|
2022-07-18 18:47:31 -04:00
|
|
|
old_op: &OpTy<'tcx, M::Provenance>,
|
2020-02-17 22:59:16 +01:00
|
|
|
field: usize,
|
2022-07-18 18:47:31 -04:00
|
|
|
new_op: &OpTy<'tcx, M::Provenance>,
|
2020-02-17 22:59:16 +01:00
|
|
|
) -> InterpResult<'tcx> {
|
|
|
|
let elem = self.aggregate_field_path_elem(old_op.layout, field);
|
2020-07-05 13:40:27 +02:00
|
|
|
self.with_elem(elem, move |this| this.visit_value(new_op))
|
2020-02-17 22:59:16 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
fn visit_variant(
|
|
|
|
&mut self,
|
2022-07-18 18:47:31 -04:00
|
|
|
old_op: &OpTy<'tcx, M::Provenance>,
|
2020-02-17 22:59:16 +01:00
|
|
|
variant_id: VariantIdx,
|
2022-07-18 18:47:31 -04:00
|
|
|
new_op: &OpTy<'tcx, M::Provenance>,
|
2020-02-17 22:59:16 +01:00
|
|
|
) -> InterpResult<'tcx> {
|
2020-08-03 00:49:11 +02:00
|
|
|
let name = match old_op.layout.ty.kind() {
|
2022-03-05 07:28:41 +11:00
|
|
|
ty::Adt(adt, _) => PathElem::Variant(adt.variant(variant_id).name),
|
2020-02-17 22:59:16 +01:00
|
|
|
// Generators also have variants
|
|
|
|
ty::Generator(..) => PathElem::GeneratorState(variant_id),
|
|
|
|
_ => bug!("Unexpected type with variant: {:?}", old_op.layout.ty),
|
|
|
|
};
|
2020-07-05 13:40:27 +02:00
|
|
|
self.with_elem(name, move |this| this.visit_value(new_op))
|
2020-02-17 22:59:16 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
#[inline(always)]
|
2020-04-16 15:15:46 +00:00
|
|
|
fn visit_union(
|
|
|
|
&mut self,
|
2022-07-18 18:47:31 -04:00
|
|
|
op: &OpTy<'tcx, M::Provenance>,
|
2020-04-16 15:15:46 +00:00
|
|
|
_fields: NonZeroUsize,
|
|
|
|
) -> InterpResult<'tcx> {
|
2021-10-28 00:00:00 +00:00
|
|
|
// Special check preventing `UnsafeCell` inside unions in the inner part of constants.
|
|
|
|
if matches!(self.ctfe_mode, Some(CtfeValidationMode::Const { inner: true, .. })) {
|
|
|
|
if !op.layout.ty.is_freeze(self.ecx.tcx.at(DUMMY_SP), self.ecx.param_env) {
|
|
|
|
throw_validation_failure!(self.path, { "`UnsafeCell` in a `const`" });
|
|
|
|
}
|
|
|
|
}
|
2020-02-17 22:59:16 +01:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2022-07-03 22:55:25 -04:00
|
|
|
#[inline]
|
2022-07-18 18:47:31 -04:00
|
|
|
fn visit_box(&mut self, op: &OpTy<'tcx, M::Provenance>) -> InterpResult<'tcx> {
|
2022-07-03 22:55:25 -04:00
|
|
|
self.check_safe_pointer(op, "box")?;
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2020-02-17 22:59:16 +01:00
|
|
|
#[inline]
|
2022-07-18 18:47:31 -04:00
|
|
|
fn visit_value(&mut self, op: &OpTy<'tcx, M::Provenance>) -> InterpResult<'tcx> {
|
2020-02-17 22:59:16 +01:00
|
|
|
trace!("visit_value: {:?}, {:?}", *op, op.layout);
|
|
|
|
|
2022-02-24 19:38:37 -05:00
|
|
|
// Check primitive types -- the leaves of our recursive descent.
|
2020-03-02 22:24:23 +01:00
|
|
|
if self.try_visit_primitive(op)? {
|
2020-03-02 13:09:13 +01:00
|
|
|
return Ok(());
|
2020-02-17 22:59:16 +01:00
|
|
|
}
|
|
|
|
|
2020-12-20 19:34:29 +01:00
|
|
|
// Special check preventing `UnsafeCell` in the inner part of constants
|
2020-10-24 20:49:17 +02:00
|
|
|
if let Some(def) = op.layout.ty.ty_adt_def() {
|
2020-12-20 19:34:29 +01:00
|
|
|
if matches!(self.ctfe_mode, Some(CtfeValidationMode::Const { inner: true, .. }))
|
2022-07-07 10:46:22 +00:00
|
|
|
&& def.is_unsafe_cell()
|
2020-10-24 20:49:17 +02:00
|
|
|
{
|
|
|
|
throw_validation_failure!(self.path, { "`UnsafeCell` in a `const`" });
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-07-05 13:40:27 +02:00
|
|
|
// Recursively walk the value at its type.
|
|
|
|
self.walk_value(op)?;
|
2020-02-17 22:59:16 +01:00
|
|
|
|
|
|
|
// *After* all of this, check the ABI. We need to check the ABI to handle
|
|
|
|
// types like `NonNull` where the `Scalar` info is more restrictive than what
|
2020-02-26 12:00:33 +01:00
|
|
|
// the fields say (`rustc_layout_scalar_valid_range_start`).
|
|
|
|
// But in most cases, this will just propagate what the fields say,
|
2020-02-17 22:59:16 +01:00
|
|
|
// and then we want the error to point at the field -- so, first recurse,
|
|
|
|
// then check ABI.
|
|
|
|
//
|
|
|
|
// FIXME: We could avoid some redundant checks here. For newtypes wrapping
|
|
|
|
// scalars, we do the same check on every "level" (e.g., first we check
|
|
|
|
// MyNewtype and then the scalar in there).
|
|
|
|
match op.layout.abi {
|
2020-03-31 18:16:47 +02:00
|
|
|
Abi::Uninhabited => {
|
2020-05-06 11:42:18 +02:00
|
|
|
throw_validation_failure!(self.path,
|
|
|
|
{ "a value of uninhabited type {:?}", op.layout.ty }
|
2020-03-02 13:09:13 +01:00
|
|
|
);
|
|
|
|
}
|
2021-08-29 11:06:55 +02:00
|
|
|
Abi::Scalar(scalar_layout) => {
|
2022-07-04 08:48:05 -04:00
|
|
|
// We use a 'forced' read because we always need a `Immediate` here
|
|
|
|
// and treating "partially uninit" as "fully uninit" is fine for us.
|
2022-05-04 22:47:46 +02:00
|
|
|
let scalar = self.read_immediate_forced(op)?.to_scalar_or_uninit();
|
|
|
|
self.visit_scalar(scalar, scalar_layout)?;
|
|
|
|
}
|
|
|
|
Abi::ScalarPair(a_layout, b_layout) => {
|
2022-07-14 19:19:15 -04:00
|
|
|
// There is no `rustc_layout_scalar_valid_range_start` for pairs, so
|
|
|
|
// we would validate these things as we descend into the fields,
|
2022-05-04 22:47:46 +02:00
|
|
|
// but that can miss bugs in layout computation. Layout computation
|
|
|
|
// is subtle due to enums having ScalarPair layout, where one field
|
|
|
|
// is the discriminant.
|
|
|
|
if cfg!(debug_assertions) {
|
2022-07-04 08:48:05 -04:00
|
|
|
// We use a 'forced' read because we always need a `Immediate` here
|
|
|
|
// and treating "partially uninit" as "fully uninit" is fine for us.
|
2022-05-04 22:47:46 +02:00
|
|
|
let (a, b) = self.read_immediate_forced(op)?.to_scalar_or_uninit_pair();
|
|
|
|
self.visit_scalar(a, a_layout)?;
|
|
|
|
self.visit_scalar(b, b_layout)?;
|
|
|
|
}
|
2020-02-26 12:00:33 +01:00
|
|
|
}
|
2022-05-04 22:47:46 +02:00
|
|
|
Abi::Vector { .. } => {
|
|
|
|
// No checks here, we assume layout computation gets this right.
|
2022-07-14 19:19:15 -04:00
|
|
|
// (This is harder to check since Miri does not represent these as `Immediate`. We
|
|
|
|
// also cannot use field projections since this might be a newtype around a vector.)
|
2020-02-26 12:00:33 +01:00
|
|
|
}
|
2020-03-31 18:16:47 +02:00
|
|
|
Abi::Aggregate { .. } => {
|
2020-02-26 12:00:33 +01:00
|
|
|
// Nothing to do.
|
2020-02-17 22:59:16 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
2018-10-02 16:06:50 +02:00
|
|
|
|
2018-11-02 10:52:07 +01:00
|
|
|
fn visit_aggregate(
|
|
|
|
&mut self,
|
2022-07-18 18:47:31 -04:00
|
|
|
op: &OpTy<'tcx, M::Provenance>,
|
2019-06-07 18:56:27 +02:00
|
|
|
fields: impl Iterator<Item = InterpResult<'tcx, Self::V>>,
|
|
|
|
) -> InterpResult<'tcx> {
|
2020-08-03 00:49:11 +02:00
|
|
|
match op.layout.ty.kind() {
|
2018-10-31 18:44:00 +01:00
|
|
|
ty::Str => {
|
2022-07-04 08:48:05 -04:00
|
|
|
let mplace = op.assert_mem_place(); // strings are unsized and hence never immediate
|
2020-05-12 09:46:41 +02:00
|
|
|
let len = mplace.len(self.ecx)?;
|
2019-12-27 00:38:10 +01:00
|
|
|
try_validation!(
|
2022-04-03 13:05:49 -04:00
|
|
|
self.ecx.read_bytes_ptr(mplace.ptr, Size::from_bytes(len)),
|
2020-05-06 00:07:53 +02:00
|
|
|
self.path,
|
2020-05-12 09:46:41 +02:00
|
|
|
err_ub!(InvalidUninitBytes(..)) => { "uninitialized data in `str`" },
|
2021-05-15 15:04:41 +02:00
|
|
|
err_unsup!(ReadPointerAsBytes) => { "a pointer in `str`" },
|
2019-12-27 00:38:10 +01:00
|
|
|
);
|
2018-10-31 18:44:00 +01:00
|
|
|
}
|
2018-10-31 16:46:33 +01:00
|
|
|
ty::Array(tys, ..) | ty::Slice(tys)
|
2020-10-21 09:26:11 +02:00
|
|
|
// This optimization applies for types that can hold arbitrary bytes (such as
|
|
|
|
// integer and floating point types) or for structs or tuples with no fields.
|
|
|
|
// FIXME(wesleywiser) This logic could be extended further to arbitrary structs
|
|
|
|
// or tuples made up of integer/floating point types or inhabited ZSTs with no
|
|
|
|
// padding.
|
|
|
|
if matches!(tys.kind(), ty::Int(..) | ty::Uint(..) | ty::Float(..))
|
|
|
|
=>
|
2018-10-31 16:46:33 +01:00
|
|
|
{
|
2019-11-02 17:46:11 +01:00
|
|
|
// Optimized handling for arrays of integer/float type.
|
|
|
|
|
2018-10-31 16:46:33 +01:00
|
|
|
// This is the length of the array/slice.
|
2022-07-04 08:48:05 -04:00
|
|
|
let len = op.len(self.ecx)?;
|
2018-10-31 16:46:33 +01:00
|
|
|
// This is the element type size.
|
Overhaul `TyS` and `Ty`.
Specifically, change `Ty` from this:
```
pub type Ty<'tcx> = &'tcx TyS<'tcx>;
```
to this
```
pub struct Ty<'tcx>(Interned<'tcx, TyS<'tcx>>);
```
There are two benefits to this.
- It's now a first class type, so we can define methods on it. This
means we can move a lot of methods away from `TyS`, leaving `TyS` as a
barely-used type, which is appropriate given that it's not meant to
be used directly.
- The uniqueness requirement is now explicit, via the `Interned` type.
E.g. the pointer-based `Eq` and `Hash` comes from `Interned`, rather
than via `TyS`, which wasn't obvious at all.
Much of this commit is boring churn. The interesting changes are in
these files:
- compiler/rustc_middle/src/arena.rs
- compiler/rustc_middle/src/mir/visit.rs
- compiler/rustc_middle/src/ty/context.rs
- compiler/rustc_middle/src/ty/mod.rs
Specifically:
- Most mentions of `TyS` are removed. It's very much a dumb struct now;
`Ty` has all the smarts.
- `TyS` now has `crate` visibility instead of `pub`.
- `TyS::make_for_test` is removed in favour of the static `BOOL_TY`,
which just works better with the new structure.
- The `Eq`/`Ord`/`Hash` impls are removed from `TyS`. `Interned`s impls
of `Eq`/`Hash` now suffice. `Ord` is now partly on `Interned`
(pointer-based, for the `Equal` case) and partly on `TyS`
(contents-based, for the other cases).
- There are many tedious sigil adjustments, i.e. adding or removing `*`
or `&`. They seem to be unavoidable.
2022-01-25 14:13:38 +11:00
|
|
|
let layout = self.ecx.layout_of(*tys)?;
|
2020-03-24 16:43:50 +01:00
|
|
|
// This is the size in bytes of the whole array. (This checks for overflow.)
|
|
|
|
let size = layout.size * len;
|
2022-07-04 08:48:05 -04:00
|
|
|
// If the size is 0, there is nothing to check.
|
|
|
|
// (`size` can only be 0 of `len` is 0, and empty arrays are always valid.)
|
|
|
|
if size == Size::ZERO {
|
|
|
|
return Ok(());
|
|
|
|
}
|
|
|
|
// Now that we definitely have a non-ZST array, we know it lives in memory.
|
|
|
|
let mplace = match op.try_as_mplace() {
|
|
|
|
Ok(mplace) => mplace,
|
|
|
|
Err(imm) => match *imm {
|
|
|
|
Immediate::Uninit =>
|
|
|
|
throw_validation_failure!(self.path, { "uninitialized bytes" }),
|
|
|
|
Immediate::Scalar(..) | Immediate::ScalarPair(..) =>
|
|
|
|
bug!("arrays/slices can never have Scalar/ScalarPair layout"),
|
|
|
|
}
|
|
|
|
};
|
2018-11-12 13:26:53 +01:00
|
|
|
|
2019-12-27 14:33:22 -05:00
|
|
|
// Optimization: we just check the entire range at once.
|
2018-10-31 16:46:33 +01:00
|
|
|
// NOTE: Keep this in sync with the handling of integer and float
|
|
|
|
// types above, in `visit_primitive`.
|
|
|
|
// In run-time mode, we accept pointers in here. This is actually more
|
2018-11-27 02:59:49 +00:00
|
|
|
// permissive than a per-element check would be, e.g., we accept
|
2021-08-22 18:15:49 +02:00
|
|
|
// a &[u8] that contains a pointer even though bytewise checking would
|
2018-10-31 16:46:33 +01:00
|
|
|
// reject it. However, that's good: We don't inherently want
|
|
|
|
// to reject those pointers, we just do not have the machinery to
|
|
|
|
// talk about parts of a pointer.
|
2020-08-08 07:53:47 -06:00
|
|
|
// We also accept uninit, for consistency with the slow path.
|
2022-07-04 08:48:05 -04:00
|
|
|
let alloc = self.ecx.get_ptr_alloc(mplace.ptr, size, mplace.align)?.expect("we already excluded size 0");
|
2021-05-16 18:53:20 +02:00
|
|
|
|
|
|
|
match alloc.check_bytes(
|
|
|
|
alloc_range(Size::ZERO, size),
|
2022-05-19 20:16:25 +02:00
|
|
|
/*allow_uninit*/ !M::enforce_number_init(self.ecx),
|
2022-07-23 10:15:37 -04:00
|
|
|
/*allow_ptr*/ false,
|
2018-10-31 16:46:33 +01:00
|
|
|
) {
|
|
|
|
// In the happy case, we needn't check anything else.
|
2018-11-02 08:17:40 +01:00
|
|
|
Ok(()) => {}
|
2018-10-31 16:46:33 +01:00
|
|
|
// Some error happened, try to provide a more detailed description.
|
|
|
|
Err(err) => {
|
2020-05-06 13:26:24 +02:00
|
|
|
// For some errors we might be able to provide extra information.
|
|
|
|
// (This custom logic does not fit the `try_validation!` macro.)
|
2021-02-14 00:00:00 +00:00
|
|
|
match err.kind() {
|
2021-05-16 18:53:20 +02:00
|
|
|
err_ub!(InvalidUninitBytes(Some((_alloc_id, access)))) => {
|
2020-04-15 12:18:20 +02:00
|
|
|
// Some byte was uninitialized, determine which
|
2018-10-31 16:46:33 +01:00
|
|
|
// element that byte belongs to so we can
|
|
|
|
// provide an index.
|
2020-05-14 07:46:43 -05:00
|
|
|
let i = usize::try_from(
|
2022-07-06 10:52:20 -04:00
|
|
|
access.uninit.start.bytes() / layout.size.bytes(),
|
2020-05-14 07:46:43 -05:00
|
|
|
)
|
|
|
|
.unwrap();
|
2018-10-31 16:46:33 +01:00
|
|
|
self.path.push(PathElem::ArrayElem(i));
|
|
|
|
|
2020-05-06 11:42:18 +02:00
|
|
|
throw_validation_failure!(self.path, { "uninitialized bytes" })
|
2018-10-31 16:46:33 +01:00
|
|
|
}
|
2020-07-05 16:01:18 +02:00
|
|
|
err_unsup!(ReadPointerAsBytes) => {
|
|
|
|
throw_validation_failure!(self.path, { "a pointer" } expected { "plain (non-pointer) bytes" })
|
|
|
|
}
|
2020-07-05 13:40:27 +02:00
|
|
|
|
2020-04-30 13:01:36 +10:00
|
|
|
// Propagate upwards (that will also check for unexpected errors).
|
2018-10-31 16:46:33 +01:00
|
|
|
_ => return Err(err),
|
2018-08-25 14:36:24 +02:00
|
|
|
}
|
2018-08-24 15:27:05 +02:00
|
|
|
}
|
2018-08-17 12:18:02 +02:00
|
|
|
}
|
2018-10-31 16:46:33 +01:00
|
|
|
}
|
2020-01-13 17:58:37 +01:00
|
|
|
// Fast path for arrays and slices of ZSTs. We only need to check a single ZST element
|
|
|
|
// of an array and not all of them, because there's only a single value of a specific
|
|
|
|
// ZST type, so either validation fails for all elements or none.
|
Overhaul `TyS` and `Ty`.
Specifically, change `Ty` from this:
```
pub type Ty<'tcx> = &'tcx TyS<'tcx>;
```
to this
```
pub struct Ty<'tcx>(Interned<'tcx, TyS<'tcx>>);
```
There are two benefits to this.
- It's now a first class type, so we can define methods on it. This
means we can move a lot of methods away from `TyS`, leaving `TyS` as a
barely-used type, which is appropriate given that it's not meant to
be used directly.
- The uniqueness requirement is now explicit, via the `Interned` type.
E.g. the pointer-based `Eq` and `Hash` comes from `Interned`, rather
than via `TyS`, which wasn't obvious at all.
Much of this commit is boring churn. The interesting changes are in
these files:
- compiler/rustc_middle/src/arena.rs
- compiler/rustc_middle/src/mir/visit.rs
- compiler/rustc_middle/src/ty/context.rs
- compiler/rustc_middle/src/ty/mod.rs
Specifically:
- Most mentions of `TyS` are removed. It's very much a dumb struct now;
`Ty` has all the smarts.
- `TyS` now has `crate` visibility instead of `pub`.
- `TyS::make_for_test` is removed in favour of the static `BOOL_TY`,
which just works better with the new structure.
- The `Eq`/`Ord`/`Hash` impls are removed from `TyS`. `Interned`s impls
of `Eq`/`Hash` now suffice. `Ord` is now partly on `Interned`
(pointer-based, for the `Equal` case) and partly on `TyS`
(contents-based, for the other cases).
- There are many tedious sigil adjustments, i.e. adding or removing `*`
or `&`. They seem to be unavoidable.
2022-01-25 14:13:38 +11:00
|
|
|
ty::Array(tys, ..) | ty::Slice(tys) if self.ecx.layout_of(*tys)?.is_zst() => {
|
2020-10-21 09:26:11 +02:00
|
|
|
// Validate just the first element (if any).
|
2020-01-13 17:58:37 +01:00
|
|
|
self.walk_aggregate(op, fields.take(1))?
|
|
|
|
}
|
2018-11-02 08:17:40 +01:00
|
|
|
_ => {
|
2018-11-02 10:52:07 +01:00
|
|
|
self.walk_aggregate(op, fields)? // default handler
|
2018-11-02 08:17:40 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
Ok(())
|
2018-08-17 12:18:02 +02:00
|
|
|
}
|
2018-10-31 16:46:33 +01:00
|
|
|
}
|
2018-08-17 12:18:02 +02:00
|
|
|
|
2020-03-16 15:12:42 -07:00
|
|
|
impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
|
2020-03-05 23:31:39 +01:00
|
|
|
fn validate_operand_internal(
|
2018-11-02 14:06:43 +01:00
|
|
|
&self,
|
2022-07-18 18:47:31 -04:00
|
|
|
op: &OpTy<'tcx, M::Provenance>,
|
2018-10-31 16:46:33 +01:00
|
|
|
path: Vec<PathElem>,
|
2022-07-18 18:47:31 -04:00
|
|
|
ref_tracking: Option<&mut RefTracking<MPlaceTy<'tcx, M::Provenance>, Vec<PathElem>>>,
|
2020-10-24 20:49:17 +02:00
|
|
|
ctfe_mode: Option<CtfeValidationMode>,
|
2019-06-07 18:56:27 +02:00
|
|
|
) -> InterpResult<'tcx> {
|
2020-03-05 23:31:39 +01:00
|
|
|
trace!("validate_operand_internal: {:?}, {:?}", *op, op.layout.ty);
|
2018-08-17 12:18:02 +02:00
|
|
|
|
2018-10-31 16:46:33 +01:00
|
|
|
// Construct a visitor
|
2020-10-24 20:49:17 +02:00
|
|
|
let mut visitor = ValidityVisitor { path, ref_tracking, ctfe_mode, ecx: self };
|
2018-08-17 12:18:02 +02:00
|
|
|
|
2020-03-04 08:43:03 +01:00
|
|
|
// Run it.
|
2021-02-15 00:00:00 +00:00
|
|
|
match visitor.visit_value(&op) {
|
2020-03-04 08:43:03 +01:00
|
|
|
Ok(()) => Ok(()),
|
2020-04-30 14:38:02 +10:00
|
|
|
// Pass through validation failures.
|
2021-02-14 00:00:00 +00:00
|
|
|
Err(err) if matches!(err.kind(), err_ub!(ValidationFailure { .. })) => Err(err),
|
2020-04-30 14:38:02 +10:00
|
|
|
// Also pass through InvalidProgram, those just indicate that we could not
|
|
|
|
// validate and each caller will know best what to do with them.
|
2021-02-14 00:00:00 +00:00
|
|
|
Err(err) if matches!(err.kind(), InterpError::InvalidProgram(_)) => Err(err),
|
2020-04-29 09:45:13 +10:00
|
|
|
// Avoid other errors as those do not show *where* in the value the issue lies.
|
2020-05-06 09:22:52 +02:00
|
|
|
Err(err) => {
|
|
|
|
err.print_backtrace();
|
|
|
|
bug!("Unexpected error during validation: {}", err);
|
|
|
|
}
|
2020-03-04 08:43:03 +01:00
|
|
|
}
|
2018-08-17 12:18:02 +02:00
|
|
|
}
|
2020-03-05 23:31:39 +01:00
|
|
|
|
|
|
|
/// This function checks the data at `op` to be const-valid.
|
|
|
|
/// `op` is assumed to cover valid memory if it is an indirect operand.
|
|
|
|
/// It will error if the bits at the destination do not match the ones described by the layout.
|
|
|
|
///
|
|
|
|
/// `ref_tracking` is used to record references that we encounter so that they
|
|
|
|
/// can be checked recursively by an outside driving loop.
|
|
|
|
///
|
2020-10-24 20:49:17 +02:00
|
|
|
/// `constant` controls whether this must satisfy the rules for constants:
|
|
|
|
/// - no pointers to statics.
|
|
|
|
/// - no `UnsafeCell` or non-ZST `&mut`.
|
2020-03-05 23:31:39 +01:00
|
|
|
#[inline(always)]
|
|
|
|
pub fn const_validate_operand(
|
|
|
|
&self,
|
2022-07-18 18:47:31 -04:00
|
|
|
op: &OpTy<'tcx, M::Provenance>,
|
2020-03-05 23:31:39 +01:00
|
|
|
path: Vec<PathElem>,
|
2022-07-18 18:47:31 -04:00
|
|
|
ref_tracking: &mut RefTracking<MPlaceTy<'tcx, M::Provenance>, Vec<PathElem>>,
|
2020-10-24 20:49:17 +02:00
|
|
|
ctfe_mode: CtfeValidationMode,
|
2020-03-05 23:31:39 +01:00
|
|
|
) -> InterpResult<'tcx> {
|
2020-10-24 20:49:17 +02:00
|
|
|
self.validate_operand_internal(op, path, Some(ref_tracking), Some(ctfe_mode))
|
2020-03-05 23:31:39 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
/// This function checks the data at `op` to be runtime-valid.
|
|
|
|
/// `op` is assumed to cover valid memory if it is an indirect operand.
|
|
|
|
/// It will error if the bits at the destination do not match the ones described by the layout.
|
|
|
|
#[inline(always)]
|
2022-07-18 18:47:31 -04:00
|
|
|
pub fn validate_operand(&self, op: &OpTy<'tcx, M::Provenance>) -> InterpResult<'tcx> {
|
2020-10-24 20:49:17 +02:00
|
|
|
self.validate_operand_internal(op, vec![], None, None)
|
2020-03-05 23:31:39 +01:00
|
|
|
}
|
2018-08-17 12:18:02 +02:00
|
|
|
}
|