4 use crate::hir::map::definitions::DefPathData;
6 use crate::ty::{self, Ty, layout};
7 use crate::ty::layout::{Size, Align, LayoutError};
8 use rustc_target::spec::abi::Abi;
9 use rustc_macros::HashStable;
11 use super::{RawConst, Pointer, CheckInAllocMsg, ScalarMaybeUndef};
13 use backtrace::Backtrace;
15 use crate::ty::query::TyCtxtAt;
16 use errors::DiagnosticBuilder;
18 use syntax_pos::{Pos, Span};
19 use syntax::symbol::Symbol;
21 #[derive(Debug, Copy, Clone, PartialEq, Eq, HashStable, RustcEncodable, RustcDecodable)]
22 pub enum ErrorHandled {
23 /// Already reported a lint or an error for this evaluation.
25 /// Don't emit an error, the evaluation failed because the MIR was generic
26 /// and the substs didn't fully monomorphize it.
31 pub fn assert_reported(self) {
33 ErrorHandled::Reported => {},
34 ErrorHandled::TooGeneric => bug!("MIR interpretation failed without reporting an error \
35 even though it was fully monomorphized"),
40 CloneTypeFoldableImpls! {
44 pub type ConstEvalRawResult<'tcx> = Result<RawConst<'tcx>, ErrorHandled>;
45 pub type ConstEvalResult<'tcx> = Result<&'tcx ty::Const<'tcx>, ErrorHandled>;
47 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
48 pub struct ConstEvalErr<'tcx> {
50 pub error: crate::mir::interpret::InterpError<'tcx, u64>,
51 pub stacktrace: Vec<FrameInfo<'tcx>>,
54 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
55 pub struct FrameInfo<'tcx> {
56 /// This span is in the caller.
58 pub instance: ty::Instance<'tcx>,
59 pub lint_root: Option<hir::HirId>,
62 impl<'tcx> fmt::Display for FrameInfo<'tcx> {
63 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65 if tcx.def_key(self.instance.def_id()).disambiguated_data.data
66 == DefPathData::ClosureExpr
68 write!(f, "inside call to closure")?;
70 write!(f, "inside call to `{}`", self.instance)?;
72 if !self.call_site.is_dummy() {
73 let lo = tcx.sess.source_map().lookup_char_pos(self.call_site.lo());
74 write!(f, " at {}:{}:{}", lo.file.name, lo.line, lo.col.to_usize() + 1)?;
81 impl<'tcx> ConstEvalErr<'tcx> {
86 ) -> Result<DiagnosticBuilder<'tcx>, ErrorHandled> {
87 self.struct_generic(tcx, message, None)
90 pub fn report_as_error(&self, tcx: TyCtxtAt<'tcx>, message: &str) -> ErrorHandled {
91 let err = self.struct_error(tcx, message);
95 ErrorHandled::Reported
101 pub fn report_as_lint(
105 lint_root: hir::HirId,
108 let lint = self.struct_generic(
115 if let Some(span) = span {
116 let primary_spans = lint.span.primary_spans().to_vec();
117 // point at the actual error as the primary span
118 lint.replace_span_with(span);
119 // point to the `const` statement as a secondary span
120 // they don't have any label
121 for sp in primary_spans {
123 lint.span_label(sp, "");
128 ErrorHandled::Reported
138 lint_root: Option<hir::HirId>,
139 ) -> Result<DiagnosticBuilder<'tcx>, ErrorHandled> {
141 InterpError::Layout(LayoutError::Unknown(_)) |
142 InterpError::TooGeneric => return Err(ErrorHandled::TooGeneric),
143 InterpError::Layout(LayoutError::SizeOverflow(_)) |
144 InterpError::TypeckError => return Err(ErrorHandled::Reported),
147 trace!("reporting const eval failure at {:?}", self.span);
148 let mut err = if let Some(lint_root) = lint_root {
149 let hir_id = self.stacktrace
152 .filter_map(|frame| frame.lint_root)
154 .unwrap_or(lint_root);
155 tcx.struct_span_lint_hir(
156 crate::rustc::lint::builtin::CONST_ERR,
162 struct_error(tcx, message)
164 err.span_label(self.span, self.error.to_string());
165 // Skip the last, which is just the environment of the constant. The stacktrace
166 // is sometimes empty because we create "fake" eval contexts in CTFE to do work
167 // on constant values.
168 if self.stacktrace.len() > 0 {
169 for frame_info in &self.stacktrace[..self.stacktrace.len()-1] {
170 err.span_label(frame_info.call_site, frame_info.to_string());
177 pub fn struct_error<'tcx>(tcx: TyCtxtAt<'tcx>, msg: &str) -> DiagnosticBuilder<'tcx> {
178 struct_span_err!(tcx.sess, tcx.span, E0080, "{}", msg)
181 /// Packages the kind of error we got from the const code interpreter
182 /// up with a Rust-level backtrace of where the error occured.
183 /// Thsese should always be constructed by calling `.into()` on
184 /// a `InterpError`. In `librustc_mir::interpret`, we have the `err!`
186 #[derive(Debug, Clone)]
187 pub struct InterpErrorInfo<'tcx> {
188 pub kind: InterpError<'tcx, u64>,
189 backtrace: Option<Box<Backtrace>>,
192 impl<'tcx> InterpErrorInfo<'tcx> {
193 pub fn print_backtrace(&mut self) {
194 if let Some(ref mut backtrace) = self.backtrace {
195 print_backtrace(&mut *backtrace);
200 fn print_backtrace(backtrace: &mut Backtrace) {
202 eprintln!("\n\nAn error occurred in miri:\n{:?}", backtrace);
205 impl<'tcx> From<InterpError<'tcx, u64>> for InterpErrorInfo<'tcx> {
206 fn from(kind: InterpError<'tcx, u64>) -> Self {
207 let backtrace = match env::var("RUST_CTFE_BACKTRACE") {
208 // Matching `RUST_BACKTRACE` -- we treat "0" the same as "not present".
209 Ok(ref val) if val != "0" => {
210 let mut backtrace = Backtrace::new_unresolved();
212 if val == "immediate" {
214 print_backtrace(&mut backtrace);
217 Some(Box::new(backtrace))
229 pub type AssertMessage<'tcx> = InterpError<'tcx, mir::Operand<'tcx>>;
231 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
232 pub enum InterpError<'tcx, O> {
233 /// This variant is used by machines to signal their own errors that do not
234 /// match an existing variant.
235 MachineError(String),
237 /// Not actually an interpreter error -- used to signal that execution has exited
238 /// with the given status code. Used by Miri, but not by CTFE.
241 FunctionAbiMismatch(Abi, Abi),
242 FunctionArgMismatch(Ty<'tcx>, Ty<'tcx>),
243 FunctionRetMismatch(Ty<'tcx>, Ty<'tcx>),
244 FunctionArgCountMismatch,
246 UnterminatedCString(Pointer),
247 DanglingPointerDeref,
250 InvalidFunctionPointer,
252 InvalidDiscriminant(ScalarMaybeUndef),
255 msg: CheckInAllocMsg,
256 allocation_size: Size,
258 InvalidNullPointerUsage,
263 ReadUndefBytes(Size),
265 InvalidBoolOp(mir::BinOp),
266 Unimplemented(String),
267 DerefFunctionPointer,
269 BoundsCheck { len: O, index: O },
270 Overflow(mir::BinOp),
276 StackFrameLimitReached,
279 AbiViolation(String),
280 AlignmentCheckFailed {
284 ValidationFailure(String),
285 CalledClosureAsFunction,
286 VtableForArgumentlessMethod,
287 ModifiedConstantMemory,
291 TypeNotPrimitive(Ty<'tcx>),
292 ReallocatedWrongMemoryKind(String, String),
293 DeallocatedWrongMemoryKind(String, String),
294 ReallocateNonBasePtr,
295 DeallocateNonBasePtr,
296 IncorrectAllocationInformation(Size, Size, Align, Align),
297 Layout(layout::LayoutError<'tcx>),
299 HeapAllocNonPowerOfTwoAlignment(u64),
307 ReadFromReturnPointer,
308 PathNotFound(Vec<String>),
309 UnimplementedTraitSelection,
310 /// Abort in case type errors are reached
312 /// Resolution can fail if we are in a too generic context
314 /// Cannot compute this constant because it depends on another one
315 /// which already produced an error
317 GeneratorResumedAfterReturn,
318 GeneratorResumedAfterPanic,
322 pub type InterpResult<'tcx, T = ()> = Result<T, InterpErrorInfo<'tcx>>;
324 impl<'tcx, O> InterpError<'tcx, O> {
325 pub fn description(&self) -> &str {
326 use self::InterpError::*;
328 MachineError(ref inner) => inner,
331 FunctionAbiMismatch(..) | FunctionArgMismatch(..) | FunctionRetMismatch(..)
332 | FunctionArgCountMismatch =>
333 "tried to call a function through a function pointer of incompatible type",
334 InvalidMemoryAccess =>
335 "tried to access memory through an invalid pointer",
336 DanglingPointerDeref =>
337 "dangling pointer was dereferenced",
339 "tried to deallocate dangling pointer",
340 InvalidFunctionPointer =>
341 "tried to use a function pointer after offsetting it",
343 "invalid boolean value read",
344 InvalidDiscriminant(..) =>
345 "invalid enum discriminant value read",
346 PointerOutOfBounds { .. } =>
347 "pointer offset outside bounds of allocation",
348 InvalidNullPointerUsage =>
349 "invalid use of NULL pointer",
350 ValidationFailure(..) =>
351 "type validation failed",
352 ReadPointerAsBytes =>
353 "a raw memory access tried to access part of a pointer value as raw bytes",
354 ReadBytesAsPointer =>
355 "a memory access tried to interpret some bytes as a pointer",
357 "tried to read from foreign (extern) static",
358 InvalidPointerMath =>
359 "attempted to do invalid arithmetic on pointers that would leak base addresses, \
360 e.g., comparing pointers into different allocations",
362 "attempted to read undefined bytes",
364 "tried to access a dead local variable",
366 "invalid boolean operation",
367 Unimplemented(ref msg) => msg,
368 DerefFunctionPointer =>
369 "tried to dereference a function pointer",
371 "tried to treat a memory pointer as a function pointer",
373 "array index out of bounds",
379 "tried to interpret an invalid 32-bit value as a char",
380 StackFrameLimitReached =>
381 "reached the configured maximum number of stack frames",
383 "reached the maximum number of representable TLS keys",
385 "accessed an invalid (unallocated) TLS key",
386 AbiViolation(ref msg) => msg,
387 AlignmentCheckFailed{..} =>
388 "tried to execute a misaligned read or write",
389 CalledClosureAsFunction =>
390 "tried to call a closure through a function pointer",
391 VtableForArgumentlessMethod =>
392 "tried to call a vtable function without arguments",
393 ModifiedConstantMemory =>
394 "tried to modify constant memory",
396 "tried to modify a static's initial value from another static's initializer",
398 "`assume` argument was false",
400 "miri does not support inline assembly",
401 TypeNotPrimitive(_) =>
402 "expected primitive type, got nonprimitive",
403 ReallocatedWrongMemoryKind(_, _) =>
404 "tried to reallocate memory from one kind to another",
405 DeallocatedWrongMemoryKind(_, _) =>
406 "tried to deallocate memory of the wrong kind",
407 ReallocateNonBasePtr =>
408 "tried to reallocate with a pointer not to the beginning of an existing object",
409 DeallocateNonBasePtr =>
410 "tried to deallocate with a pointer not to the beginning of an existing object",
411 IncorrectAllocationInformation(..) =>
412 "tried to deallocate or reallocate using incorrect alignment or size",
414 "rustc layout computation failed",
415 UnterminatedCString(_) =>
416 "attempted to get length of a null terminated string, but no null found before end \
418 HeapAllocZeroBytes =>
419 "tried to re-, de- or allocate zero bytes on the heap",
420 HeapAllocNonPowerOfTwoAlignment(_) =>
421 "tried to re-, de-, or allocate heap memory with alignment that is not a power of \
424 "entered unreachable code",
426 "the evaluated program panicked",
427 ReadFromReturnPointer =>
428 "tried to read from the return pointer",
430 "a path could not be resolved, maybe the crate is not loaded",
431 UnimplementedTraitSelection =>
432 "there were unresolved type arguments during trait selection",
434 "encountered constants with type errors, stopping evaluation",
436 "encountered overly generic constant",
437 ReferencedConstant =>
438 "referenced constant has errors",
439 Overflow(mir::BinOp::Add) => "attempt to add with overflow",
440 Overflow(mir::BinOp::Sub) => "attempt to subtract with overflow",
441 Overflow(mir::BinOp::Mul) => "attempt to multiply with overflow",
442 Overflow(mir::BinOp::Div) => "attempt to divide with overflow",
443 Overflow(mir::BinOp::Rem) => "attempt to calculate the remainder with overflow",
444 OverflowNeg => "attempt to negate with overflow",
445 Overflow(mir::BinOp::Shr) => "attempt to shift right with overflow",
446 Overflow(mir::BinOp::Shl) => "attempt to shift left with overflow",
447 Overflow(op) => bug!("{:?} cannot overflow", op),
448 DivisionByZero => "attempt to divide by zero",
449 RemainderByZero => "attempt to calculate the remainder with a divisor of zero",
450 GeneratorResumedAfterReturn => "generator resumed after completion",
451 GeneratorResumedAfterPanic => "generator resumed after panicking",
453 "duplicate interpreter state observed here, const evaluation will never terminate",
458 impl<'tcx> fmt::Display for InterpErrorInfo<'tcx> {
459 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
460 write!(f, "{}", self.kind)
464 impl<'tcx> fmt::Display for InterpError<'tcx, u64> {
465 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
466 write!(f, "{:?}", self)
470 impl<'tcx, O: fmt::Debug> fmt::Debug for InterpError<'tcx, O> {
471 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
472 use self::InterpError::*;
474 PointerOutOfBounds { ptr, msg, allocation_size } => {
475 write!(f, "{} failed: pointer must be in-bounds at offset {}, \
476 but is outside bounds of allocation {} which has size {}",
477 msg, ptr.offset.bytes(), ptr.alloc_id, allocation_size.bytes())
479 ValidationFailure(ref err) => {
480 write!(f, "type validation failed: {}", err)
482 NoMirFor(ref func) => write!(f, "no mir for `{}`", func),
483 FunctionAbiMismatch(caller_abi, callee_abi) =>
484 write!(f, "tried to call a function with ABI {:?} using caller ABI {:?}",
485 callee_abi, caller_abi),
486 FunctionArgMismatch(caller_ty, callee_ty) =>
487 write!(f, "tried to call a function with argument of type {:?} \
488 passing data of type {:?}",
489 callee_ty, caller_ty),
490 FunctionRetMismatch(caller_ty, callee_ty) =>
491 write!(f, "tried to call a function with return type {:?} \
492 passing return place of type {:?}",
493 callee_ty, caller_ty),
494 FunctionArgCountMismatch =>
495 write!(f, "tried to call a function with incorrect number of arguments"),
496 BoundsCheck { ref len, ref index } =>
497 write!(f, "index out of bounds: the len is {:?} but the index is {:?}", len, index),
498 ReallocatedWrongMemoryKind(ref old, ref new) =>
499 write!(f, "tried to reallocate memory from {} to {}", old, new),
500 DeallocatedWrongMemoryKind(ref old, ref new) =>
501 write!(f, "tried to deallocate {} memory but gave {} as the kind", old, new),
502 Intrinsic(ref err) =>
503 write!(f, "{}", err),
505 write!(f, "tried to interpret an invalid 32-bit value as a char: {}", c),
506 AlignmentCheckFailed { required, has } =>
507 write!(f, "tried to access memory with alignment {}, but alignment {} is required",
508 has.bytes(), required.bytes()),
509 TypeNotPrimitive(ty) =>
510 write!(f, "expected primitive type, got {}", ty),
512 write!(f, "rustc layout computation failed: {:?}", err),
513 PathNotFound(ref path) =>
514 write!(f, "Cannot find path {:?}", path),
515 MachineError(ref inner) =>
516 write!(f, "{}", inner),
517 IncorrectAllocationInformation(size, size2, align, align2) =>
518 write!(f, "incorrect alloc info: expected size {} and align {}, \
519 got size {} and align {}",
520 size.bytes(), align.bytes(), size2.bytes(), align2.bytes()),
521 Panic { ref msg, line, col, ref file } =>
522 write!(f, "the evaluated program panicked at '{}', {}:{}:{}", msg, file, line, col),
523 InvalidDiscriminant(val) =>
524 write!(f, "encountered invalid enum discriminant {}", val),
526 write!(f, "exited with status code {}", code),
527 _ => write!(f, "{}", self.description()),