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