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