]> git.lizzy.rs Git - rust.git/blob - src/librustc/mir/interpret/error.rs
Make is_mutable use PlaceRef instead of it's fields
[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>,
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>,
189     backtrace: Option<Box<Backtrace>>,
190 }
191
192
193 impl fmt::Display for InterpErrorInfo<'_> {
194     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
195         write!(f, "{}", self.kind)
196     }
197 }
198
199 impl InterpErrorInfo<'_> {
200     pub fn print_backtrace(&mut self) {
201         if let Some(ref mut backtrace) = self.backtrace {
202             print_backtrace(&mut *backtrace);
203         }
204     }
205 }
206
207 fn print_backtrace(backtrace: &mut Backtrace) {
208     backtrace.resolve();
209     eprintln!("\n\nAn error occurred in miri:\n{:?}", backtrace);
210 }
211
212 impl<'tcx> From<InterpError<'tcx>> for InterpErrorInfo<'tcx> {
213     fn from(kind: InterpError<'tcx>) -> Self {
214         let backtrace = match env::var("RUST_CTFE_BACKTRACE") {
215             // Matching `RUST_BACKTRACE` -- we treat "0" the same as "not present".
216             Ok(ref val) if val != "0" => {
217                 let mut backtrace = Backtrace::new_unresolved();
218
219                 if val == "immediate" {
220                     // Print it now.
221                     print_backtrace(&mut backtrace);
222                     None
223                 } else {
224                     Some(Box::new(backtrace))
225                 }
226             },
227             _ => None,
228         };
229         InterpErrorInfo {
230             kind,
231             backtrace,
232         }
233     }
234 }
235
236 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
237 pub enum PanicMessage<O> {
238     Panic {
239         msg: Symbol,
240         line: u32,
241         col: u32,
242         file: Symbol,
243     },
244     BoundsCheck {
245         len: O,
246         index: O,
247     },
248     Overflow(mir::BinOp),
249     OverflowNeg,
250     DivisionByZero,
251     RemainderByZero,
252     GeneratorResumedAfterReturn,
253     GeneratorResumedAfterPanic,
254 }
255
256 /// Type for MIR `Assert` terminator error messages.
257 pub type AssertMessage<'tcx> = PanicMessage<mir::Operand<'tcx>>;
258
259 impl<O> PanicMessage<O> {
260     /// Getting a description does not require `O` to be printable, and does not
261     /// require allocation.
262     /// The caller is expected to handle `Panic` and `BoundsCheck` separately.
263     pub fn description(&self) -> &'static str {
264         use PanicMessage::*;
265         match self {
266             Overflow(mir::BinOp::Add) =>
267                 "attempt to add with overflow",
268             Overflow(mir::BinOp::Sub) =>
269                 "attempt to subtract with overflow",
270             Overflow(mir::BinOp::Mul) =>
271                 "attempt to multiply with overflow",
272             Overflow(mir::BinOp::Div) =>
273                 "attempt to divide with overflow",
274             Overflow(mir::BinOp::Rem) =>
275                 "attempt to calculate the remainder with overflow",
276             OverflowNeg =>
277                 "attempt to negate with overflow",
278             Overflow(mir::BinOp::Shr) =>
279                 "attempt to shift right with overflow",
280             Overflow(mir::BinOp::Shl) =>
281                 "attempt to shift left with overflow",
282             Overflow(op) =>
283                 bug!("{:?} cannot overflow", op),
284             DivisionByZero =>
285                 "attempt to divide by zero",
286             RemainderByZero =>
287                 "attempt to calculate the remainder with a divisor of zero",
288             GeneratorResumedAfterReturn =>
289                 "generator resumed after completion",
290             GeneratorResumedAfterPanic =>
291                 "generator resumed after panicking",
292             Panic { .. } | BoundsCheck { .. } =>
293                 bug!("Unexpected PanicMessage"),
294         }
295     }
296 }
297
298 impl<O: fmt::Debug> fmt::Debug for PanicMessage<O> {
299     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
300         use PanicMessage::*;
301         match self {
302             Panic { ref msg, line, col, ref file } =>
303                 write!(f, "the evaluated program panicked at '{}', {}:{}:{}", msg, file, line, col),
304             BoundsCheck { ref len, ref index } =>
305                 write!(f, "index out of bounds: the len is {:?} but the index is {:?}", len, index),
306             _ =>
307                 write!(f, "{}", self.description()),
308         }
309     }
310 }
311
312 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
313 pub enum InterpError<'tcx> {
314     /// This variant is used by machines to signal their own errors that do not
315     /// match an existing variant.
316     MachineError(String),
317
318     /// Not actually an interpreter error -- used to signal that execution has exited
319     /// with the given status code.  Used by Miri, but not by CTFE.
320     Exit(i32),
321
322     FunctionAbiMismatch(Abi, Abi),
323     FunctionArgMismatch(Ty<'tcx>, Ty<'tcx>),
324     FunctionRetMismatch(Ty<'tcx>, Ty<'tcx>),
325     FunctionArgCountMismatch,
326     NoMirFor(String),
327     UnterminatedCString(Pointer),
328     DanglingPointerDeref,
329     DoubleFree,
330     InvalidMemoryAccess,
331     InvalidFunctionPointer,
332     InvalidBool,
333     InvalidDiscriminant(ScalarMaybeUndef),
334     PointerOutOfBounds {
335         ptr: Pointer,
336         msg: CheckInAllocMsg,
337         allocation_size: Size,
338     },
339     InvalidNullPointerUsage,
340     ReadPointerAsBytes,
341     ReadBytesAsPointer,
342     ReadForeignStatic,
343     InvalidPointerMath,
344     ReadUndefBytes(Size),
345     DeadLocal,
346     InvalidBoolOp(mir::BinOp),
347     Unimplemented(String),
348     DerefFunctionPointer,
349     ExecuteMemory,
350     Intrinsic(String),
351     InvalidChar(u128),
352     StackFrameLimitReached,
353     OutOfTls,
354     TlsOutOfBounds,
355     AbiViolation(String),
356     AlignmentCheckFailed {
357         required: Align,
358         has: Align,
359     },
360     ValidationFailure(String),
361     CalledClosureAsFunction,
362     VtableForArgumentlessMethod,
363     ModifiedConstantMemory,
364     ModifiedStatic,
365     AssumptionNotHeld,
366     InlineAsm,
367     TypeNotPrimitive(Ty<'tcx>),
368     ReallocatedWrongMemoryKind(String, String),
369     DeallocatedWrongMemoryKind(String, String),
370     ReallocateNonBasePtr,
371     DeallocateNonBasePtr,
372     IncorrectAllocationInformation(Size, Size, Align, Align),
373     Layout(layout::LayoutError<'tcx>),
374     HeapAllocZeroBytes,
375     HeapAllocNonPowerOfTwoAlignment(u64),
376     Unreachable,
377     Panic(PanicMessage<u64>),
378     ReadFromReturnPointer,
379     PathNotFound(Vec<String>),
380     UnimplementedTraitSelection,
381     /// Abort in case type errors are reached
382     TypeckError,
383     /// Resolution can fail if we are in a too generic context
384     TooGeneric,
385     /// Cannot compute this constant because it depends on another one
386     /// which already produced an error
387     ReferencedConstant,
388     InfiniteLoop,
389 }
390
391 pub type InterpResult<'tcx, T = ()> = Result<T, InterpErrorInfo<'tcx>>;
392
393 impl fmt::Display for InterpError<'_> {
394     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
395         // Forward `Display` to `Debug`
396         write!(f, "{:?}", self)
397     }
398 }
399
400 impl fmt::Debug for InterpError<'_> {
401     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
402         use InterpError::*;
403         match *self {
404             PointerOutOfBounds { ptr, msg, allocation_size } => {
405                 write!(f, "{} failed: pointer must be in-bounds at offset {}, \
406                           but is outside bounds of allocation {} which has size {}",
407                     msg, ptr.offset.bytes(), ptr.alloc_id, allocation_size.bytes())
408             },
409             ValidationFailure(ref err) => {
410                 write!(f, "type validation failed: {}", err)
411             }
412             NoMirFor(ref func) => write!(f, "no mir for `{}`", func),
413             FunctionAbiMismatch(caller_abi, callee_abi) =>
414                 write!(f, "tried to call a function with ABI {:?} using caller ABI {:?}",
415                     callee_abi, caller_abi),
416             FunctionArgMismatch(caller_ty, callee_ty) =>
417                 write!(f, "tried to call a function with argument of type {:?} \
418                            passing data of type {:?}",
419                     callee_ty, caller_ty),
420             FunctionRetMismatch(caller_ty, callee_ty) =>
421                 write!(f, "tried to call a function with return type {:?} \
422                            passing return place of type {:?}",
423                     callee_ty, caller_ty),
424             FunctionArgCountMismatch =>
425                 write!(f, "tried to call a function with incorrect number of arguments"),
426             ReallocatedWrongMemoryKind(ref old, ref new) =>
427                 write!(f, "tried to reallocate memory from {} to {}", old, new),
428             DeallocatedWrongMemoryKind(ref old, ref new) =>
429                 write!(f, "tried to deallocate {} memory but gave {} as the kind", old, new),
430             InvalidChar(c) =>
431                 write!(f, "tried to interpret an invalid 32-bit value as a char: {}", c),
432             AlignmentCheckFailed { required, has } =>
433                write!(f, "tried to access memory with alignment {}, but alignment {} is required",
434                       has.bytes(), required.bytes()),
435             TypeNotPrimitive(ty) =>
436                 write!(f, "expected primitive type, got {}", ty),
437             Layout(ref err) =>
438                 write!(f, "rustc layout computation failed: {:?}", err),
439             PathNotFound(ref path) =>
440                 write!(f, "Cannot find path {:?}", path),
441             IncorrectAllocationInformation(size, size2, align, align2) =>
442                 write!(f, "incorrect alloc info: expected size {} and align {}, \
443                            got size {} and align {}",
444                     size.bytes(), align.bytes(), size2.bytes(), align2.bytes()),
445             InvalidDiscriminant(val) =>
446                 write!(f, "encountered invalid enum discriminant {}", val),
447             Exit(code) =>
448                 write!(f, "exited with status code {}", code),
449             InvalidMemoryAccess =>
450                 write!(f, "tried to access memory through an invalid pointer"),
451             DanglingPointerDeref =>
452                 write!(f, "dangling pointer was dereferenced"),
453             DoubleFree =>
454                 write!(f, "tried to deallocate dangling pointer"),
455             InvalidFunctionPointer =>
456                 write!(f, "tried to use a function pointer after offsetting it"),
457             InvalidBool =>
458                 write!(f, "invalid boolean value read"),
459             InvalidNullPointerUsage =>
460                 write!(f, "invalid use of NULL pointer"),
461             ReadPointerAsBytes =>
462                 write!(f, "a raw memory access tried to access part of a pointer value as raw \
463                     bytes"),
464             ReadBytesAsPointer =>
465                 write!(f, "a memory access tried to interpret some bytes as a pointer"),
466             ReadForeignStatic =>
467                 write!(f, "tried to read from foreign (extern) static"),
468             InvalidPointerMath =>
469                 write!(f, "attempted to do invalid arithmetic on pointers that would leak base \
470                     addresses, e.g., comparing pointers into different allocations"),
471             DeadLocal =>
472                 write!(f, "tried to access a dead local variable"),
473             DerefFunctionPointer =>
474                 write!(f, "tried to dereference a function pointer"),
475             ExecuteMemory =>
476                 write!(f, "tried to treat a memory pointer as a function pointer"),
477             StackFrameLimitReached =>
478                 write!(f, "reached the configured maximum number of stack frames"),
479             OutOfTls =>
480                 write!(f, "reached the maximum number of representable TLS keys"),
481             TlsOutOfBounds =>
482                 write!(f, "accessed an invalid (unallocated) TLS key"),
483             CalledClosureAsFunction =>
484                 write!(f, "tried to call a closure through a function pointer"),
485             VtableForArgumentlessMethod =>
486                 write!(f, "tried to call a vtable function without arguments"),
487             ModifiedConstantMemory =>
488                 write!(f, "tried to modify constant memory"),
489             ModifiedStatic =>
490                 write!(f, "tried to modify a static's initial value from another static's \
491                     initializer"),
492             AssumptionNotHeld =>
493                 write!(f, "`assume` argument was false"),
494             InlineAsm =>
495                 write!(f, "miri does not support inline assembly"),
496             ReallocateNonBasePtr =>
497                 write!(f, "tried to reallocate with a pointer not to the beginning of an \
498                     existing object"),
499             DeallocateNonBasePtr =>
500                 write!(f, "tried to deallocate with a pointer not to the beginning of an \
501                     existing object"),
502             HeapAllocZeroBytes =>
503                 write!(f, "tried to re-, de- or allocate zero bytes on the heap"),
504             Unreachable =>
505                 write!(f, "entered unreachable code"),
506             ReadFromReturnPointer =>
507                 write!(f, "tried to read from the return pointer"),
508             UnimplementedTraitSelection =>
509                 write!(f, "there were unresolved type arguments during trait selection"),
510             TypeckError =>
511                 write!(f, "encountered constants with type errors, stopping evaluation"),
512             TooGeneric =>
513                 write!(f, "encountered overly generic constant"),
514             ReferencedConstant =>
515                 write!(f, "referenced constant has errors"),
516             InfiniteLoop =>
517                 write!(f, "duplicate interpreter state observed here, const evaluation will never \
518                     terminate"),
519             InvalidBoolOp(_) =>
520                 write!(f, "invalid boolean operation"),
521             UnterminatedCString(_) =>
522                 write!(f, "attempted to get length of a null terminated string, but no null \
523                     found before end of allocation"),
524             ReadUndefBytes(_) =>
525                 write!(f, "attempted to read undefined bytes"),
526             HeapAllocNonPowerOfTwoAlignment(_) =>
527                 write!(f, "tried to re-, de-, or allocate heap memory with alignment that is \
528                     not a power of two"),
529             MachineError(ref msg) |
530             Unimplemented(ref msg) |
531             AbiViolation(ref msg) |
532             Intrinsic(ref msg) =>
533                 write!(f, "{}", msg),
534             Panic(ref msg) =>
535                 write!(f, "{:?}", msg),
536         }
537     }
538 }