]> git.lizzy.rs Git - rust.git/blob - src/tools/miri/src/diagnostics.rs
Rollup merge of #102125 - notriddle:notriddle/content-item-info, r=GuillaumeGomez
[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     CreatedPointerTag(NonZeroU64, Option<(AllocId, AllocRange)>),
64     /// This `Item` was popped from the borrow stack, either due to an access with the given tag or
65     /// a deallocation when the second argument is `None`.
66     PoppedPointerTag(Item, Option<(ProvenanceExtra, AccessKind)>),
67     CreatedCallId(CallId),
68     CreatedAlloc(AllocId, Size, Align, MemoryKind<MiriMemoryKind>),
69     FreedAlloc(AllocId),
70     RejectedIsolatedOp(String),
71     ProgressReport {
72         block_count: u64, // how many basic blocks have been run so far
73     },
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<'tcx>(
91     mut stacktrace: Vec<FrameInfo<'tcx>>,
92     machine: &MiriMachine<'_, 'tcx>,
93 ) -> (Vec<FrameInfo<'tcx>>, bool) {
94     match 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(machine.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| 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
113                     .retain(|frame| !frame.instance.def.requires_caller_location(machine.tcx));
114
115                 // This is part of the logic that `std` uses to select the relevant part of a
116                 // backtrace. But here, we only look for __rust_begin_short_backtrace, not
117                 // __rust_end_short_backtrace because the end symbol comes from a call to the default
118                 // panic handler.
119                 stacktrace = stacktrace
120                     .into_iter()
121                     .take_while(|frame| {
122                         let def_id = frame.instance.def_id();
123                         let path = machine.tcx.def_path_str(def_id);
124                         !path.contains("__rust_begin_short_backtrace")
125                     })
126                     .collect::<Vec<_>>();
127
128                 // After we prune frames from the bottom, there are a few left that are part of the
129                 // Rust runtime. So we remove frames until we get to a local symbol, which should be
130                 // main or a test.
131                 // This len check ensures that we don't somehow remove every frame, as doing so breaks
132                 // the primary error message.
133                 while stacktrace.len() > 1
134                     && stacktrace.last().map_or(false, |frame| !machine.is_local(frame))
135                 {
136                     stacktrace.pop();
137                 }
138             }
139             let was_pruned = stacktrace.len() != original_len;
140             (stacktrace, was_pruned)
141         }
142         BacktraceStyle::Full => (stacktrace, false),
143     }
144 }
145
146 /// Emit a custom diagnostic without going through the miri-engine machinery
147 pub fn report_error<'tcx, 'mir>(
148     ecx: &InterpCx<'mir, 'tcx, MiriMachine<'mir, 'tcx>>,
149     e: InterpErrorInfo<'tcx>,
150 ) -> Option<i64> {
151     use InterpError::*;
152
153     let mut msg = vec![];
154
155     let (title, helps) = match &e.kind() {
156         MachineStop(info) => {
157             let info = info.downcast_ref::<TerminationInfo>().expect("invalid MachineStop payload");
158             use TerminationInfo::*;
159             let title = match info {
160                 Exit(code) => return Some(*code),
161                 Abort(_) => Some("abnormal termination"),
162                 UnsupportedInIsolation(_) | Int2PtrWithStrictProvenance =>
163                     Some("unsupported operation"),
164                 StackedBorrowsUb { .. } => Some("Undefined Behavior"),
165                 Deadlock => Some("deadlock"),
166                 MultipleSymbolDefinitions { .. } | SymbolShimClashing { .. } => None,
167             };
168             #[rustfmt::skip]
169             let helps = match info {
170                 UnsupportedInIsolation(_) =>
171                     vec![
172                         (None, format!("pass the flag `-Zmiri-disable-isolation` to disable isolation;")),
173                         (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")),
174                     ],
175                 StackedBorrowsUb { help, history, .. } => {
176                     let url = "https://github.com/rust-lang/unsafe-code-guidelines/blob/master/wip/stacked-borrows.md";
177                     msg.extend(help.clone());
178                     let mut helps = vec![
179                         (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")),
180                         (None, format!("see {url} for further information")),
181                     ];
182                     if let Some(TagHistory {created, invalidated, protected}) = history.clone() {
183                         helps.push((Some(created.1), created.0));
184                         if let Some((msg, span)) = invalidated {
185                             helps.push((Some(span), msg));
186                         }
187                         if let Some((protector_msg, protector_span)) = protected {
188                             helps.push((Some(protector_span), protector_msg));
189                         }
190                     }
191                     helps
192                 }
193                 MultipleSymbolDefinitions { first, first_crate, second, second_crate, .. } =>
194                     vec![
195                         (Some(*first), format!("it's first defined here, in crate `{first_crate}`")),
196                         (Some(*second), format!("then it's defined here again, in crate `{second_crate}`")),
197                     ],
198                 SymbolShimClashing { link_name, span } =>
199                     vec![(Some(*span), format!("the `{link_name}` symbol is defined here"))],
200                 Int2PtrWithStrictProvenance =>
201                     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"))],
202                 _ => vec![],
203             };
204             (title, helps)
205         }
206         _ => {
207             #[rustfmt::skip]
208             let title = match e.kind() {
209                 Unsupported(_) =>
210                     "unsupported operation",
211                 UndefinedBehavior(_) =>
212                     "Undefined Behavior",
213                 ResourceExhaustion(_) =>
214                     "resource exhaustion",
215                 InvalidProgram(
216                     InvalidProgramInfo::AlreadyReported(_) |
217                     InvalidProgramInfo::Layout(..) |
218                     InvalidProgramInfo::ReferencedConstant
219                 ) =>
220                     "post-monomorphization error",
221                 kind =>
222                     bug!("This error should be impossible in Miri: {kind:?}"),
223             };
224             #[rustfmt::skip]
225             let helps = match e.kind() {
226                 Unsupported(
227                     UnsupportedOpInfo::ThreadLocalStatic(_) |
228                     UnsupportedOpInfo::ReadExternStatic(_) |
229                     UnsupportedOpInfo::PartialPointerOverwrite(_) | // we make memory uninit instead
230                     UnsupportedOpInfo::ReadPointerAsBytes
231                 ) =>
232                     panic!("Error should never be raised by Miri: {kind:?}", kind = e.kind()),
233                 Unsupported(
234                     UnsupportedOpInfo::Unsupported(_) |
235                     UnsupportedOpInfo::PartialPointerCopy(_)
236                 ) =>
237                     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"))],
238                 UndefinedBehavior(UndefinedBehaviorInfo::AlignmentCheckFailed { .. })
239                     if ecx.machine.check_alignment == AlignmentCheck::Symbolic
240                 =>
241                     vec![
242                         (None, format!("this usually indicates that your program performed an invalid operation and caused Undefined Behavior")),
243                         (None, format!("but due to `-Zmiri-symbolic-alignment-check`, alignment errors can also be false positives")),
244                     ],
245                 UndefinedBehavior(_) =>
246                     vec![
247                         (None, format!("this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior")),
248                         (None, format!("see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information")),
249                     ],
250                 InvalidProgram(_) | ResourceExhaustion(_) | MachineStop(_) =>
251                     vec![],
252             };
253             (Some(title), helps)
254         }
255     };
256
257     let stacktrace = ecx.generate_stacktrace();
258     let (stacktrace, was_pruned) = prune_stacktrace(stacktrace, &ecx.machine);
259     e.print_backtrace();
260     msg.insert(0, e.to_string());
261     report_msg(
262         DiagLevel::Error,
263         &if let Some(title) = title { format!("{}: {}", title, msg[0]) } else { msg[0].clone() },
264         msg,
265         vec![],
266         helps,
267         &stacktrace,
268         &ecx.machine,
269     );
270
271     // Include a note like `std` does when we omit frames from a backtrace
272     if was_pruned {
273         ecx.tcx.sess.diagnostic().note_without_error(
274             "some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace",
275         );
276     }
277
278     // Debug-dump all locals.
279     for (i, frame) in ecx.active_thread_stack().iter().enumerate() {
280         trace!("-------------------");
281         trace!("Frame {}", i);
282         trace!("    return: {:?}", *frame.return_place);
283         for (i, local) in frame.locals.iter().enumerate() {
284             trace!("    local {}: {:?}", i, local.value);
285         }
286     }
287
288     // Extra output to help debug specific issues.
289     match e.kind() {
290         UndefinedBehavior(UndefinedBehaviorInfo::InvalidUninitBytes(Some((alloc_id, access)))) => {
291             eprintln!(
292                 "Uninitialized memory occurred at {alloc_id:?}{range:?}, in this allocation:",
293                 range = access.uninit,
294             );
295             eprintln!("{:?}", ecx.dump_alloc(*alloc_id));
296         }
297         _ => {}
298     }
299
300     None
301 }
302
303 /// Report an error or note (depending on the `error` argument) with the given stacktrace.
304 /// Also emits a full stacktrace of the interpreter stack.
305 /// We want to present a multi-line span message for some errors. Diagnostics do not support this
306 /// directly, so we pass the lines as a `Vec<String>` and display each line after the first with an
307 /// additional `span_label` or `note` call.
308 fn report_msg<'tcx>(
309     diag_level: DiagLevel,
310     title: &str,
311     span_msg: Vec<String>,
312     notes: Vec<(Option<SpanData>, String)>,
313     helps: Vec<(Option<SpanData>, String)>,
314     stacktrace: &[FrameInfo<'tcx>],
315     machine: &MiriMachine<'_, 'tcx>,
316 ) {
317     let span = stacktrace.first().map_or(DUMMY_SP, |fi| fi.span);
318     let sess = machine.tcx.sess;
319     let mut err = match diag_level {
320         DiagLevel::Error => sess.struct_span_err(span, title).forget_guarantee(),
321         DiagLevel::Warning => sess.struct_span_warn(span, title),
322         DiagLevel::Note => sess.diagnostic().span_note_diag(span, title),
323     };
324
325     // Show main message.
326     if span != DUMMY_SP {
327         for line in span_msg {
328             err.span_label(span, line);
329         }
330     } else {
331         // Make sure we show the message even when it is a dummy span.
332         for line in span_msg {
333             err.note(&line);
334         }
335         err.note("(no span available)");
336     }
337
338     // Show note and help messages.
339     for (span_data, note) in &notes {
340         if let Some(span_data) = span_data {
341             err.span_note(span_data.span(), note);
342         } else {
343             err.note(note);
344         }
345     }
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     if notes.len() + helps.len() > 0 {
354         // Add visual separator before backtrace.
355         err.note("BACKTRACE:");
356     }
357     // Add backtrace
358     for (idx, frame_info) in stacktrace.iter().enumerate() {
359         let is_local = machine.is_local(frame_info);
360         // No span for non-local frames and the first frame (which is the error site).
361         if is_local && idx > 0 {
362             err.span_note(frame_info.span, &frame_info.to_string());
363         } else {
364             err.note(&frame_info.to_string());
365         }
366     }
367
368     err.emit();
369 }
370
371 impl<'mir, 'tcx> MiriMachine<'mir, 'tcx> {
372     pub fn emit_diagnostic(&self, e: NonHaltingDiagnostic) {
373         use NonHaltingDiagnostic::*;
374
375         let stacktrace =
376             MiriInterpCx::generate_stacktrace_from_stack(self.threads.active_thread_stack());
377         let (stacktrace, _was_pruned) = prune_stacktrace(stacktrace, self);
378
379         let (title, diag_level) = match e {
380             RejectedIsolatedOp(_) => ("operation rejected by isolation", DiagLevel::Warning),
381             Int2Ptr { .. } => ("integer-to-pointer cast", DiagLevel::Warning),
382             CreatedPointerTag(..)
383             | PoppedPointerTag(..)
384             | CreatedCallId(..)
385             | CreatedAlloc(..)
386             | FreedAlloc(..)
387             | ProgressReport { .. }
388             | WeakMemoryOutdatedLoad => ("tracking was triggered", DiagLevel::Note),
389         };
390
391         let msg = match e {
392             CreatedPointerTag(tag, None) => format!("created tag {tag:?}"),
393             CreatedPointerTag(tag, Some((alloc_id, range))) =>
394                 format!("created tag {tag:?} at {alloc_id:?}{range:?}"),
395             PoppedPointerTag(item, tag) =>
396                 match tag {
397                     None => format!("popped tracked tag for item {item:?} due to deallocation",),
398                     Some((tag, access)) => {
399                         format!(
400                             "popped tracked tag for item {item:?} due to {access:?} access for {tag:?}",
401                         )
402                     }
403                 },
404             CreatedCallId(id) => format!("function call with id {id}"),
405             CreatedAlloc(AllocId(id), size, align, kind) =>
406                 format!(
407                     "created {kind} allocation of {size} bytes (alignment {align} bytes) with id {id}",
408                     size = size.bytes(),
409                     align = align.bytes(),
410                 ),
411             FreedAlloc(AllocId(id)) => format!("freed allocation with id {id}"),
412             RejectedIsolatedOp(ref op) =>
413                 format!("{op} was made to return an error due to isolation"),
414             ProgressReport { .. } =>
415                 format!("progress report: current operation being executed is here"),
416             Int2Ptr { .. } => format!("integer-to-pointer cast"),
417             WeakMemoryOutdatedLoad =>
418                 format!("weak memory emulation: outdated value returned from load"),
419         };
420
421         let notes = match e {
422             ProgressReport { block_count } => {
423                 // It is important that each progress report is slightly different, since
424                 // identical diagnostics are being deduplicated.
425                 vec![(None, format!("so far, {block_count} basic blocks have been executed"))]
426             }
427             _ => vec![],
428         };
429
430         let helps = match e {
431             Int2Ptr { details: true } =>
432                 vec![
433                     (
434                         None,
435                         format!(
436                             "This program is using integer-to-pointer casts or (equivalently) `ptr::from_exposed_addr`,"
437                         ),
438                     ),
439                     (
440                         None,
441                         format!("which means that Miri might miss pointer bugs in this program."),
442                     ),
443                     (
444                         None,
445                         format!(
446                             "See https://doc.rust-lang.org/nightly/std/ptr/fn.from_exposed_addr.html for more details on that operation."
447                         ),
448                     ),
449                     (
450                         None,
451                         format!(
452                             "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."
453                         ),
454                     ),
455                     (
456                         None,
457                         format!(
458                             "You can then pass the `-Zmiri-strict-provenance` flag to Miri, to ensure you are not relying on `from_exposed_addr` semantics."
459                         ),
460                     ),
461                     (
462                         None,
463                         format!(
464                             "Alternatively, the `-Zmiri-permissive-provenance` flag disables this warning."
465                         ),
466                     ),
467                 ],
468             _ => vec![],
469         };
470
471         report_msg(diag_level, title, vec![msg], notes, helps, &stacktrace, self);
472     }
473 }
474
475 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriInterpCx<'mir, 'tcx> {}
476 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> {
477     fn emit_diagnostic(&self, e: NonHaltingDiagnostic) {
478         let this = self.eval_context_ref();
479         this.machine.emit_diagnostic(e);
480     }
481
482     /// We had a panic in Miri itself, try to print something useful.
483     fn handle_ice(&self) {
484         eprintln!();
485         eprintln!(
486             "Miri caused an ICE during evaluation. Here's the interpreter backtrace at the time of the panic:"
487         );
488         let this = self.eval_context_ref();
489         let stacktrace = this.generate_stacktrace();
490         report_msg(
491             DiagLevel::Note,
492             "the place in the program where the ICE was triggered",
493             vec![],
494             vec![],
495             vec![],
496             &stacktrace,
497             &this.machine,
498         );
499     }
500 }