]> git.lizzy.rs Git - rust.git/blob - src/diagnostics.rs
c387eed5c41cae20022db68de4aa3473c2780e96
[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                     ],
101                 UndefinedBehavior(_) =>
102                     vec![
103                         format!("this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior"),
104                         format!("see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information"),
105                     ],
106                 _ => vec![],
107             };
108             (title, helps)
109         }
110     };
111
112     e.print_backtrace();
113     let msg = e.to_string();
114     report_msg(ecx, &format!("{}: {}", title, msg), msg, helps, true)
115 }
116
117 /// Report an error or note (depending on the `error` argument) at the current frame's current statement.
118 /// Also emits a full stacktrace of the interpreter stack.
119 fn report_msg<'tcx, 'mir>(
120     ecx: &InterpCx<'mir, 'tcx, Evaluator<'tcx>>,
121     title: &str,
122     span_msg: String,
123     mut helps: Vec<String>,
124     error: bool,
125 ) -> Option<i64> {
126     let span = if let Some(frame) = ecx.stack().last() {
127         frame.current_source_info().unwrap().span
128     } else {
129         DUMMY_SP
130     };
131     let mut err = if error {
132         ecx.tcx.sess.struct_span_err(span, title)
133     } else {
134         ecx.tcx.sess.diagnostic().span_note_diag(span, title)
135     };
136     err.span_label(span, span_msg);
137     if !helps.is_empty() {
138         // Add visual separator before backtrace.
139         helps.last_mut().unwrap().push_str("\n");
140         for help in helps {
141             err.help(&help);
142         }
143     }
144     // Add backtrace
145     let frames = ecx.generate_stacktrace();
146     for (idx, frame_info) in frames.iter().enumerate() {
147         let is_local = frame_info.instance.def_id().is_local();
148         // No span for non-local frames and the first frame (which is the error site).
149         if is_local && idx > 0 {
150             err.span_note(frame_info.span, &frame_info.to_string());
151         } else {
152             err.note(&frame_info.to_string());
153         }
154     }
155
156     err.emit();
157
158     for (i, frame) in ecx.stack().iter().enumerate() {
159         trace!("-------------------");
160         trace!("Frame {}", i);
161         trace!("    return: {:?}", frame.return_place.map(|p| *p));
162         for (i, local) in frame.locals.iter().enumerate() {
163             trace!("    local {}: {:?}", i, local.value);
164         }
165     }
166     // Let the reported error determine the return code.
167     return None;
168 }
169
170 thread_local! {
171     static DIAGNOSTICS: RefCell<Vec<NonHaltingDiagnostic>> = RefCell::new(Vec::new());
172 }
173
174 /// Schedule a diagnostic for emitting. This function works even if you have no `InterpCx` available.
175 /// The diagnostic will be emitted after the current interpreter step is finished.
176 pub fn register_diagnostic(e: NonHaltingDiagnostic) {
177     DIAGNOSTICS.with(|diagnostics| diagnostics.borrow_mut().push(e));
178 }
179
180 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
181 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
182     /// Emit all diagnostics that were registed with `register_diagnostics`
183     fn process_diagnostics(&self) {
184         let this = self.eval_context_ref();
185         DIAGNOSTICS.with(|diagnostics| {
186             for e in diagnostics.borrow_mut().drain(..) {
187                 use NonHaltingDiagnostic::*;
188                 let msg = match e {
189                     PoppedTrackedPointerTag(item) =>
190                         format!("popped tracked tag for item {:?}", item),
191                     CreatedAlloc(AllocId(id)) =>
192                         format!("created allocation with id {}", id),
193                 };
194                 report_msg(this, "tracking was triggered", msg, vec![], false);
195             }
196         });
197     }
198 }