4 use ty::{FnSig, Ty, layout};
5 use ty::layout::{Size, Align};
6 use rustc_data_structures::sync::Lrc;
9 Pointer, Lock, AccessKind
12 use backtrace::Backtrace;
15 use ty::query::TyCtxtAt;
16 use errors::DiagnosticBuilder;
21 pub type ConstEvalResult<'tcx> = Result<&'tcx ty::Const<'tcx>, Lrc<ConstEvalErr<'tcx>>>;
23 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
24 pub struct ConstEvalErr<'tcx> {
26 pub error: ::mir::interpret::EvalError<'tcx>,
27 pub stacktrace: Vec<FrameInfo>,
30 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
31 pub struct FrameInfo {
34 pub lint_root: Option<ast::NodeId>,
37 impl<'a, 'gcx, 'tcx> ConstEvalErr<'tcx> {
38 pub fn struct_error(&self,
39 tcx: TyCtxtAt<'a, 'gcx, 'tcx>,
41 -> Option<DiagnosticBuilder<'tcx>>
43 self.struct_generic(tcx, message, None)
46 pub fn report_as_error(&self,
47 tcx: TyCtxtAt<'a, 'gcx, 'tcx>,
50 let err = self.struct_generic(tcx, message, None);
51 if let Some(mut err) = err {
56 pub fn report_as_lint(&self,
57 tcx: TyCtxtAt<'a, 'gcx, 'tcx>,
59 lint_root: ast::NodeId,
61 let lint = self.struct_generic(
66 if let Some(mut lint) = lint {
73 tcx: TyCtxtAt<'a, 'gcx, 'tcx>,
75 lint_root: Option<ast::NodeId>,
76 ) -> Option<DiagnosticBuilder<'tcx>> {
77 match self.error.kind {
78 ::mir::interpret::EvalErrorKind::TypeckError |
79 ::mir::interpret::EvalErrorKind::TooGeneric |
80 ::mir::interpret::EvalErrorKind::CheckMatchError |
81 ::mir::interpret::EvalErrorKind::Layout(_) => return None,
82 ::mir::interpret::EvalErrorKind::ReferencedConstant(ref inner) => {
83 inner.struct_generic(tcx, "referenced constant has errors", lint_root)?.emit();
87 trace!("reporting const eval failure at {:?}", self.span);
88 let mut err = if let Some(lint_root) = lint_root {
89 let node_id = self.stacktrace
92 .filter_map(|frame| frame.lint_root)
94 .unwrap_or(lint_root);
95 tcx.struct_span_lint_node(
96 ::rustc::lint::builtin::CONST_ERR,
102 struct_error(tcx, message)
104 err.span_label(self.span, self.error.to_string());
105 for FrameInfo { span, location, .. } in &self.stacktrace {
106 err.span_label(*span, format!("inside call to `{}`", location));
112 pub fn struct_error<'a, 'gcx, 'tcx>(
113 tcx: TyCtxtAt<'a, 'gcx, 'tcx>,
115 ) -> DiagnosticBuilder<'tcx> {
116 struct_span_err!(tcx.sess, tcx.span, E0080, "{}", msg)
119 #[derive(Debug, Clone, RustcEncodable, RustcDecodable)]
120 pub struct EvalError<'tcx> {
121 pub kind: EvalErrorKind<'tcx, u64>,
124 impl<'tcx> From<EvalErrorKind<'tcx, u64>> for EvalError<'tcx> {
125 fn from(kind: EvalErrorKind<'tcx, u64>) -> Self {
126 match env::var("MIRI_BACKTRACE") {
127 Ok(ref val) if !val.is_empty() => {
128 let backtrace = Backtrace::new();
131 let mut trace_text = "\n\nAn error occurred in miri:\n".to_string();
132 write!(trace_text, "backtrace frames: {}\n", backtrace.frames().len()).unwrap();
133 'frames: for (i, frame) in backtrace.frames().iter().enumerate() {
134 if frame.symbols().is_empty() {
135 write!(trace_text, "{}: no symbols\n", i).unwrap();
137 for symbol in frame.symbols() {
138 write!(trace_text, "{}: ", i).unwrap();
139 if let Some(name) = symbol.name() {
140 write!(trace_text, "{}\n", name).unwrap();
142 write!(trace_text, "<unknown>\n").unwrap();
144 write!(trace_text, "\tat ").unwrap();
145 if let Some(file_path) = symbol.filename() {
146 write!(trace_text, "{}", file_path.display()).unwrap();
148 write!(trace_text, "<unknown_file>").unwrap();
150 if let Some(line) = symbol.lineno() {
151 write!(trace_text, ":{}\n", line).unwrap();
153 write!(trace_text, "\n").unwrap();
157 error!("{}", trace_text);
167 pub type AssertMessage<'tcx> = EvalErrorKind<'tcx, mir::Operand<'tcx>>;
169 #[derive(Clone, RustcEncodable, RustcDecodable)]
170 pub enum EvalErrorKind<'tcx, O> {
171 /// This variant is used by machines to signal their own errors that do not
172 /// match an existing variant
173 MachineError(String),
174 FunctionPointerTyMismatch(FnSig<'tcx>, FnSig<'tcx>),
176 UnterminatedCString(Pointer),
177 DanglingPointerDeref,
180 InvalidFunctionPointer,
186 allocation_size: Size,
188 InvalidNullPointerUsage,
195 InvalidBoolOp(mir::BinOp),
196 Unimplemented(String),
197 DerefFunctionPointer,
199 BoundsCheck { len: O, index: O },
200 Overflow(mir::BinOp),
206 StackFrameLimitReached,
209 AbiViolation(String),
210 AlignmentCheckFailed {
214 MemoryLockViolation {
221 MemoryAcquireConflict {
227 InvalidMemoryLockRelease {
233 DeallocatedLockedMemory {
237 ValidationFailure(String),
238 CalledClosureAsFunction,
239 VtableForArgumentlessMethod,
240 ModifiedConstantMemory,
243 TypeNotPrimitive(Ty<'tcx>),
244 ReallocatedWrongMemoryKind(String, String),
245 DeallocatedWrongMemoryKind(String, String),
246 ReallocateNonBasePtr,
247 DeallocateNonBasePtr,
248 IncorrectAllocationInformation(Size, Size, Align, Align),
249 Layout(layout::LayoutError<'tcx>),
251 HeapAllocNonPowerOfTwoAlignment(u64),
254 ReadFromReturnPointer,
255 PathNotFound(Vec<String>),
256 UnimplementedTraitSelection,
257 /// Abort in case type errors are reached
259 /// Resolution can fail if we are in a too generic context
262 /// Cannot compute this constant because it depends on another one
263 /// which already produced an error
264 ReferencedConstant(Lrc<ConstEvalErr<'tcx>>),
265 GeneratorResumedAfterReturn,
266 GeneratorResumedAfterPanic,
269 pub type EvalResult<'tcx, T = ()> = Result<T, EvalError<'tcx>>;
271 impl<'tcx, O> EvalErrorKind<'tcx, O> {
272 pub fn description(&self) -> &str {
273 use self::EvalErrorKind::*;
275 MachineError(ref inner) => inner,
276 FunctionPointerTyMismatch(..) =>
277 "tried to call a function through a function pointer of a different type",
278 InvalidMemoryAccess =>
279 "tried to access memory through an invalid pointer",
280 DanglingPointerDeref =>
281 "dangling pointer was dereferenced",
283 "tried to deallocate dangling pointer",
284 InvalidFunctionPointer =>
285 "tried to use a function pointer after offsetting it",
287 "invalid boolean value read",
288 InvalidDiscriminant =>
289 "invalid enum discriminant value read",
290 PointerOutOfBounds { .. } =>
291 "pointer offset outside bounds of allocation",
292 InvalidNullPointerUsage =>
293 "invalid use of NULL pointer",
294 MemoryLockViolation { .. } =>
295 "memory access conflicts with lock",
296 MemoryAcquireConflict { .. } =>
297 "new memory lock conflicts with existing lock",
298 ValidationFailure(..) =>
299 "type validation failed",
300 InvalidMemoryLockRelease { .. } =>
301 "invalid attempt to release write lock",
302 DeallocatedLockedMemory { .. } =>
303 "tried to deallocate memory in conflict with a lock",
304 ReadPointerAsBytes =>
305 "a raw memory access tried to access part of a pointer value as raw bytes",
306 ReadBytesAsPointer =>
307 "a memory access tried to interpret some bytes as a pointer",
309 "tried to read from foreign (extern) static",
310 InvalidPointerMath =>
311 "attempted to do invalid arithmetic on pointers that would leak base addresses, e.g. comparing pointers into different allocations",
313 "attempted to read undefined bytes",
315 "tried to access a dead local variable",
317 "invalid boolean operation",
318 Unimplemented(ref msg) => msg,
319 DerefFunctionPointer =>
320 "tried to dereference a function pointer",
322 "tried to treat a memory pointer as a function pointer",
324 "array index out of bounds",
330 "tried to interpret an invalid 32-bit value as a char",
331 StackFrameLimitReached =>
332 "reached the configured maximum number of stack frames",
334 "reached the maximum number of representable TLS keys",
336 "accessed an invalid (unallocated) TLS key",
337 AbiViolation(ref msg) => msg,
338 AlignmentCheckFailed{..} =>
339 "tried to execute a misaligned read or write",
340 CalledClosureAsFunction =>
341 "tried to call a closure through a function pointer",
342 VtableForArgumentlessMethod =>
343 "tried to call a vtable function without arguments",
344 ModifiedConstantMemory =>
345 "tried to modify constant memory",
347 "`assume` argument was false",
349 "miri does not support inline assembly",
350 TypeNotPrimitive(_) =>
351 "expected primitive type, got nonprimitive",
352 ReallocatedWrongMemoryKind(_, _) =>
353 "tried to reallocate memory from one kind to another",
354 DeallocatedWrongMemoryKind(_, _) =>
355 "tried to deallocate memory of the wrong kind",
356 ReallocateNonBasePtr =>
357 "tried to reallocate with a pointer not to the beginning of an existing object",
358 DeallocateNonBasePtr =>
359 "tried to deallocate with a pointer not to the beginning of an existing object",
360 IncorrectAllocationInformation(..) =>
361 "tried to deallocate or reallocate using incorrect alignment or size",
363 "rustc layout computation failed",
364 UnterminatedCString(_) =>
365 "attempted to get length of a null terminated string, but no null found before end of allocation",
366 HeapAllocZeroBytes =>
367 "tried to re-, de- or allocate zero bytes on the heap",
368 HeapAllocNonPowerOfTwoAlignment(_) =>
369 "tried to re-, de-, or allocate heap memory with alignment that is not a power of two",
371 "entered unreachable code",
373 "the evaluated program panicked",
374 ReadFromReturnPointer =>
375 "tried to read from the return pointer",
377 "a path could not be resolved, maybe the crate is not loaded",
378 UnimplementedTraitSelection =>
379 "there were unresolved type arguments during trait selection",
381 "encountered constants with type errors, stopping evaluation",
383 "encountered overly generic constant",
385 "match checking failed",
386 ReferencedConstant(_) =>
387 "referenced constant has errors",
388 Overflow(mir::BinOp::Add) => "attempt to add with overflow",
389 Overflow(mir::BinOp::Sub) => "attempt to subtract with overflow",
390 Overflow(mir::BinOp::Mul) => "attempt to multiply with overflow",
391 Overflow(mir::BinOp::Div) => "attempt to divide with overflow",
392 Overflow(mir::BinOp::Rem) => "attempt to calculate the remainder with overflow",
393 OverflowNeg => "attempt to negate with overflow",
394 Overflow(mir::BinOp::Shr) => "attempt to shift right with overflow",
395 Overflow(mir::BinOp::Shl) => "attempt to shift left with overflow",
396 Overflow(op) => bug!("{:?} cannot overflow", op),
397 DivisionByZero => "attempt to divide by zero",
398 RemainderByZero => "attempt to calculate the remainder with a divisor of zero",
399 GeneratorResumedAfterReturn => "generator resumed after completion",
400 GeneratorResumedAfterPanic => "generator resumed after panicking",
405 impl<'tcx> fmt::Display for EvalError<'tcx> {
406 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
407 write!(f, "{:?}", self.kind)
411 impl<'tcx, O: fmt::Debug> fmt::Debug for EvalErrorKind<'tcx, O> {
412 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
413 use self::EvalErrorKind::*;
415 PointerOutOfBounds { ptr, access, allocation_size } => {
416 write!(f, "{} at offset {}, outside bounds of allocation {} which has size {}",
417 if access { "memory access" } else { "pointer computed" },
418 ptr.offset.bytes(), ptr.alloc_id, allocation_size.bytes())
420 MemoryLockViolation { ptr, len, frame, access, ref lock } => {
421 write!(f, "{:?} access by frame {} at {:?}, size {}, is in conflict with lock {:?}",
422 access, frame, ptr, len, lock)
424 MemoryAcquireConflict { ptr, len, kind, ref lock } => {
425 write!(f, "new {:?} lock at {:?}, size {}, is in conflict with lock {:?}",
426 kind, ptr, len, lock)
428 InvalidMemoryLockRelease { ptr, len, frame, ref lock } => {
429 write!(f, "frame {} tried to release memory write lock at {:?}, size {}, but cannot release lock {:?}",
430 frame, ptr, len, lock)
432 DeallocatedLockedMemory { ptr, ref lock } => {
433 write!(f, "tried to deallocate memory at {:?} in conflict with lock {:?}",
436 ValidationFailure(ref err) => {
437 write!(f, "type validation failed: {}", err)
439 NoMirFor(ref func) => write!(f, "no mir for `{}`", func),
440 FunctionPointerTyMismatch(sig, got) =>
441 write!(f, "tried to call a function with sig {} through a function pointer of type {}", sig, got),
442 BoundsCheck { ref len, ref index } =>
443 write!(f, "index out of bounds: the len is {:?} but the index is {:?}", len, index),
444 ReallocatedWrongMemoryKind(ref old, ref new) =>
445 write!(f, "tried to reallocate memory from {} to {}", old, new),
446 DeallocatedWrongMemoryKind(ref old, ref new) =>
447 write!(f, "tried to deallocate {} memory but gave {} as the kind", old, new),
448 Intrinsic(ref err) =>
449 write!(f, "{}", err),
451 write!(f, "tried to interpret an invalid 32-bit value as a char: {}", c),
452 AlignmentCheckFailed { required, has } =>
453 write!(f, "tried to access memory with alignment {}, but alignment {} is required",
454 has.abi(), required.abi()),
455 TypeNotPrimitive(ty) =>
456 write!(f, "expected primitive type, got {}", ty),
458 write!(f, "rustc layout computation failed: {:?}", err),
459 PathNotFound(ref path) =>
460 write!(f, "Cannot find path {:?}", path),
461 MachineError(ref inner) =>
462 write!(f, "{}", inner),
463 IncorrectAllocationInformation(size, size2, align, align2) =>
464 write!(f, "incorrect alloc info: expected size {} and align {}, got size {} and align {}", size.bytes(), align.abi(), size2.bytes(), align2.abi()),
465 _ => write!(f, "{}", self.description()),