]> git.lizzy.rs Git - rust.git/blob - src/diagnostics.rs
Auto merge of #2195 - RalfJung:vtable-validation, r=RalfJung
[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;
8 use rustc_span::{source_map::DUMMY_SP, Span, SpanData, Symbol};
9
10 use crate::helpers::HexRange;
11 use crate::stacked_borrows::{diagnostics::TagHistory, AccessKind, SbTag};
12 use crate::*;
13
14 /// Details of premature program termination.
15 pub enum TerminationInfo {
16     Exit(i64),
17     Abort(String),
18     UnsupportedInIsolation(String),
19     StackedBorrowsUb {
20         msg: String,
21         help: Option<String>,
22         history: Option<TagHistory>,
23     },
24     Deadlock,
25     MultipleSymbolDefinitions {
26         link_name: Symbol,
27         first: SpanData,
28         first_crate: Symbol,
29         second: SpanData,
30         second_crate: Symbol,
31     },
32     SymbolShimClashing {
33         link_name: Symbol,
34         span: SpanData,
35     },
36 }
37
38 impl fmt::Display for TerminationInfo {
39     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40         use TerminationInfo::*;
41         match self {
42             Exit(code) => write!(f, "the evaluated program completed with exit code {}", code),
43             Abort(msg) => write!(f, "{}", msg),
44             UnsupportedInIsolation(msg) => write!(f, "{}", msg),
45             StackedBorrowsUb { msg, .. } => write!(f, "{}", msg),
46             Deadlock => write!(f, "the evaluated program deadlocked"),
47             MultipleSymbolDefinitions { link_name, .. } =>
48                 write!(f, "multiple definitions of symbol `{}`", link_name),
49             SymbolShimClashing { link_name, .. } =>
50                 write!(
51                     f,
52                     "found `{}` symbol definition that clashes with a built-in shim",
53                     link_name
54                 ),
55         }
56     }
57 }
58
59 impl MachineStopType for TerminationInfo {}
60
61 /// Miri specific diagnostics
62 pub enum NonHaltingDiagnostic {
63     CreatedPointerTag(NonZeroU64),
64     /// This `Item` was popped from the borrow stack, either due to a grant of
65     /// `AccessKind` to `SbTag` or a deallocation when the second argument is `None`.
66     PoppedPointerTag(Item, Option<(SbTag, AccessKind)>),
67     CreatedCallId(CallId),
68     CreatedAlloc(AllocId),
69     FreedAlloc(AllocId),
70     RejectedIsolatedOp(String),
71 }
72
73 /// Level of Miri specific diagnostics
74 enum DiagLevel {
75     Error,
76     Warning,
77     Note,
78 }
79
80 /// Attempts to prune a stacktrace to omit the Rust runtime, and returns a bool indicating if any
81 /// frames were pruned. If the stacktrace does not have any local frames, we conclude that it must
82 /// be pointing to a problem in the Rust runtime itself, and do not prune it at all.
83 fn prune_stacktrace<'mir, 'tcx>(
84     ecx: &InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
85     mut stacktrace: Vec<FrameInfo<'tcx>>,
86 ) -> (Vec<FrameInfo<'tcx>>, bool) {
87     match ecx.machine.backtrace_style {
88         BacktraceStyle::Off => {
89             // Retain one frame so that we can print a span for the error itself
90             stacktrace.truncate(1);
91             (stacktrace, false)
92         }
93         BacktraceStyle::Short => {
94             let original_len = stacktrace.len();
95             // Only prune frames if there is at least one local frame. This check ensures that if
96             // we get a backtrace that never makes it to the user code because it has detected a
97             // bug in the Rust runtime, we don't prune away every frame.
98             let has_local_frame = stacktrace.iter().any(|frame| ecx.machine.is_local(frame));
99             if has_local_frame {
100                 // This is part of the logic that `std` uses to select the relevant part of a
101                 // backtrace. But here, we only look for __rust_begin_short_backtrace, not
102                 // __rust_end_short_backtrace because the end symbol comes from a call to the default
103                 // panic handler.
104                 stacktrace = stacktrace
105                     .into_iter()
106                     .take_while(|frame| {
107                         let def_id = frame.instance.def_id();
108                         let path = ecx.tcx.tcx.def_path_str(def_id);
109                         !path.contains("__rust_begin_short_backtrace")
110                     })
111                     .collect::<Vec<_>>();
112
113                 // After we prune frames from the bottom, there are a few left that are part of the
114                 // Rust runtime. So we remove frames until we get to a local symbol, which should be
115                 // main or a test.
116                 // This len check ensures that we don't somehow remove every frame, as doing so breaks
117                 // the primary error message.
118                 while stacktrace.len() > 1
119                     && stacktrace.last().map_or(false, |frame| !ecx.machine.is_local(frame))
120                 {
121                     stacktrace.pop();
122                 }
123             }
124             let was_pruned = stacktrace.len() != original_len;
125             (stacktrace, was_pruned)
126         }
127         BacktraceStyle::Full => (stacktrace, false),
128     }
129 }
130
131 /// Emit a custom diagnostic without going through the miri-engine machinery
132 pub fn report_error<'tcx, 'mir>(
133     ecx: &InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
134     e: InterpErrorInfo<'tcx>,
135 ) -> Option<i64> {
136     use InterpError::*;
137
138     let mut msg = vec![];
139
140     let (title, helps) = match &e.kind() {
141         MachineStop(info) => {
142             let info = info.downcast_ref::<TerminationInfo>().expect("invalid MachineStop payload");
143             use TerminationInfo::*;
144             let title = match info {
145                 Exit(code) => return Some(*code),
146                 Abort(_) => Some("abnormal termination"),
147                 UnsupportedInIsolation(_) => Some("unsupported operation"),
148                 StackedBorrowsUb { .. } => Some("Undefined Behavior"),
149                 Deadlock => Some("deadlock"),
150                 MultipleSymbolDefinitions { .. } | SymbolShimClashing { .. } => None,
151             };
152             #[rustfmt::skip]
153             let helps = match info {
154                 UnsupportedInIsolation(_) =>
155                     vec![
156                         (None, format!("pass the flag `-Zmiri-disable-isolation` to disable isolation;")),
157                         (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")),
158                     ],
159                 StackedBorrowsUb { help, history, .. } => {
160                     let url = "https://github.com/rust-lang/unsafe-code-guidelines/blob/master/wip/stacked-borrows.md";
161                     msg.extend(help.clone());
162                     let mut helps = vec![
163                         (None, format!("this indicates a potential bug in the program: it performed an invalid operation, but the Stacked Borrows rules it violated are still experimental")),
164                         (None, format!("see {url} for further information")),
165                     ];
166                     match history {
167                         Some(TagHistory::Tagged {tag, created: (created_range, created_span), invalidated, protected }) => {
168                             let msg = format!("{:?} was created by a retag at offsets {}", tag, HexRange(*created_range));
169                             helps.push((Some(*created_span), msg));
170                             if let Some((invalidated_range, invalidated_span)) = invalidated {
171                                 let msg = format!("{:?} was later invalidated at offsets {}", tag, HexRange(*invalidated_range));
172                                 helps.push((Some(*invalidated_span), msg));
173                             }
174                             if let Some((protecting_tag, protecting_tag_span, protection_span)) = protected {
175                                 helps.push((Some(*protecting_tag_span), format!("{:?} was protected due to {:?} which was created here", tag, protecting_tag)));
176                                 helps.push((Some(*protection_span), "this protector is live for this call".to_string()));
177                             }
178                         }
179                         Some(TagHistory::Untagged{ recently_created, recently_invalidated, matching_created, protected }) => {
180                             if let Some((range, span)) = recently_created {
181                                 let msg = format!("tag was most recently created at offsets {}", HexRange(*range));
182                                 helps.push((Some(*span), msg));
183                             }
184                             if let Some((range, span)) = recently_invalidated {
185                                 let msg = format!("tag was later invalidated at offsets {}", HexRange(*range));
186                                 helps.push((Some(*span), msg));
187                             }
188                             if let Some((range, span)) = matching_created {
189                                 let msg = format!("this tag was also created here at offsets {}", HexRange(*range));
190                                 helps.push((Some(*span), msg));
191                             }
192                             if let Some((protecting_tag, protecting_tag_span, protection_span)) = protected {
193                                 helps.push((Some(*protecting_tag_span), format!("{:?} was protected due to a tag which was created here", protecting_tag)));
194                                 helps.push((Some(*protection_span), "this protector is live for this call".to_string()));
195                             }
196                         }
197                         None => {}
198                     }
199                     helps
200                 }
201                 MultipleSymbolDefinitions { first, first_crate, second, second_crate, .. } =>
202                     vec![
203                         (Some(*first), format!("it's first defined here, in crate `{}`", first_crate)),
204                         (Some(*second), format!("then it's defined here again, in crate `{}`", second_crate)),
205                     ],
206                 SymbolShimClashing { link_name, span } =>
207                     vec![(Some(*span), format!("the `{}` symbol is defined here", link_name))],
208                 _ => vec![],
209             };
210             (title, helps)
211         }
212         _ => {
213             #[rustfmt::skip]
214             let title = match e.kind() {
215                 Unsupported(_) =>
216                     "unsupported operation",
217                 UndefinedBehavior(_) =>
218                     "Undefined Behavior",
219                 ResourceExhaustion(_) =>
220                     "resource exhaustion",
221                 InvalidProgram(
222                     InvalidProgramInfo::AlreadyReported(_) |
223                     InvalidProgramInfo::Layout(..) |
224                     InvalidProgramInfo::ReferencedConstant
225                 ) =>
226                     "post-monomorphization error",
227                 kind =>
228                     bug!("This error should be impossible in Miri: {:?}", kind),
229             };
230             #[rustfmt::skip]
231             let helps = match e.kind() {
232                 Unsupported(
233                     UnsupportedOpInfo::ThreadLocalStatic(_) |
234                     UnsupportedOpInfo::ReadExternStatic(_)
235                 ) =>
236                     panic!("Error should never be raised by Miri: {:?}", e.kind()),
237                 Unsupported(
238                     UnsupportedOpInfo::Unsupported(_) |
239                     UnsupportedOpInfo::PartialPointerOverwrite(_) |
240                     UnsupportedOpInfo::ReadPointerAsBytes
241                 ) =>
242                     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"))],
243                 UndefinedBehavior(UndefinedBehaviorInfo::AlignmentCheckFailed { .. })
244                     if ecx.machine.check_alignment == AlignmentCheck::Symbolic
245                 =>
246                     vec![
247                         (None, format!("this usually indicates that your program performed an invalid operation and caused Undefined Behavior")),
248                         (None, format!("but due to `-Zmiri-symbolic-alignment-check`, alignment errors can also be false positives")),
249                     ],
250                 UndefinedBehavior(_) =>
251                     vec![
252                         (None, format!("this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior")),
253                         (None, format!("see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information")),
254                     ],
255                 InvalidProgram(_) | ResourceExhaustion(_) | MachineStop(_) =>
256                     vec![],
257             };
258             (Some(title), helps)
259         }
260     };
261
262     let stacktrace = ecx.generate_stacktrace();
263     let (stacktrace, was_pruned) = prune_stacktrace(ecx, stacktrace);
264     e.print_backtrace();
265     msg.insert(0, e.to_string());
266     report_msg(
267         ecx,
268         DiagLevel::Error,
269         &if let Some(title) = title { format!("{}: {}", title, msg[0]) } else { msg[0].clone() },
270         msg,
271         helps,
272         &stacktrace,
273     );
274
275     // Include a note like `std` does when we omit frames from a backtrace
276     if was_pruned {
277         ecx.tcx.sess.diagnostic().note_without_error(
278             "some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace",
279         );
280     }
281
282     // Debug-dump all locals.
283     for (i, frame) in ecx.active_thread_stack().iter().enumerate() {
284         trace!("-------------------");
285         trace!("Frame {}", i);
286         trace!("    return: {:?}", *frame.return_place);
287         for (i, local) in frame.locals.iter().enumerate() {
288             trace!("    local {}: {:?}", i, local.value);
289         }
290     }
291
292     // Extra output to help debug specific issues.
293     match e.kind() {
294         UndefinedBehavior(UndefinedBehaviorInfo::InvalidUninitBytes(Some((alloc_id, access)))) => {
295             eprintln!(
296                 "Uninitialized read occurred at offsets 0x{:x}..0x{:x} into this allocation:",
297                 access.uninit_offset.bytes(),
298                 access.uninit_offset.bytes() + access.uninit_size.bytes(),
299             );
300             eprintln!("{:?}", ecx.dump_alloc(*alloc_id));
301         }
302         _ => {}
303     }
304
305     None
306 }
307
308 /// Report an error or note (depending on the `error` argument) with the given stacktrace.
309 /// Also emits a full stacktrace of the interpreter stack.
310 /// We want to present a multi-line span message for some errors. Diagnostics do not support this
311 /// directly, so we pass the lines as a `Vec<String>` and display each line after the first with an
312 /// additional `span_label` or `note` call.
313 fn report_msg<'mir, 'tcx>(
314     ecx: &InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
315     diag_level: DiagLevel,
316     title: &str,
317     span_msg: Vec<String>,
318     mut helps: Vec<(Option<SpanData>, String)>,
319     stacktrace: &[FrameInfo<'tcx>],
320 ) {
321     let span = stacktrace.first().map_or(DUMMY_SP, |fi| fi.span);
322     let sess = ecx.tcx.sess;
323     let mut err = match diag_level {
324         DiagLevel::Error => sess.struct_span_err(span, title).forget_guarantee(),
325         DiagLevel::Warning => sess.struct_span_warn(span, title),
326         DiagLevel::Note => sess.diagnostic().span_note_diag(span, title),
327     };
328
329     // Show main message.
330     if span != DUMMY_SP {
331         for line in span_msg {
332             err.span_label(span, line);
333         }
334     } else {
335         // Make sure we show the message even when it is a dummy span.
336         for line in span_msg {
337             err.note(&line);
338         }
339         err.note("(no span available)");
340     }
341
342     // Show help messages.
343     if !helps.is_empty() {
344         // Add visual separator before backtrace.
345         helps.last_mut().unwrap().1.push('\n');
346         for (span_data, help) in helps {
347             if let Some(span_data) = span_data {
348                 err.span_help(span_data.span(), &help);
349             } else {
350                 err.help(&help);
351             }
352         }
353     }
354     // Add backtrace
355     for (idx, frame_info) in stacktrace.iter().enumerate() {
356         let is_local = ecx.machine.is_local(frame_info);
357         // No span for non-local frames and the first frame (which is the error site).
358         if is_local && idx > 0 {
359             err.span_note(frame_info.span, &frame_info.to_string());
360         } else {
361             err.note(&frame_info.to_string());
362         }
363     }
364
365     err.emit();
366 }
367
368 thread_local! {
369     static DIAGNOSTICS: RefCell<Vec<NonHaltingDiagnostic>> = RefCell::new(Vec::new());
370 }
371
372 /// Schedule a diagnostic for emitting. This function works even if you have no `InterpCx` available.
373 /// The diagnostic will be emitted after the current interpreter step is finished.
374 pub fn register_diagnostic(e: NonHaltingDiagnostic) {
375     DIAGNOSTICS.with(|diagnostics| diagnostics.borrow_mut().push(e));
376 }
377
378 /// Remember enough about the topmost frame so that we can restore the stack
379 /// after a step was taken.
380 pub struct TopFrameInfo<'tcx> {
381     stack_size: usize,
382     instance: Option<ty::Instance<'tcx>>,
383     span: Span,
384 }
385
386 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
387 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
388     fn preprocess_diagnostics(&self) -> TopFrameInfo<'tcx> {
389         // Ensure we have no lingering diagnostics.
390         DIAGNOSTICS.with(|diagnostics| assert!(diagnostics.borrow().is_empty()));
391
392         let this = self.eval_context_ref();
393         if this.active_thread_stack().is_empty() {
394             // Diagnostics can happen even with the empty stack (e.g. deallocation of thread-local statics).
395             return TopFrameInfo { stack_size: 0, instance: None, span: DUMMY_SP };
396         }
397         let frame = this.frame();
398
399         TopFrameInfo {
400             stack_size: this.active_thread_stack().len(),
401             instance: Some(frame.instance),
402             span: frame.current_span(),
403         }
404     }
405
406     /// Emit all diagnostics that were registed with `register_diagnostics`
407     fn process_diagnostics(&self, info: TopFrameInfo<'tcx>) {
408         let this = self.eval_context_ref();
409         DIAGNOSTICS.with(|diagnostics| {
410             let mut diagnostics = diagnostics.borrow_mut();
411             if diagnostics.is_empty() {
412                 return;
413             }
414             // We need to fix up the stack trace, because the machine has already
415             // stepped to the next statement.
416             let mut stacktrace = this.generate_stacktrace();
417             // Remove newly pushed frames.
418             while stacktrace.len() > info.stack_size {
419                 stacktrace.remove(0);
420             }
421             // Add popped frame back.
422             if stacktrace.len() < info.stack_size {
423                 assert!(
424                     stacktrace.len() == info.stack_size - 1,
425                     "we should never pop more than one frame at once"
426                 );
427                 let frame_info = FrameInfo {
428                     instance: info.instance.unwrap(),
429                     span: info.span,
430                     lint_root: None,
431                 };
432                 stacktrace.insert(0, frame_info);
433             } else if let Some(instance) = info.instance {
434                 // Adjust topmost frame.
435                 stacktrace[0].span = info.span;
436                 assert_eq!(
437                     stacktrace[0].instance, instance,
438                     "we should not pop and push a frame in one step"
439                 );
440             }
441
442             let (stacktrace, _was_pruned) = prune_stacktrace(this, stacktrace);
443
444             // Show diagnostics.
445             for e in diagnostics.drain(..) {
446                 use NonHaltingDiagnostic::*;
447                 let msg = match e {
448                     CreatedPointerTag(tag) => format!("created tag {:?}", tag),
449                     PoppedPointerTag(item, tag) =>
450                         match tag {
451                             None =>
452                                 format!(
453                                     "popped tracked tag for item {:?} due to deallocation",
454                                     item
455                                 ),
456                             Some((tag, access)) => {
457                                 format!(
458                                     "popped tracked tag for item {:?} due to {:?} access for {:?}",
459                                     item, access, tag
460                                 )
461                             }
462                         },
463                     CreatedCallId(id) => format!("function call with id {id}"),
464                     CreatedAlloc(AllocId(id)) => format!("created allocation with id {id}"),
465                     FreedAlloc(AllocId(id)) => format!("freed allocation with id {id}"),
466                     RejectedIsolatedOp(ref op) =>
467                         format!("{op} was made to return an error due to isolation"),
468                 };
469
470                 let (title, diag_level) = match e {
471                     RejectedIsolatedOp(_) =>
472                         ("operation rejected by isolation", DiagLevel::Warning),
473                     _ => ("tracking was triggered", DiagLevel::Note),
474                 };
475
476                 report_msg(this, diag_level, title, vec![msg], vec![], &stacktrace);
477             }
478         });
479     }
480 }