]> git.lizzy.rs Git - rust.git/blob - src/diagnostics.rs
0d91f5246151ffa4246a3e6fb07adef65e297698
[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, SpanData, Symbol};
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 {
18         msg: String,
19         url: String,
20     },
21     Deadlock,
22     MultipleSymbolDefinitions {
23         link_name: Symbol,
24         first: SpanData,
25         first_crate: Symbol,
26         second: SpanData,
27         second_crate: Symbol,
28     },
29     SymbolShimClashing {
30         link_name: Symbol,
31         span: SpanData,
32     },
33 }
34
35 impl fmt::Display for TerminationInfo {
36     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37         use TerminationInfo::*;
38         match self {
39             Exit(code) => write!(f, "the evaluated program completed with exit code {}", code),
40             Abort(msg) => write!(f, "{}", msg),
41             UnsupportedInIsolation(msg) => write!(f, "{}", msg),
42             ExperimentalUb { msg, .. } => write!(f, "{}", msg),
43             Deadlock => write!(f, "the evaluated program deadlocked"),
44             MultipleSymbolDefinitions { link_name, .. } =>
45                 write!(f, "multiple definitions of symbol `{}`", link_name),
46             SymbolShimClashing { link_name, .. } =>
47                 write!(
48                     f,
49                     "found `{}` symbol definition that clashes with a built-in shim",
50                     link_name
51                 ),
52         }
53     }
54 }
55
56 impl MachineStopType for TerminationInfo {}
57
58 /// Miri specific diagnostics
59 pub enum NonHaltingDiagnostic {
60     CreatedPointerTag(NonZeroU64),
61     PoppedPointerTag(Item),
62     CreatedCallId(CallId),
63     CreatedAlloc(AllocId),
64     FreedAlloc(AllocId),
65     RejectedIsolatedOp(String),
66 }
67
68 /// Level of Miri specific diagnostics
69 enum DiagLevel {
70     Error,
71     Warning,
72     Note,
73 }
74
75 /// Emit a custom diagnostic without going through the miri-engine machinery
76 pub fn report_error<'tcx, 'mir>(
77     ecx: &InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
78     e: InterpErrorInfo<'tcx>,
79 ) -> Option<i64> {
80     use InterpError::*;
81
82     let (title, helps) = match &e.kind() {
83         MachineStop(info) => {
84             let info = info.downcast_ref::<TerminationInfo>().expect("invalid MachineStop payload");
85             use TerminationInfo::*;
86             let title = match info {
87                 Exit(code) => return Some(*code),
88                 Abort(_) => Some("abnormal termination"),
89                 UnsupportedInIsolation(_) => Some("unsupported operation"),
90                 ExperimentalUb { .. } => Some("Undefined Behavior"),
91                 Deadlock => Some("deadlock"),
92                 MultipleSymbolDefinitions { .. } | SymbolShimClashing { .. } => None,
93             };
94             #[rustfmt::skip]
95             let helps = match info {
96                 UnsupportedInIsolation(_) =>
97                     vec![
98                         (None, format!("pass the flag `-Zmiri-disable-isolation` to disable isolation;")),
99                         (None, format!("or pass `-Zmiri-isolation-error=warn to configure Miri to return an error code from isolated operations (if supported for that operation) and continue with a warning")),
100                     ],
101                 ExperimentalUb { url, .. } =>
102                     vec![
103                         (None, format!("this indicates a potential bug in the program: it performed an invalid operation, but the rules it violated are still experimental")),
104                         (None, format!("see {} for further information", url)),
105                     ],
106                 MultipleSymbolDefinitions { first, first_crate, second, second_crate, .. } =>
107                     vec![
108                         (Some(*first), format!("it's first defined here, in crate `{}`", first_crate)),
109                         (Some(*second), format!("then it's defined here again, in crate `{}`", second_crate)),
110                     ],
111                 SymbolShimClashing { link_name, span } =>
112                     vec![(Some(*span), format!("the `{}` symbol is defined here", link_name))],
113                 _ => vec![],
114             };
115             (title, helps)
116         }
117         _ => {
118             #[rustfmt::skip]
119             let title = match e.kind() {
120                 Unsupported(_) =>
121                     "unsupported operation",
122                 UndefinedBehavior(_) =>
123                     "Undefined Behavior",
124                 ResourceExhaustion(_) =>
125                     "resource exhaustion",
126                 InvalidProgram(InvalidProgramInfo::ReferencedConstant) =>
127                     "post-monomorphization error",
128                 InvalidProgram(InvalidProgramInfo::AlreadyReported(_)) =>
129                     "error occurred",
130                 kind =>
131                     bug!("This error should be impossible in Miri: {:?}", kind),
132             };
133             #[rustfmt::skip]
134             let helps = match e.kind() {
135                 Unsupported(UnsupportedOpInfo::ThreadLocalStatic(_) | UnsupportedOpInfo::ReadExternStatic(_)) =>
136                     panic!("Error should never be raised by Miri: {:?}", e.kind()),
137                 Unsupported(_) =>
138                     vec![(None, format!("this is likely not a bug in the program; it indicates that the program performed an operation that the interpreter does not support"))],
139                 UndefinedBehavior(UndefinedBehaviorInfo::AlignmentCheckFailed { .. })
140                     if ecx.memory.extra.check_alignment == AlignmentCheck::Symbolic
141                 =>
142                     vec![
143                         (None, format!("this usually indicates that your program performed an invalid operation and caused Undefined Behavior")),
144                         (None, format!("but due to `-Zmiri-symbolic-alignment-check`, alignment errors can also be false positives")),
145                     ],
146                 UndefinedBehavior(_) =>
147                     vec![
148                         (None, format!("this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior")),
149                         (None, format!("see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information")),
150                     ],
151                 _ => vec![],
152             };
153             (Some(title), helps)
154         }
155     };
156
157     e.print_backtrace();
158     let msg = e.to_string();
159     report_msg(
160         *ecx.tcx,
161         DiagLevel::Error,
162         &if let Some(title) = title { format!("{}: {}", title, msg) } else { msg.clone() },
163         msg,
164         helps,
165         &ecx.generate_stacktrace(),
166     );
167
168     // Debug-dump all locals.
169     for (i, frame) in ecx.active_thread_stack().iter().enumerate() {
170         trace!("-------------------");
171         trace!("Frame {}", i);
172         trace!("    return: {:?}", frame.return_place.map(|p| *p));
173         for (i, local) in frame.locals.iter().enumerate() {
174             trace!("    local {}: {:?}", i, local.value);
175         }
176     }
177
178     // Extra output to help debug specific issues.
179     match e.kind() {
180         UndefinedBehavior(UndefinedBehaviorInfo::InvalidUninitBytes(Some((alloc_id, access)))) => {
181             eprintln!(
182                 "Uninitialized read occurred at offsets 0x{:x}..0x{:x} into this allocation:",
183                 access.uninit_offset.bytes(),
184                 access.uninit_offset.bytes() + access.uninit_size.bytes(),
185             );
186             eprintln!("{:?}", ecx.memory.dump_alloc(*alloc_id));
187         }
188         _ => {}
189     }
190
191     None
192 }
193
194 /// Report an error or note (depending on the `error` argument) with the given stacktrace.
195 /// Also emits a full stacktrace of the interpreter stack.
196 fn report_msg<'tcx>(
197     tcx: TyCtxt<'tcx>,
198     diag_level: DiagLevel,
199     title: &str,
200     span_msg: String,
201     mut helps: Vec<(Option<SpanData>, String)>,
202     stacktrace: &[FrameInfo<'tcx>],
203 ) {
204     let span = stacktrace.first().map_or(DUMMY_SP, |fi| fi.span);
205     let mut err = match diag_level {
206         DiagLevel::Error => tcx.sess.struct_span_err(span, title),
207         DiagLevel::Warning => tcx.sess.struct_span_warn(span, title),
208         DiagLevel::Note => tcx.sess.diagnostic().span_note_diag(span, title),
209     };
210
211     // Show main message.
212     if span != DUMMY_SP {
213         err.span_label(span, span_msg);
214     } else {
215         // Make sure we show the message even when it is a dummy span.
216         err.note(&span_msg);
217         err.note("(no span available)");
218     }
219     // Show help messages.
220     if !helps.is_empty() {
221         // Add visual separator before backtrace.
222         helps.last_mut().unwrap().1.push_str("\n");
223         for (span_data, help) in helps {
224             if let Some(span_data) = span_data {
225                 err.span_help(span_data.span(), &help);
226             } else {
227                 err.help(&help);
228             }
229         }
230     }
231     // Add backtrace
232     for (idx, frame_info) in stacktrace.iter().enumerate() {
233         let is_local = frame_info.instance.def_id().is_local();
234         // No span for non-local frames and the first frame (which is the error site).
235         if is_local && idx > 0 {
236             err.span_note(frame_info.span, &frame_info.to_string());
237         } else {
238             err.note(&frame_info.to_string());
239         }
240     }
241
242     err.emit();
243 }
244
245 thread_local! {
246     static DIAGNOSTICS: RefCell<Vec<NonHaltingDiagnostic>> = RefCell::new(Vec::new());
247 }
248
249 /// Schedule a diagnostic for emitting. This function works even if you have no `InterpCx` available.
250 /// The diagnostic will be emitted after the current interpreter step is finished.
251 pub fn register_diagnostic(e: NonHaltingDiagnostic) {
252     DIAGNOSTICS.with(|diagnostics| diagnostics.borrow_mut().push(e));
253 }
254
255 /// Remember enough about the topmost frame so that we can restore the stack
256 /// after a step was taken.
257 pub struct TopFrameInfo<'tcx> {
258     stack_size: usize,
259     instance: Option<ty::Instance<'tcx>>,
260     span: Span,
261 }
262
263 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
264 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
265     fn preprocess_diagnostics(&self) -> TopFrameInfo<'tcx> {
266         // Ensure we have no lingering diagnostics.
267         DIAGNOSTICS.with(|diagnostics| assert!(diagnostics.borrow().is_empty()));
268
269         let this = self.eval_context_ref();
270         if this.active_thread_stack().is_empty() {
271             // Diagnostics can happen even with the empty stack (e.g. deallocation of thread-local statics).
272             return TopFrameInfo { stack_size: 0, instance: None, span: DUMMY_SP };
273         }
274         let frame = this.frame();
275
276         TopFrameInfo {
277             stack_size: this.active_thread_stack().len(),
278             instance: Some(frame.instance),
279             span: frame.current_span(),
280         }
281     }
282
283     /// Emit all diagnostics that were registed with `register_diagnostics`
284     fn process_diagnostics(&self, info: TopFrameInfo<'tcx>) {
285         let this = self.eval_context_ref();
286         DIAGNOSTICS.with(|diagnostics| {
287             let mut diagnostics = diagnostics.borrow_mut();
288             if diagnostics.is_empty() {
289                 return;
290             }
291             // We need to fix up the stack trace, because the machine has already
292             // stepped to the next statement.
293             let mut stacktrace = this.generate_stacktrace();
294             // Remove newly pushed frames.
295             while stacktrace.len() > info.stack_size {
296                 stacktrace.remove(0);
297             }
298             // Add popped frame back.
299             if stacktrace.len() < info.stack_size {
300                 assert!(
301                     stacktrace.len() == info.stack_size - 1,
302                     "we should never pop more than one frame at once"
303                 );
304                 let frame_info = FrameInfo {
305                     instance: info.instance.unwrap(),
306                     span: info.span,
307                     lint_root: None,
308                 };
309                 stacktrace.insert(0, frame_info);
310             } else if let Some(instance) = info.instance {
311                 // Adjust topmost frame.
312                 stacktrace[0].span = info.span;
313                 assert_eq!(
314                     stacktrace[0].instance, instance,
315                     "we should not pop and push a frame in one step"
316                 );
317             }
318
319             // Show diagnostics.
320             for e in diagnostics.drain(..) {
321                 use NonHaltingDiagnostic::*;
322                 let msg = match e {
323                     CreatedPointerTag(tag) => format!("created tag {:?}", tag),
324                     PoppedPointerTag(item) => format!("popped tracked tag for item {:?}", item),
325                     CreatedCallId(id) => format!("function call with id {}", id),
326                     CreatedAlloc(AllocId(id)) => format!("created allocation with id {}", id),
327                     FreedAlloc(AllocId(id)) => format!("freed allocation with id {}", id),
328                     RejectedIsolatedOp(ref op) =>
329                         format!("{} was made to return an error due to isolation", op),
330                 };
331
332                 let (title, diag_level) = match e {
333                     RejectedIsolatedOp(_) =>
334                         ("operation rejected by isolation", DiagLevel::Warning),
335                     _ => ("tracking was triggered", DiagLevel::Note),
336                 };
337
338                 report_msg(*this.tcx, diag_level, title, msg, vec![], &stacktrace);
339             }
340         });
341     }
342 }