]> git.lizzy.rs Git - rust.git/blob - src/diagnostics.rs
add option to track call IDs
[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::Display 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     PoppedPointerTag(Item),
44     CreatedCallId(CallId),
45     CreatedAlloc(AllocId),
46     FreedAlloc(AllocId),
47 }
48
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>,
53 ) -> Option<i64> {
54     use InterpError::*;
55
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),
62                 Abort(_) =>
63                     "abnormal termination",
64                 UnsupportedInIsolation(_) =>
65                     "unsupported operation",
66                 ExperimentalUb { .. } =>
67                     "Undefined Behavior",
68                 Deadlock => "deadlock",
69             };
70             let helps = match info {
71                 UnsupportedInIsolation(_) =>
72                     vec![format!("pass the flag `-Zmiri-disable-isolation` to disable isolation")],
73                 ExperimentalUb { url, .. } =>
74                     vec![
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),
77                     ],
78                 _ => vec![],
79             };
80             (title, helps)
81         }
82         _ => {
83             let title = match e.kind {
84                 Unsupported(_) =>
85                     "unsupported operation",
86                 UndefinedBehavior(_) =>
87                     "Undefined Behavior",
88                 ResourceExhaustion(_) =>
89                     "resource exhaustion",
90                 _ =>
91                     bug!("This error should be impossible in Miri: {}", e),
92             };
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"),
98                 Unsupported(_) =>
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 { .. }) =>
101                     vec![
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")
105                     ],
106                 UndefinedBehavior(_) =>
107                     vec![
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"),
110                     ],
111                 _ => vec![],
112             };
113             (title, helps)
114         }
115     };
116
117     e.print_backtrace();
118     let msg = e.to_string();
119     report_msg(ecx, &format!("{}: {}", title, msg), msg, helps, true);
120
121     // Extra output to help debug specific issues.
122     match e.kind {
123         UndefinedBehavior(UndefinedBehaviorInfo::InvalidUninitBytes(Some(access))) => {
124             eprintln!(
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(),
128             );
129             ecx.memory.dump_alloc(access.uninit_ptr.alloc_id);
130             eprintln!();
131         }
132         _ => {}
133     }
134
135     None
136 }
137
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>>,
142     title: &str,
143     span_msg: String,
144     mut helps: Vec<String>,
145     error: bool,
146 ) {
147     let span = if let Some(frame) = ecx.active_thread_stack().last() {
148         frame.current_source_info().unwrap().span
149     } else {
150         DUMMY_SP
151     };
152     let mut err = if error {
153         ecx.tcx.sess.struct_span_err(span, title)
154     } else {
155         ecx.tcx.sess.diagnostic().span_note_diag(span, title)
156     };
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");
161         for help in helps {
162             err.help(&help);
163         }
164     }
165     // Add backtrace
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());
172         } else {
173             err.note(&frame_info.to_string());
174         }
175     }
176
177     err.emit();
178
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);
185         }
186     }
187 }
188
189 thread_local! {
190     static DIAGNOSTICS: RefCell<Vec<NonHaltingDiagnostic>> = RefCell::new(Vec::new());
191 }
192
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));
197 }
198
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::*;
207                 let msg = match e {
208                     PoppedPointerTag(item) =>
209                         format!("popped tracked tag for item {:?}", item),
210                     CreatedCallId(id) =>
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),
216                 };
217                 report_msg(this, "tracking was triggered", msg, vec![], false);
218             }
219         });
220     }
221 }