]>
Commit | Line | Data |
---|---|---|
1b1a35ee | 1 | use super::{AllocId, ConstAlloc, Pointer, Scalar}; |
ea8adc8c | 2 | |
74b04a01 | 3 | use crate::mir::interpret::ConstValue; |
3dfed10e | 4 | use crate::ty::{layout, query::TyCtxtAt, tls, FnSig, Ty}; |
ea8adc8c | 5 | |
ba9703b0 | 6 | use rustc_data_structures::sync::Lock; |
f9f354fc | 7 | use rustc_errors::{pluralize, struct_span_err, DiagnosticBuilder, ErrorReported}; |
e1599b0c | 8 | use rustc_macros::HashStable; |
ba9703b0 | 9 | use rustc_session::CtfeBacktrace; |
3dfed10e | 10 | use rustc_span::def_id::DefId; |
ba9703b0 | 11 | use rustc_target::abi::{Align, Size}; |
6a06907d | 12 | use std::{any::Any, backtrace::Backtrace, fmt}; |
e1599b0c | 13 | |
3dfed10e | 14 | #[derive(Debug, Copy, Clone, PartialEq, Eq, HashStable, TyEncodable, TyDecodable)] |
a1dfa0c6 | 15 | pub enum ErrorHandled { |
ba9703b0 XL |
16 | /// Already reported an error for this evaluation, and the compilation is |
17 | /// *guaranteed* to fail. Warnings/lints *must not* produce `Reported`. | |
18 | Reported(ErrorReported), | |
19 | /// Already emitted a lint for this evaluation. | |
20 | Linted, | |
a1dfa0c6 XL |
21 | /// Don't emit an error, the evaluation failed because the MIR was generic |
22 | /// and the substs didn't fully monomorphize it. | |
23 | TooGeneric, | |
24 | } | |
25 | ||
1b1a35ee XL |
26 | impl From<ErrorReported> for ErrorHandled { |
27 | fn from(err: ErrorReported) -> ErrorHandled { | |
28 | ErrorHandled::Reported(err) | |
29 | } | |
30 | } | |
31 | ||
fc512014 | 32 | TrivialTypeFoldableAndLiftImpls! { |
dc9dc135 XL |
33 | ErrorHandled, |
34 | } | |
35 | ||
1b1a35ee XL |
36 | pub type EvalToAllocationRawResult<'tcx> = Result<ConstAlloc<'tcx>, ErrorHandled>; |
37 | pub type EvalToConstValueResult<'tcx> = Result<ConstValue<'tcx>, ErrorHandled>; | |
8faf50e0 | 38 | |
dc9dc135 | 39 | pub fn struct_error<'tcx>(tcx: TyCtxtAt<'tcx>, msg: &str) -> DiagnosticBuilder<'tcx> { |
8faf50e0 XL |
40 | struct_span_err!(tcx.sess, tcx.span, E0080, "{}", msg) |
41 | } | |
42 | ||
6a06907d XL |
43 | #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] |
44 | static_assert_size!(InterpErrorInfo<'_>, 8); | |
45 | ||
dc9dc135 | 46 | /// Packages the kind of error we got from the const code interpreter |
60c5eb7d | 47 | /// up with a Rust-level backtrace of where the error occurred. |
cdc7bbd5 XL |
48 | /// These should always be constructed by calling `.into()` on |
49 | /// a `InterpError`. In `rustc_mir::interpret`, we have `throw_err_*` | |
416331ca | 50 | /// macros for this. |
60c5eb7d | 51 | #[derive(Debug)] |
6a06907d XL |
52 | pub struct InterpErrorInfo<'tcx>(Box<InterpErrorInfoInner<'tcx>>); |
53 | ||
54 | #[derive(Debug)] | |
55 | struct InterpErrorInfoInner<'tcx> { | |
56 | kind: InterpError<'tcx>, | |
dc9dc135 | 57 | backtrace: Option<Box<Backtrace>>, |
a1dfa0c6 XL |
58 | } |
59 | ||
416331ca XL |
60 | impl fmt::Display for InterpErrorInfo<'_> { |
61 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | |
6a06907d | 62 | write!(f, "{}", self.0.kind) |
416331ca XL |
63 | } |
64 | } | |
65 | ||
6a06907d | 66 | impl InterpErrorInfo<'tcx> { |
f9f354fc | 67 | pub fn print_backtrace(&self) { |
6a06907d | 68 | if let Some(backtrace) = self.0.backtrace.as_ref() { |
f9f354fc | 69 | print_backtrace(backtrace); |
a1dfa0c6 XL |
70 | } |
71 | } | |
6a06907d XL |
72 | |
73 | pub fn into_kind(self) -> InterpError<'tcx> { | |
74 | let InterpErrorInfo(box InterpErrorInfoInner { kind, .. }) = self; | |
75 | kind | |
76 | } | |
77 | ||
78 | #[inline] | |
79 | pub fn kind(&self) -> &InterpError<'tcx> { | |
80 | &self.0.kind | |
81 | } | |
a1dfa0c6 XL |
82 | } |
83 | ||
f9f354fc XL |
84 | fn print_backtrace(backtrace: &Backtrace) { |
85 | eprintln!("\n\nAn error occurred in miri:\n{}", backtrace); | |
ea8adc8c XL |
86 | } |
87 | ||
74b04a01 | 88 | impl From<ErrorHandled> for InterpErrorInfo<'_> { |
e1599b0c XL |
89 | fn from(err: ErrorHandled) -> Self { |
90 | match err { | |
ba9703b0 XL |
91 | ErrorHandled::Reported(ErrorReported) | ErrorHandled::Linted => { |
92 | err_inval!(ReferencedConstant) | |
93 | } | |
e1599b0c | 94 | ErrorHandled::TooGeneric => err_inval!(TooGeneric), |
dfeec247 XL |
95 | } |
96 | .into() | |
e1599b0c XL |
97 | } |
98 | } | |
99 | ||
29967ef6 XL |
100 | impl From<ErrorReported> for InterpErrorInfo<'_> { |
101 | fn from(err: ErrorReported) -> Self { | |
102 | InterpError::InvalidProgram(InvalidProgramInfo::AlreadyReported(err)).into() | |
103 | } | |
104 | } | |
105 | ||
416331ca XL |
106 | impl<'tcx> From<InterpError<'tcx>> for InterpErrorInfo<'tcx> { |
107 | fn from(kind: InterpError<'tcx>) -> Self { | |
3dfed10e XL |
108 | let capture_backtrace = tls::with_opt(|tcx| { |
109 | if let Some(tcx) = tcx { | |
110 | *Lock::borrow(&tcx.sess.ctfe_backtrace) | |
ba9703b0 XL |
111 | } else { |
112 | CtfeBacktrace::Disabled | |
113 | } | |
114 | }); | |
a1dfa0c6 | 115 | |
ba9703b0 XL |
116 | let backtrace = match capture_backtrace { |
117 | CtfeBacktrace::Disabled => None, | |
f9f354fc | 118 | CtfeBacktrace::Capture => Some(Box::new(Backtrace::force_capture())), |
ba9703b0 XL |
119 | CtfeBacktrace::Immediate => { |
120 | // Print it now. | |
f9f354fc XL |
121 | let backtrace = Backtrace::force_capture(); |
122 | print_backtrace(&backtrace); | |
ba9703b0 | 123 | None |
dfeec247 | 124 | } |
a1dfa0c6 | 125 | }; |
ba9703b0 | 126 | |
6a06907d | 127 | InterpErrorInfo(Box::new(InterpErrorInfoInner { kind, backtrace })) |
ea8adc8c XL |
128 | } |
129 | } | |
130 | ||
e1599b0c XL |
131 | /// Error information for when the program we executed turned out not to actually be a valid |
132 | /// program. This cannot happen in stand-alone Miri, but it can happen during CTFE/ConstProp | |
133 | /// where we work on generic code or execution does not have all information available. | |
416331ca XL |
134 | pub enum InvalidProgramInfo<'tcx> { |
135 | /// Resolution can fail if we are in a too generic context. | |
136 | TooGeneric, | |
137 | /// Cannot compute this constant because it depends on another one | |
138 | /// which already produced an error. | |
139 | ReferencedConstant, | |
29967ef6 XL |
140 | /// Abort in case errors are already reported. |
141 | AlreadyReported(ErrorReported), | |
416331ca XL |
142 | /// An error occurred during layout computation. |
143 | Layout(layout::LayoutError<'tcx>), | |
ba9703b0 XL |
144 | /// An invalid transmute happened. |
145 | TransmuteSizeDiff(Ty<'tcx>, Ty<'tcx>), | |
5869c6ff XL |
146 | /// SizeOf of unsized type was requested. |
147 | SizeOfUnsizedType(Ty<'tcx>), | |
416331ca | 148 | } |
b7449926 | 149 | |
f9f354fc | 150 | impl fmt::Display for InvalidProgramInfo<'_> { |
416331ca XL |
151 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
152 | use InvalidProgramInfo::*; | |
153 | match self { | |
dfeec247 XL |
154 | TooGeneric => write!(f, "encountered overly generic constant"), |
155 | ReferencedConstant => write!(f, "referenced constant has errors"), | |
29967ef6 | 156 | AlreadyReported(ErrorReported) => { |
ba9703b0 XL |
157 | write!(f, "encountered constants with type errors, stopping evaluation") |
158 | } | |
dfeec247 | 159 | Layout(ref err) => write!(f, "{}", err), |
ba9703b0 XL |
160 | TransmuteSizeDiff(from_ty, to_ty) => write!( |
161 | f, | |
162 | "transmuting `{}` to `{}` is not possible, because these types do not have the same size", | |
163 | from_ty, to_ty | |
164 | ), | |
5869c6ff | 165 | SizeOfUnsizedType(ty) => write!(f, "size_of called on unsized type `{}`", ty), |
416331ca XL |
166 | } |
167 | } | |
168 | } | |
169 | ||
f9f354fc | 170 | /// Details of why a pointer had to be in-bounds. |
3dfed10e | 171 | #[derive(Debug, Copy, Clone, TyEncodable, TyDecodable, HashStable)] |
f9f354fc | 172 | pub enum CheckInAllocMsg { |
17df50a5 | 173 | /// We are access memory. |
f9f354fc | 174 | MemoryAccessTest, |
17df50a5 | 175 | /// We are doing pointer arithmetic. |
f9f354fc | 176 | PointerArithmeticTest, |
17df50a5 | 177 | /// None of the above -- generic/unspecific inbounds test. |
f9f354fc XL |
178 | InboundsTest, |
179 | } | |
180 | ||
181 | impl fmt::Display for CheckInAllocMsg { | |
182 | /// When this is printed as an error the context looks like this | |
17df50a5 | 183 | /// "{msg}pointer must be in-bounds at offset..." |
f9f354fc XL |
184 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
185 | write!( | |
186 | f, | |
187 | "{}", | |
188 | match *self { | |
17df50a5 XL |
189 | CheckInAllocMsg::MemoryAccessTest => "memory access failed: ", |
190 | CheckInAllocMsg::PointerArithmeticTest => "pointer arithmetic failed: ", | |
191 | CheckInAllocMsg::InboundsTest => "", | |
f9f354fc XL |
192 | } |
193 | ) | |
194 | } | |
195 | } | |
196 | ||
197 | /// Details of an access to uninitialized bytes where it is not allowed. | |
198 | #[derive(Debug)] | |
199 | pub struct UninitBytesAccess { | |
200 | /// Location of the original memory access. | |
17df50a5 | 201 | pub access_offset: Size, |
f9f354fc XL |
202 | /// Size of the original memory access. |
203 | pub access_size: Size, | |
204 | /// Location of the first uninitialized byte that was accessed. | |
17df50a5 | 205 | pub uninit_offset: Size, |
f9f354fc XL |
206 | /// Number of consecutive uninitialized bytes that were accessed. |
207 | pub uninit_size: Size, | |
208 | } | |
209 | ||
e1599b0c | 210 | /// Error information for when the program caused Undefined Behavior. |
f9f354fc | 211 | pub enum UndefinedBehaviorInfo<'tcx> { |
416331ca XL |
212 | /// Free-form case. Only for errors that are never caught! |
213 | Ub(String), | |
416331ca XL |
214 | /// Unreachable code was executed. |
215 | Unreachable, | |
60c5eb7d | 216 | /// A slice/array index projection went out-of-bounds. |
ba9703b0 XL |
217 | BoundsCheckFailed { |
218 | len: u64, | |
219 | index: u64, | |
220 | }, | |
60c5eb7d XL |
221 | /// Something was divided by 0 (x / 0). |
222 | DivisionByZero, | |
223 | /// Something was "remainded" by 0 (x % 0). | |
224 | RemainderByZero, | |
225 | /// Overflowing inbounds pointer arithmetic. | |
226 | PointerArithOverflow, | |
74b04a01 XL |
227 | /// Invalid metadata in a wide pointer (using `str` to avoid allocations). |
228 | InvalidMeta(&'static str), | |
f9f354fc XL |
229 | /// Invalid drop function in vtable. |
230 | InvalidDropFn(FnSig<'tcx>), | |
ba9703b0 XL |
231 | /// Reading a C string that does not end within its allocation. |
232 | UnterminatedCString(Pointer), | |
233 | /// Dereferencing a dangling pointer after it got freed. | |
234 | PointerUseAfterFree(AllocId), | |
235 | /// Used a pointer outside the bounds it is valid for. | |
236 | PointerOutOfBounds { | |
237 | ptr: Pointer, | |
238 | msg: CheckInAllocMsg, | |
239 | allocation_size: Size, | |
240 | }, | |
f9f354fc XL |
241 | /// Using an integer as a pointer in the wrong way. |
242 | DanglingIntPointer(u64, CheckInAllocMsg), | |
ba9703b0 XL |
243 | /// Used a pointer with bad alignment. |
244 | AlignmentCheckFailed { | |
245 | required: Align, | |
246 | has: Align, | |
247 | }, | |
ba9703b0 XL |
248 | /// Writing to read-only memory. |
249 | WriteToReadOnly(AllocId), | |
ba9703b0 XL |
250 | // Trying to access the data behind a function pointer. |
251 | DerefFunctionPointer(AllocId), | |
252 | /// The value validity check found a problem. | |
253 | /// Should only be thrown by `validity.rs` and always point out which part of the value | |
254 | /// is the problem. | |
255 | ValidationFailure(String), | |
256 | /// Using a non-boolean `u8` as bool. | |
257 | InvalidBool(u8), | |
258 | /// Using a non-character `u32` as character. | |
259 | InvalidChar(u32), | |
f035d41b XL |
260 | /// The tag of an enum does not encode an actual discriminant. |
261 | InvalidTag(Scalar), | |
f9f354fc XL |
262 | /// Using a pointer-not-to-a-function as function pointer. |
263 | InvalidFunctionPointer(Pointer), | |
264 | /// Using a string that is not valid UTF-8, | |
265 | InvalidStr(std::str::Utf8Error), | |
ba9703b0 | 266 | /// Using uninitialized data where it is not allowed. |
17df50a5 | 267 | InvalidUninitBytes(Option<(AllocId, UninitBytesAccess)>), |
ba9703b0 XL |
268 | /// Working with a local that is not currently live. |
269 | DeadLocal, | |
f9f354fc XL |
270 | /// Data size is not equal to target size. |
271 | ScalarSizeMismatch { | |
272 | target_size: u64, | |
273 | data_size: u64, | |
274 | }, | |
416331ca | 275 | } |
48663c56 | 276 | |
f9f354fc | 277 | impl fmt::Display for UndefinedBehaviorInfo<'_> { |
416331ca XL |
278 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
279 | use UndefinedBehaviorInfo::*; | |
280 | match self { | |
ba9703b0 | 281 | Ub(msg) => write!(f, "{}", msg), |
dfeec247 | 282 | Unreachable => write!(f, "entering unreachable code"), |
f9f354fc XL |
283 | BoundsCheckFailed { ref len, ref index } => { |
284 | write!(f, "indexing out of bounds: the len is {} but the index is {}", len, index) | |
285 | } | |
dfeec247 XL |
286 | DivisionByZero => write!(f, "dividing by zero"), |
287 | RemainderByZero => write!(f, "calculating the remainder with a divisor of zero"), | |
288 | PointerArithOverflow => write!(f, "overflowing in-bounds pointer arithmetic"), | |
74b04a01 | 289 | InvalidMeta(msg) => write!(f, "invalid metadata in wide pointer: {}", msg), |
f9f354fc XL |
290 | InvalidDropFn(sig) => write!( |
291 | f, | |
292 | "invalid drop function signature: got {}, expected exactly one argument which must be a pointer type", | |
293 | sig | |
294 | ), | |
ba9703b0 XL |
295 | UnterminatedCString(p) => write!( |
296 | f, | |
f9f354fc | 297 | "reading a null-terminated string starting at {} with no null found before end of allocation", |
ba9703b0 XL |
298 | p, |
299 | ), | |
300 | PointerUseAfterFree(a) => { | |
f9f354fc | 301 | write!(f, "pointer to {} was dereferenced after this allocation got freed", a) |
ba9703b0 XL |
302 | } |
303 | PointerOutOfBounds { ptr, msg, allocation_size } => write!( | |
304 | f, | |
17df50a5 | 305 | "{}pointer must be in-bounds at offset {}, \ |
ba9703b0 XL |
306 | but is outside bounds of {} which has size {}", |
307 | msg, | |
308 | ptr.offset.bytes(), | |
309 | ptr.alloc_id, | |
310 | allocation_size.bytes() | |
311 | ), | |
17df50a5 XL |
312 | DanglingIntPointer(0, CheckInAllocMsg::InboundsTest) => { |
313 | write!(f, "null pointer is not a valid pointer for this operation") | |
f9f354fc XL |
314 | } |
315 | DanglingIntPointer(i, msg) => { | |
17df50a5 | 316 | write!(f, "{}0x{:x} is not a valid pointer", msg, i) |
f9f354fc | 317 | } |
ba9703b0 XL |
318 | AlignmentCheckFailed { required, has } => write!( |
319 | f, | |
320 | "accessing memory with alignment {}, but alignment {} is required", | |
321 | has.bytes(), | |
322 | required.bytes() | |
323 | ), | |
f9f354fc XL |
324 | WriteToReadOnly(a) => write!(f, "writing to {} which is read-only", a), |
325 | DerefFunctionPointer(a) => write!(f, "accessing {} which contains a function", a), | |
326 | ValidationFailure(ref err) => write!(f, "type validation failed: {}", err), | |
327 | InvalidBool(b) => { | |
328 | write!(f, "interpreting an invalid 8-bit value as a bool: 0x{:02x}", b) | |
329 | } | |
330 | InvalidChar(c) => { | |
331 | write!(f, "interpreting an invalid 32-bit value as a char: 0x{:08x}", c) | |
332 | } | |
f035d41b | 333 | InvalidTag(val) => write!(f, "enum value has invalid tag: {}", val), |
ba9703b0 | 334 | InvalidFunctionPointer(p) => { |
f9f354fc | 335 | write!(f, "using {} as function pointer but it does not point to a function", p) |
ba9703b0 | 336 | } |
f9f354fc | 337 | InvalidStr(err) => write!(f, "this string is not valid UTF-8: {}", err), |
17df50a5 | 338 | InvalidUninitBytes(Some((alloc, access))) => write!( |
ba9703b0 | 339 | f, |
f9f354fc XL |
340 | "reading {} byte{} of memory starting at {}, \ |
341 | but {} byte{} {} uninitialized starting at {}, \ | |
342 | and this operation requires initialized memory", | |
343 | access.access_size.bytes(), | |
344 | pluralize!(access.access_size.bytes()), | |
17df50a5 | 345 | Pointer::new(*alloc, access.access_offset), |
f9f354fc XL |
346 | access.uninit_size.bytes(), |
347 | pluralize!(access.uninit_size.bytes()), | |
348 | if access.uninit_size.bytes() != 1 { "are" } else { "is" }, | |
17df50a5 | 349 | Pointer::new(*alloc, access.uninit_offset), |
ba9703b0 | 350 | ), |
f9f354fc | 351 | InvalidUninitBytes(None) => write!( |
ba9703b0 XL |
352 | f, |
353 | "using uninitialized data, but this operation requires initialized memory" | |
354 | ), | |
355 | DeadLocal => write!(f, "accessing a dead local variable"), | |
f9f354fc XL |
356 | ScalarSizeMismatch { target_size, data_size } => write!( |
357 | f, | |
358 | "scalar size mismatch: expected {} bytes but got {} bytes instead", | |
359 | target_size, data_size | |
360 | ), | |
416331ca XL |
361 | } |
362 | } | |
363 | } | |
364 | ||
e1599b0c XL |
365 | /// Error information for when the program did something that might (or might not) be correct |
366 | /// to do according to the Rust spec, but due to limitations in the interpreter, the | |
367 | /// operation could not be carried out. These limitations can differ between CTFE and the | |
f9f354fc | 368 | /// Miri engine, e.g., CTFE does not support dereferencing pointers at integral addresses. |
ba9703b0 | 369 | pub enum UnsupportedOpInfo { |
416331ca XL |
370 | /// Free-form case. Only for errors that are never caught! |
371 | Unsupported(String), | |
ba9703b0 XL |
372 | /// Could not find MIR for a function. |
373 | NoMirFor(DefId), | |
374 | /// Encountered a pointer where we needed raw bytes. | |
ea8adc8c | 375 | ReadPointerAsBytes, |
f9f354fc XL |
376 | // |
377 | // The variants below are only reachable from CTFE/const prop, miri will never emit them. | |
378 | // | |
ba9703b0 | 379 | /// Encountered raw bytes where we needed a pointer. |
ea8adc8c | 380 | ReadBytesAsPointer, |
f9f354fc XL |
381 | /// Accessing thread local statics |
382 | ThreadLocalStatic(DefId), | |
3dfed10e XL |
383 | /// Accessing an unsupported extern static. |
384 | ReadExternStatic(DefId), | |
ea8adc8c XL |
385 | } |
386 | ||
f9f354fc | 387 | impl fmt::Display for UnsupportedOpInfo { |
a1dfa0c6 | 388 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
416331ca XL |
389 | use UnsupportedOpInfo::*; |
390 | match self { | |
dfeec247 | 391 | Unsupported(ref msg) => write!(f, "{}", msg), |
3dfed10e | 392 | ReadExternStatic(did) => write!(f, "cannot read from extern static ({:?})", did), |
ba9703b0 XL |
393 | NoMirFor(did) => write!(f, "no MIR body is available for {:?}", did), |
394 | ReadPointerAsBytes => write!(f, "unable to turn pointer into raw bytes",), | |
395 | ReadBytesAsPointer => write!(f, "unable to turn bytes into a pointer"), | |
f9f354fc | 396 | ThreadLocalStatic(did) => write!(f, "cannot access thread local static ({:?})", did), |
416331ca XL |
397 | } |
398 | } | |
399 | } | |
400 | ||
e1599b0c XL |
401 | /// Error information for when the program exhausted the resources granted to it |
402 | /// by the interpreter. | |
416331ca XL |
403 | pub enum ResourceExhaustionInfo { |
404 | /// The stack grew too big. | |
405 | StackFrameLimitReached, | |
ba9703b0 XL |
406 | /// The program ran for too long. |
407 | /// | |
408 | /// The exact limit is set by the `const_eval_limit` attribute. | |
409 | StepLimitReached, | |
416331ca XL |
410 | } |
411 | ||
f9f354fc | 412 | impl fmt::Display for ResourceExhaustionInfo { |
416331ca XL |
413 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
414 | use ResourceExhaustionInfo::*; | |
415 | match self { | |
dfeec247 XL |
416 | StackFrameLimitReached => { |
417 | write!(f, "reached the configured maximum number of stack frames") | |
418 | } | |
ba9703b0 XL |
419 | StepLimitReached => { |
420 | write!(f, "exceeded interpreter step limit (see `#[const_eval_limit]`)") | |
421 | } | |
416331ca XL |
422 | } |
423 | } | |
424 | } | |
425 | ||
ba9703b0 XL |
426 | /// A trait to work around not having trait object upcasting. |
427 | pub trait AsAny: Any { | |
428 | fn as_any(&self) -> &dyn Any; | |
429 | } | |
ba9703b0 XL |
430 | impl<T: Any> AsAny for T { |
431 | #[inline(always)] | |
432 | fn as_any(&self) -> &dyn Any { | |
433 | self | |
434 | } | |
435 | } | |
436 | ||
437 | /// A trait for machine-specific errors (or other "machine stop" conditions). | |
17df50a5 XL |
438 | pub trait MachineStopType: AsAny + fmt::Display + Send { |
439 | /// If `true`, emit a hard error instead of going through the `CONST_ERR` lint | |
440 | fn is_hard_err(&self) -> bool { | |
441 | false | |
442 | } | |
443 | } | |
ba9703b0 XL |
444 | |
445 | impl dyn MachineStopType { | |
446 | #[inline(always)] | |
447 | pub fn downcast_ref<T: Any>(&self) -> Option<&T> { | |
448 | self.as_any().downcast_ref() | |
449 | } | |
450 | } | |
451 | ||
6a06907d | 452 | #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] |
17df50a5 | 453 | static_assert_size!(InterpError<'_>, 64); |
f9f354fc | 454 | |
416331ca | 455 | pub enum InterpError<'tcx> { |
416331ca | 456 | /// The program caused undefined behavior. |
f9f354fc | 457 | UndefinedBehavior(UndefinedBehaviorInfo<'tcx>), |
416331ca XL |
458 | /// The program did something the interpreter does not support (some of these *might* be UB |
459 | /// but the interpreter is not sure). | |
ba9703b0 | 460 | Unsupported(UnsupportedOpInfo), |
60c5eb7d | 461 | /// The program was invalid (ill-typed, bad MIR, not sufficiently monomorphized, ...). |
416331ca XL |
462 | InvalidProgram(InvalidProgramInfo<'tcx>), |
463 | /// The program exhausted the interpreter's resources (stack/heap too big, | |
60c5eb7d | 464 | /// execution takes too long, ...). |
416331ca | 465 | ResourceExhaustion(ResourceExhaustionInfo), |
60c5eb7d XL |
466 | /// Stop execution for a machine-controlled reason. This is never raised by |
467 | /// the core engine itself. | |
ba9703b0 | 468 | MachineStop(Box<dyn MachineStopType>), |
416331ca XL |
469 | } |
470 | ||
471 | pub type InterpResult<'tcx, T = ()> = Result<T, InterpErrorInfo<'tcx>>; | |
472 | ||
473 | impl fmt::Display for InterpError<'_> { | |
474 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | |
f9f354fc XL |
475 | use InterpError::*; |
476 | match *self { | |
477 | Unsupported(ref msg) => write!(f, "{}", msg), | |
478 | InvalidProgram(ref msg) => write!(f, "{}", msg), | |
479 | UndefinedBehavior(ref msg) => write!(f, "{}", msg), | |
480 | ResourceExhaustion(ref msg) => write!(f, "{}", msg), | |
481 | MachineStop(ref msg) => write!(f, "{}", msg), | |
482 | } | |
416331ca XL |
483 | } |
484 | } | |
485 | ||
f9f354fc | 486 | // Forward `Debug` to `Display`, so it does not look awful. |
416331ca XL |
487 | impl fmt::Debug for InterpError<'_> { |
488 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | |
f9f354fc | 489 | fmt::Display::fmt(self, f) |
74b04a01 XL |
490 | } |
491 | } | |
492 | ||
493 | impl InterpError<'_> { | |
6a06907d XL |
494 | /// Some errors to string formatting even if the error is never printed. |
495 | /// To avoid performance issues, there are places where we want to be sure to never raise these formatting errors, | |
496 | /// so this method lets us detect them and `bug!` on unexpected errors. | |
497 | pub fn formatted_string(&self) -> bool { | |
74b04a01 | 498 | match self { |
ba9703b0 XL |
499 | InterpError::Unsupported(UnsupportedOpInfo::Unsupported(_)) |
500 | | InterpError::UndefinedBehavior(UndefinedBehaviorInfo::ValidationFailure(_)) | |
6a06907d | 501 | | InterpError::UndefinedBehavior(UndefinedBehaviorInfo::Ub(_)) => true, |
74b04a01 | 502 | _ => false, |
ea8adc8c XL |
503 | } |
504 | } | |
505 | } |