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