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