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::Display 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 PoppedPointerTag(Item),
44 CreatedCallId(CallId),
45 CreatedAlloc(AllocId),
49 /// Emit a custom diagnostic without going through the miri-engine machinery
50 pub fn report_error<'tcx, 'mir>(
51 ecx: &InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
52 e: InterpErrorInfo<'tcx>,
56 let (title, helps) = match &e.kind {
57 MachineStop(info) => {
58 let info = info.downcast_ref::<TerminationInfo>().expect("invalid MachineStop payload");
59 use TerminationInfo::*;
60 let title = match info {
61 Exit(code) => return Some(*code),
63 "abnormal termination",
64 UnsupportedInIsolation(_) =>
65 "unsupported operation",
66 ExperimentalUb { .. } =>
68 Deadlock => "deadlock",
70 let helps = match info {
71 UnsupportedInIsolation(_) =>
72 vec![format!("pass the flag `-Zmiri-disable-isolation` to disable isolation")],
73 ExperimentalUb { url, .. } =>
75 format!("this indicates a potential bug in the program: it performed an invalid operation, but the rules it violated are still experimental"),
76 format!("see {} for further information", url),
83 let title = match e.kind {
85 "unsupported operation",
86 UndefinedBehavior(_) =>
88 ResourceExhaustion(_) =>
89 "resource exhaustion",
91 bug!("This error should be impossible in Miri: {}", e),
93 let helps = match e.kind {
94 Unsupported(UnsupportedOpInfo::NoMirFor(..)) =>
95 vec![format!("make sure to use a Miri sysroot, which you can prepare with `cargo miri setup`")],
96 Unsupported(UnsupportedOpInfo::ReadBytesAsPointer) =>
97 panic!("`ReadBytesAsPointer` cannot be raised by Miri"),
99 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")],
100 UndefinedBehavior(UndefinedBehaviorInfo::AlignmentCheckFailed { .. }) =>
102 format!("this usually indicates that your program performed an invalid operation and caused Undefined Behavior"),
103 format!("but alignment errors can also be false positives, see https://github.com/rust-lang/miri/issues/1074"),
104 format!("you can disable the alignment check with `-Zmiri-disable-alignment-check`, but that could hide true bugs")
106 UndefinedBehavior(_) =>
108 format!("this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior"),
109 format!("see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information"),
118 let msg = e.to_string();
119 report_msg(ecx, &format!("{}: {}", title, msg), msg, helps, true);
121 // Extra output to help debug specific issues.
123 UndefinedBehavior(UndefinedBehaviorInfo::InvalidUninitBytes(Some(access))) => {
125 "Uninitialized read occurred at offsets 0x{:x}..0x{:x} into this allocation:",
126 access.uninit_ptr.offset.bytes(),
127 access.uninit_ptr.offset.bytes() + access.uninit_size.bytes(),
129 ecx.memory.dump_alloc(access.uninit_ptr.alloc_id);
138 /// Report an error or note (depending on the `error` argument) at the current frame's current statement.
139 /// Also emits a full stacktrace of the interpreter stack.
140 fn report_msg<'tcx, 'mir>(
141 ecx: &InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
144 mut helps: Vec<String>,
147 let span = if let Some(frame) = ecx.active_thread_stack().last() {
148 frame.current_source_info().unwrap().span
152 let mut err = if error {
153 ecx.tcx.sess.struct_span_err(span, title)
155 ecx.tcx.sess.diagnostic().span_note_diag(span, title)
157 err.span_label(span, span_msg);
158 if !helps.is_empty() {
159 // Add visual separator before backtrace.
160 helps.last_mut().unwrap().push_str("\n");
166 let frames = ecx.generate_stacktrace();
167 for (idx, frame_info) in frames.iter().enumerate() {
168 let is_local = frame_info.instance.def_id().is_local();
169 // No span for non-local frames and the first frame (which is the error site).
170 if is_local && idx > 0 {
171 err.span_note(frame_info.span, &frame_info.to_string());
173 err.note(&frame_info.to_string());
179 for (i, frame) in ecx.active_thread_stack().iter().enumerate() {
180 trace!("-------------------");
181 trace!("Frame {}", i);
182 trace!(" return: {:?}", frame.return_place.map(|p| *p));
183 for (i, local) in frame.locals.iter().enumerate() {
184 trace!(" local {}: {:?}", i, local.value);
190 static DIAGNOSTICS: RefCell<Vec<NonHaltingDiagnostic>> = RefCell::new(Vec::new());
193 /// Schedule a diagnostic for emitting. This function works even if you have no `InterpCx` available.
194 /// The diagnostic will be emitted after the current interpreter step is finished.
195 pub fn register_diagnostic(e: NonHaltingDiagnostic) {
196 DIAGNOSTICS.with(|diagnostics| diagnostics.borrow_mut().push(e));
199 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
200 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
201 /// Emit all diagnostics that were registed with `register_diagnostics`
202 fn process_diagnostics(&self) {
203 let this = self.eval_context_ref();
204 DIAGNOSTICS.with(|diagnostics| {
205 for e in diagnostics.borrow_mut().drain(..) {
206 use NonHaltingDiagnostic::*;
208 PoppedPointerTag(item) =>
209 format!("popped tracked tag for item {:?}", item),
211 format!("function call with id {}", id),
212 CreatedAlloc(AllocId(id)) =>
213 format!("created allocation with id {}", id),
214 FreedAlloc(AllocId(id)) =>
215 format!("freed allocation with id {}", id),
217 report_msg(this, "tracking was triggered", msg, vec![], false);