]> git.lizzy.rs Git - rust.git/blob - src/diagnostics.rs
accept ReferencedConstant errors in Miri (can happen post-monomorphization)
[rust.git] / src / diagnostics.rs
1 use std::cell::RefCell;
2 use std::fmt;
3
4 use log::trace;
5
6 use rustc_middle::ty::{self, TyCtxt};
7 use rustc_span::{source_map::DUMMY_SP, Span};
8
9 use crate::*;
10
11 /// Details of premature program termination.
12 pub enum TerminationInfo {
13     Exit(i64),
14     Abort(Option<String>),
15     UnsupportedInIsolation(String),
16     ExperimentalUb { msg: String, url: String },
17     Deadlock,
18 }
19
20 impl fmt::Display for TerminationInfo {
21     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
22         use TerminationInfo::*;
23         match self {
24             Exit(code) =>
25                 write!(f, "the evaluated program completed with exit code {}", code),
26             Abort(None) =>
27                 write!(f, "the evaluated program aborted execution"),
28             Abort(Some(msg)) =>
29                 write!(f, "the evaluated program aborted execution: {}", msg),
30             UnsupportedInIsolation(msg) =>
31                 write!(f, "{}", msg),
32             ExperimentalUb { msg, .. } =>
33                 write!(f, "{}", msg),
34             Deadlock =>
35                 write!(f, "the evaluated program deadlocked"),
36         }
37     }
38 }
39
40 impl MachineStopType for TerminationInfo {}
41
42 /// Miri specific diagnostics
43 pub enum NonHaltingDiagnostic {
44     PoppedPointerTag(Item),
45     CreatedCallId(CallId),
46     CreatedAlloc(AllocId),
47     FreedAlloc(AllocId),
48 }
49
50 /// Emit a custom diagnostic without going through the miri-engine machinery
51 pub fn report_error<'tcx, 'mir>(
52     ecx: &InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
53     e: InterpErrorInfo<'tcx>,
54 ) -> Option<i64> {
55     use InterpError::*;
56
57     let (title, helps) = match &e.kind {
58         MachineStop(info) => {
59             let info = info.downcast_ref::<TerminationInfo>().expect("invalid MachineStop payload");
60             use TerminationInfo::*;
61             let title = match info {
62                 Exit(code) => return Some(*code),
63                 Abort(_) =>
64                     "abnormal termination",
65                 UnsupportedInIsolation(_) =>
66                     "unsupported operation",
67                 ExperimentalUb { .. } =>
68                     "Undefined Behavior",
69                 Deadlock => "deadlock",
70             };
71             let helps = match info {
72                 UnsupportedInIsolation(_) =>
73                     vec![format!("pass the flag `-Zmiri-disable-isolation` to disable isolation")],
74                 ExperimentalUb { url, .. } =>
75                     vec![
76                         format!("this indicates a potential bug in the program: it performed an invalid operation, but the rules it violated are still experimental"),
77                         format!("see {} for further information", url),
78                     ],
79                 _ => vec![],
80             };
81             (title, helps)
82         }
83         _ => {
84             let title = match e.kind {
85                 Unsupported(_) =>
86                     "unsupported operation",
87                 UndefinedBehavior(_) =>
88                     "Undefined Behavior",
89                 ResourceExhaustion(_) =>
90                     "resource exhaustion",
91                 InvalidProgram(InvalidProgramInfo::ReferencedConstant) =>
92                     "post-monomorphization error",
93                 _ =>
94                     bug!("This error should be impossible in Miri: {}", e),
95             };
96             let helps = match e.kind {
97                 Unsupported(UnsupportedOpInfo::NoMirFor(..)) =>
98                     vec![format!("make sure to use a Miri sysroot, which you can prepare with `cargo miri setup`")],
99                 Unsupported(UnsupportedOpInfo::ReadBytesAsPointer | UnsupportedOpInfo::ThreadLocalStatic(_) | UnsupportedOpInfo::ReadExternStatic(_)) =>
100                     panic!("Error should never be raised by Miri: {:?}", e.kind),
101                 Unsupported(_) =>
102                     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")],
103                 UndefinedBehavior(UndefinedBehaviorInfo::AlignmentCheckFailed { .. }) =>
104                     vec![
105                         format!("this usually indicates that your program performed an invalid operation and caused Undefined Behavior"),
106                         format!("but alignment errors can also be false positives, see https://github.com/rust-lang/miri/issues/1074"),
107                         format!("you can disable the alignment check with `-Zmiri-disable-alignment-check`, but that could hide true bugs")
108                     ],
109                 UndefinedBehavior(_) =>
110                     vec![
111                         format!("this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior"),
112                         format!("see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information"),
113                     ],
114                 _ => vec![],
115             };
116             (title, helps)
117         }
118     };
119
120     e.print_backtrace();
121     let msg = e.to_string();
122     report_msg(*ecx.tcx, /*error*/true, &format!("{}: {}", title, msg), msg, helps, &ecx.generate_stacktrace());
123
124     // Debug-dump all locals.
125     for (i, frame) in ecx.active_thread_stack().iter().enumerate() {
126         trace!("-------------------");
127         trace!("Frame {}", i);
128         trace!("    return: {:?}", frame.return_place.map(|p| *p));
129         for (i, local) in frame.locals.iter().enumerate() {
130             trace!("    local {}: {:?}", i, local.value);
131         }
132     }
133
134     // Extra output to help debug specific issues.
135     match e.kind {
136         UndefinedBehavior(UndefinedBehaviorInfo::InvalidUninitBytes(Some(access))) => {
137             eprintln!(
138                 "Uninitialized read occurred at offsets 0x{:x}..0x{:x} into this allocation:",
139                 access.uninit_ptr.offset.bytes(),
140                 access.uninit_ptr.offset.bytes() + access.uninit_size.bytes(),
141             );
142             eprintln!("{:?}", ecx.memory.dump_alloc(access.uninit_ptr.alloc_id));
143         }
144         _ => {}
145     }
146
147     None
148 }
149
150 /// Report an error or note (depending on the `error` argument) with the given stacktrace.
151 /// Also emits a full stacktrace of the interpreter stack.
152 fn report_msg<'tcx>(
153     tcx: TyCtxt<'tcx>,
154     error: bool,
155     title: &str,
156     span_msg: String,
157     mut helps: Vec<String>,
158     stacktrace: &[FrameInfo<'tcx>],
159 ) {
160     let span = stacktrace.first().map_or(DUMMY_SP, |fi| fi.span);
161     let mut err = if error {
162         tcx.sess.struct_span_err(span, title)
163     } else {
164         tcx.sess.diagnostic().span_note_diag(span, title)
165     };
166     // Show main message.
167     if span != DUMMY_SP {
168         err.span_label(span, span_msg);
169     } else {
170         // Make sure we show the message even when it is a dummy span.
171         err.note(&span_msg);
172         err.note("(no span available)");
173     }
174     // Show help messages.
175     if !helps.is_empty() {
176         // Add visual separator before backtrace.
177         helps.last_mut().unwrap().push_str("\n");
178         for help in helps {
179             err.help(&help);
180         }
181     }
182     // Add backtrace
183     for (idx, frame_info) in stacktrace.iter().enumerate() {
184         let is_local = frame_info.instance.def_id().is_local();
185         // No span for non-local frames and the first frame (which is the error site).
186         if is_local && idx > 0 {
187             err.span_note(frame_info.span, &frame_info.to_string());
188         } else {
189             err.note(&frame_info.to_string());
190         }
191     }
192
193     err.emit();
194 }
195
196 thread_local! {
197     static DIAGNOSTICS: RefCell<Vec<NonHaltingDiagnostic>> = RefCell::new(Vec::new());
198 }
199
200 /// Schedule a diagnostic for emitting. This function works even if you have no `InterpCx` available.
201 /// The diagnostic will be emitted after the current interpreter step is finished.
202 pub fn register_diagnostic(e: NonHaltingDiagnostic) {
203     DIAGNOSTICS.with(|diagnostics| diagnostics.borrow_mut().push(e));
204 }
205
206 /// Remember enough about the topmost frame so that we can restore the stack
207 /// after a step was taken.
208 pub struct TopFrameInfo<'tcx> {
209     stack_size: usize,
210     instance: Option<ty::Instance<'tcx>>,
211     span: Span,
212 }
213
214 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
215 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
216     fn preprocess_diagnostics(&self) -> TopFrameInfo<'tcx> {
217         // Ensure we have no lingering diagnostics.
218         DIAGNOSTICS.with(|diagnostics| assert!(diagnostics.borrow().is_empty()));
219
220         let this = self.eval_context_ref();
221         if this.active_thread_stack().is_empty() {
222             // Diagnostics can happen even with the empty stack (e.g. deallocation of thread-local statics).
223             return TopFrameInfo { stack_size: 0, instance: None, span: DUMMY_SP };
224         }
225         let frame = this.frame();
226
227         TopFrameInfo {
228             stack_size: this.active_thread_stack().len(),
229             instance: Some(frame.instance),
230             span: frame.current_source_info().map_or(DUMMY_SP, |si| si.span),
231         }
232     }
233
234     /// Emit all diagnostics that were registed with `register_diagnostics`
235     fn process_diagnostics(&self, info: TopFrameInfo<'tcx>) {
236         let this = self.eval_context_ref();
237         DIAGNOSTICS.with(|diagnostics| {
238             let mut diagnostics = diagnostics.borrow_mut();
239             if diagnostics.is_empty() {
240                 return;
241             }
242             // We need to fix up the stack trace, because the machine has already
243             // stepped to the next statement.
244             let mut stacktrace = this.generate_stacktrace();
245             // Remove newly pushed frames.
246             while stacktrace.len() > info.stack_size {
247                 stacktrace.remove(0);
248             }
249             // Add popped frame back.
250             if stacktrace.len() < info.stack_size {
251                 assert!(stacktrace.len() == info.stack_size-1, "we should never pop more than one frame at once");
252                 let frame_info = FrameInfo {
253                     instance: info.instance.unwrap(),
254                     span: info.span,
255                     lint_root: None,
256                 };
257                 stacktrace.insert(0, frame_info);
258             } else if let Some(instance) = info.instance {
259                 // Adjust topmost frame.
260                 stacktrace[0].span = info.span;
261                 assert_eq!(stacktrace[0].instance, instance, "we should not pop and push a frame in one step");
262             }
263
264             // Show diagnostics.
265             for e in diagnostics.drain(..) {
266                 use NonHaltingDiagnostic::*;
267                 let msg = match e {
268                     PoppedPointerTag(item) =>
269                         format!("popped tracked tag for item {:?}", item),
270                     CreatedCallId(id) =>
271                         format!("function call with id {}", id),
272                     CreatedAlloc(AllocId(id)) =>
273                         format!("created allocation with id {}", id),
274                     FreedAlloc(AllocId(id)) =>
275                         format!("freed allocation with id {}", id),
276                 };
277                 report_msg(*this.tcx, /*error*/false, "tracking was triggered", msg, vec![], &stacktrace);
278             }
279         });
280     }
281 }