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 report_msg(ecx, &format!("{}: {}", title, msg), msg, helps, true);
120 // Extra output to help debug specific issues.
121 if let UndefinedBehavior(UndefinedBehaviorInfo::InvalidUndefBytes(Some(ptr))) = e.kind {
123 "Uninitialized read occurred at offset 0x{:x} into this allocation:",
126 ecx.memory.dump_alloc(ptr.alloc_id);
133 /// Report an error or note (depending on the `error` argument) at the current frame's current statement.
134 /// Also emits a full stacktrace of the interpreter stack.
135 fn report_msg<'tcx, 'mir>(
136 ecx: &InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
139 mut helps: Vec<String>,
142 let span = if let Some(frame) = ecx.active_thread_stack().last() {
143 frame.current_source_info().unwrap().span
147 let mut err = if error {
148 ecx.tcx.sess.struct_span_err(span, title)
150 ecx.tcx.sess.diagnostic().span_note_diag(span, title)
152 err.span_label(span, span_msg);
153 if !helps.is_empty() {
154 // Add visual separator before backtrace.
155 helps.last_mut().unwrap().push_str("\n");
161 let frames = ecx.generate_stacktrace();
162 for (idx, frame_info) in frames.iter().enumerate() {
163 let is_local = frame_info.instance.def_id().is_local();
164 // No span for non-local frames and the first frame (which is the error site).
165 if is_local && idx > 0 {
166 err.span_note(frame_info.span, &frame_info.to_string());
168 err.note(&frame_info.to_string());
174 for (i, frame) in ecx.active_thread_stack().iter().enumerate() {
175 trace!("-------------------");
176 trace!("Frame {}", i);
177 trace!(" return: {:?}", frame.return_place.map(|p| *p));
178 for (i, local) in frame.locals.iter().enumerate() {
179 trace!(" local {}: {:?}", i, local.value);
185 static DIAGNOSTICS: RefCell<Vec<NonHaltingDiagnostic>> = RefCell::new(Vec::new());
188 /// Schedule a diagnostic for emitting. This function works even if you have no `InterpCx` available.
189 /// The diagnostic will be emitted after the current interpreter step is finished.
190 pub fn register_diagnostic(e: NonHaltingDiagnostic) {
191 DIAGNOSTICS.with(|diagnostics| diagnostics.borrow_mut().push(e));
194 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
195 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
196 /// Emit all diagnostics that were registed with `register_diagnostics`
197 fn process_diagnostics(&self) {
198 let this = self.eval_context_ref();
199 DIAGNOSTICS.with(|diagnostics| {
200 for e in diagnostics.borrow_mut().drain(..) {
201 use NonHaltingDiagnostic::*;
203 PoppedTrackedPointerTag(item) =>
204 format!("popped tracked tag for item {:?}", item),
205 CreatedAlloc(AllocId(id)) =>
206 format!("created allocation with id {}", id),
207 FreedAlloc(AllocId(id)) =>
208 format!("freed allocation with id {}", id),
210 report_msg(this, "tracking was triggered", msg, vec![], false);