]> git.lizzy.rs Git - rust.git/blob - src/tools/miri/src/diagnostics.rs
Rollup merge of #103396 - RalfJung:pinning-closure-captures, r=dtolnay
[rust.git] / src / tools / miri / src / diagnostics.rs
1 use std::fmt;
2 use std::num::NonZeroU64;
3
4 use log::trace;
5
6 use rustc_span::{source_map::DUMMY_SP, SpanData, Symbol};
7 use rustc_target::abi::{Align, Size};
8
9 use crate::stacked_borrows::{diagnostics::TagHistory, AccessKind};
10 use crate::*;
11
12 /// Details of premature program termination.
13 pub enum TerminationInfo {
14     Exit(i64),
15     Abort(String),
16     UnsupportedInIsolation(String),
17     StackedBorrowsUb {
18         msg: String,
19         help: Option<String>,
20         history: Option<TagHistory>,
21     },
22     Int2PtrWithStrictProvenance,
23     Deadlock,
24     MultipleSymbolDefinitions {
25         link_name: Symbol,
26         first: SpanData,
27         first_crate: Symbol,
28         second: SpanData,
29         second_crate: Symbol,
30     },
31     SymbolShimClashing {
32         link_name: Symbol,
33         span: SpanData,
34     },
35 }
36
37 impl fmt::Display for TerminationInfo {
38     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
39         use TerminationInfo::*;
40         match self {
41             Exit(code) => write!(f, "the evaluated program completed with exit code {code}"),
42             Abort(msg) => write!(f, "{msg}"),
43             UnsupportedInIsolation(msg) => write!(f, "{msg}"),
44             Int2PtrWithStrictProvenance =>
45                 write!(
46                     f,
47                     "integer-to-pointer casts and `ptr::from_exposed_addr` are not supported with `-Zmiri-strict-provenance`"
48                 ),
49             StackedBorrowsUb { msg, .. } => write!(f, "{msg}"),
50             Deadlock => write!(f, "the evaluated program deadlocked"),
51             MultipleSymbolDefinitions { link_name, .. } =>
52                 write!(f, "multiple definitions of symbol `{link_name}`"),
53             SymbolShimClashing { link_name, .. } =>
54                 write!(f, "found `{link_name}` symbol definition that clashes with a built-in shim",),
55         }
56     }
57 }
58
59 impl MachineStopType for TerminationInfo {}
60
61 /// Miri specific diagnostics
62 pub enum NonHaltingDiagnostic {
63     /// (new_tag, new_kind, (alloc_id, base_offset, orig_tag))
64     ///
65     /// new_kind is `None` for base tags.
66     CreatedPointerTag(NonZeroU64, Option<String>, Option<(AllocId, AllocRange, ProvenanceExtra)>),
67     /// This `Item` was popped from the borrow stack, either due to an access with the given tag or
68     /// a deallocation when the second argument is `None`.
69     PoppedPointerTag(Item, Option<(ProvenanceExtra, AccessKind)>),
70     CreatedCallId(CallId),
71     CreatedAlloc(AllocId, Size, Align, MemoryKind<MiriMemoryKind>),
72     FreedAlloc(AllocId),
73     RejectedIsolatedOp(String),
74     ProgressReport {
75         block_count: u64, // how many basic blocks have been run so far
76     },
77     Int2Ptr {
78         details: bool,
79     },
80     WeakMemoryOutdatedLoad,
81 }
82
83 /// Level of Miri specific diagnostics
84 enum DiagLevel {
85     Error,
86     Warning,
87     Note,
88 }
89
90 /// Attempts to prune a stacktrace to omit the Rust runtime, and returns a bool indicating if any
91 /// frames were pruned. If the stacktrace does not have any local frames, we conclude that it must
92 /// be pointing to a problem in the Rust runtime itself, and do not prune it at all.
93 fn prune_stacktrace<'tcx>(
94     mut stacktrace: Vec<FrameInfo<'tcx>>,
95     machine: &MiriMachine<'_, 'tcx>,
96 ) -> (Vec<FrameInfo<'tcx>>, bool) {
97     match machine.backtrace_style {
98         BacktraceStyle::Off => {
99             // Remove all frames marked with `caller_location` -- that attribute indicates we
100             // usually want to point at the caller, not them.
101             stacktrace.retain(|frame| !frame.instance.def.requires_caller_location(machine.tcx));
102             // Retain one frame so that we can print a span for the error itself
103             stacktrace.truncate(1);
104             (stacktrace, false)
105         }
106         BacktraceStyle::Short => {
107             let original_len = stacktrace.len();
108             // Only prune frames if there is at least one local frame. This check ensures that if
109             // we get a backtrace that never makes it to the user code because it has detected a
110             // bug in the Rust runtime, we don't prune away every frame.
111             let has_local_frame = stacktrace.iter().any(|frame| machine.is_local(frame));
112             if has_local_frame {
113                 // Remove all frames marked with `caller_location` -- that attribute indicates we
114                 // usually want to point at the caller, not them.
115                 stacktrace
116                     .retain(|frame| !frame.instance.def.requires_caller_location(machine.tcx));
117
118                 // This is part of the logic that `std` uses to select the relevant part of a
119                 // backtrace. But here, we only look for __rust_begin_short_backtrace, not
120                 // __rust_end_short_backtrace because the end symbol comes from a call to the default
121                 // panic handler.
122                 stacktrace = stacktrace
123                     .into_iter()
124                     .take_while(|frame| {
125                         let def_id = frame.instance.def_id();
126                         let path = machine.tcx.def_path_str(def_id);
127                         !path.contains("__rust_begin_short_backtrace")
128                     })
129                     .collect::<Vec<_>>();
130
131                 // After we prune frames from the bottom, there are a few left that are part of the
132                 // Rust runtime. So we remove frames until we get to a local symbol, which should be
133                 // main or a test.
134                 // This len check ensures that we don't somehow remove every frame, as doing so breaks
135                 // the primary error message.
136                 while stacktrace.len() > 1
137                     && stacktrace.last().map_or(false, |frame| !machine.is_local(frame))
138                 {
139                     stacktrace.pop();
140                 }
141             }
142             let was_pruned = stacktrace.len() != original_len;
143             (stacktrace, was_pruned)
144         }
145         BacktraceStyle::Full => (stacktrace, false),
146     }
147 }
148
149 /// Emit a custom diagnostic without going through the miri-engine machinery.
150 ///
151 /// Returns `Some` if this was regular program termination with a given exit code, `None` otherwise.
152 pub fn report_error<'tcx, 'mir>(
153     ecx: &InterpCx<'mir, 'tcx, MiriMachine<'mir, 'tcx>>,
154     e: InterpErrorInfo<'tcx>,
155 ) -> Option<i64> {
156     use InterpError::*;
157
158     let mut msg = vec![];
159
160     let (title, helps) = if let MachineStop(info) = e.kind() {
161         let info = info.downcast_ref::<TerminationInfo>().expect("invalid MachineStop payload");
162         use TerminationInfo::*;
163         let title = match info {
164             Exit(code) => return Some(*code),
165             Abort(_) => Some("abnormal termination"),
166             UnsupportedInIsolation(_) | Int2PtrWithStrictProvenance =>
167                 Some("unsupported operation"),
168             StackedBorrowsUb { .. } => Some("Undefined Behavior"),
169             Deadlock => Some("deadlock"),
170             MultipleSymbolDefinitions { .. } | SymbolShimClashing { .. } => None,
171         };
172         #[rustfmt::skip]
173         let helps = match info {
174             UnsupportedInIsolation(_) =>
175                 vec![
176                     (None, format!("pass the flag `-Zmiri-disable-isolation` to disable isolation;")),
177                     (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")),
178                 ],
179             StackedBorrowsUb { help, history, .. } => {
180                 let url = "https://github.com/rust-lang/unsafe-code-guidelines/blob/master/wip/stacked-borrows.md";
181                 msg.extend(help.clone());
182                 let mut helps = vec![
183                     (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")),
184                     (None, format!("see {url} for further information")),
185                 ];
186                 if let Some(TagHistory {created, invalidated, protected}) = history.clone() {
187                     helps.push((Some(created.1), created.0));
188                     if let Some((msg, span)) = invalidated {
189                         helps.push((Some(span), msg));
190                     }
191                     if let Some((protector_msg, protector_span)) = protected {
192                         helps.push((Some(protector_span), protector_msg));
193                     }
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     } else {
210         #[rustfmt::skip]
211         let title = match e.kind() {
212             UndefinedBehavior(_) =>
213                 "Undefined Behavior",
214             ResourceExhaustion(_) =>
215                 "resource exhaustion",
216             Unsupported(
217                 // We list only the ones that can actually happen.
218                 UnsupportedOpInfo::Unsupported(_)
219             ) =>
220                 "unsupported operation",
221             InvalidProgram(
222                 // We list only the ones that can actually happen.
223                 InvalidProgramInfo::AlreadyReported(_) |
224                 InvalidProgramInfo::Layout(..)
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                 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"))],
234             UndefinedBehavior(UndefinedBehaviorInfo::AlignmentCheckFailed { .. })
235                 if ecx.machine.check_alignment == AlignmentCheck::Symbolic
236             =>
237                 vec![
238                     (None, format!("this usually indicates that your program performed an invalid operation and caused Undefined Behavior")),
239                     (None, format!("but due to `-Zmiri-symbolic-alignment-check`, alignment errors can also be false positives")),
240                 ],
241             UndefinedBehavior(_) =>
242                 vec![
243                     (None, format!("this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior")),
244                     (None, format!("see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information")),
245                 ],
246             InvalidProgram(
247                 InvalidProgramInfo::AlreadyReported(rustc_errors::ErrorGuaranteed { .. })
248             ) => {
249                 // This got already reported. No point in reporting it again.
250                 return None;
251             }
252             _ =>
253                 vec![],
254         };
255         (Some(title), helps)
256     };
257
258     let stacktrace = ecx.generate_stacktrace();
259     let (stacktrace, was_pruned) = prune_stacktrace(stacktrace, &ecx.machine);
260     e.print_backtrace();
261     msg.insert(0, e.to_string());
262     report_msg(
263         DiagLevel::Error,
264         &if let Some(title) = title { format!("{title}: {}", msg[0]) } else { msg[0].clone() },
265         msg,
266         vec![],
267         helps,
268         &stacktrace,
269         &ecx.machine,
270     );
271
272     // Include a note like `std` does when we omit frames from a backtrace
273     if was_pruned {
274         ecx.tcx.sess.diagnostic().note_without_error(
275             "some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace",
276         );
277     }
278
279     // Debug-dump all locals.
280     for (i, frame) in ecx.active_thread_stack().iter().enumerate() {
281         trace!("-------------------");
282         trace!("Frame {}", i);
283         trace!("    return: {:?}", *frame.return_place);
284         for (i, local) in frame.locals.iter().enumerate() {
285             trace!("    local {}: {:?}", i, local.value);
286         }
287     }
288
289     // Extra output to help debug specific issues.
290     match e.kind() {
291         UndefinedBehavior(UndefinedBehaviorInfo::InvalidUninitBytes(Some((alloc_id, access)))) => {
292             eprintln!(
293                 "Uninitialized memory occurred at {alloc_id:?}{range:?}, in this allocation:",
294                 range = access.uninit,
295             );
296             eprintln!("{:?}", ecx.dump_alloc(*alloc_id));
297         }
298         _ => {}
299     }
300
301     None
302 }
303
304 /// Report an error or note (depending on the `error` argument) with the given stacktrace.
305 /// Also emits a full stacktrace of the interpreter stack.
306 /// We want to present a multi-line span message for some errors. Diagnostics do not support this
307 /// directly, so we pass the lines as a `Vec<String>` and display each line after the first with an
308 /// additional `span_label` or `note` call.
309 fn report_msg<'tcx>(
310     diag_level: DiagLevel,
311     title: &str,
312     span_msg: Vec<String>,
313     notes: Vec<(Option<SpanData>, String)>,
314     helps: Vec<(Option<SpanData>, String)>,
315     stacktrace: &[FrameInfo<'tcx>],
316     machine: &MiriMachine<'_, 'tcx>,
317 ) {
318     let span = stacktrace.first().map_or(DUMMY_SP, |fi| fi.span);
319     let sess = machine.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 note and help messages.
340     for (span_data, note) in &notes {
341         if let Some(span_data) = span_data {
342             err.span_note(span_data.span(), note);
343         } else {
344             err.note(note);
345         }
346     }
347     for (span_data, help) in &helps {
348         if let Some(span_data) = span_data {
349             err.span_help(span_data.span(), help);
350         } else {
351             err.help(help);
352         }
353     }
354     if notes.len() + helps.len() > 0 {
355         // Add visual separator before backtrace.
356         err.note("BACKTRACE:");
357     }
358     // Add backtrace
359     for (idx, frame_info) in stacktrace.iter().enumerate() {
360         let is_local = machine.is_local(frame_info);
361         // No span for non-local frames and the first frame (which is the error site).
362         if is_local && idx > 0 {
363             err.span_note(frame_info.span, &frame_info.to_string());
364         } else {
365             err.note(&frame_info.to_string());
366         }
367     }
368
369     err.emit();
370 }
371
372 impl<'mir, 'tcx> MiriMachine<'mir, 'tcx> {
373     pub fn emit_diagnostic(&self, e: NonHaltingDiagnostic) {
374         use NonHaltingDiagnostic::*;
375
376         let stacktrace =
377             MiriInterpCx::generate_stacktrace_from_stack(self.threads.active_thread_stack());
378         let (stacktrace, _was_pruned) = prune_stacktrace(stacktrace, self);
379
380         let (title, diag_level) = match &e {
381             RejectedIsolatedOp(_) => ("operation rejected by isolation", DiagLevel::Warning),
382             Int2Ptr { .. } => ("integer-to-pointer cast", DiagLevel::Warning),
383             CreatedPointerTag(..)
384             | PoppedPointerTag(..)
385             | CreatedCallId(..)
386             | CreatedAlloc(..)
387             | FreedAlloc(..)
388             | ProgressReport { .. }
389             | WeakMemoryOutdatedLoad => ("tracking was triggered", DiagLevel::Note),
390         };
391
392         let msg = match &e {
393             CreatedPointerTag(tag, None, _) => format!("created base tag {tag:?}"),
394             CreatedPointerTag(tag, Some(kind), None) => format!("created {tag:?} for {kind}"),
395             CreatedPointerTag(tag, Some(kind), Some((alloc_id, range, orig_tag))) =>
396                 format!(
397                     "created tag {tag:?} for {kind} at {alloc_id:?}{range:?} derived from {orig_tag:?}"
398                 ),
399             PoppedPointerTag(item, tag) =>
400                 match tag {
401                     None => format!("popped tracked tag for item {item:?} due to deallocation",),
402                     Some((tag, access)) => {
403                         format!(
404                             "popped tracked tag for item {item:?} due to {access:?} access for {tag:?}",
405                         )
406                     }
407                 },
408             CreatedCallId(id) => format!("function call with id {id}"),
409             CreatedAlloc(AllocId(id), size, align, kind) =>
410                 format!(
411                     "created {kind} allocation of {size} bytes (alignment {align} bytes) with id {id}",
412                     size = size.bytes(),
413                     align = align.bytes(),
414                 ),
415             FreedAlloc(AllocId(id)) => format!("freed allocation with id {id}"),
416             RejectedIsolatedOp(ref op) =>
417                 format!("{op} was made to return an error due to isolation"),
418             ProgressReport { .. } =>
419                 format!("progress report: current operation being executed is here"),
420             Int2Ptr { .. } => format!("integer-to-pointer cast"),
421             WeakMemoryOutdatedLoad =>
422                 format!("weak memory emulation: outdated value returned from load"),
423         };
424
425         let notes = match &e {
426             ProgressReport { block_count } => {
427                 // It is important that each progress report is slightly different, since
428                 // identical diagnostics are being deduplicated.
429                 vec![(None, format!("so far, {block_count} basic blocks have been executed"))]
430             }
431             _ => vec![],
432         };
433
434         let helps = match &e {
435             Int2Ptr { details: true } =>
436                 vec![
437                     (
438                         None,
439                         format!(
440                             "This program is using integer-to-pointer casts or (equivalently) `ptr::from_exposed_addr`,"
441                         ),
442                     ),
443                     (
444                         None,
445                         format!("which means that Miri might miss pointer bugs in this program."),
446                     ),
447                     (
448                         None,
449                         format!(
450                             "See https://doc.rust-lang.org/nightly/std/ptr/fn.from_exposed_addr.html for more details on that operation."
451                         ),
452                     ),
453                     (
454                         None,
455                         format!(
456                             "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."
457                         ),
458                     ),
459                     (
460                         None,
461                         format!(
462                             "You can then pass the `-Zmiri-strict-provenance` flag to Miri, to ensure you are not relying on `from_exposed_addr` semantics."
463                         ),
464                     ),
465                     (
466                         None,
467                         format!(
468                             "Alternatively, the `-Zmiri-permissive-provenance` flag disables this warning."
469                         ),
470                     ),
471                 ],
472             _ => vec![],
473         };
474
475         report_msg(diag_level, title, vec![msg], notes, helps, &stacktrace, self);
476     }
477 }
478
479 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriInterpCx<'mir, 'tcx> {}
480 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> {
481     fn emit_diagnostic(&self, e: NonHaltingDiagnostic) {
482         let this = self.eval_context_ref();
483         this.machine.emit_diagnostic(e);
484     }
485
486     /// We had a panic in Miri itself, try to print something useful.
487     fn handle_ice(&self) {
488         eprintln!();
489         eprintln!(
490             "Miri caused an ICE during evaluation. Here's the interpreter backtrace at the time of the panic:"
491         );
492         let this = self.eval_context_ref();
493         let stacktrace = this.generate_stacktrace();
494         report_msg(
495             DiagLevel::Note,
496             "the place in the program where the ICE was triggered",
497             vec![],
498             vec![],
499             vec![],
500             &stacktrace,
501             &this.machine,
502         );
503     }
504 }