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