]> git.lizzy.rs Git - rust.git/blob - src/librustc/mir/interpret/error.rs
09c822f7508a02b20383f42f483f1b6dbe74da8c
[rust.git] / src / librustc / mir / interpret / error.rs
1 use super::{RawConst, Pointer, CheckInAllocMsg, ScalarMaybeUndef};
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 crate::ty::query::TyCtxtAt;
9
10 use backtrace::Backtrace;
11 use errors::DiagnosticBuilder;
12 use rustc_macros::HashStable;
13 use rustc_target::spec::abi::Abi;
14 use syntax_pos::{Pos, Span};
15 use syntax::symbol::Symbol;
16
17 use std::{fmt, env};
18
19 #[derive(Debug, Copy, Clone, PartialEq, Eq, HashStable, RustcEncodable, RustcDecodable)]
20 pub enum ErrorHandled {
21     /// Already reported a lint or an error for this evaluation.
22     Reported,
23     /// Don't emit an error, the evaluation failed because the MIR was generic
24     /// and the substs didn't fully monomorphize it.
25     TooGeneric,
26 }
27
28 impl ErrorHandled {
29     pub fn assert_reported(self) {
30         match self {
31             ErrorHandled::Reported => {},
32             ErrorHandled::TooGeneric => bug!("MIR interpretation failed without reporting an error \
33                                               even though it was fully monomorphized"),
34         }
35     }
36 }
37
38 CloneTypeFoldableImpls! {
39     ErrorHandled,
40 }
41
42 pub type ConstEvalRawResult<'tcx> = Result<RawConst<'tcx>, ErrorHandled>;
43 pub type ConstEvalResult<'tcx> = Result<&'tcx ty::Const<'tcx>, ErrorHandled>;
44
45 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
46 pub struct ConstEvalErr<'tcx> {
47     pub span: Span,
48     pub error: crate::mir::interpret::InterpError<'tcx>,
49     pub stacktrace: Vec<FrameInfo<'tcx>>,
50 }
51
52 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
53 pub struct FrameInfo<'tcx> {
54     /// This span is in the caller.
55     pub call_site: Span,
56     pub instance: ty::Instance<'tcx>,
57     pub lint_root: Option<hir::HirId>,
58 }
59
60 impl<'tcx> fmt::Display for FrameInfo<'tcx> {
61     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62         ty::tls::with(|tcx| {
63             if tcx.def_key(self.instance.def_id()).disambiguated_data.data
64                 == DefPathData::ClosureExpr
65             {
66                 write!(f, "inside call to closure")?;
67             } else {
68                 write!(f, "inside call to `{}`", self.instance)?;
69             }
70             if !self.call_site.is_dummy() {
71                 let lo = tcx.sess.source_map().lookup_char_pos(self.call_site.lo());
72                 write!(f, " at {}:{}:{}", lo.file.name, lo.line, lo.col.to_usize() + 1)?;
73             }
74             Ok(())
75         })
76     }
77 }
78
79 impl<'tcx> ConstEvalErr<'tcx> {
80     pub fn struct_error(
81         &self,
82         tcx: TyCtxtAt<'tcx>,
83         message: &str,
84     ) -> Result<DiagnosticBuilder<'tcx>, ErrorHandled> {
85         self.struct_generic(tcx, message, None)
86     }
87
88     pub fn report_as_error(&self, tcx: TyCtxtAt<'tcx>, message: &str) -> ErrorHandled {
89         let err = self.struct_error(tcx, message);
90         match err {
91             Ok(mut err) => {
92                 err.emit();
93                 ErrorHandled::Reported
94             },
95             Err(err) => err,
96         }
97     }
98
99     pub fn report_as_lint(
100         &self,
101         tcx: TyCtxtAt<'tcx>,
102         message: &str,
103         lint_root: hir::HirId,
104         span: Option<Span>,
105     ) -> ErrorHandled {
106         let lint = self.struct_generic(
107             tcx,
108             message,
109             Some(lint_root),
110         );
111         match lint {
112             Ok(mut lint) => {
113                 if let Some(span) = span {
114                     let primary_spans = lint.span.primary_spans().to_vec();
115                     // point at the actual error as the primary span
116                     lint.replace_span_with(span);
117                     // point to the `const` statement as a secondary span
118                     // they don't have any label
119                     for sp in primary_spans {
120                         if sp != span {
121                             lint.span_label(sp, "");
122                         }
123                     }
124                 }
125                 lint.emit();
126                 ErrorHandled::Reported
127             },
128             Err(err) => err,
129         }
130     }
131
132     fn struct_generic(
133         &self,
134         tcx: TyCtxtAt<'tcx>,
135         message: &str,
136         lint_root: Option<hir::HirId>,
137     ) -> Result<DiagnosticBuilder<'tcx>, ErrorHandled> {
138         let must_error = match self.error {
139             err_inval!(Layout(LayoutError::Unknown(_))) |
140             err_inval!(TooGeneric) =>
141                 return Err(ErrorHandled::TooGeneric),
142             err_inval!(TypeckError) =>
143                 return Err(ErrorHandled::Reported),
144             err_inval!(Layout(LayoutError::SizeOverflow(_))) => true,
145             _ => false,
146         };
147         trace!("reporting const eval failure at {:?}", self.span);
148         let mut err = if let (Some(lint_root), false) = (lint_root, must_error) {
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 if must_error {
162             struct_error(tcx, &self.error.to_string())
163         } else {
164             struct_error(tcx, message)
165         };
166         if !must_error {
167             err.span_label(self.span, self.error.to_string());
168         }
169         // Skip the last, which is just the environment of the constant.  The stacktrace
170         // is sometimes empty because we create "fake" eval contexts in CTFE to do work
171         // on constant values.
172         if self.stacktrace.len() > 0 {
173             for frame_info in &self.stacktrace[..self.stacktrace.len()-1] {
174                 err.span_label(frame_info.call_site, frame_info.to_string());
175             }
176         }
177         Ok(err)
178     }
179 }
180
181 pub fn struct_error<'tcx>(tcx: TyCtxtAt<'tcx>, msg: &str) -> DiagnosticBuilder<'tcx> {
182     struct_span_err!(tcx.sess, tcx.span, E0080, "{}", msg)
183 }
184
185 /// Packages the kind of error we got from the const code interpreter
186 /// up with a Rust-level backtrace of where the error occured.
187 /// Thsese should always be constructed by calling `.into()` on
188 /// a `InterpError`. In `librustc_mir::interpret`, we have `throw_err_*`
189 /// macros for this.
190 #[derive(Debug, Clone)]
191 pub struct InterpErrorInfo<'tcx> {
192     pub kind: InterpError<'tcx>,
193     backtrace: Option<Box<Backtrace>>,
194 }
195
196
197 impl fmt::Display for InterpErrorInfo<'_> {
198     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
199         write!(f, "{}", self.kind)
200     }
201 }
202
203 impl InterpErrorInfo<'_> {
204     pub fn print_backtrace(&mut self) {
205         if let Some(ref mut backtrace) = self.backtrace {
206             print_backtrace(&mut *backtrace);
207         }
208     }
209 }
210
211 fn print_backtrace(backtrace: &mut Backtrace) {
212     backtrace.resolve();
213     eprintln!("\n\nAn error occurred in miri:\n{:?}", backtrace);
214 }
215
216 impl<'tcx> From<InterpError<'tcx>> for InterpErrorInfo<'tcx> {
217     fn from(kind: InterpError<'tcx>) -> Self {
218         let backtrace = match env::var("RUSTC_CTFE_BACKTRACE") {
219             // Matching `RUST_BACKTRACE` -- we treat "0" the same as "not present".
220             Ok(ref val) if val != "0" => {
221                 let mut backtrace = Backtrace::new_unresolved();
222
223                 if val == "immediate" {
224                     // Print it now.
225                     print_backtrace(&mut backtrace);
226                     None
227                 } else {
228                     Some(Box::new(backtrace))
229                 }
230             },
231             _ => None,
232         };
233         InterpErrorInfo {
234             kind,
235             backtrace,
236         }
237     }
238 }
239
240 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
241 pub enum PanicInfo<O> {
242     Panic {
243         msg: Symbol,
244         line: u32,
245         col: u32,
246         file: Symbol,
247     },
248     BoundsCheck {
249         len: O,
250         index: O,
251     },
252     Overflow(mir::BinOp),
253     OverflowNeg,
254     DivisionByZero,
255     RemainderByZero,
256     GeneratorResumedAfterReturn,
257     GeneratorResumedAfterPanic,
258 }
259
260 /// Type for MIR `Assert` terminator error messages.
261 pub type AssertMessage<'tcx> = PanicInfo<mir::Operand<'tcx>>;
262
263 impl<O> PanicInfo<O> {
264     /// Getting a description does not require `O` to be printable, and does not
265     /// require allocation.
266     /// The caller is expected to handle `Panic` and `BoundsCheck` separately.
267     pub fn description(&self) -> &'static str {
268         use PanicInfo::*;
269         match self {
270             Overflow(mir::BinOp::Add) =>
271                 "attempt to add with overflow",
272             Overflow(mir::BinOp::Sub) =>
273                 "attempt to subtract with overflow",
274             Overflow(mir::BinOp::Mul) =>
275                 "attempt to multiply with overflow",
276             Overflow(mir::BinOp::Div) =>
277                 "attempt to divide with overflow",
278             Overflow(mir::BinOp::Rem) =>
279                 "attempt to calculate the remainder with overflow",
280             OverflowNeg =>
281                 "attempt to negate with overflow",
282             Overflow(mir::BinOp::Shr) =>
283                 "attempt to shift right with overflow",
284             Overflow(mir::BinOp::Shl) =>
285                 "attempt to shift left with overflow",
286             Overflow(op) =>
287                 bug!("{:?} cannot overflow", op),
288             DivisionByZero =>
289                 "attempt to divide by zero",
290             RemainderByZero =>
291                 "attempt to calculate the remainder with a divisor of zero",
292             GeneratorResumedAfterReturn =>
293                 "generator resumed after completion",
294             GeneratorResumedAfterPanic =>
295                 "generator resumed after panicking",
296             Panic { .. } | BoundsCheck { .. } =>
297                 bug!("Unexpected PanicInfo"),
298         }
299     }
300 }
301
302 impl<O: fmt::Debug> fmt::Debug for PanicInfo<O> {
303     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
304         use PanicInfo::*;
305         match self {
306             Panic { ref msg, line, col, ref file } =>
307                 write!(f, "the evaluated program panicked at '{}', {}:{}:{}", msg, file, line, col),
308             BoundsCheck { ref len, ref index } =>
309                 write!(f, "index out of bounds: the len is {:?} but the index is {:?}", len, index),
310             _ =>
311                 write!(f, "{}", self.description()),
312         }
313     }
314 }
315
316 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
317 pub enum InvalidProgramInfo<'tcx> {
318     /// Resolution can fail if we are in a too generic context.
319     TooGeneric,
320     /// Cannot compute this constant because it depends on another one
321     /// which already produced an error.
322     ReferencedConstant,
323     /// Abort in case type errors are reached.
324     TypeckError,
325     /// An error occurred during layout computation.
326     Layout(layout::LayoutError<'tcx>),
327 }
328
329 impl fmt::Debug for InvalidProgramInfo<'tcx> {
330     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
331         use InvalidProgramInfo::*;
332         match self {
333             TooGeneric =>
334                 write!(f, "encountered overly generic constant"),
335             ReferencedConstant =>
336                 write!(f, "referenced constant has errors"),
337             TypeckError =>
338                 write!(f, "encountered constants with type errors, stopping evaluation"),
339             Layout(ref err) =>
340                 write!(f, "{}", err),
341         }
342     }
343 }
344
345 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
346 pub enum UndefinedBehaviorInfo {
347     /// Free-form case. Only for errors that are never caught!
348     Ub(String),
349     /// Free-form case for experimental UB. Only for errors that are never caught!
350     UbExperimental(String),
351     /// Unreachable code was executed.
352     Unreachable,
353 }
354
355 impl fmt::Debug for UndefinedBehaviorInfo {
356     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
357         use UndefinedBehaviorInfo::*;
358         match self {
359             Ub(msg) | UbExperimental(msg) =>
360                 write!(f, "{}", msg),
361             Unreachable =>
362                 write!(f, "entered unreachable code"),
363         }
364     }
365 }
366
367 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
368 pub enum UnsupportedOpInfo<'tcx> {
369     /// Free-form case. Only for errors that are never caught!
370     Unsupported(String),
371
372     // -- Everything below is not classified yet --
373     FunctionAbiMismatch(Abi, Abi),
374     FunctionArgMismatch(Ty<'tcx>, Ty<'tcx>),
375     FunctionRetMismatch(Ty<'tcx>, Ty<'tcx>),
376     FunctionArgCountMismatch,
377     UnterminatedCString(Pointer),
378     DanglingPointerDeref,
379     DoubleFree,
380     InvalidMemoryAccess,
381     InvalidFunctionPointer,
382     InvalidBool,
383     InvalidDiscriminant(ScalarMaybeUndef),
384     PointerOutOfBounds {
385         ptr: Pointer,
386         msg: CheckInAllocMsg,
387         allocation_size: Size,
388     },
389     InvalidNullPointerUsage,
390     ReadPointerAsBytes,
391     ReadBytesAsPointer,
392     ReadForeignStatic,
393     InvalidPointerMath,
394     ReadUndefBytes(Size),
395     DeadLocal,
396     InvalidBoolOp(mir::BinOp),
397     UnimplementedTraitSelection,
398     CalledClosureAsFunction,
399     NoMirFor(String),
400     DerefFunctionPointer,
401     ExecuteMemory,
402     InvalidChar(u128),
403     OutOfTls,
404     TlsOutOfBounds,
405     AlignmentCheckFailed {
406         required: Align,
407         has: Align,
408     },
409     ValidationFailure(String),
410     VtableForArgumentlessMethod,
411     ModifiedConstantMemory,
412     ModifiedStatic,
413     TypeNotPrimitive(Ty<'tcx>),
414     ReallocatedWrongMemoryKind(String, String),
415     DeallocatedWrongMemoryKind(String, String),
416     ReallocateNonBasePtr,
417     DeallocateNonBasePtr,
418     IncorrectAllocationInformation(Size, Size, Align, Align),
419     HeapAllocZeroBytes,
420     HeapAllocNonPowerOfTwoAlignment(u64),
421     ReadFromReturnPointer,
422     PathNotFound(Vec<String>),
423 }
424
425 impl fmt::Debug for UnsupportedOpInfo<'tcx> {
426     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
427         use UnsupportedOpInfo::*;
428         match self {
429             PointerOutOfBounds { ptr, msg, allocation_size } => {
430                 write!(f, "{} failed: pointer must be in-bounds at offset {}, \
431                            but is outside bounds of allocation {} which has size {}",
432                     msg, ptr.offset.bytes(), ptr.alloc_id, allocation_size.bytes())
433             },
434             ValidationFailure(ref err) => {
435                 write!(f, "type validation failed: {}", err)
436             }
437             NoMirFor(ref func) => write!(f, "no MIR for `{}`", func),
438             FunctionAbiMismatch(caller_abi, callee_abi) =>
439                 write!(f, "tried to call a function with ABI {:?} using caller ABI {:?}",
440                     callee_abi, caller_abi),
441             FunctionArgMismatch(caller_ty, callee_ty) =>
442                 write!(f, "tried to call a function with argument of type {:?} \
443                            passing data of type {:?}",
444                     callee_ty, caller_ty),
445             FunctionRetMismatch(caller_ty, callee_ty) =>
446                 write!(f, "tried to call a function with return type {:?} \
447                            passing return place of type {:?}",
448                     callee_ty, caller_ty),
449             FunctionArgCountMismatch =>
450                 write!(f, "tried to call a function with incorrect number of arguments"),
451             ReallocatedWrongMemoryKind(ref old, ref new) =>
452                 write!(f, "tried to reallocate memory from `{}` to `{}`", old, new),
453             DeallocatedWrongMemoryKind(ref old, ref new) =>
454                 write!(f, "tried to deallocate `{}` memory but gave `{}` as the kind", old, new),
455             InvalidChar(c) =>
456                 write!(f, "tried to interpret an invalid 32-bit value as a char: {}", c),
457             AlignmentCheckFailed { required, has } =>
458                write!(f, "tried to access memory with alignment {}, but alignment {} is required",
459                       has.bytes(), required.bytes()),
460             TypeNotPrimitive(ty) =>
461                 write!(f, "expected primitive type, got {}", ty),
462             PathNotFound(ref path) =>
463                 write!(f, "cannot find path {:?}", path),
464             IncorrectAllocationInformation(size, size2, align, align2) =>
465                 write!(f, "incorrect alloc info: expected size {} and align {}, \
466                            got size {} and align {}",
467                     size.bytes(), align.bytes(), size2.bytes(), align2.bytes()),
468             InvalidDiscriminant(val) =>
469                 write!(f, "encountered invalid enum discriminant {}", val),
470             InvalidMemoryAccess =>
471                 write!(f, "tried to access memory through an invalid pointer"),
472             DanglingPointerDeref =>
473                 write!(f, "dangling pointer was dereferenced"),
474             DoubleFree =>
475                 write!(f, "tried to deallocate dangling pointer"),
476             InvalidFunctionPointer =>
477                 write!(f, "tried to use a function pointer after offsetting it"),
478             InvalidBool =>
479                 write!(f, "invalid boolean value read"),
480             InvalidNullPointerUsage =>
481                 write!(f, "invalid use of NULL pointer"),
482             ReadPointerAsBytes =>
483                 write!(f, "a raw memory access tried to access part of a pointer value as raw \
484                     bytes"),
485             ReadBytesAsPointer =>
486                 write!(f, "a memory access tried to interpret some bytes as a pointer"),
487             ReadForeignStatic =>
488                 write!(f, "tried to read from foreign (extern) static"),
489             InvalidPointerMath =>
490                 write!(f, "attempted to do invalid arithmetic on pointers that would leak base \
491                     addresses, e.g., comparing pointers into different allocations"),
492             DeadLocal =>
493                 write!(f, "tried to access a dead local variable"),
494             DerefFunctionPointer =>
495                 write!(f, "tried to dereference a function pointer"),
496             ExecuteMemory =>
497                 write!(f, "tried to treat a memory pointer as a function pointer"),
498             OutOfTls =>
499                 write!(f, "reached the maximum number of representable TLS keys"),
500             TlsOutOfBounds =>
501                 write!(f, "accessed an invalid (unallocated) TLS key"),
502             CalledClosureAsFunction =>
503                 write!(f, "tried to call a closure through a function pointer"),
504             VtableForArgumentlessMethod =>
505                 write!(f, "tried to call a vtable function without arguments"),
506             ModifiedConstantMemory =>
507                 write!(f, "tried to modify constant memory"),
508             ModifiedStatic =>
509                 write!(f, "tried to modify a static's initial value from another static's \
510                     initializer"),
511             ReallocateNonBasePtr =>
512                 write!(f, "tried to reallocate with a pointer not to the beginning of an \
513                     existing object"),
514             DeallocateNonBasePtr =>
515                 write!(f, "tried to deallocate with a pointer not to the beginning of an \
516                     existing object"),
517             HeapAllocZeroBytes =>
518                 write!(f, "tried to re-, de- or allocate zero bytes on the heap"),
519             ReadFromReturnPointer =>
520                 write!(f, "tried to read from the return pointer"),
521             UnimplementedTraitSelection =>
522                 write!(f, "there were unresolved type arguments during trait selection"),
523             InvalidBoolOp(_) =>
524                 write!(f, "invalid boolean operation"),
525             UnterminatedCString(_) =>
526                 write!(f, "attempted to get length of a null-terminated string, but no null \
527                     found before end of allocation"),
528             ReadUndefBytes(_) =>
529                 write!(f, "attempted to read undefined bytes"),
530             HeapAllocNonPowerOfTwoAlignment(_) =>
531                 write!(f, "tried to re-, de-, or allocate heap memory with alignment that is \
532                     not a power of two"),
533             Unsupported(ref msg) =>
534                 write!(f, "{}", msg),
535         }
536     }
537 }
538
539 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
540 pub enum ResourceExhaustionInfo {
541     /// The stack grew too big.
542     StackFrameLimitReached,
543     /// The program ran into an infinite loop.
544     InfiniteLoop,
545 }
546
547 impl fmt::Debug for ResourceExhaustionInfo {
548     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
549         use ResourceExhaustionInfo::*;
550         match self {
551             StackFrameLimitReached =>
552                 write!(f, "reached the configured maximum number of stack frames"),
553             InfiniteLoop =>
554                 write!(f, "duplicate interpreter state observed here, const evaluation will never \
555                     terminate"),
556         }
557     }
558 }
559
560 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
561 pub enum InterpError<'tcx> {
562     /// The program panicked.
563     Panic(PanicInfo<u64>),
564     /// The program caused undefined behavior.
565     UndefinedBehavior(UndefinedBehaviorInfo),
566     /// The program did something the interpreter does not support (some of these *might* be UB
567     /// but the interpreter is not sure).
568     Unsupported(UnsupportedOpInfo<'tcx>),
569     /// The program was invalid (ill-typed, not sufficiently monomorphized, ...).
570     InvalidProgram(InvalidProgramInfo<'tcx>),
571     /// The program exhausted the interpreter's resources (stack/heap too big,
572     /// execution takes too long, ..).
573     ResourceExhaustion(ResourceExhaustionInfo),
574     /// Not actually an interpreter error -- used to signal that execution has exited
575     /// with the given status code.  Used by Miri, but not by CTFE.
576     Exit(i32),
577 }
578
579 pub type InterpResult<'tcx, T = ()> = Result<T, InterpErrorInfo<'tcx>>;
580
581 impl fmt::Display for InterpError<'_> {
582     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
583         // Forward `Display` to `Debug`.
584         write!(f, "{:?}", self)
585     }
586 }
587
588 impl fmt::Debug for InterpError<'_> {
589     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
590         use InterpError::*;
591         match *self {
592             Unsupported(ref msg) =>
593                 write!(f, "{:?}", msg),
594             InvalidProgram(ref msg) =>
595                 write!(f, "{:?}", msg),
596             UndefinedBehavior(ref msg) =>
597                 write!(f, "{:?}", msg),
598             ResourceExhaustion(ref msg) =>
599                 write!(f, "{:?}", msg),
600             Panic(ref msg) =>
601                 write!(f, "{:?}", msg),
602             Exit(code) =>
603                 write!(f, "exited with status code {}", code),
604         }
605     }
606 }