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