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