]> git.lizzy.rs Git - rust.git/blob - src/tools/miri/src/diagnostics.rs
Rollup merge of #103468 - chenyukang:yukang/fix-103435-extra-parentheses, r=estebank
[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 pub fn report_error<'tcx, 'mir>(
151     ecx: &InterpCx<'mir, 'tcx, MiriMachine<'mir, 'tcx>>,
152     e: InterpErrorInfo<'tcx>,
153 ) -> Option<i64> {
154     use InterpError::*;
155
156     let mut msg = vec![];
157
158     let (title, helps) = match &e.kind() {
159         MachineStop(info) => {
160             let info = info.downcast_ref::<TerminationInfo>().expect("invalid MachineStop payload");
161             use TerminationInfo::*;
162             let title = match info {
163                 Exit(code) => return Some(*code),
164                 Abort(_) => Some("abnormal termination"),
165                 UnsupportedInIsolation(_) | Int2PtrWithStrictProvenance =>
166                     Some("unsupported operation"),
167                 StackedBorrowsUb { .. } => Some("Undefined Behavior"),
168                 Deadlock => Some("deadlock"),
169                 MultipleSymbolDefinitions { .. } | SymbolShimClashing { .. } => None,
170             };
171             #[rustfmt::skip]
172             let helps = match info {
173                 UnsupportedInIsolation(_) =>
174                     vec![
175                         (None, format!("pass the flag `-Zmiri-disable-isolation` to disable isolation;")),
176                         (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")),
177                     ],
178                 StackedBorrowsUb { help, history, .. } => {
179                     let url = "https://github.com/rust-lang/unsafe-code-guidelines/blob/master/wip/stacked-borrows.md";
180                     msg.extend(help.clone());
181                     let mut helps = vec![
182                         (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")),
183                         (None, format!("see {url} for further information")),
184                     ];
185                     if let Some(TagHistory {created, invalidated, protected}) = history.clone() {
186                         helps.push((Some(created.1), created.0));
187                         if let Some((msg, span)) = invalidated {
188                             helps.push((Some(span), msg));
189                         }
190                         if let Some((protector_msg, protector_span)) = protected {
191                             helps.push((Some(protector_span), protector_msg));
192                         }
193                     }
194                     helps
195                 }
196                 MultipleSymbolDefinitions { first, first_crate, second, second_crate, .. } =>
197                     vec![
198                         (Some(*first), format!("it's first defined here, in crate `{first_crate}`")),
199                         (Some(*second), format!("then it's defined here again, in crate `{second_crate}`")),
200                     ],
201                 SymbolShimClashing { link_name, span } =>
202                     vec![(Some(*span), format!("the `{link_name}` symbol is defined here"))],
203                 Int2PtrWithStrictProvenance =>
204                     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"))],
205                 _ => vec![],
206             };
207             (title, helps)
208         }
209         _ => {
210             #[rustfmt::skip]
211             let title = match e.kind() {
212                 Unsupported(_) =>
213                     "unsupported operation",
214                 UndefinedBehavior(_) =>
215                     "Undefined Behavior",
216                 ResourceExhaustion(_) =>
217                     "resource exhaustion",
218                 InvalidProgram(
219                     InvalidProgramInfo::AlreadyReported(_) |
220                     InvalidProgramInfo::Layout(..) |
221                     InvalidProgramInfo::ReferencedConstant
222                 ) =>
223                     "post-monomorphization error",
224                 kind =>
225                     bug!("This error should be impossible in Miri: {kind:?}"),
226             };
227             #[rustfmt::skip]
228             let helps = match e.kind() {
229                 Unsupported(
230                     UnsupportedOpInfo::ThreadLocalStatic(_) |
231                     UnsupportedOpInfo::ReadExternStatic(_) |
232                     UnsupportedOpInfo::PartialPointerOverwrite(_) | // we make memory uninit instead
233                     UnsupportedOpInfo::ReadPointerAsBytes
234                 ) =>
235                     panic!("Error should never be raised by Miri: {kind:?}", kind = e.kind()),
236                 Unsupported(
237                     UnsupportedOpInfo::Unsupported(_) |
238                     UnsupportedOpInfo::PartialPointerCopy(_)
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(stacktrace, &ecx.machine);
262     e.print_backtrace();
263     msg.insert(0, e.to_string());
264     report_msg(
265         DiagLevel::Error,
266         &if let Some(title) = title { format!("{title}: {}", msg[0]) } else { msg[0].clone() },
267         msg,
268         vec![],
269         helps,
270         &stacktrace,
271         &ecx.machine,
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<'tcx>(
312     diag_level: DiagLevel,
313     title: &str,
314     span_msg: Vec<String>,
315     notes: Vec<(Option<SpanData>, String)>,
316     helps: Vec<(Option<SpanData>, String)>,
317     stacktrace: &[FrameInfo<'tcx>],
318     machine: &MiriMachine<'_, 'tcx>,
319 ) {
320     let span = stacktrace.first().map_or(DUMMY_SP, |fi| fi.span);
321     let sess = machine.tcx.sess;
322     let mut err = match diag_level {
323         DiagLevel::Error => sess.struct_span_err(span, title).forget_guarantee(),
324         DiagLevel::Warning => sess.struct_span_warn(span, title),
325         DiagLevel::Note => sess.diagnostic().span_note_diag(span, title),
326     };
327
328     // Show main message.
329     if span != DUMMY_SP {
330         for line in span_msg {
331             err.span_label(span, line);
332         }
333     } else {
334         // Make sure we show the message even when it is a dummy span.
335         for line in span_msg {
336             err.note(&line);
337         }
338         err.note("(no span available)");
339     }
340
341     // Show note and help messages.
342     for (span_data, note) in &notes {
343         if let Some(span_data) = span_data {
344             err.span_note(span_data.span(), note);
345         } else {
346             err.note(note);
347         }
348     }
349     for (span_data, help) in &helps {
350         if let Some(span_data) = span_data {
351             err.span_help(span_data.span(), help);
352         } else {
353             err.help(help);
354         }
355     }
356     if notes.len() + helps.len() > 0 {
357         // Add visual separator before backtrace.
358         err.note("BACKTRACE:");
359     }
360     // Add backtrace
361     for (idx, frame_info) in stacktrace.iter().enumerate() {
362         let is_local = machine.is_local(frame_info);
363         // No span for non-local frames and the first frame (which is the error site).
364         if is_local && idx > 0 {
365             err.span_note(frame_info.span, &frame_info.to_string());
366         } else {
367             err.note(&frame_info.to_string());
368         }
369     }
370
371     err.emit();
372 }
373
374 impl<'mir, 'tcx> MiriMachine<'mir, 'tcx> {
375     pub fn emit_diagnostic(&self, e: NonHaltingDiagnostic) {
376         use NonHaltingDiagnostic::*;
377
378         let stacktrace =
379             MiriInterpCx::generate_stacktrace_from_stack(self.threads.active_thread_stack());
380         let (stacktrace, _was_pruned) = prune_stacktrace(stacktrace, self);
381
382         let (title, diag_level) = match &e {
383             RejectedIsolatedOp(_) => ("operation rejected by isolation", DiagLevel::Warning),
384             Int2Ptr { .. } => ("integer-to-pointer cast", DiagLevel::Warning),
385             CreatedPointerTag(..)
386             | PoppedPointerTag(..)
387             | CreatedCallId(..)
388             | CreatedAlloc(..)
389             | FreedAlloc(..)
390             | ProgressReport { .. }
391             | WeakMemoryOutdatedLoad => ("tracking was triggered", DiagLevel::Note),
392         };
393
394         let msg = match &e {
395             CreatedPointerTag(tag, None, _) => format!("created base tag {tag:?}"),
396             CreatedPointerTag(tag, Some(kind), None) => format!("created {tag:?} for {kind}"),
397             CreatedPointerTag(tag, Some(kind), Some((alloc_id, range, orig_tag))) =>
398                 format!(
399                     "created tag {tag:?} for {kind} at {alloc_id:?}{range:?} derived from {orig_tag:?}"
400                 ),
401             PoppedPointerTag(item, tag) =>
402                 match tag {
403                     None => format!("popped tracked tag for item {item:?} due to deallocation",),
404                     Some((tag, access)) => {
405                         format!(
406                             "popped tracked tag for item {item:?} due to {access:?} access for {tag:?}",
407                         )
408                     }
409                 },
410             CreatedCallId(id) => format!("function call with id {id}"),
411             CreatedAlloc(AllocId(id), size, align, kind) =>
412                 format!(
413                     "created {kind} allocation of {size} bytes (alignment {align} bytes) with id {id}",
414                     size = size.bytes(),
415                     align = align.bytes(),
416                 ),
417             FreedAlloc(AllocId(id)) => format!("freed allocation with id {id}"),
418             RejectedIsolatedOp(ref op) =>
419                 format!("{op} was made to return an error due to isolation"),
420             ProgressReport { .. } =>
421                 format!("progress report: current operation being executed is here"),
422             Int2Ptr { .. } => format!("integer-to-pointer cast"),
423             WeakMemoryOutdatedLoad =>
424                 format!("weak memory emulation: outdated value returned from load"),
425         };
426
427         let notes = match &e {
428             ProgressReport { block_count } => {
429                 // It is important that each progress report is slightly different, since
430                 // identical diagnostics are being deduplicated.
431                 vec![(None, format!("so far, {block_count} basic blocks have been executed"))]
432             }
433             _ => vec![],
434         };
435
436         let helps = match &e {
437             Int2Ptr { details: true } =>
438                 vec![
439                     (
440                         None,
441                         format!(
442                             "This program is using integer-to-pointer casts or (equivalently) `ptr::from_exposed_addr`,"
443                         ),
444                     ),
445                     (
446                         None,
447                         format!("which means that Miri might miss pointer bugs in this program."),
448                     ),
449                     (
450                         None,
451                         format!(
452                             "See https://doc.rust-lang.org/nightly/std/ptr/fn.from_exposed_addr.html for more details on that operation."
453                         ),
454                     ),
455                     (
456                         None,
457                         format!(
458                             "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."
459                         ),
460                     ),
461                     (
462                         None,
463                         format!(
464                             "You can then pass the `-Zmiri-strict-provenance` flag to Miri, to ensure you are not relying on `from_exposed_addr` semantics."
465                         ),
466                     ),
467                     (
468                         None,
469                         format!(
470                             "Alternatively, the `-Zmiri-permissive-provenance` flag disables this warning."
471                         ),
472                     ),
473                 ],
474             _ => vec![],
475         };
476
477         report_msg(diag_level, title, vec![msg], notes, helps, &stacktrace, self);
478     }
479 }
480
481 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriInterpCx<'mir, 'tcx> {}
482 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> {
483     fn emit_diagnostic(&self, e: NonHaltingDiagnostic) {
484         let this = self.eval_context_ref();
485         this.machine.emit_diagnostic(e);
486     }
487
488     /// We had a panic in Miri itself, try to print something useful.
489     fn handle_ice(&self) {
490         eprintln!();
491         eprintln!(
492             "Miri caused an ICE during evaluation. Here's the interpreter backtrace at the time of the panic:"
493         );
494         let this = self.eval_context_ref();
495         let stacktrace = this.generate_stacktrace();
496         report_msg(
497             DiagLevel::Note,
498             "the place in the program where the ICE was triggered",
499             vec![],
500             vec![],
501             vec![],
502             &stacktrace,
503             &this.machine,
504         );
505     }
506 }