]> git.lizzy.rs Git - rust.git/blob - src/diagnostics.rs
Move the stack to the evaluator to make Miri compile with the newest Rustc.
[rust.git] / src / diagnostics.rs
1 use std::cell::RefCell;
2 use std::fmt;
3
4 use log::trace;
5
6 use rustc_span::DUMMY_SP;
7
8 use crate::*;
9
10 /// Details of premature program termination.
11 pub enum TerminationInfo {
12     Exit(i64),
13     Abort(Option<String>),
14     UnsupportedInIsolation(String),
15     ExperimentalUb { msg: String, url: String },
16     Deadlock,
17 }
18
19 impl fmt::Debug for TerminationInfo {
20     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
21         use TerminationInfo::*;
22         match self {
23             Exit(code) =>
24                 write!(f, "the evaluated program completed with exit code {}", code),
25             Abort(None) =>
26                 write!(f, "the evaluated program aborted execution"),
27             Abort(Some(msg)) =>
28                 write!(f, "the evaluated program aborted execution: {}", msg),
29             UnsupportedInIsolation(msg) =>
30                 write!(f, "{}", msg),
31             ExperimentalUb { msg, .. } =>
32                 write!(f, "{}", msg),
33             Deadlock =>
34                 write!(f, "the evaluated program deadlocked"),
35         }
36     }
37 }
38
39 impl MachineStopType for TerminationInfo {}
40
41 /// Miri specific diagnostics
42 pub enum NonHaltingDiagnostic {
43     PoppedTrackedPointerTag(Item),
44     CreatedAlloc(AllocId),
45     FreedAlloc(AllocId),
46 }
47
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>,
52 ) -> Option<i64> {
53     use InterpError::*;
54
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),
61                 Abort(_) =>
62                     "abnormal termination",
63                 UnsupportedInIsolation(_) =>
64                     "unsupported operation",
65                 ExperimentalUb { .. } =>
66                     "Undefined Behavior",
67                 Deadlock => "deadlock",
68             };
69             let helps = match info {
70                 UnsupportedInIsolation(_) =>
71                     vec![format!("pass the flag `-Zmiri-disable-isolation` to disable isolation")],
72                 ExperimentalUb { url, .. } =>
73                     vec![
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),
76                     ],
77                 _ => vec![],
78             };
79             (title, helps)
80         }
81         _ => {
82             let title = match e.kind {
83                 Unsupported(_) =>
84                     "unsupported operation",
85                 UndefinedBehavior(_) =>
86                     "Undefined Behavior",
87                 ResourceExhaustion(_) =>
88                     "resource exhaustion",
89                 _ =>
90                     bug!("This error should be impossible in Miri: {}", e),
91             };
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"),
97                 Unsupported(_) =>
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 { .. }) =>
100                     vec![
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")
104                     ],
105                 UndefinedBehavior(_) =>
106                     vec![
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"),
109                     ],
110                 _ => vec![],
111             };
112             (title, helps)
113         }
114     };
115
116     e.print_backtrace();
117     let msg = e.to_string();
118     report_msg(ecx, &format!("{}: {}", title, msg), msg, helps, true)
119 }
120
121 /// Report an error or note (depending on the `error` argument) at the current frame's current statement.
122 /// Also emits a full stacktrace of the interpreter stack.
123 fn report_msg<'tcx, 'mir>(
124     ecx: &InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
125     title: &str,
126     span_msg: String,
127     mut helps: Vec<String>,
128     error: bool,
129 ) -> Option<i64> {
130     let span = if let Some(frame) = ecx.machine.stack.last() {
131         frame.current_source_info().unwrap().span
132     } else {
133         DUMMY_SP
134     };
135     let mut err = if error {
136         ecx.tcx.sess.struct_span_err(span, title)
137     } else {
138         ecx.tcx.sess.diagnostic().span_note_diag(span, title)
139     };
140     err.span_label(span, span_msg);
141     if !helps.is_empty() {
142         // Add visual separator before backtrace.
143         helps.last_mut().unwrap().push_str("\n");
144         for help in helps {
145             err.help(&help);
146         }
147     }
148     // Add backtrace
149     let frames = ecx.generate_stacktrace();
150     for (idx, frame_info) in frames.iter().enumerate() {
151         let is_local = frame_info.instance.def_id().is_local();
152         // No span for non-local frames and the first frame (which is the error site).
153         if is_local && idx > 0 {
154             err.span_note(frame_info.span, &frame_info.to_string());
155         } else {
156             err.note(&frame_info.to_string());
157         }
158     }
159
160     err.emit();
161
162     for (i, frame) in ecx.machine.stack.iter().enumerate() {
163         trace!("-------------------");
164         trace!("Frame {}", i);
165         trace!("    return: {:?}", frame.return_place.map(|p| *p));
166         for (i, local) in frame.locals.iter().enumerate() {
167             trace!("    local {}: {:?}", i, local.value);
168         }
169     }
170     // Let the reported error determine the return code.
171     return None;
172 }
173
174 thread_local! {
175     static DIAGNOSTICS: RefCell<Vec<NonHaltingDiagnostic>> = RefCell::new(Vec::new());
176 }
177
178 /// Schedule a diagnostic for emitting. This function works even if you have no `InterpCx` available.
179 /// The diagnostic will be emitted after the current interpreter step is finished.
180 pub fn register_diagnostic(e: NonHaltingDiagnostic) {
181     DIAGNOSTICS.with(|diagnostics| diagnostics.borrow_mut().push(e));
182 }
183
184 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
185 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
186     /// Emit all diagnostics that were registed with `register_diagnostics`
187     fn process_diagnostics(&self) {
188         let this = self.eval_context_ref();
189         DIAGNOSTICS.with(|diagnostics| {
190             for e in diagnostics.borrow_mut().drain(..) {
191                 use NonHaltingDiagnostic::*;
192                 let msg = match e {
193                     PoppedTrackedPointerTag(item) =>
194                         format!("popped tracked tag for item {:?}", item),
195                     CreatedAlloc(AllocId(id)) =>
196                         format!("created allocation with id {}", id),
197                     FreedAlloc(AllocId(id)) =>
198                         format!("freed allocation with id {}", id),
199                 };
200                 report_msg(this, "tracking was triggered", msg, vec![], false);
201             }
202         });
203     }
204 }