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