]> git.lizzy.rs Git - rust.git/blob - src/diagnostics.rs
Fix bug with reporting wrong thread for races with reads & add thread ids to data...
[rust.git] / src / diagnostics.rs
1 use std::cell::RefCell;
2 use std::fmt;
3 use std::num::NonZeroU64;
4
5 use log::trace;
6
7 use rustc_middle::ty::{self, TyCtxt};
8 use rustc_span::{source_map::DUMMY_SP, Span};
9
10 use crate::*;
11
12 /// Details of premature program termination.
13 pub enum TerminationInfo {
14     Exit(i64),
15     Abort(String),
16     UnsupportedInIsolation(String),
17     ExperimentalUb { msg: String, url: String },
18     Deadlock,
19 }
20
21 impl fmt::Display for TerminationInfo {
22     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
23         use TerminationInfo::*;
24         match self {
25             Exit(code) =>
26                 write!(f, "the evaluated program completed with exit code {}", code),
27             Abort(msg) =>
28                 write!(f, "{}", 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     CreatedPointerTag(NonZeroU64),
44     PoppedPointerTag(Item),
45     CreatedCallId(CallId),
46     CreatedAlloc(AllocId),
47     FreedAlloc(AllocId),
48 }
49
50 /// Emit a custom diagnostic without going through the miri-engine machinery
51 pub fn report_error<'tcx, 'mir>(
52     ecx: &InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
53     e: InterpErrorInfo<'tcx>,
54 ) -> Option<i64> {
55     use InterpError::*;
56
57     let (title, helps) = match &e.kind {
58         MachineStop(info) => {
59             let info = info.downcast_ref::<TerminationInfo>().expect("invalid MachineStop payload");
60             use TerminationInfo::*;
61             let title = match info {
62                 Exit(code) => return Some(*code),
63                 Abort(_) =>
64                     "abnormal termination",
65                 UnsupportedInIsolation(_) =>
66                     "unsupported operation",
67                 ExperimentalUb { .. } =>
68                     "Undefined Behavior",
69                 Deadlock => "deadlock",
70             };
71             let helps = match info {
72                 UnsupportedInIsolation(_) =>
73                     vec![format!("pass the flag `-Zmiri-disable-isolation` to disable isolation")],
74                 ExperimentalUb { url, .. } =>
75                     vec![
76                         format!("this indicates a potential bug in the program: it performed an invalid operation, but the rules it violated are still experimental"),
77                         format!("see {} for further information", url),
78                     ],
79                 _ => vec![],
80             };
81             (title, helps)
82         }
83         _ => {
84             let title = match e.kind {
85                 Unsupported(_) =>
86                     "unsupported operation",
87                 UndefinedBehavior(_) =>
88                     "Undefined Behavior",
89                 ResourceExhaustion(_) =>
90                     "resource exhaustion",
91                 InvalidProgram(InvalidProgramInfo::ReferencedConstant) =>
92                     "post-monomorphization error",
93                 _ =>
94                     bug!("This error should be impossible in Miri: {}", e),
95             };
96             let helps = match e.kind {
97                 Unsupported(UnsupportedOpInfo::NoMirFor(..)) =>
98                     vec![format!("make sure to use a Miri sysroot, which you can prepare with `cargo miri setup`")],
99                 Unsupported(UnsupportedOpInfo::ReadBytesAsPointer | UnsupportedOpInfo::ThreadLocalStatic(_) | UnsupportedOpInfo::ReadExternStatic(_)) =>
100                     panic!("Error should never be raised by Miri: {:?}", e.kind),
101                 Unsupported(_) =>
102                     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")],
103                 UndefinedBehavior(UndefinedBehaviorInfo::AlignmentCheckFailed { .. })
104                     if ecx.memory.extra.check_alignment == AlignmentCheck::Symbolic
105                 =>
106                     vec![
107                         format!("this usually indicates that your program performed an invalid operation and caused Undefined Behavior"),
108                         format!("but due to `-Zmiri-symbolic-alignment-check`, alignment errors can also be false positives"),
109                     ],
110                 UndefinedBehavior(_) =>
111                     vec![
112                         format!("this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior"),
113                         format!("see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information"),
114                     ],
115                 _ => vec![],
116             };
117             (title, helps)
118         }
119     };
120
121     e.print_backtrace();
122     let msg = e.to_string();
123     report_msg(*ecx.tcx, /*error*/true, &format!("{}: {}", title, msg), msg, helps, &ecx.generate_stacktrace());
124
125     // Debug-dump all locals.
126     for (i, frame) in ecx.active_thread_stack().iter().enumerate() {
127         trace!("-------------------");
128         trace!("Frame {}", i);
129         trace!("    return: {:?}", frame.return_place.map(|p| *p));
130         for (i, local) in frame.locals.iter().enumerate() {
131             trace!("    local {}: {:?}", i, local.value);
132         }
133     }
134
135     // Extra output to help debug specific issues.
136     match e.kind {
137         UndefinedBehavior(UndefinedBehaviorInfo::InvalidUninitBytes(Some(access))) => {
138             eprintln!(
139                 "Uninitialized read occurred at offsets 0x{:x}..0x{:x} into this allocation:",
140                 access.uninit_ptr.offset.bytes(),
141                 access.uninit_ptr.offset.bytes() + access.uninit_size.bytes(),
142             );
143             eprintln!("{:?}", ecx.memory.dump_alloc(access.uninit_ptr.alloc_id));
144         }
145         _ => {}
146     }
147
148     None
149 }
150
151 /// Report an error or note (depending on the `error` argument) with the given stacktrace.
152 /// Also emits a full stacktrace of the interpreter stack.
153 fn report_msg<'tcx>(
154     tcx: TyCtxt<'tcx>,
155     error: bool,
156     title: &str,
157     span_msg: String,
158     mut helps: Vec<String>,
159     stacktrace: &[FrameInfo<'tcx>],
160 ) {
161     let span = stacktrace.first().map_or(DUMMY_SP, |fi| fi.span);
162     let mut err = if error {
163         tcx.sess.struct_span_err(span, title)
164     } else {
165         tcx.sess.diagnostic().span_note_diag(span, title)
166     };
167     // Show main message.
168     if span != DUMMY_SP {
169         err.span_label(span, span_msg);
170     } else {
171         // Make sure we show the message even when it is a dummy span.
172         err.note(&span_msg);
173         err.note("(no span available)");
174     }
175     // Show help messages.
176     if !helps.is_empty() {
177         // Add visual separator before backtrace.
178         helps.last_mut().unwrap().push_str("\n");
179         for help in helps {
180             err.help(&help);
181         }
182     }
183     // Add backtrace
184     for (idx, frame_info) in stacktrace.iter().enumerate() {
185         let is_local = frame_info.instance.def_id().is_local();
186         // No span for non-local frames and the first frame (which is the error site).
187         if is_local && idx > 0 {
188             err.span_note(frame_info.span, &frame_info.to_string());
189         } else {
190             err.note(&frame_info.to_string());
191         }
192     }
193
194     err.emit();
195 }
196
197 thread_local! {
198     static DIAGNOSTICS: RefCell<Vec<NonHaltingDiagnostic>> = RefCell::new(Vec::new());
199 }
200
201 /// Schedule a diagnostic for emitting. This function works even if you have no `InterpCx` available.
202 /// The diagnostic will be emitted after the current interpreter step is finished.
203 pub fn register_diagnostic(e: NonHaltingDiagnostic) {
204     DIAGNOSTICS.with(|diagnostics| diagnostics.borrow_mut().push(e));
205 }
206
207 /// Remember enough about the topmost frame so that we can restore the stack
208 /// after a step was taken.
209 pub struct TopFrameInfo<'tcx> {
210     stack_size: usize,
211     instance: Option<ty::Instance<'tcx>>,
212     span: Span,
213 }
214
215 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
216 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
217     fn preprocess_diagnostics(&self) -> TopFrameInfo<'tcx> {
218         // Ensure we have no lingering diagnostics.
219         DIAGNOSTICS.with(|diagnostics| assert!(diagnostics.borrow().is_empty()));
220
221         let this = self.eval_context_ref();
222         if this.active_thread_stack().is_empty() {
223             // Diagnostics can happen even with the empty stack (e.g. deallocation of thread-local statics).
224             return TopFrameInfo { stack_size: 0, instance: None, span: DUMMY_SP };
225         }
226         let frame = this.frame();
227
228         TopFrameInfo {
229             stack_size: this.active_thread_stack().len(),
230             instance: Some(frame.instance),
231             span: frame.current_span(),
232         }
233     }
234
235     /// Emit all diagnostics that were registed with `register_diagnostics`
236     fn process_diagnostics(&self, info: TopFrameInfo<'tcx>) {
237         let this = self.eval_context_ref();
238         DIAGNOSTICS.with(|diagnostics| {
239             let mut diagnostics = diagnostics.borrow_mut();
240             if diagnostics.is_empty() {
241                 return;
242             }
243             // We need to fix up the stack trace, because the machine has already
244             // stepped to the next statement.
245             let mut stacktrace = this.generate_stacktrace();
246             // Remove newly pushed frames.
247             while stacktrace.len() > info.stack_size {
248                 stacktrace.remove(0);
249             }
250             // Add popped frame back.
251             if stacktrace.len() < info.stack_size {
252                 assert!(stacktrace.len() == info.stack_size-1, "we should never pop more than one frame at once");
253                 let frame_info = FrameInfo {
254                     instance: info.instance.unwrap(),
255                     span: info.span,
256                     lint_root: None,
257                 };
258                 stacktrace.insert(0, frame_info);
259             } else if let Some(instance) = info.instance {
260                 // Adjust topmost frame.
261                 stacktrace[0].span = info.span;
262                 assert_eq!(stacktrace[0].instance, instance, "we should not pop and push a frame in one step");
263             }
264
265             // Show diagnostics.
266             for e in diagnostics.drain(..) {
267                 use NonHaltingDiagnostic::*;
268                 let msg = match e {
269                     CreatedPointerTag(tag) =>
270                         format!("created tag {:?}", tag),
271                     PoppedPointerTag(item) =>
272                         format!("popped tracked tag for item {:?}", item),
273                     CreatedCallId(id) =>
274                         format!("function call with id {}", id),
275                     CreatedAlloc(AllocId(id)) =>
276                         format!("created allocation with id {}", id),
277                     FreedAlloc(AllocId(id)) =>
278                         format!("freed allocation with id {}", id),
279                 };
280                 report_msg(*this.tcx, /*error*/false, "tracking was triggered", msg, vec![], &stacktrace);
281             }
282         });
283     }
284 }