]> git.lizzy.rs Git - rust.git/blob - src/diagnostics.rs
4476ce237ff494b3e2c67d4d3f38beee814223f8
[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::NoMirFor(..)) =>
136                     vec![(None, format!("make sure to use a Miri sysroot, which you can prepare with `cargo miri setup`"))],
137                 Unsupported(UnsupportedOpInfo::ReadBytesAsPointer | UnsupportedOpInfo::ThreadLocalStatic(_) | UnsupportedOpInfo::ReadExternStatic(_)) =>
138                     panic!("Error should never be raised by Miri: {:?}", e.kind()),
139                 Unsupported(_) =>
140                     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"))],
141                 UndefinedBehavior(UndefinedBehaviorInfo::AlignmentCheckFailed { .. })
142                     if ecx.memory.extra.check_alignment == AlignmentCheck::Symbolic
143                 =>
144                     vec![
145                         (None, format!("this usually indicates that your program performed an invalid operation and caused Undefined Behavior")),
146                         (None, format!("but due to `-Zmiri-symbolic-alignment-check`, alignment errors can also be false positives")),
147                     ],
148                 UndefinedBehavior(_) =>
149                     vec![
150                         (None, format!("this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior")),
151                         (None, format!("see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information")),
152                     ],
153                 _ => vec![],
154             };
155             (Some(title), helps)
156         }
157     };
158
159     e.print_backtrace();
160     let msg = e.to_string();
161     report_msg(
162         *ecx.tcx,
163         DiagLevel::Error,
164         &if let Some(title) = title { format!("{}: {}", title, msg) } else { msg.clone() },
165         msg,
166         helps,
167         &ecx.generate_stacktrace(),
168     );
169
170     // Debug-dump all locals.
171     for (i, frame) in ecx.active_thread_stack().iter().enumerate() {
172         trace!("-------------------");
173         trace!("Frame {}", i);
174         trace!("    return: {:?}", frame.return_place.map(|p| *p));
175         for (i, local) in frame.locals.iter().enumerate() {
176             trace!("    local {}: {:?}", i, local.value);
177         }
178     }
179
180     // Extra output to help debug specific issues.
181     match e.kind() {
182         UndefinedBehavior(UndefinedBehaviorInfo::InvalidUninitBytes(Some((alloc_id, access)))) => {
183             eprintln!(
184                 "Uninitialized read occurred at offsets 0x{:x}..0x{:x} into this allocation:",
185                 access.uninit_offset.bytes(),
186                 access.uninit_offset.bytes() + access.uninit_size.bytes(),
187             );
188             eprintln!("{:?}", ecx.memory.dump_alloc(*alloc_id));
189         }
190         _ => {}
191     }
192
193     None
194 }
195
196 /// Report an error or note (depending on the `error` argument) with the given stacktrace.
197 /// Also emits a full stacktrace of the interpreter stack.
198 fn report_msg<'tcx>(
199     tcx: TyCtxt<'tcx>,
200     diag_level: DiagLevel,
201     title: &str,
202     span_msg: String,
203     mut helps: Vec<(Option<SpanData>, String)>,
204     stacktrace: &[FrameInfo<'tcx>],
205 ) {
206     let span = stacktrace.first().map_or(DUMMY_SP, |fi| fi.span);
207     let mut err = match diag_level {
208         DiagLevel::Error => tcx.sess.struct_span_err(span, title),
209         DiagLevel::Warning => tcx.sess.struct_span_warn(span, title),
210         DiagLevel::Note => tcx.sess.diagnostic().span_note_diag(span, title),
211     };
212
213     // Show main message.
214     if span != DUMMY_SP {
215         err.span_label(span, span_msg);
216     } else {
217         // Make sure we show the message even when it is a dummy span.
218         err.note(&span_msg);
219         err.note("(no span available)");
220     }
221     // Show help messages.
222     if !helps.is_empty() {
223         // Add visual separator before backtrace.
224         helps.last_mut().unwrap().1.push_str("\n");
225         for (span_data, help) in helps {
226             if let Some(span_data) = span_data {
227                 err.span_help(span_data.span(), &help);
228             } else {
229                 err.help(&help);
230             }
231         }
232     }
233     // Add backtrace
234     for (idx, frame_info) in stacktrace.iter().enumerate() {
235         let is_local = frame_info.instance.def_id().is_local();
236         // No span for non-local frames and the first frame (which is the error site).
237         if is_local && idx > 0 {
238             err.span_note(frame_info.span, &frame_info.to_string());
239         } else {
240             err.note(&frame_info.to_string());
241         }
242     }
243
244     err.emit();
245 }
246
247 thread_local! {
248     static DIAGNOSTICS: RefCell<Vec<NonHaltingDiagnostic>> = RefCell::new(Vec::new());
249 }
250
251 /// Schedule a diagnostic for emitting. This function works even if you have no `InterpCx` available.
252 /// The diagnostic will be emitted after the current interpreter step is finished.
253 pub fn register_diagnostic(e: NonHaltingDiagnostic) {
254     DIAGNOSTICS.with(|diagnostics| diagnostics.borrow_mut().push(e));
255 }
256
257 /// Remember enough about the topmost frame so that we can restore the stack
258 /// after a step was taken.
259 pub struct TopFrameInfo<'tcx> {
260     stack_size: usize,
261     instance: Option<ty::Instance<'tcx>>,
262     span: Span,
263 }
264
265 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
266 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
267     fn preprocess_diagnostics(&self) -> TopFrameInfo<'tcx> {
268         // Ensure we have no lingering diagnostics.
269         DIAGNOSTICS.with(|diagnostics| assert!(diagnostics.borrow().is_empty()));
270
271         let this = self.eval_context_ref();
272         if this.active_thread_stack().is_empty() {
273             // Diagnostics can happen even with the empty stack (e.g. deallocation of thread-local statics).
274             return TopFrameInfo { stack_size: 0, instance: None, span: DUMMY_SP };
275         }
276         let frame = this.frame();
277
278         TopFrameInfo {
279             stack_size: this.active_thread_stack().len(),
280             instance: Some(frame.instance),
281             span: frame.current_span(),
282         }
283     }
284
285     /// Emit all diagnostics that were registed with `register_diagnostics`
286     fn process_diagnostics(&self, info: TopFrameInfo<'tcx>) {
287         let this = self.eval_context_ref();
288         DIAGNOSTICS.with(|diagnostics| {
289             let mut diagnostics = diagnostics.borrow_mut();
290             if diagnostics.is_empty() {
291                 return;
292             }
293             // We need to fix up the stack trace, because the machine has already
294             // stepped to the next statement.
295             let mut stacktrace = this.generate_stacktrace();
296             // Remove newly pushed frames.
297             while stacktrace.len() > info.stack_size {
298                 stacktrace.remove(0);
299             }
300             // Add popped frame back.
301             if stacktrace.len() < info.stack_size {
302                 assert!(
303                     stacktrace.len() == info.stack_size - 1,
304                     "we should never pop more than one frame at once"
305                 );
306                 let frame_info = FrameInfo {
307                     instance: info.instance.unwrap(),
308                     span: info.span,
309                     lint_root: None,
310                 };
311                 stacktrace.insert(0, frame_info);
312             } else if let Some(instance) = info.instance {
313                 // Adjust topmost frame.
314                 stacktrace[0].span = info.span;
315                 assert_eq!(
316                     stacktrace[0].instance, instance,
317                     "we should not pop and push a frame in one step"
318                 );
319             }
320
321             // Show diagnostics.
322             for e in diagnostics.drain(..) {
323                 use NonHaltingDiagnostic::*;
324                 let msg = match e {
325                     CreatedPointerTag(tag) => format!("created tag {:?}", tag),
326                     PoppedPointerTag(item) => format!("popped tracked tag for item {:?}", item),
327                     CreatedCallId(id) => format!("function call with id {}", id),
328                     CreatedAlloc(AllocId(id)) => format!("created allocation with id {}", id),
329                     FreedAlloc(AllocId(id)) => format!("freed allocation with id {}", id),
330                     RejectedIsolatedOp(ref op) =>
331                         format!("`{}` was made to return an error due to isolation", op),
332                 };
333
334                 let (title, diag_level) = match e {
335                     RejectedIsolatedOp(_) =>
336                         ("operation rejected by isolation", DiagLevel::Warning),
337                     _ => ("tracking was triggered", DiagLevel::Note),
338                 };
339
340                 report_msg(*this.tcx, diag_level, title, msg, vec![], &stacktrace);
341             }
342         });
343     }
344 }