1 use std::cell::RefCell;
6 use rustc_span::DUMMY_SP;
10 /// Details of premature program termination.
11 pub enum TerminationInfo {
13 Abort(Option<String>),
14 UnsupportedInIsolation(String),
15 ExperimentalUb { msg: String, url: String },
19 impl fmt::Debug for TerminationInfo {
20 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
21 use TerminationInfo::*;
24 write!(f, "the evaluated program completed with exit code {}", code),
26 write!(f, "the evaluated program aborted execution"),
28 write!(f, "the evaluated program aborted execution: {}", msg),
29 UnsupportedInIsolation(msg) =>
31 ExperimentalUb { msg, .. } =>
34 write!(f, "the evaluated program deadlocked"),
39 impl MachineStopType for TerminationInfo {}
41 /// Miri specific diagnostics
42 pub enum NonHaltingDiagnostic {
43 PoppedTrackedPointerTag(Item),
44 CreatedAlloc(AllocId),
48 /// Emit a custom diagnostic without going through the miri-engine machinery
49 pub fn report_error<'tcx, 'mir>(
50 ecx: &InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
51 mut e: InterpErrorInfo<'tcx>,
55 let (title, helps) = match &e.kind {
56 MachineStop(info) => {
57 let info = info.downcast_ref::<TerminationInfo>().expect("invalid MachineStop payload");
58 use TerminationInfo::*;
59 let title = match info {
60 Exit(code) => return Some(*code),
62 "abnormal termination",
63 UnsupportedInIsolation(_) =>
64 "unsupported operation",
65 ExperimentalUb { .. } =>
67 Deadlock => "deadlock",
69 let helps = match info {
70 UnsupportedInIsolation(_) =>
71 vec![format!("pass the flag `-Zmiri-disable-isolation` to disable isolation")],
72 ExperimentalUb { url, .. } =>
74 format!("this indicates a potential bug in the program: it performed an invalid operation, but the rules it violated are still experimental"),
75 format!("see {} for further information", url),
82 let title = match e.kind {
84 "unsupported operation",
85 UndefinedBehavior(_) =>
87 ResourceExhaustion(_) =>
88 "resource exhaustion",
90 bug!("This error should be impossible in Miri: {}", e),
92 let helps = match e.kind {
93 Unsupported(UnsupportedOpInfo::NoMirFor(..)) =>
94 vec![format!("make sure to use a Miri sysroot, which you can prepare with `cargo miri setup`")],
95 Unsupported(UnsupportedOpInfo::ReadBytesAsPointer) =>
96 panic!("`ReadBytesAsPointer` cannot be raised by Miri"),
98 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")],
99 UndefinedBehavior(UndefinedBehaviorInfo::AlignmentCheckFailed { .. }) =>
101 format!("this usually indicates that your program performed an invalid operation and caused Undefined Behavior"),
102 format!("but alignment errors can also be false positives, see https://github.com/rust-lang/miri/issues/1074"),
103 format!("you can disable the alignment check with `-Zmiri-disable-alignment-check`, but that could hide true bugs")
105 UndefinedBehavior(_) =>
107 format!("this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior"),
108 format!("see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information"),
117 let msg = e.to_string();
118 let result = report_msg(ecx, &format!("{}: {}", title, msg), msg, helps, true);
120 if let UndefinedBehavior(UndefinedBehaviorInfo::InvalidUndefBytes(Some(ptr))) = e.kind {
122 "Uninitialized read occurred at offset 0x{:x} into this allocation:",
125 ecx.memory.dump_alloc(ptr.alloc_id);
132 /// Report an error or note (depending on the `error` argument) at the current frame's current statement.
133 /// Also emits a full stacktrace of the interpreter stack.
134 fn report_msg<'tcx, 'mir>(
135 ecx: &InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
138 mut helps: Vec<String>,
141 let span = if let Some(frame) = ecx.machine.stack.last() {
142 frame.current_source_info().unwrap().span
146 let mut err = if error {
147 ecx.tcx.sess.struct_span_err(span, title)
149 ecx.tcx.sess.diagnostic().span_note_diag(span, title)
151 err.span_label(span, span_msg);
152 if !helps.is_empty() {
153 // Add visual separator before backtrace.
154 helps.last_mut().unwrap().push_str("\n");
160 let frames = ecx.generate_stacktrace();
161 for (idx, frame_info) in frames.iter().enumerate() {
162 let is_local = frame_info.instance.def_id().is_local();
163 // No span for non-local frames and the first frame (which is the error site).
164 if is_local && idx > 0 {
165 err.span_note(frame_info.span, &frame_info.to_string());
167 err.note(&frame_info.to_string());
173 for (i, frame) in ecx.machine.stack.iter().enumerate() {
174 trace!("-------------------");
175 trace!("Frame {}", i);
176 trace!(" return: {:?}", frame.return_place.map(|p| *p));
177 for (i, local) in frame.locals.iter().enumerate() {
178 trace!(" local {}: {:?}", i, local.value);
181 // Let the reported error determine the return code.
186 static DIAGNOSTICS: RefCell<Vec<NonHaltingDiagnostic>> = RefCell::new(Vec::new());
189 /// Schedule a diagnostic for emitting. This function works even if you have no `InterpCx` available.
190 /// The diagnostic will be emitted after the current interpreter step is finished.
191 pub fn register_diagnostic(e: NonHaltingDiagnostic) {
192 DIAGNOSTICS.with(|diagnostics| diagnostics.borrow_mut().push(e));
195 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
196 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
197 /// Emit all diagnostics that were registed with `register_diagnostics`
198 fn process_diagnostics(&self) {
199 let this = self.eval_context_ref();
200 DIAGNOSTICS.with(|diagnostics| {
201 for e in diagnostics.borrow_mut().drain(..) {
202 use NonHaltingDiagnostic::*;
204 PoppedTrackedPointerTag(item) =>
205 format!("popped tracked tag for item {:?}", item),
206 CreatedAlloc(AllocId(id)) =>
207 format!("created allocation with id {}", id),
208 FreedAlloc(AllocId(id)) =>
209 format!("freed allocation with id {}", id),
211 report_msg(this, "tracking was triggered", msg, vec![], false);