]> git.lizzy.rs Git - rust.git/blob - src/diagnostics.rs
Explain the behavior of the cache upon clear
[rust.git] / src / diagnostics.rs
1 use std::cell::RefCell;
2 use std::fmt;
3 use std::num::NonZeroU64;
4
5 use log::trace;
6
7 use rustc_middle::ty;
8 use rustc_span::{source_map::DUMMY_SP, Span, SpanData, Symbol};
9 use rustc_target::abi::{Align, Size};
10
11 use crate::helpers::HexRange;
12 use crate::stacked_borrows::{diagnostics::TagHistory, AccessKind};
13 use crate::*;
14
15 /// Details of premature program termination.
16 pub enum TerminationInfo {
17     Exit(i64),
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!(
58                     f,
59                     "found `{}` symbol definition that clashes with a built-in shim",
60                     link_name
61                 ),
62         }
63     }
64 }
65
66 impl MachineStopType for TerminationInfo {}
67
68 /// Miri specific diagnostics
69 pub enum NonHaltingDiagnostic {
70     CreatedPointerTag(NonZeroU64),
71     /// This `Item` was popped from the borrow stack, either due to an access with the given tag or
72     /// a deallocation when the second argument is `None`.
73     PoppedPointerTag(Item, Option<(SbTagExtra, AccessKind)>),
74     CreatedCallId(CallId),
75     CreatedAlloc(AllocId, Size, Align, MemoryKind<MiriMemoryKind>),
76     FreedAlloc(AllocId),
77     RejectedIsolatedOp(String),
78     ProgressReport,
79     Int2Ptr {
80         details: bool,
81     },
82 }
83
84 /// Level of Miri specific diagnostics
85 enum DiagLevel {
86     Error,
87     Warning,
88     Note,
89 }
90
91 /// Attempts to prune a stacktrace to omit the Rust runtime, and returns a bool indicating if any
92 /// frames were pruned. If the stacktrace does not have any local frames, we conclude that it must
93 /// be pointing to a problem in the Rust runtime itself, and do not prune it at all.
94 fn prune_stacktrace<'mir, 'tcx>(
95     ecx: &InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
96     mut stacktrace: Vec<FrameInfo<'tcx>>,
97 ) -> (Vec<FrameInfo<'tcx>>, bool) {
98     match ecx.machine.backtrace_style {
99         BacktraceStyle::Off => {
100             // Remove all frames marked with `caller_location` -- that attribute indicates we
101             // usually want to point at the caller, not them.
102             stacktrace.retain(|frame| !frame.instance.def.requires_caller_location(*ecx.tcx));
103             // Retain one frame so that we can print a span for the error itself
104             stacktrace.truncate(1);
105             (stacktrace, false)
106         }
107         BacktraceStyle::Short => {
108             let original_len = stacktrace.len();
109             // Only prune frames if there is at least one local frame. This check ensures that if
110             // we get a backtrace that never makes it to the user code because it has detected a
111             // bug in the Rust runtime, we don't prune away every frame.
112             let has_local_frame = stacktrace.iter().any(|frame| ecx.machine.is_local(frame));
113             if has_local_frame {
114                 // Remove all frames marked with `caller_location` -- that attribute indicates we
115                 // usually want to point at the caller, not them.
116                 stacktrace.retain(|frame| !frame.instance.def.requires_caller_location(*ecx.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 = ecx.tcx.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| !ecx.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, Evaluator<'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                     match history {
186                         Some(TagHistory::Tagged {tag, created: (created_range, created_span), invalidated, protected }) => {
187                             let msg = format!("{:?} was created by a retag at offsets {}", tag, HexRange(*created_range));
188                             helps.push((Some(*created_span), msg));
189                             if let Some((invalidated_range, invalidated_span)) = invalidated {
190                                 let msg = format!("{:?} was later invalidated at offsets {}", tag, HexRange(*invalidated_range));
191                                 helps.push((Some(*invalidated_span), msg));
192                             }
193                             if let Some((protecting_tag, protecting_tag_span, protection_span)) = protected {
194                                 helps.push((Some(*protecting_tag_span), format!("{:?} was protected due to {:?} which was created here", tag, protecting_tag)));
195                                 helps.push((Some(*protection_span), format!("this protector is live for this call")));
196                             }
197                         }
198                         None => {}
199                     }
200                     helps
201                 }
202                 MultipleSymbolDefinitions { first, first_crate, second, second_crate, .. } =>
203                     vec![
204                         (Some(*first), format!("it's first defined here, in crate `{}`", first_crate)),
205                         (Some(*second), format!("then it's defined here again, in crate `{}`", second_crate)),
206                     ],
207                 SymbolShimClashing { link_name, span } =>
208                     vec![(Some(*span), format!("the `{}` symbol is defined here", link_name))],
209                 Int2PtrWithStrictProvenance =>
210                     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"))],
211                 _ => vec![],
212             };
213             (title, helps)
214         }
215         _ => {
216             #[rustfmt::skip]
217             let title = match e.kind() {
218                 Unsupported(_) =>
219                     "unsupported operation",
220                 UndefinedBehavior(_) =>
221                     "Undefined Behavior",
222                 ResourceExhaustion(_) =>
223                     "resource exhaustion",
224                 InvalidProgram(
225                     InvalidProgramInfo::AlreadyReported(_) |
226                     InvalidProgramInfo::Layout(..) |
227                     InvalidProgramInfo::ReferencedConstant
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                     UnsupportedOpInfo::ThreadLocalStatic(_) |
237                     UnsupportedOpInfo::ReadExternStatic(_)
238                 ) =>
239                     panic!("Error should never be raised by Miri: {:?}", e.kind()),
240                 Unsupported(
241                     UnsupportedOpInfo::Unsupported(_) |
242                     UnsupportedOpInfo::PartialPointerOverwrite(_) |
243                     UnsupportedOpInfo::ReadPointerAsBytes
244                 ) =>
245                     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"))],
246                 UndefinedBehavior(UndefinedBehaviorInfo::AlignmentCheckFailed { .. })
247                     if ecx.machine.check_alignment == AlignmentCheck::Symbolic
248                 =>
249                     vec![
250                         (None, format!("this usually indicates that your program performed an invalid operation and caused Undefined Behavior")),
251                         (None, format!("but due to `-Zmiri-symbolic-alignment-check`, alignment errors can also be false positives")),
252                     ],
253                 UndefinedBehavior(_) =>
254                     vec![
255                         (None, format!("this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior")),
256                         (None, format!("see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information")),
257                     ],
258                 InvalidProgram(_) | ResourceExhaustion(_) | MachineStop(_) =>
259                     vec![],
260             };
261             (Some(title), helps)
262         }
263     };
264
265     let stacktrace = ecx.generate_stacktrace();
266     let (stacktrace, was_pruned) = prune_stacktrace(ecx, stacktrace);
267     e.print_backtrace();
268     msg.insert(0, e.to_string());
269     report_msg(
270         ecx,
271         DiagLevel::Error,
272         &if let Some(title) = title { format!("{}: {}", title, msg[0]) } else { msg[0].clone() },
273         msg,
274         helps,
275         &stacktrace,
276     );
277
278     // Include a note like `std` does when we omit frames from a backtrace
279     if was_pruned {
280         ecx.tcx.sess.diagnostic().note_without_error(
281             "some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace",
282         );
283     }
284
285     // Debug-dump all locals.
286     for (i, frame) in ecx.active_thread_stack().iter().enumerate() {
287         trace!("-------------------");
288         trace!("Frame {}", i);
289         trace!("    return: {:?}", *frame.return_place);
290         for (i, local) in frame.locals.iter().enumerate() {
291             trace!("    local {}: {:?}", i, local.value);
292         }
293     }
294
295     // Extra output to help debug specific issues.
296     match e.kind() {
297         UndefinedBehavior(UndefinedBehaviorInfo::InvalidUninitBytes(Some((alloc_id, access)))) => {
298             eprintln!(
299                 "Uninitialized read occurred at offsets 0x{:x}..0x{:x} into this allocation:",
300                 access.uninit_offset.bytes(),
301                 access.uninit_offset.bytes() + access.uninit_size.bytes(),
302             );
303             eprintln!("{:?}", ecx.dump_alloc(*alloc_id));
304         }
305         _ => {}
306     }
307
308     None
309 }
310
311 /// Report an error or note (depending on the `error` argument) with the given stacktrace.
312 /// Also emits a full stacktrace of the interpreter stack.
313 /// We want to present a multi-line span message for some errors. Diagnostics do not support this
314 /// directly, so we pass the lines as a `Vec<String>` and display each line after the first with an
315 /// additional `span_label` or `note` call.
316 fn report_msg<'mir, 'tcx>(
317     ecx: &InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
318     diag_level: DiagLevel,
319     title: &str,
320     span_msg: Vec<String>,
321     mut helps: Vec<(Option<SpanData>, String)>,
322     stacktrace: &[FrameInfo<'tcx>],
323 ) {
324     let span = stacktrace.first().map_or(DUMMY_SP, |fi| fi.span);
325     let sess = ecx.tcx.sess;
326     let mut err = match diag_level {
327         DiagLevel::Error => sess.struct_span_err(span, title).forget_guarantee(),
328         DiagLevel::Warning => sess.struct_span_warn(span, title),
329         DiagLevel::Note => sess.diagnostic().span_note_diag(span, title),
330     };
331
332     // Show main message.
333     if span != DUMMY_SP {
334         for line in span_msg {
335             err.span_label(span, line);
336         }
337     } else {
338         // Make sure we show the message even when it is a dummy span.
339         for line in span_msg {
340             err.note(&line);
341         }
342         err.note("(no span available)");
343     }
344
345     // Show help messages.
346     if !helps.is_empty() {
347         // Add visual separator before backtrace.
348         helps.last_mut().unwrap().1.push('\n');
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     }
357     // Add backtrace
358     for (idx, frame_info) in stacktrace.iter().enumerate() {
359         let is_local = ecx.machine.is_local(frame_info);
360         // No span for non-local frames and the first frame (which is the error site).
361         if is_local && idx > 0 {
362             err.span_note(frame_info.span, &frame_info.to_string());
363         } else {
364             err.note(&frame_info.to_string());
365         }
366     }
367
368     err.emit();
369 }
370
371 thread_local! {
372     static DIAGNOSTICS: RefCell<Vec<NonHaltingDiagnostic>> = RefCell::new(Vec::new());
373 }
374
375 /// Schedule a diagnostic for emitting. This function works even if you have no `InterpCx` available.
376 /// The diagnostic will be emitted after the current interpreter step is finished.
377 pub fn register_diagnostic(e: NonHaltingDiagnostic) {
378     DIAGNOSTICS.with(|diagnostics| diagnostics.borrow_mut().push(e));
379 }
380
381 /// Remember enough about the topmost frame so that we can restore the stack
382 /// after a step was taken.
383 pub struct TopFrameInfo<'tcx> {
384     stack_size: usize,
385     instance: Option<ty::Instance<'tcx>>,
386     span: Span,
387 }
388
389 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
390 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
391     fn preprocess_diagnostics(&self) -> TopFrameInfo<'tcx> {
392         // Ensure we have no lingering diagnostics.
393         DIAGNOSTICS.with(|diagnostics| assert!(diagnostics.borrow().is_empty()));
394
395         let this = self.eval_context_ref();
396         if this.active_thread_stack().is_empty() {
397             // Diagnostics can happen even with the empty stack (e.g. deallocation of thread-local statics).
398             return TopFrameInfo { stack_size: 0, instance: None, span: DUMMY_SP };
399         }
400         let frame = this.frame();
401
402         TopFrameInfo {
403             stack_size: this.active_thread_stack().len(),
404             instance: Some(frame.instance),
405             span: frame.current_span(),
406         }
407     }
408
409     /// Emit all diagnostics that were registed with `register_diagnostics`
410     fn process_diagnostics(&self, info: TopFrameInfo<'tcx>) {
411         let this = self.eval_context_ref();
412         DIAGNOSTICS.with(|diagnostics| {
413             let mut diagnostics = diagnostics.borrow_mut();
414             if diagnostics.is_empty() {
415                 return;
416             }
417             // We need to fix up the stack trace, because the machine has already
418             // stepped to the next statement.
419             let mut stacktrace = this.generate_stacktrace();
420             // Remove newly pushed frames.
421             while stacktrace.len() > info.stack_size {
422                 stacktrace.remove(0);
423             }
424             // Add popped frame back.
425             if stacktrace.len() < info.stack_size {
426                 assert!(
427                     stacktrace.len() == info.stack_size - 1,
428                     "we should never pop more than one frame at once"
429                 );
430                 let frame_info = FrameInfo {
431                     instance: info.instance.unwrap(),
432                     span: info.span,
433                     lint_root: None,
434                 };
435                 stacktrace.insert(0, frame_info);
436             } else if let Some(instance) = info.instance {
437                 // Adjust topmost frame.
438                 stacktrace[0].span = info.span;
439                 assert_eq!(
440                     stacktrace[0].instance, instance,
441                     "we should not pop and push a frame in one step"
442                 );
443             }
444
445             let (stacktrace, _was_pruned) = prune_stacktrace(this, stacktrace);
446
447             // Show diagnostics.
448             for e in diagnostics.drain(..) {
449                 use NonHaltingDiagnostic::*;
450                 let msg = match e {
451                     CreatedPointerTag(tag) => format!("created tag {:?}", tag),
452                     PoppedPointerTag(item, tag) =>
453                         match tag {
454                             None =>
455                                 format!(
456                                     "popped tracked tag for item {:?} due to deallocation",
457                                     item
458                                 ),
459                             Some((tag, access)) => {
460                                 format!(
461                                     "popped tracked tag for item {:?} due to {:?} access for {:?}",
462                                     item, access, tag
463                                 )
464                             }
465                         },
466                     CreatedCallId(id) => format!("function call with id {id}"),
467                     CreatedAlloc(AllocId(id), size, align, kind) =>
468                         format!("created {kind} allocation of {} bytes (alignment {} bytes) with id {id}", size.bytes(), align.bytes()),
469                     FreedAlloc(AllocId(id)) => format!("freed allocation with id {id}"),
470                     RejectedIsolatedOp(ref op) =>
471                         format!("{op} was made to return an error due to isolation"),
472                     ProgressReport =>
473                         format!("progress report: current operation being executed is here"),
474                     Int2Ptr { .. } => format!("integer-to-pointer cast"),
475                 };
476
477                 let (title, diag_level) = match e {
478                     RejectedIsolatedOp(_) =>
479                         ("operation rejected by isolation", DiagLevel::Warning),
480                     Int2Ptr { .. } => ("integer-to-pointer cast", DiagLevel::Warning),
481                     CreatedPointerTag(..)
482                     | PoppedPointerTag(..)
483                     | CreatedCallId(..)
484                     | CreatedAlloc(..)
485                     | FreedAlloc(..)
486                     | ProgressReport => ("tracking was triggered", DiagLevel::Note),
487                 };
488
489                 let helps = match e {
490                     Int2Ptr { details: true } =>
491                         vec![
492                             (None, format!("This program is using integer-to-pointer casts or (equivalently) `ptr::from_exposed_addr`,")),
493                             (None, format!("which means that Miri might miss pointer bugs in this program.")),
494                             (None, format!("See https://doc.rust-lang.org/nightly/std/ptr/fn.from_exposed_addr.html for more details on that operation.")),
495                             (None, format!("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.")),
496                             (None, format!("You can then pass the `-Zmiri-strict-provenance` flag to Miri, to ensure you are not relying on `from_exposed_addr` semantics.")),
497                             (None, format!("Alternatively, the `-Zmiri-permissive-provenance` flag disables this warning.")),
498                         ],
499                     _ => vec![],
500                 };
501
502                 report_msg(this, diag_level, title, vec![msg], helps, &stacktrace);
503             }
504         });
505     }
506 }