1 use super::{AllocId, ConstAlloc, Pointer, Scalar};
3 use crate::mir::interpret::ConstValue;
4 use crate::ty::{layout, query::TyCtxtAt, tls, FnSig, Ty};
6 use rustc_data_structures::sync::Lock;
7 use rustc_errors::{pluralize, struct_span_err, DiagnosticBuilder, ErrorReported};
8 use rustc_macros::HashStable;
9 use rustc_session::CtfeBacktrace;
10 use rustc_span::def_id::DefId;
11 use rustc_target::abi::{Align, Size};
12 use std::{any::Any, backtrace::Backtrace, fmt};
14 #[derive(Debug, Copy, Clone, PartialEq, Eq, HashStable, TyEncodable, TyDecodable)]
15 pub enum ErrorHandled {
16 /// Already reported an error for this evaluation, and the compilation is
17 /// *guaranteed* to fail. Warnings/lints *must not* produce `Reported`.
18 Reported(ErrorReported),
19 /// Already emitted a lint for this evaluation.
21 /// Don't emit an error, the evaluation failed because the MIR was generic
22 /// and the substs didn't fully monomorphize it.
26 impl From<ErrorReported> for ErrorHandled {
27 fn from(err: ErrorReported) -> ErrorHandled {
28 ErrorHandled::Reported(err)
32 TrivialTypeFoldableAndLiftImpls! {
36 pub type EvalToAllocationRawResult<'tcx> = Result<ConstAlloc<'tcx>, ErrorHandled>;
37 pub type EvalToConstValueResult<'tcx> = Result<ConstValue<'tcx>, ErrorHandled>;
39 pub fn struct_error<'tcx>(tcx: TyCtxtAt<'tcx>, msg: &str) -> DiagnosticBuilder<'tcx> {
40 struct_span_err!(tcx.sess, tcx.span, E0080, "{}", msg)
43 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
44 static_assert_size!(InterpErrorInfo<'_>, 8);
46 /// Packages the kind of error we got from the const code interpreter
47 /// up with a Rust-level backtrace of where the error occurred.
48 /// These should always be constructed by calling `.into()` on
49 /// a `InterpError`. In `rustc_mir::interpret`, we have `throw_err_*`
52 pub struct InterpErrorInfo<'tcx>(Box<InterpErrorInfoInner<'tcx>>);
55 struct InterpErrorInfoInner<'tcx> {
56 kind: InterpError<'tcx>,
57 backtrace: Option<Box<Backtrace>>,
60 impl fmt::Display for InterpErrorInfo<'_> {
61 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62 write!(f, "{}", self.0.kind)
66 impl InterpErrorInfo<'tcx> {
67 pub fn print_backtrace(&self) {
68 if let Some(backtrace) = self.0.backtrace.as_ref() {
69 print_backtrace(backtrace);
73 pub fn into_kind(self) -> InterpError<'tcx> {
74 let InterpErrorInfo(box InterpErrorInfoInner { kind, .. }) = self;
79 pub fn kind(&self) -> &InterpError<'tcx> {
84 fn print_backtrace(backtrace: &Backtrace) {
85 eprintln!("\n\nAn error occurred in miri:\n{}", backtrace);
88 impl From<ErrorHandled> for InterpErrorInfo<'_> {
89 fn from(err: ErrorHandled) -> Self {
91 ErrorHandled::Reported(ErrorReported) | ErrorHandled::Linted => {
92 err_inval!(ReferencedConstant)
94 ErrorHandled::TooGeneric => err_inval!(TooGeneric),
100 impl From<ErrorReported> for InterpErrorInfo<'_> {
101 fn from(err: ErrorReported) -> Self {
102 InterpError::InvalidProgram(InvalidProgramInfo::AlreadyReported(err)).into()
106 impl<'tcx> From<InterpError<'tcx>> for InterpErrorInfo<'tcx> {
107 fn from(kind: InterpError<'tcx>) -> Self {
108 let capture_backtrace = tls::with_opt(|tcx| {
109 if let Some(tcx) = tcx {
110 *Lock::borrow(&tcx.sess.ctfe_backtrace)
112 CtfeBacktrace::Disabled
116 let backtrace = match capture_backtrace {
117 CtfeBacktrace::Disabled => None,
118 CtfeBacktrace::Capture => Some(Box::new(Backtrace::force_capture())),
119 CtfeBacktrace::Immediate => {
121 let backtrace = Backtrace::force_capture();
122 print_backtrace(&backtrace);
127 InterpErrorInfo(Box::new(InterpErrorInfoInner { kind, backtrace }))
131 /// Error information for when the program we executed turned out not to actually be a valid
132 /// program. This cannot happen in stand-alone Miri, but it can happen during CTFE/ConstProp
133 /// where we work on generic code or execution does not have all information available.
134 pub enum InvalidProgramInfo<'tcx> {
135 /// Resolution can fail if we are in a too generic context.
137 /// Cannot compute this constant because it depends on another one
138 /// which already produced an error.
140 /// Abort in case errors are already reported.
141 AlreadyReported(ErrorReported),
142 /// An error occurred during layout computation.
143 Layout(layout::LayoutError<'tcx>),
144 /// An invalid transmute happened.
145 TransmuteSizeDiff(Ty<'tcx>, Ty<'tcx>),
146 /// SizeOf of unsized type was requested.
147 SizeOfUnsizedType(Ty<'tcx>),
150 impl fmt::Display for InvalidProgramInfo<'_> {
151 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
152 use InvalidProgramInfo::*;
154 TooGeneric => write!(f, "encountered overly generic constant"),
155 ReferencedConstant => write!(f, "referenced constant has errors"),
156 AlreadyReported(ErrorReported) => {
157 write!(f, "encountered constants with type errors, stopping evaluation")
159 Layout(ref err) => write!(f, "{}", err),
160 TransmuteSizeDiff(from_ty, to_ty) => write!(
162 "transmuting `{}` to `{}` is not possible, because these types do not have the same size",
165 SizeOfUnsizedType(ty) => write!(f, "size_of called on unsized type `{}`", ty),
170 /// Details of why a pointer had to be in-bounds.
171 #[derive(Debug, Copy, Clone, TyEncodable, TyDecodable, HashStable)]
172 pub enum CheckInAllocMsg {
173 /// We are dereferencing a pointer (i.e., creating a place).
175 /// We are access memory.
177 /// We are doing pointer arithmetic.
178 PointerArithmeticTest,
179 /// None of the above -- generic/unspecific inbounds test.
183 impl fmt::Display for CheckInAllocMsg {
184 /// When this is printed as an error the context looks like this
185 /// "{msg}pointer must be in-bounds at offset..."
186 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
191 CheckInAllocMsg::DerefTest => "dereferencing pointer failed: ",
192 CheckInAllocMsg::MemoryAccessTest => "memory access failed: ",
193 CheckInAllocMsg::PointerArithmeticTest => "pointer arithmetic failed: ",
194 CheckInAllocMsg::InboundsTest => "",
200 /// Details of an access to uninitialized bytes where it is not allowed.
202 pub struct UninitBytesAccess {
203 /// Location of the original memory access.
204 pub access_offset: Size,
205 /// Size of the original memory access.
206 pub access_size: Size,
207 /// Location of the first uninitialized byte that was accessed.
208 pub uninit_offset: Size,
209 /// Number of consecutive uninitialized bytes that were accessed.
210 pub uninit_size: Size,
213 /// Error information for when the program caused Undefined Behavior.
214 pub enum UndefinedBehaviorInfo<'tcx> {
215 /// Free-form case. Only for errors that are never caught!
217 /// Unreachable code was executed.
219 /// A slice/array index projection went out-of-bounds.
224 /// Something was divided by 0 (x / 0).
226 /// Something was "remainded" by 0 (x % 0).
228 /// Overflowing inbounds pointer arithmetic.
229 PointerArithOverflow,
230 /// Invalid metadata in a wide pointer (using `str` to avoid allocations).
231 InvalidMeta(&'static str),
232 /// Invalid drop function in vtable.
233 InvalidVtableDropFn(FnSig<'tcx>),
234 /// Invalid size in a vtable: too large.
236 /// Invalid alignment in a vtable: too large, or not a power of 2.
237 InvalidVtableAlignment(String),
238 /// Reading a C string that does not end within its allocation.
239 UnterminatedCString(Pointer),
240 /// Dereferencing a dangling pointer after it got freed.
241 PointerUseAfterFree(AllocId),
242 /// Used a pointer outside the bounds it is valid for.
247 msg: CheckInAllocMsg,
248 allocation_size: Size,
250 /// Using an integer as a pointer in the wrong way.
251 DanglingIntPointer(u64, CheckInAllocMsg),
252 /// Used a pointer with bad alignment.
253 AlignmentCheckFailed {
257 /// Writing to read-only memory.
258 WriteToReadOnly(AllocId),
259 // Trying to access the data behind a function pointer.
260 DerefFunctionPointer(AllocId),
261 /// The value validity check found a problem.
262 /// Should only be thrown by `validity.rs` and always point out which part of the value
265 /// The "path" to the value in question, e.g. `.0[5].field` for a struct
266 /// field in the 6th element of an array that is the first element of a tuple.
267 path: Option<String>,
270 /// Using a non-boolean `u8` as bool.
272 /// Using a non-character `u32` as character.
274 /// The tag of an enum does not encode an actual discriminant.
276 /// Using a pointer-not-to-a-function as function pointer.
277 InvalidFunctionPointer(Pointer),
278 /// Using a string that is not valid UTF-8,
279 InvalidStr(std::str::Utf8Error),
280 /// Using uninitialized data where it is not allowed.
281 InvalidUninitBytes(Option<(AllocId, UninitBytesAccess)>),
282 /// Working with a local that is not currently live.
284 /// Data size is not equal to target size.
291 impl fmt::Display for UndefinedBehaviorInfo<'_> {
292 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
293 use UndefinedBehaviorInfo::*;
295 Ub(msg) => write!(f, "{}", msg),
296 Unreachable => write!(f, "entering unreachable code"),
297 BoundsCheckFailed { ref len, ref index } => {
298 write!(f, "indexing out of bounds: the len is {} but the index is {}", len, index)
300 DivisionByZero => write!(f, "dividing by zero"),
301 RemainderByZero => write!(f, "calculating the remainder with a divisor of zero"),
302 PointerArithOverflow => write!(f, "overflowing in-bounds pointer arithmetic"),
303 InvalidMeta(msg) => write!(f, "invalid metadata in wide pointer: {}", msg),
304 InvalidVtableDropFn(sig) => write!(
306 "invalid drop function signature: got {}, expected exactly one argument which must be a pointer type",
309 InvalidVtableSize => {
310 write!(f, "invalid vtable: size is bigger than largest supported object")
312 InvalidVtableAlignment(msg) => write!(f, "invalid vtable: alignment {}", msg),
313 UnterminatedCString(p) => write!(
315 "reading a null-terminated string starting at {:?} with no null found before end of allocation",
318 PointerUseAfterFree(a) => {
319 write!(f, "pointer to {} was dereferenced after this allocation got freed", a)
321 PointerOutOfBounds { alloc_id, offset, size, msg, allocation_size } => write!(
323 "{}pointer must be in-bounds for {} bytes at offset {}, but {} has size {}",
328 allocation_size.bytes()
330 DanglingIntPointer(0, CheckInAllocMsg::InboundsTest) => {
331 write!(f, "null pointer is not a valid pointer for this operation")
333 DanglingIntPointer(i, msg) => {
334 write!(f, "{}0x{:x} is not a valid pointer", msg, i)
336 AlignmentCheckFailed { required, has } => write!(
338 "accessing memory with alignment {}, but alignment {} is required",
342 WriteToReadOnly(a) => write!(f, "writing to {} which is read-only", a),
343 DerefFunctionPointer(a) => write!(f, "accessing {} which contains a function", a),
344 ValidationFailure { path: None, msg } => write!(f, "type validation failed: {}", msg),
345 ValidationFailure { path: Some(path), msg } => {
346 write!(f, "type validation failed at {}: {}", path, msg)
349 write!(f, "interpreting an invalid 8-bit value as a bool: 0x{:02x}", b)
352 write!(f, "interpreting an invalid 32-bit value as a char: 0x{:08x}", c)
354 InvalidTag(val) => write!(f, "enum value has invalid tag: {}", val),
355 InvalidFunctionPointer(p) => {
356 write!(f, "using {:?} as function pointer but it does not point to a function", p)
358 InvalidStr(err) => write!(f, "this string is not valid UTF-8: {}", err),
359 InvalidUninitBytes(Some((alloc, access))) => write!(
361 "reading {} byte{} of memory starting at {:?}, \
362 but {} byte{} {} uninitialized starting at {:?}, \
363 and this operation requires initialized memory",
364 access.access_size.bytes(),
365 pluralize!(access.access_size.bytes()),
366 Pointer::new(*alloc, access.access_offset),
367 access.uninit_size.bytes(),
368 pluralize!(access.uninit_size.bytes()),
369 if access.uninit_size.bytes() != 1 { "are" } else { "is" },
370 Pointer::new(*alloc, access.uninit_offset),
372 InvalidUninitBytes(None) => write!(
374 "using uninitialized data, but this operation requires initialized memory"
376 DeadLocal => write!(f, "accessing a dead local variable"),
377 ScalarSizeMismatch { target_size, data_size } => write!(
379 "scalar size mismatch: expected {} bytes but got {} bytes instead",
380 target_size, data_size
386 /// Error information for when the program did something that might (or might not) be correct
387 /// to do according to the Rust spec, but due to limitations in the interpreter, the
388 /// operation could not be carried out. These limitations can differ between CTFE and the
389 /// Miri engine, e.g., CTFE does not support dereferencing pointers at integral addresses.
390 pub enum UnsupportedOpInfo {
391 /// Free-form case. Only for errors that are never caught!
393 /// Could not find MIR for a function.
395 /// Encountered a pointer where we needed raw bytes.
398 // The variants below are only reachable from CTFE/const prop, miri will never emit them.
400 /// Encountered raw bytes where we needed a pointer.
402 /// Accessing thread local statics
403 ThreadLocalStatic(DefId),
404 /// Accessing an unsupported extern static.
405 ReadExternStatic(DefId),
408 impl fmt::Display for UnsupportedOpInfo {
409 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
410 use UnsupportedOpInfo::*;
412 Unsupported(ref msg) => write!(f, "{}", msg),
413 ReadExternStatic(did) => write!(f, "cannot read from extern static ({:?})", did),
414 NoMirFor(did) => write!(f, "no MIR body is available for {:?}", did),
415 ReadPointerAsBytes => write!(f, "unable to turn pointer into raw bytes",),
416 ReadBytesAsPointer => write!(f, "unable to turn bytes into a pointer"),
417 ThreadLocalStatic(did) => write!(f, "cannot access thread local static ({:?})", did),
422 /// Error information for when the program exhausted the resources granted to it
423 /// by the interpreter.
424 pub enum ResourceExhaustionInfo {
425 /// The stack grew too big.
426 StackFrameLimitReached,
427 /// The program ran for too long.
429 /// The exact limit is set by the `const_eval_limit` attribute.
431 /// There is not enough memory to perform an allocation.
435 impl fmt::Display for ResourceExhaustionInfo {
436 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
437 use ResourceExhaustionInfo::*;
439 StackFrameLimitReached => {
440 write!(f, "reached the configured maximum number of stack frames")
442 StepLimitReached => {
443 write!(f, "exceeded interpreter step limit (see `#[const_eval_limit]`)")
446 write!(f, "tried to allocate more memory than available to compiler")
452 /// A trait to work around not having trait object upcasting.
453 pub trait AsAny: Any {
454 fn as_any(&self) -> &dyn Any;
456 impl<T: Any> AsAny for T {
458 fn as_any(&self) -> &dyn Any {
463 /// A trait for machine-specific errors (or other "machine stop" conditions).
464 pub trait MachineStopType: AsAny + fmt::Display + Send {
465 /// If `true`, emit a hard error instead of going through the `CONST_ERR` lint
466 fn is_hard_err(&self) -> bool {
471 impl dyn MachineStopType {
473 pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
474 self.as_any().downcast_ref()
478 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
479 static_assert_size!(InterpError<'_>, 64);
481 pub enum InterpError<'tcx> {
482 /// The program caused undefined behavior.
483 UndefinedBehavior(UndefinedBehaviorInfo<'tcx>),
484 /// The program did something the interpreter does not support (some of these *might* be UB
485 /// but the interpreter is not sure).
486 Unsupported(UnsupportedOpInfo),
487 /// The program was invalid (ill-typed, bad MIR, not sufficiently monomorphized, ...).
488 InvalidProgram(InvalidProgramInfo<'tcx>),
489 /// The program exhausted the interpreter's resources (stack/heap too big,
490 /// execution takes too long, ...).
491 ResourceExhaustion(ResourceExhaustionInfo),
492 /// Stop execution for a machine-controlled reason. This is never raised by
493 /// the core engine itself.
494 MachineStop(Box<dyn MachineStopType>),
497 pub type InterpResult<'tcx, T = ()> = Result<T, InterpErrorInfo<'tcx>>;
499 impl fmt::Display for InterpError<'_> {
500 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
503 Unsupported(ref msg) => write!(f, "{}", msg),
504 InvalidProgram(ref msg) => write!(f, "{}", msg),
505 UndefinedBehavior(ref msg) => write!(f, "{}", msg),
506 ResourceExhaustion(ref msg) => write!(f, "{}", msg),
507 MachineStop(ref msg) => write!(f, "{}", msg),
512 // Forward `Debug` to `Display`, so it does not look awful.
513 impl fmt::Debug for InterpError<'_> {
514 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
515 fmt::Display::fmt(self, f)
519 impl InterpError<'_> {
520 /// Some errors do string formatting even if the error is never printed.
521 /// To avoid performance issues, there are places where we want to be sure to never raise these formatting errors,
522 /// so this method lets us detect them and `bug!` on unexpected errors.
523 pub fn formatted_string(&self) -> bool {
525 InterpError::Unsupported(UnsupportedOpInfo::Unsupported(_))
526 | InterpError::UndefinedBehavior(UndefinedBehaviorInfo::ValidationFailure { .. })
527 | InterpError::UndefinedBehavior(UndefinedBehaviorInfo::Ub(_)) => true,
532 /// Should this error be reported as a hard error, preventing compilation, or a soft error,
533 /// causing a deny-by-default lint?
534 pub fn is_hard_err(&self) -> bool {
537 MachineStop(ref err) => err.is_hard_err(),
538 UndefinedBehavior(_) => true,
539 ResourceExhaustion(ResourceExhaustionInfo::MemoryExhausted) => true,