1 use std::cell::RefCell;
6 use rustc_middle::ty::{self, TyCtxt};
7 use rustc_span::{source_map::DUMMY_SP, Span};
11 /// Details of premature program termination.
12 pub enum TerminationInfo {
14 Abort(Option<String>),
15 UnsupportedInIsolation(String),
16 ExperimentalUb { msg: String, url: String },
20 impl fmt::Display for TerminationInfo {
21 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
22 use TerminationInfo::*;
25 write!(f, "the evaluated program completed with exit code {}", code),
27 write!(f, "the evaluated program aborted execution"),
29 write!(f, "the evaluated program aborted execution: {}", msg),
30 UnsupportedInIsolation(msg) =>
32 ExperimentalUb { msg, .. } =>
35 write!(f, "the evaluated program deadlocked"),
40 impl MachineStopType for TerminationInfo {}
42 /// Miri specific diagnostics
43 pub enum NonHaltingDiagnostic {
44 PoppedPointerTag(Item),
45 CreatedCallId(CallId),
46 CreatedAlloc(AllocId),
50 /// Emit a custom diagnostic without going through the miri-engine machinery
51 pub fn report_error<'tcx, 'mir>(
52 ecx: &InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
53 e: InterpErrorInfo<'tcx>,
57 let (title, helps) = match &e.kind {
58 MachineStop(info) => {
59 let info = info.downcast_ref::<TerminationInfo>().expect("invalid MachineStop payload");
60 use TerminationInfo::*;
61 let title = match info {
62 Exit(code) => return Some(*code),
64 "abnormal termination",
65 UnsupportedInIsolation(_) =>
66 "unsupported operation",
67 ExperimentalUb { .. } =>
69 Deadlock => "deadlock",
71 let helps = match info {
72 UnsupportedInIsolation(_) =>
73 vec![format!("pass the flag `-Zmiri-disable-isolation` to disable isolation")],
74 ExperimentalUb { url, .. } =>
76 format!("this indicates a potential bug in the program: it performed an invalid operation, but the rules it violated are still experimental"),
77 format!("see {} for further information", url),
84 let title = match e.kind {
86 "unsupported operation",
87 UndefinedBehavior(_) =>
89 ResourceExhaustion(_) =>
90 "resource exhaustion",
92 bug!("This error should be impossible in Miri: {}", e),
94 let helps = match e.kind {
95 Unsupported(UnsupportedOpInfo::NoMirFor(..)) =>
96 vec![format!("make sure to use a Miri sysroot, which you can prepare with `cargo miri setup`")],
97 Unsupported(UnsupportedOpInfo::ReadBytesAsPointer | UnsupportedOpInfo::ThreadLocalStatic(_) | UnsupportedOpInfo::ReadExternStatic(_)) =>
98 panic!("Error should never be raised by Miri: {:?}", e.kind),
100 vec![format!("this is likely not a bug in the program; it indicates that the program performed an operation that the interpreter does not support")],
101 UndefinedBehavior(UndefinedBehaviorInfo::AlignmentCheckFailed { .. }) =>
103 format!("this usually indicates that your program performed an invalid operation and caused Undefined Behavior"),
104 format!("but alignment errors can also be false positives, see https://github.com/rust-lang/miri/issues/1074"),
105 format!("you can disable the alignment check with `-Zmiri-disable-alignment-check`, but that could hide true bugs")
107 UndefinedBehavior(_) =>
109 format!("this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior"),
110 format!("see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information"),
119 let msg = e.to_string();
120 report_msg(*ecx.tcx, /*error*/true, &format!("{}: {}", title, msg), msg, helps, &ecx.generate_stacktrace());
122 // Debug-dump all locals.
123 for (i, frame) in ecx.active_thread_stack().iter().enumerate() {
124 trace!("-------------------");
125 trace!("Frame {}", i);
126 trace!(" return: {:?}", frame.return_place.map(|p| *p));
127 for (i, local) in frame.locals.iter().enumerate() {
128 trace!(" local {}: {:?}", i, local.value);
132 // Extra output to help debug specific issues.
134 UndefinedBehavior(UndefinedBehaviorInfo::InvalidUninitBytes(Some(access))) => {
136 "Uninitialized read occurred at offsets 0x{:x}..0x{:x} into this allocation:",
137 access.uninit_ptr.offset.bytes(),
138 access.uninit_ptr.offset.bytes() + access.uninit_size.bytes(),
140 ecx.memory.dump_alloc(access.uninit_ptr.alloc_id);
149 /// Report an error or note (depending on the `error` argument) with the given stacktrace.
150 /// Also emits a full stacktrace of the interpreter stack.
156 mut helps: Vec<String>,
157 stacktrace: &[FrameInfo<'tcx>],
159 let span = stacktrace.first().map_or(DUMMY_SP, |fi| fi.span);
160 let mut err = if error {
161 tcx.sess.struct_span_err(span, title)
163 tcx.sess.diagnostic().span_note_diag(span, title)
165 err.span_label(span, span_msg);
166 if !helps.is_empty() {
167 // Add visual separator before backtrace.
168 helps.last_mut().unwrap().push_str("\n");
174 for (idx, frame_info) in stacktrace.iter().enumerate() {
175 let is_local = frame_info.instance.def_id().is_local();
176 // No span for non-local frames and the first frame (which is the error site).
177 if is_local && idx > 0 {
178 err.span_note(frame_info.span, &frame_info.to_string());
180 err.note(&frame_info.to_string());
188 static DIAGNOSTICS: RefCell<Vec<NonHaltingDiagnostic>> = RefCell::new(Vec::new());
191 /// Schedule a diagnostic for emitting. This function works even if you have no `InterpCx` available.
192 /// The diagnostic will be emitted after the current interpreter step is finished.
193 pub fn register_diagnostic(e: NonHaltingDiagnostic) {
194 DIAGNOSTICS.with(|diagnostics| diagnostics.borrow_mut().push(e));
197 /// Remember enough about the topmost frame so that we can restore the stack
198 /// after a step was taken.
199 pub struct TopFrameInfo<'tcx> {
201 instance: ty::Instance<'tcx>,
205 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
206 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
207 fn preprocess_diagnostics(&self) -> TopFrameInfo<'tcx> {
208 // Ensure we have no lingering diagnostics.
209 DIAGNOSTICS.with(|diagnostics| assert!(diagnostics.borrow().is_empty()));
211 let this = self.eval_context_ref();
212 let frame = this.frame();
215 stack_size: this.active_thread_stack().len(),
216 instance: frame.instance,
217 span: frame.current_source_info().map_or(DUMMY_SP, |si| si.span),
221 /// Emit all diagnostics that were registed with `register_diagnostics`
222 fn process_diagnostics(&self, info: TopFrameInfo<'tcx>) {
223 let this = self.eval_context_ref();
224 DIAGNOSTICS.with(|diagnostics| {
225 let mut diagnostics = diagnostics.borrow_mut();
226 if diagnostics.is_empty() {
229 // We need to fix up the stack trace, because the machine has already
230 // stepped to the next statement.
231 let mut stacktrace = this.generate_stacktrace();
232 // Remove newly pushed frames.
233 while stacktrace.len() > info.stack_size {
234 stacktrace.remove(0);
236 // Add popped frame back.
237 if stacktrace.len() < info.stack_size {
238 assert!(stacktrace.len() == info.stack_size-1, "we should never pop more than one frame at once");
239 let frame_info = FrameInfo {
240 instance: info.instance,
244 stacktrace.insert(0, frame_info);
246 // Adjust topmost frame.
247 stacktrace[0].span = info.span;
248 assert_eq!(stacktrace[0].instance, info.instance, "we should not pop and push a frame in one step");
252 for e in diagnostics.drain(..) {
253 use NonHaltingDiagnostic::*;
255 PoppedPointerTag(item) =>
256 format!("popped tracked tag for item {:?}", item),
258 format!("function call with id {}", id),
259 CreatedAlloc(AllocId(id)) =>
260 format!("created allocation with id {}", id),
261 FreedAlloc(AllocId(id)) =>
262 format!("freed allocation with id {}", id),
264 report_msg(*this.tcx, /*error*/false, "tracking was triggered", msg, vec![], &stacktrace);