]> git.lizzy.rs Git - rust.git/blob - src/diagnostics.rs
2359b67323d753856d4d831c3f32138932cb0a9a
[rust.git] / src / diagnostics.rs
1 use std::cell::RefCell;
2 use std::fmt;
3
4 use log::trace;
5
6 use rustc_span::DUMMY_SP;
7
8 use crate::*;
9
10 /// Details of premature program termination.
11 pub enum TerminationInfo {
12     Exit(i64),
13     Abort(Option<String>),
14     UnsupportedInIsolation(String),
15     ExperimentalUb { msg: String, url: String },
16     Deadlock,
17 }
18
19 impl fmt::Debug for TerminationInfo {
20     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
21         use TerminationInfo::*;
22         match self {
23             Exit(code) =>
24                 write!(f, "the evaluated program completed with exit code {}", code),
25             Abort(None) =>
26                 write!(f, "the evaluated program aborted execution"),
27             Abort(Some(msg)) =>
28                 write!(f, "the evaluated program aborted execution: {}", msg),
29             UnsupportedInIsolation(msg) =>
30                 write!(f, "{}", msg),
31             ExperimentalUb { msg, .. } =>
32                 write!(f, "{}", msg),
33             Deadlock =>
34                 write!(f, "the evaluated program deadlocked"),
35         }
36     }
37 }
38
39 impl MachineStopType for TerminationInfo {}
40
41 /// Miri specific diagnostics
42 pub enum NonHaltingDiagnostic {
43     PoppedTrackedPointerTag(Item),
44     CreatedAlloc(AllocId),
45 }
46
47 /// Emit a custom diagnostic without going through the miri-engine machinery
48 pub fn report_error<'tcx, 'mir>(
49     ecx: &InterpCx<'mir, 'tcx, Evaluator<'tcx>>,
50     mut e: InterpErrorInfo<'tcx>,
51 ) -> Option<i64> {
52     use InterpError::*;
53
54     let (title, helps) = match &e.kind {
55         MachineStop(info) => {
56             let info = info.downcast_ref::<TerminationInfo>().expect("invalid MachineStop payload");
57             use TerminationInfo::*;
58             let title = match info {
59                 Exit(code) => return Some(*code),
60                 Abort(_) =>
61                     "abnormal termination",
62                 UnsupportedInIsolation(_) =>
63                     "unsupported operation",
64                 ExperimentalUb { .. } =>
65                     "Undefined Behavior",
66                 Deadlock => "deadlock",
67             };
68             let helps = match info {
69                 UnsupportedInIsolation(_) =>
70                     vec![format!("pass the flag `-Zmiri-disable-isolation` to disable isolation")],
71                 ExperimentalUb { url, .. } =>
72                     vec![
73                         format!("this indicates a potential bug in the program: it performed an invalid operation, but the rules it violated are still experimental"),
74                         format!("see {} for further information", url),
75                     ],
76                 _ => vec![],
77             };
78             (title, helps)
79         }
80         _ => {
81             let title = match e.kind {
82                 Unsupported(_) =>
83                     "unsupported operation",
84                 UndefinedBehavior(_) =>
85                     "Undefined Behavior",
86                 ResourceExhaustion(_) =>
87                     "resource exhaustion",
88                 _ =>
89                     bug!("This error should be impossible in Miri: {}", e),
90             };
91             let helps = match e.kind {
92                 Unsupported(UnsupportedOpInfo::NoMirFor(..)) =>
93                     vec![format!("make sure to use a Miri sysroot, which you can prepare with `cargo miri setup`")],
94                 Unsupported(_) =>
95                     vec![format!("this is likely not a bug in the program; it indicates that the program performed an operation that the interpreter does not support")],
96                 UndefinedBehavior(UndefinedBehaviorInfo::AlignmentCheckFailed { .. }) =>
97                     vec![
98                         format!("this usually indicates that your program performed an invalid operation and caused Undefined Behavior"),
99                         format!("but alignment errors can also be false positives, see https://github.com/rust-lang/miri/issues/1074"),
100                         format!("you can disable the alignment check with `-Zmiri-disable-alignment-check`, but that could hide true bugs")
101                     ],
102                 UndefinedBehavior(_) =>
103                     vec![
104                         format!("this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior"),
105                         format!("see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information"),
106                     ],
107                 _ => vec![],
108             };
109             (title, helps)
110         }
111     };
112
113     e.print_backtrace();
114     let msg = e.to_string();
115     report_msg(ecx, &format!("{}: {}", title, msg), msg, helps, true)
116 }
117
118 /// Report an error or note (depending on the `error` argument) at the current frame's current statement.
119 /// Also emits a full stacktrace of the interpreter stack.
120 fn report_msg<'tcx, 'mir>(
121     ecx: &InterpCx<'mir, 'tcx, Evaluator<'tcx>>,
122     title: &str,
123     span_msg: String,
124     mut helps: Vec<String>,
125     error: bool,
126 ) -> Option<i64> {
127     let span = if let Some(frame) = ecx.stack().last() {
128         frame.current_source_info().unwrap().span
129     } else {
130         DUMMY_SP
131     };
132     let mut err = if error {
133         ecx.tcx.sess.struct_span_err(span, title)
134     } else {
135         ecx.tcx.sess.diagnostic().span_note_diag(span, title)
136     };
137     err.span_label(span, span_msg);
138     if !helps.is_empty() {
139         // Add visual separator before backtrace.
140         helps.last_mut().unwrap().push_str("\n");
141         for help in helps {
142             err.help(&help);
143         }
144     }
145     // Add backtrace
146     let frames = ecx.generate_stacktrace();
147     for (idx, frame_info) in frames.iter().enumerate() {
148         let is_local = frame_info.instance.def_id().is_local();
149         // No span for non-local frames and the first frame (which is the error site).
150         if is_local && idx > 0 {
151             err.span_note(frame_info.span, &frame_info.to_string());
152         } else {
153             err.note(&frame_info.to_string());
154         }
155     }
156
157     err.emit();
158
159     for (i, frame) in ecx.stack().iter().enumerate() {
160         trace!("-------------------");
161         trace!("Frame {}", i);
162         trace!("    return: {:?}", frame.return_place.map(|p| *p));
163         for (i, local) in frame.locals.iter().enumerate() {
164             trace!("    local {}: {:?}", i, local.value);
165         }
166     }
167     // Let the reported error determine the return code.
168     return None;
169 }
170
171 thread_local! {
172     static DIAGNOSTICS: RefCell<Vec<NonHaltingDiagnostic>> = RefCell::new(Vec::new());
173 }
174
175 /// Schedule a diagnostic for emitting. This function works even if you have no `InterpCx` available.
176 /// The diagnostic will be emitted after the current interpreter step is finished.
177 pub fn register_diagnostic(e: NonHaltingDiagnostic) {
178     DIAGNOSTICS.with(|diagnostics| diagnostics.borrow_mut().push(e));
179 }
180
181 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
182 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
183     /// Emit all diagnostics that were registed with `register_diagnostics`
184     fn process_diagnostics(&self) {
185         let this = self.eval_context_ref();
186         DIAGNOSTICS.with(|diagnostics| {
187             for e in diagnostics.borrow_mut().drain(..) {
188                 use NonHaltingDiagnostic::*;
189                 let msg = match e {
190                     PoppedTrackedPointerTag(item) =>
191                         format!("popped tracked tag for item {:?}", item),
192                     CreatedAlloc(AllocId(id)) =>
193                         format!("created allocation with id {}", id),
194                 };
195                 report_msg(this, "tracking was triggered", msg, vec![], false);
196             }
197         });
198     }
199 }