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),
47 /// Emit a custom diagnostic without going through the miri-engine machinery
48 pub fn report_error<'tcx, 'mir>(
49 ecx: &InterpCx<'mir, 'tcx, Evaluator<'tcx>>,
50 mut e: InterpErrorInfo<'tcx>,
54 let (title, helps) = match &e.kind {
55 MachineStop(info) => {
56 let info = info.downcast_ref::<TerminationInfo>().expect("invalid MachineStop payload");
57 use TerminationInfo::*;
58 let title = match info {
59 Exit(code) => return Some(*code),
61 "abnormal termination",
62 UnsupportedInIsolation(_) =>
63 "unsupported operation",
64 ExperimentalUb { .. } =>
66 Deadlock => "deadlock",
68 let helps = match info {
69 UnsupportedInIsolation(_) =>
70 vec![format!("pass the flag `-Zmiri-disable-isolation` to disable isolation")],
71 ExperimentalUb { url, .. } =>
73 format!("this indicates a potential bug in the program: it performed an invalid operation, but the rules it violated are still experimental"),
74 format!("see {} for further information", url),
81 let title = match e.kind {
83 "unsupported operation",
84 UndefinedBehavior(_) =>
86 ResourceExhaustion(_) =>
87 "resource exhaustion",
89 bug!("This error should be impossible in Miri: {}", e),
91 let helps = match e.kind {
92 Unsupported(UnsupportedOpInfo::NoMirFor(..)) =>
93 vec![format!("make sure to use a Miri sysroot, which you can prepare with `cargo miri setup`")],
95 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")],
96 UndefinedBehavior(UndefinedBehaviorInfo::AlignmentCheckFailed { .. }) =>
98 format!("this usually indicates that your program performed an invalid operation and caused Undefined Behavior"),
99 format!("but alignment errors can also be false positives, see https://github.com/rust-lang/miri/issues/1074"),
101 UndefinedBehavior(_) =>
103 format!("this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior"),
104 format!("see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information"),
113 let msg = e.to_string();
114 report_msg(ecx, &format!("{}: {}", title, msg), msg, helps, true)
117 /// Report an error or note (depending on the `error` argument) at the current frame's current statement.
118 /// Also emits a full stacktrace of the interpreter stack.
119 fn report_msg<'tcx, 'mir>(
120 ecx: &InterpCx<'mir, 'tcx, Evaluator<'tcx>>,
123 mut helps: Vec<String>,
126 let span = if let Some(frame) = ecx.stack().last() {
127 frame.current_source_info().unwrap().span
131 let mut err = if error {
132 ecx.tcx.sess.struct_span_err(span, title)
134 ecx.tcx.sess.diagnostic().span_note_diag(span, title)
136 err.span_label(span, span_msg);
137 if !helps.is_empty() {
138 // Add visual separator before backtrace.
139 helps.last_mut().unwrap().push_str("\n");
145 let frames = ecx.generate_stacktrace();
146 for (idx, frame_info) in frames.iter().enumerate() {
147 let is_local = frame_info.instance.def_id().is_local();
148 // No span for non-local frames and the first frame (which is the error site).
149 if is_local && idx > 0 {
150 err.span_note(frame_info.span, &frame_info.to_string());
152 err.note(&frame_info.to_string());
158 for (i, frame) in ecx.stack().iter().enumerate() {
159 trace!("-------------------");
160 trace!("Frame {}", i);
161 trace!(" return: {:?}", frame.return_place.map(|p| *p));
162 for (i, local) in frame.locals.iter().enumerate() {
163 trace!(" local {}: {:?}", i, local.value);
166 // Let the reported error determine the return code.
171 static DIAGNOSTICS: RefCell<Vec<NonHaltingDiagnostic>> = RefCell::new(Vec::new());
174 /// Schedule a diagnostic for emitting. This function works even if you have no `InterpCx` available.
175 /// The diagnostic will be emitted after the current interpreter step is finished.
176 pub fn register_diagnostic(e: NonHaltingDiagnostic) {
177 DIAGNOSTICS.with(|diagnostics| diagnostics.borrow_mut().push(e));
180 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
181 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
182 /// Emit all diagnostics that were registed with `register_diagnostics`
183 fn process_diagnostics(&self) {
184 let this = self.eval_context_ref();
185 DIAGNOSTICS.with(|diagnostics| {
186 for e in diagnostics.borrow_mut().drain(..) {
187 use NonHaltingDiagnostic::*;
189 PoppedTrackedPointerTag(item) =>
190 format!("popped tracked tag for item {:?}", item),
191 CreatedAlloc(AllocId(id)) =>
192 format!("created allocation with id {}", id),
194 report_msg(this, "tracking was triggered", msg, vec![], false);