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