]> git.lizzy.rs Git - rust.git/blob - src/diagnostics.rs
bump Rust, fix for renames
[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::Display 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<'mir, 'tcx>>,
51     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(UnsupportedOpInfo::ReadBytesAsPointer) =>
96                     panic!("`ReadBytesAsPointer` cannot be raised by Miri"),
97                 Unsupported(_) =>
98                     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")],
99                 UndefinedBehavior(UndefinedBehaviorInfo::AlignmentCheckFailed { .. }) =>
100                     vec![
101                         format!("this usually indicates that your program performed an invalid operation and caused Undefined Behavior"),
102                         format!("but alignment errors can also be false positives, see https://github.com/rust-lang/miri/issues/1074"),
103                         format!("you can disable the alignment check with `-Zmiri-disable-alignment-check`, but that could hide true bugs")
104                     ],
105                 UndefinedBehavior(_) =>
106                     vec![
107                         format!("this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior"),
108                         format!("see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information"),
109                     ],
110                 _ => vec![],
111             };
112             (title, helps)
113         }
114     };
115
116     e.print_backtrace();
117     let msg = e.to_string();
118     report_msg(ecx, &format!("{}: {}", title, msg), msg, helps, true);
119
120     // Extra output to help debug specific issues.
121     if let UndefinedBehavior(UndefinedBehaviorInfo::InvalidUninitBytes(Some(ptr))) = e.kind {
122         eprintln!(
123             "Uninitialized read occurred at offset 0x{:x} into this allocation:",
124             ptr.offset.bytes(),
125         );
126         ecx.memory.dump_alloc(ptr.alloc_id);
127         eprintln!();
128     }
129
130     None
131 }
132
133 /// Report an error or note (depending on the `error` argument) at the current frame's current statement.
134 /// Also emits a full stacktrace of the interpreter stack.
135 fn report_msg<'tcx, 'mir>(
136     ecx: &InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
137     title: &str,
138     span_msg: String,
139     mut helps: Vec<String>,
140     error: bool,
141 ) {
142     let span = if let Some(frame) = ecx.active_thread_stack().last() {
143         frame.current_source_info().unwrap().span
144     } else {
145         DUMMY_SP
146     };
147     let mut err = if error {
148         ecx.tcx.sess.struct_span_err(span, title)
149     } else {
150         ecx.tcx.sess.diagnostic().span_note_diag(span, title)
151     };
152     err.span_label(span, span_msg);
153     if !helps.is_empty() {
154         // Add visual separator before backtrace.
155         helps.last_mut().unwrap().push_str("\n");
156         for help in helps {
157             err.help(&help);
158         }
159     }
160     // Add backtrace
161     let frames = ecx.generate_stacktrace();
162     for (idx, frame_info) in frames.iter().enumerate() {
163         let is_local = frame_info.instance.def_id().is_local();
164         // No span for non-local frames and the first frame (which is the error site).
165         if is_local && idx > 0 {
166             err.span_note(frame_info.span, &frame_info.to_string());
167         } else {
168             err.note(&frame_info.to_string());
169         }
170     }
171
172     err.emit();
173
174     for (i, frame) in ecx.active_thread_stack().iter().enumerate() {
175         trace!("-------------------");
176         trace!("Frame {}", i);
177         trace!("    return: {:?}", frame.return_place.map(|p| *p));
178         for (i, local) in frame.locals.iter().enumerate() {
179             trace!("    local {}: {:?}", i, local.value);
180         }
181     }
182 }
183
184 thread_local! {
185     static DIAGNOSTICS: RefCell<Vec<NonHaltingDiagnostic>> = RefCell::new(Vec::new());
186 }
187
188 /// Schedule a diagnostic for emitting. This function works even if you have no `InterpCx` available.
189 /// The diagnostic will be emitted after the current interpreter step is finished.
190 pub fn register_diagnostic(e: NonHaltingDiagnostic) {
191     DIAGNOSTICS.with(|diagnostics| diagnostics.borrow_mut().push(e));
192 }
193
194 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
195 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
196     /// Emit all diagnostics that were registed with `register_diagnostics`
197     fn process_diagnostics(&self) {
198         let this = self.eval_context_ref();
199         DIAGNOSTICS.with(|diagnostics| {
200             for e in diagnostics.borrow_mut().drain(..) {
201                 use NonHaltingDiagnostic::*;
202                 let msg = match e {
203                     PoppedTrackedPointerTag(item) =>
204                         format!("popped tracked tag for item {:?}", item),
205                     CreatedAlloc(AllocId(id)) =>
206                         format!("created allocation with id {}", id),
207                     FreedAlloc(AllocId(id)) =>
208                         format!("freed allocation with id {}", id),
209                 };
210                 report_msg(this, "tracking was triggered", msg, vec![], false);
211             }
212         });
213     }
214 }