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