]> git.lizzy.rs Git - rust.git/blob - src/librustc/mir/interpret/error.rs
alters the panic variant of InterpError
[rust.git] / src / librustc / mir / interpret / error.rs
1 use std::{fmt, env};
2
3 use crate::hir;
4 use crate::hir::map::definitions::DefPathData;
5 use crate::mir;
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;
10
11 use super::{RawConst, Pointer, CheckInAllocMsg, ScalarMaybeUndef};
12
13 use backtrace::Backtrace;
14
15 use crate::ty::query::TyCtxtAt;
16 use errors::DiagnosticBuilder;
17
18 use syntax_pos::{Pos, Span};
19 use syntax::symbol::Symbol;
20
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.
24     Reported,
25     /// Don't emit an error, the evaluation failed because the MIR was generic
26     /// and the substs didn't fully monomorphize it.
27     TooGeneric,
28 }
29
30 impl ErrorHandled {
31     pub fn assert_reported(self) {
32         match self {
33             ErrorHandled::Reported => {},
34             ErrorHandled::TooGeneric => bug!("MIR interpretation failed without reporting an error \
35                                               even though it was fully monomorphized"),
36         }
37     }
38 }
39
40 CloneTypeFoldableImpls! {
41     ErrorHandled,
42 }
43
44 pub type ConstEvalRawResult<'tcx> = Result<RawConst<'tcx>, ErrorHandled>;
45 pub type ConstEvalResult<'tcx> = Result<&'tcx ty::Const<'tcx>, ErrorHandled>;
46
47 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
48 pub struct ConstEvalErr<'tcx> {
49     pub span: Span,
50     pub error: crate::mir::interpret::InterpError<'tcx, u64>,
51     pub stacktrace: Vec<FrameInfo<'tcx>>,
52 }
53
54 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
55 pub struct FrameInfo<'tcx> {
56     /// This span is in the caller.
57     pub call_site: Span,
58     pub instance: ty::Instance<'tcx>,
59     pub lint_root: Option<hir::HirId>,
60 }
61
62 impl<'tcx> fmt::Display for FrameInfo<'tcx> {
63     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64         ty::tls::with(|tcx| {
65             if tcx.def_key(self.instance.def_id()).disambiguated_data.data
66                 == DefPathData::ClosureExpr
67             {
68                 write!(f, "inside call to closure")?;
69             } else {
70                 write!(f, "inside call to `{}`", self.instance)?;
71             }
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)?;
75             }
76             Ok(())
77         })
78     }
79 }
80
81 impl<'tcx> ConstEvalErr<'tcx> {
82     pub fn struct_error(
83         &self,
84         tcx: TyCtxtAt<'tcx>,
85         message: &str,
86     ) -> Result<DiagnosticBuilder<'tcx>, ErrorHandled> {
87         self.struct_generic(tcx, message, None)
88     }
89
90     pub fn report_as_error(&self, tcx: TyCtxtAt<'tcx>, message: &str) -> ErrorHandled {
91         let err = self.struct_error(tcx, message);
92         match err {
93             Ok(mut err) => {
94                 err.emit();
95                 ErrorHandled::Reported
96             },
97             Err(err) => err,
98         }
99     }
100
101     pub fn report_as_lint(
102         &self,
103         tcx: TyCtxtAt<'tcx>,
104         message: &str,
105         lint_root: hir::HirId,
106         span: Option<Span>,
107     ) -> ErrorHandled {
108         let lint = self.struct_generic(
109             tcx,
110             message,
111             Some(lint_root),
112         );
113         match lint {
114             Ok(mut lint) => {
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 {
122                         if sp != span {
123                             lint.span_label(sp, "");
124                         }
125                     }
126                 }
127                 lint.emit();
128                 ErrorHandled::Reported
129             },
130             Err(err) => err,
131         }
132     }
133
134     fn struct_generic(
135         &self,
136         tcx: TyCtxtAt<'tcx>,
137         message: &str,
138         lint_root: Option<hir::HirId>,
139     ) -> Result<DiagnosticBuilder<'tcx>, ErrorHandled> {
140         match self.error {
141             InterpError::Layout(LayoutError::Unknown(_)) |
142             InterpError::TooGeneric => return Err(ErrorHandled::TooGeneric),
143             InterpError::Layout(LayoutError::SizeOverflow(_)) |
144             InterpError::TypeckError => return Err(ErrorHandled::Reported),
145             _ => {},
146         }
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
150                 .iter()
151                 .rev()
152                 .filter_map(|frame| frame.lint_root)
153                 .next()
154                 .unwrap_or(lint_root);
155             tcx.struct_span_lint_hir(
156                 crate::rustc::lint::builtin::CONST_ERR,
157                 hir_id,
158                 tcx.span,
159                 message,
160             )
161         } else {
162             struct_error(tcx, message)
163         };
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());
171             }
172         }
173         Ok(err)
174     }
175 }
176
177 pub fn struct_error<'tcx>(tcx: TyCtxtAt<'tcx>, msg: &str) -> DiagnosticBuilder<'tcx> {
178     struct_span_err!(tcx.sess, tcx.span, E0080, "{}", msg)
179 }
180
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!`
185 /// macro for this.
186 #[derive(Debug, Clone)]
187 pub struct InterpErrorInfo<'tcx> {
188     pub kind: InterpError<'tcx, u64>,
189     backtrace: Option<Box<Backtrace>>,
190 }
191
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);
196         }
197     }
198 }
199
200 fn print_backtrace(backtrace: &mut Backtrace) {
201     backtrace.resolve();
202     eprintln!("\n\nAn error occurred in miri:\n{:?}", backtrace);
203 }
204
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();
211
212                 if val == "immediate" {
213                     // Print it now.
214                     print_backtrace(&mut backtrace);
215                     None
216                 } else {
217                     Some(Box::new(backtrace))
218                 }
219             },
220             _ => None,
221         };
222         InterpErrorInfo {
223             kind,
224             backtrace,
225         }
226     }
227 }
228
229 pub type AssertMessage<'tcx> = InterpError<'tcx, mir::Operand<'tcx>>;
230
231 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
232 pub enum EvalErrorPanic<O> {
233     Panic {
234         msg: Symbol,
235         line: u32,
236         col: u32,
237         file: Symbol,
238     },
239     BoundsCheck {
240         len: O,
241         index: O,
242     },
243     Overflow(mir::BinOp),
244     OverflowNeg,
245     DivisionByZero,
246     RemainderByZero,
247 }
248
249 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
250 pub enum InterpError<'tcx, O> {
251     /// This variant is used by machines to signal their own errors that do not
252     /// match an existing variant.
253     MachineError(String),
254
255     /// Not actually an interpreter error -- used to signal that execution has exited
256     /// with the given status code.  Used by Miri, but not by CTFE.
257     Exit(i32),
258
259     FunctionAbiMismatch(Abi, Abi),
260     FunctionArgMismatch(Ty<'tcx>, Ty<'tcx>),
261     FunctionRetMismatch(Ty<'tcx>, Ty<'tcx>),
262     FunctionArgCountMismatch,
263     NoMirFor(String),
264     UnterminatedCString(Pointer),
265     DanglingPointerDeref,
266     DoubleFree,
267     InvalidMemoryAccess,
268     InvalidFunctionPointer,
269     InvalidBool,
270     InvalidDiscriminant(ScalarMaybeUndef),
271     PointerOutOfBounds {
272         ptr: Pointer,
273         msg: CheckInAllocMsg,
274         allocation_size: Size,
275     },
276     InvalidNullPointerUsage,
277     ReadPointerAsBytes,
278     ReadBytesAsPointer,
279     ReadForeignStatic,
280     InvalidPointerMath,
281     ReadUndefBytes(Size),
282     DeadLocal,
283     InvalidBoolOp(mir::BinOp),
284     Unimplemented(String),
285     DerefFunctionPointer,
286     ExecuteMemory,
287     BoundsCheck { len: O, index: O },
288     Overflow(mir::BinOp),
289     OverflowNeg,
290     DivisionByZero,
291     RemainderByZero,
292     Intrinsic(String),
293     InvalidChar(u128),
294     StackFrameLimitReached,
295     OutOfTls,
296     TlsOutOfBounds,
297     AbiViolation(String),
298     AlignmentCheckFailed {
299         required: Align,
300         has: Align,
301     },
302     ValidationFailure(String),
303     CalledClosureAsFunction,
304     VtableForArgumentlessMethod,
305     ModifiedConstantMemory,
306     ModifiedStatic,
307     AssumptionNotHeld,
308     InlineAsm,
309     TypeNotPrimitive(Ty<'tcx>),
310     ReallocatedWrongMemoryKind(String, String),
311     DeallocatedWrongMemoryKind(String, String),
312     ReallocateNonBasePtr,
313     DeallocateNonBasePtr,
314     IncorrectAllocationInformation(Size, Size, Align, Align),
315     Layout(layout::LayoutError<'tcx>),
316     HeapAllocZeroBytes,
317     HeapAllocNonPowerOfTwoAlignment(u64),
318     Unreachable,
319     Panic(EvalErrorPanic<O>),
320     ReadFromReturnPointer,
321     PathNotFound(Vec<String>),
322     UnimplementedTraitSelection,
323     /// Abort in case type errors are reached
324     TypeckError,
325     /// Resolution can fail if we are in a too generic context
326     TooGeneric,
327     /// Cannot compute this constant because it depends on another one
328     /// which already produced an error
329     ReferencedConstant,
330     GeneratorResumedAfterReturn,
331     GeneratorResumedAfterPanic,
332     InfiniteLoop,
333 }
334
335
336 pub type InterpResult<'tcx, T = ()> = Result<T, InterpErrorInfo<'tcx>>;
337
338 impl<'tcx, O> InterpError<'tcx, O> {
339     pub fn description(&self) -> &str {
340         use self::InterpError::*;
341         match *self {
342             MachineError(ref inner) => inner,
343             Exit(..) =>
344                 "exited",
345             FunctionAbiMismatch(..) | FunctionArgMismatch(..) | FunctionRetMismatch(..)
346             | FunctionArgCountMismatch =>
347                 "tried to call a function through a function pointer of incompatible type",
348             InvalidMemoryAccess =>
349                 "tried to access memory through an invalid pointer",
350             DanglingPointerDeref =>
351                 "dangling pointer was dereferenced",
352             DoubleFree =>
353                 "tried to deallocate dangling pointer",
354             InvalidFunctionPointer =>
355                 "tried to use a function pointer after offsetting it",
356             InvalidBool =>
357                 "invalid boolean value read",
358             InvalidDiscriminant(..) =>
359                 "invalid enum discriminant value read",
360             PointerOutOfBounds { .. } =>
361                 "pointer offset outside bounds of allocation",
362             InvalidNullPointerUsage =>
363                 "invalid use of NULL pointer",
364             ValidationFailure(..) =>
365                 "type validation failed",
366             ReadPointerAsBytes =>
367                 "a raw memory access tried to access part of a pointer value as raw bytes",
368             ReadBytesAsPointer =>
369                 "a memory access tried to interpret some bytes as a pointer",
370             ReadForeignStatic =>
371                 "tried to read from foreign (extern) static",
372             InvalidPointerMath =>
373                 "attempted to do invalid arithmetic on pointers that would leak base addresses, \
374                 e.g., comparing pointers into different allocations",
375             ReadUndefBytes(_) =>
376                 "attempted to read undefined bytes",
377             DeadLocal =>
378                 "tried to access a dead local variable",
379             InvalidBoolOp(_) =>
380                 "invalid boolean operation",
381             Unimplemented(ref msg) => msg,
382             DerefFunctionPointer =>
383                 "tried to dereference a function pointer",
384             ExecuteMemory =>
385                 "tried to treat a memory pointer as a function pointer",
386             BoundsCheck{..} =>
387                 "array index out of bounds",
388             Intrinsic(..) =>
389                 "intrinsic failed",
390             NoMirFor(..) =>
391                 "mir not found",
392             InvalidChar(..) =>
393                 "tried to interpret an invalid 32-bit value as a char",
394             StackFrameLimitReached =>
395                 "reached the configured maximum number of stack frames",
396             OutOfTls =>
397                 "reached the maximum number of representable TLS keys",
398             TlsOutOfBounds =>
399                 "accessed an invalid (unallocated) TLS key",
400             AbiViolation(ref msg) => msg,
401             AlignmentCheckFailed{..} =>
402                 "tried to execute a misaligned read or write",
403             CalledClosureAsFunction =>
404                 "tried to call a closure through a function pointer",
405             VtableForArgumentlessMethod =>
406                 "tried to call a vtable function without arguments",
407             ModifiedConstantMemory =>
408                 "tried to modify constant memory",
409             ModifiedStatic =>
410                 "tried to modify a static's initial value from another static's initializer",
411             AssumptionNotHeld =>
412                 "`assume` argument was false",
413             InlineAsm =>
414                 "miri does not support inline assembly",
415             TypeNotPrimitive(_) =>
416                 "expected primitive type, got nonprimitive",
417             ReallocatedWrongMemoryKind(_, _) =>
418                 "tried to reallocate memory from one kind to another",
419             DeallocatedWrongMemoryKind(_, _) =>
420                 "tried to deallocate memory of the wrong kind",
421             ReallocateNonBasePtr =>
422                 "tried to reallocate with a pointer not to the beginning of an existing object",
423             DeallocateNonBasePtr =>
424                 "tried to deallocate with a pointer not to the beginning of an existing object",
425             IncorrectAllocationInformation(..) =>
426                 "tried to deallocate or reallocate using incorrect alignment or size",
427             Layout(_) =>
428                 "rustc layout computation failed",
429             UnterminatedCString(_) =>
430                 "attempted to get length of a null terminated string, but no null found before end \
431                 of allocation",
432             HeapAllocZeroBytes =>
433                 "tried to re-, de- or allocate zero bytes on the heap",
434             HeapAllocNonPowerOfTwoAlignment(_) =>
435                 "tried to re-, de-, or allocate heap memory with alignment that is not a power of \
436                 two",
437             Unreachable =>
438                 "entered unreachable code",
439             Panic { .. } =>
440                 "the evaluated program panicked",
441             ReadFromReturnPointer =>
442                 "tried to read from the return pointer",
443             PathNotFound(_) =>
444                 "a path could not be resolved, maybe the crate is not loaded",
445             UnimplementedTraitSelection =>
446                 "there were unresolved type arguments during trait selection",
447             TypeckError =>
448                 "encountered constants with type errors, stopping evaluation",
449             TooGeneric =>
450                 "encountered overly generic constant",
451             ReferencedConstant =>
452                 "referenced constant has errors",
453             Overflow(mir::BinOp::Add) => "attempt to add with overflow",
454             Overflow(mir::BinOp::Sub) => "attempt to subtract with overflow",
455             Overflow(mir::BinOp::Mul) => "attempt to multiply with overflow",
456             Overflow(mir::BinOp::Div) => "attempt to divide with overflow",
457             Overflow(mir::BinOp::Rem) => "attempt to calculate the remainder with overflow",
458             OverflowNeg => "attempt to negate with overflow",
459             Overflow(mir::BinOp::Shr) => "attempt to shift right with overflow",
460             Overflow(mir::BinOp::Shl) => "attempt to shift left with overflow",
461             Overflow(op) => bug!("{:?} cannot overflow", op),
462             DivisionByZero => "attempt to divide by zero",
463             RemainderByZero => "attempt to calculate the remainder with a divisor of zero",
464             GeneratorResumedAfterReturn => "generator resumed after completion",
465             GeneratorResumedAfterPanic => "generator resumed after panicking",
466             InfiniteLoop =>
467                 "duplicate interpreter state observed here, const evaluation will never terminate",
468         }
469     }
470 }
471
472 impl<'tcx> fmt::Display for InterpErrorInfo<'tcx> {
473     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
474         write!(f, "{}", self.kind)
475     }
476 }
477
478 impl<'tcx> fmt::Display for InterpError<'tcx, u64> {
479     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
480         write!(f, "{:?}", self)
481     }
482 }
483
484 impl<'tcx, O: fmt::Debug> fmt::Debug for InterpError<'tcx, O> {
485     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
486         use self::InterpError::*;
487         match *self {
488             PointerOutOfBounds { ptr, msg, allocation_size } => {
489                 write!(f, "{} failed: pointer must be in-bounds at offset {}, \
490                           but is outside bounds of allocation {} which has size {}",
491                     msg, ptr.offset.bytes(), ptr.alloc_id, allocation_size.bytes())
492             },
493             ValidationFailure(ref err) => {
494                 write!(f, "type validation failed: {}", err)
495             }
496             NoMirFor(ref func) => write!(f, "no mir for `{}`", func),
497             FunctionAbiMismatch(caller_abi, callee_abi) =>
498                 write!(f, "tried to call a function with ABI {:?} using caller ABI {:?}",
499                     callee_abi, caller_abi),
500             FunctionArgMismatch(caller_ty, callee_ty) =>
501                 write!(f, "tried to call a function with argument of type {:?} \
502                            passing data of type {:?}",
503                     callee_ty, caller_ty),
504             FunctionRetMismatch(caller_ty, callee_ty) =>
505                 write!(f, "tried to call a function with return type {:?} \
506                            passing return place of type {:?}",
507                     callee_ty, caller_ty),
508             FunctionArgCountMismatch =>
509                 write!(f, "tried to call a function with incorrect number of arguments"),
510             BoundsCheck { ref len, ref index } =>
511                 write!(f, "index out of bounds: the len is {:?} but the index is {:?}", len, index),
512             ReallocatedWrongMemoryKind(ref old, ref new) =>
513                 write!(f, "tried to reallocate memory from {} to {}", old, new),
514             DeallocatedWrongMemoryKind(ref old, ref new) =>
515                 write!(f, "tried to deallocate {} memory but gave {} as the kind", old, new),
516             Intrinsic(ref err) =>
517                 write!(f, "{}", err),
518             InvalidChar(c) =>
519                 write!(f, "tried to interpret an invalid 32-bit value as a char: {}", c),
520             AlignmentCheckFailed { required, has } =>
521                write!(f, "tried to access memory with alignment {}, but alignment {} is required",
522                       has.bytes(), required.bytes()),
523             TypeNotPrimitive(ty) =>
524                 write!(f, "expected primitive type, got {}", ty),
525             Layout(ref err) =>
526                 write!(f, "rustc layout computation failed: {:?}", err),
527             PathNotFound(ref path) =>
528                 write!(f, "Cannot find path {:?}", path),
529             MachineError(ref inner) =>
530                 write!(f, "{}", inner),
531             IncorrectAllocationInformation(size, size2, align, align2) =>
532                 write!(f, "incorrect alloc info: expected size {} and align {}, \
533                            got size {} and align {}",
534                     size.bytes(), align.bytes(), size2.bytes(), align2.bytes()),
535             Panic { .. } =>
536                 write!(f, "the evaluated program panicked"),
537             InvalidDiscriminant(val) =>
538                 write!(f, "encountered invalid enum discriminant {}", val),
539             Exit(code) =>
540                 write!(f, "exited with status code {}", code),
541             _ => write!(f, "{}", self.description()),
542         }
543     }
544 }