]> git.lizzy.rs Git - rust.git/blob - src/tools/miri/src/diagnostics.rs
fix ICE in pointer tracking
[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 }
39
40 impl fmt::Display for TerminationInfo {
41     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
42         use TerminationInfo::*;
43         match self {
44             Exit { code, .. } => write!(f, "the evaluated program completed with exit code {code}"),
45             Abort(msg) => write!(f, "{msg}"),
46             UnsupportedInIsolation(msg) => write!(f, "{msg}"),
47             Int2PtrWithStrictProvenance =>
48                 write!(
49                     f,
50                     "integer-to-pointer casts and `ptr::from_exposed_addr` are not supported with `-Zmiri-strict-provenance`"
51                 ),
52             StackedBorrowsUb { msg, .. } => write!(f, "{msg}"),
53             Deadlock => write!(f, "the evaluated program deadlocked"),
54             MultipleSymbolDefinitions { link_name, .. } =>
55                 write!(f, "multiple definitions of symbol `{link_name}`"),
56             SymbolShimClashing { link_name, .. } =>
57                 write!(f, "found `{link_name}` symbol definition that clashes with a built-in shim",),
58         }
59     }
60 }
61
62 impl MachineStopType for TerminationInfo {}
63
64 /// Miri specific diagnostics
65 pub enum NonHaltingDiagnostic {
66     /// (new_tag, new_kind, (alloc_id, base_offset, orig_tag))
67     ///
68     /// new_kind is `None` for base tags.
69     CreatedPointerTag(NonZeroU64, Option<String>, Option<(AllocId, AllocRange, ProvenanceExtra)>),
70     /// This `Item` was popped from the borrow stack. The string explains the reason.
71     PoppedPointerTag(Item, String),
72     CreatedCallId(CallId),
73     CreatedAlloc(AllocId, Size, Align, MemoryKind<MiriMemoryKind>),
74     FreedAlloc(AllocId),
75     RejectedIsolatedOp(String),
76     ProgressReport {
77         block_count: u64, // how many basic blocks have been run so far
78     },
79     Int2Ptr {
80         details: bool,
81     },
82     WeakMemoryOutdatedLoad,
83 }
84
85 /// Level of Miri specific diagnostics
86 enum DiagLevel {
87     Error,
88     Warning,
89     Note,
90 }
91
92 /// Attempts to prune a stacktrace to omit the Rust runtime, and returns a bool indicating if any
93 /// frames were pruned. If the stacktrace does not have any local frames, we conclude that it must
94 /// be pointing to a problem in the Rust runtime itself, and do not prune it at all.
95 fn prune_stacktrace<'tcx>(
96     mut stacktrace: Vec<FrameInfo<'tcx>>,
97     machine: &MiriMachine<'_, 'tcx>,
98 ) -> (Vec<FrameInfo<'tcx>>, bool) {
99     match machine.backtrace_style {
100         BacktraceStyle::Off => {
101             // Remove all frames marked with `caller_location` -- that attribute indicates we
102             // usually want to point at the caller, not them.
103             stacktrace.retain(|frame| !frame.instance.def.requires_caller_location(machine.tcx));
104             // Retain one frame so that we can print a span for the error itself
105             stacktrace.truncate(1);
106             (stacktrace, false)
107         }
108         BacktraceStyle::Short => {
109             let original_len = stacktrace.len();
110             // Only prune frames if there is at least one local frame. This check ensures that if
111             // we get a backtrace that never makes it to the user code because it has detected a
112             // bug in the Rust runtime, we don't prune away every frame.
113             let has_local_frame = stacktrace.iter().any(|frame| machine.is_local(frame));
114             if has_local_frame {
115                 // Remove all frames marked with `caller_location` -- that attribute indicates we
116                 // usually want to point at the caller, not them.
117                 stacktrace
118                     .retain(|frame| !frame.instance.def.requires_caller_location(machine.tcx));
119
120                 // This is part of the logic that `std` uses to select the relevant part of a
121                 // backtrace. But here, we only look for __rust_begin_short_backtrace, not
122                 // __rust_end_short_backtrace because the end symbol comes from a call to the default
123                 // panic handler.
124                 stacktrace = stacktrace
125                     .into_iter()
126                     .take_while(|frame| {
127                         let def_id = frame.instance.def_id();
128                         let path = machine.tcx.def_path_str(def_id);
129                         !path.contains("__rust_begin_short_backtrace")
130                     })
131                     .collect::<Vec<_>>();
132
133                 // After we prune frames from the bottom, there are a few left that are part of the
134                 // Rust runtime. So we remove frames until we get to a local symbol, which should be
135                 // main or a test.
136                 // This len check ensures that we don't somehow remove every frame, as doing so breaks
137                 // the primary error message.
138                 while stacktrace.len() > 1
139                     && stacktrace.last().map_or(false, |frame| !machine.is_local(frame))
140                 {
141                     stacktrace.pop();
142                 }
143             }
144             let was_pruned = stacktrace.len() != original_len;
145             (stacktrace, was_pruned)
146         }
147         BacktraceStyle::Full => (stacktrace, false),
148     }
149 }
150
151 /// Emit a custom diagnostic without going through the miri-engine machinery.
152 ///
153 /// 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.
154 pub fn report_error<'tcx, 'mir>(
155     ecx: &InterpCx<'mir, 'tcx, MiriMachine<'mir, 'tcx>>,
156     e: InterpErrorInfo<'tcx>,
157 ) -> Option<(i64, bool)> {
158     use InterpError::*;
159
160     let mut msg = vec![];
161
162     let (title, helps) = if let MachineStop(info) = e.kind() {
163         let info = info.downcast_ref::<TerminationInfo>().expect("invalid MachineStop payload");
164         use TerminationInfo::*;
165         let title = match info {
166             Exit { code, leak_check } => return Some((*code, *leak_check)),
167             Abort(_) => Some("abnormal termination"),
168             UnsupportedInIsolation(_) | Int2PtrWithStrictProvenance =>
169                 Some("unsupported operation"),
170             StackedBorrowsUb { .. } => Some("Undefined Behavior"),
171             Deadlock => Some("deadlock"),
172             MultipleSymbolDefinitions { .. } | SymbolShimClashing { .. } => None,
173         };
174         #[rustfmt::skip]
175         let helps = match info {
176             UnsupportedInIsolation(_) =>
177                 vec![
178                     (None, format!("pass the flag `-Zmiri-disable-isolation` to disable isolation;")),
179                     (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")),
180                 ],
181             StackedBorrowsUb { help, history, .. } => {
182                 let url = "https://github.com/rust-lang/unsafe-code-guidelines/blob/master/wip/stacked-borrows.md";
183                 msg.extend(help.clone());
184                 let mut helps = vec![
185                     (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")),
186                     (None, format!("see {url} for further information")),
187                 ];
188                 if let Some(TagHistory {created, invalidated, protected}) = history.clone() {
189                     helps.push((Some(created.1), created.0));
190                     if let Some((msg, span)) = invalidated {
191                         helps.push((Some(span), msg));
192                     }
193                     if let Some((protector_msg, protector_span)) = protected {
194                         helps.push((Some(protector_span), protector_msg));
195                     }
196                 }
197                 helps
198             }
199             MultipleSymbolDefinitions { first, first_crate, second, second_crate, .. } =>
200                 vec![
201                     (Some(*first), format!("it's first defined here, in crate `{first_crate}`")),
202                     (Some(*second), format!("then it's defined here again, in crate `{second_crate}`")),
203                 ],
204             SymbolShimClashing { link_name, span } =>
205                 vec![(Some(*span), format!("the `{link_name}` symbol is defined here"))],
206             Int2PtrWithStrictProvenance =>
207                 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"))],
208             _ => vec![],
209         };
210         (title, helps)
211     } else {
212         #[rustfmt::skip]
213         let title = match e.kind() {
214             UndefinedBehavior(_) =>
215                 "Undefined Behavior",
216             ResourceExhaustion(_) =>
217                 "resource exhaustion",
218             Unsupported(
219                 // We list only the ones that can actually happen.
220                 UnsupportedOpInfo::Unsupported(_)
221             ) =>
222                 "unsupported operation",
223             InvalidProgram(
224                 // We list only the ones that can actually happen.
225                 InvalidProgramInfo::AlreadyReported(_) |
226                 InvalidProgramInfo::Layout(..)
227             ) =>
228                 "post-monomorphization error",
229             kind =>
230                 bug!("This error should be impossible in Miri: {kind:?}"),
231         };
232         #[rustfmt::skip]
233         let helps = match e.kind() {
234             Unsupported(_) =>
235                 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"))],
236             UndefinedBehavior(UndefinedBehaviorInfo::AlignmentCheckFailed { .. })
237                 if ecx.machine.check_alignment == AlignmentCheck::Symbolic
238             =>
239                 vec![
240                     (None, format!("this usually indicates that your program performed an invalid operation and caused Undefined Behavior")),
241                     (None, format!("but due to `-Zmiri-symbolic-alignment-check`, alignment errors can also be false positives")),
242                 ],
243             UndefinedBehavior(_) =>
244                 vec![
245                     (None, format!("this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior")),
246                     (None, format!("see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information")),
247                 ],
248             InvalidProgram(
249                 InvalidProgramInfo::AlreadyReported(rustc_errors::ErrorGuaranteed { .. })
250             ) => {
251                 // This got already reported. No point in reporting it again.
252                 return None;
253             }
254             _ =>
255                 vec![],
256         };
257         (Some(title), helps)
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, cause) => format!("popped tracked tag for item {item:?}{cause}"),
402             CreatedCallId(id) => format!("function call with id {id}"),
403             CreatedAlloc(AllocId(id), size, align, kind) =>
404                 format!(
405                     "created {kind} allocation of {size} bytes (alignment {align} bytes) with id {id}",
406                     size = size.bytes(),
407                     align = align.bytes(),
408                 ),
409             FreedAlloc(AllocId(id)) => format!("freed allocation with id {id}"),
410             RejectedIsolatedOp(ref op) =>
411                 format!("{op} was made to return an error due to isolation"),
412             ProgressReport { .. } =>
413                 format!("progress report: current operation being executed is here"),
414             Int2Ptr { .. } => format!("integer-to-pointer cast"),
415             WeakMemoryOutdatedLoad =>
416                 format!("weak memory emulation: outdated value returned from load"),
417         };
418
419         let notes = match &e {
420             ProgressReport { block_count } => {
421                 // It is important that each progress report is slightly different, since
422                 // identical diagnostics are being deduplicated.
423                 vec![(None, format!("so far, {block_count} basic blocks have been executed"))]
424             }
425             _ => vec![],
426         };
427
428         let helps = match &e {
429             Int2Ptr { details: true } =>
430                 vec![
431                     (
432                         None,
433                         format!(
434                             "This program is using integer-to-pointer casts or (equivalently) `ptr::from_exposed_addr`,"
435                         ),
436                     ),
437                     (
438                         None,
439                         format!("which means that Miri might miss pointer bugs in this program."),
440                     ),
441                     (
442                         None,
443                         format!(
444                             "See https://doc.rust-lang.org/nightly/std/ptr/fn.from_exposed_addr.html for more details on that operation."
445                         ),
446                     ),
447                     (
448                         None,
449                         format!(
450                             "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."
451                         ),
452                     ),
453                     (
454                         None,
455                         format!(
456                             "You can then pass the `-Zmiri-strict-provenance` flag to Miri, to ensure you are not relying on `from_exposed_addr` semantics."
457                         ),
458                     ),
459                     (
460                         None,
461                         format!(
462                             "Alternatively, the `-Zmiri-permissive-provenance` flag disables this warning."
463                         ),
464                     ),
465                 ],
466             _ => vec![],
467         };
468
469         report_msg(diag_level, title, vec![msg], notes, helps, &stacktrace, self);
470     }
471 }
472
473 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriInterpCx<'mir, 'tcx> {}
474 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> {
475     fn emit_diagnostic(&self, e: NonHaltingDiagnostic) {
476         let this = self.eval_context_ref();
477         this.machine.emit_diagnostic(e);
478     }
479
480     /// We had a panic in Miri itself, try to print something useful.
481     fn handle_ice(&self) {
482         eprintln!();
483         eprintln!(
484             "Miri caused an ICE during evaluation. Here's the interpreter backtrace at the time of the panic:"
485         );
486         let this = self.eval_context_ref();
487         let stacktrace = this.generate_stacktrace();
488         report_msg(
489             DiagLevel::Note,
490             "the place in the program where the ICE was triggered",
491             vec![],
492             vec![],
493             vec![],
494             &stacktrace,
495             &this.machine,
496         );
497     }
498 }