]> git.lizzy.rs Git - rust.git/blob - src/diagnostics.rs
Auto merge of #1209 - RalfJung:track-alloc-id, r=oli-obk
[rust.git] / src / diagnostics.rs
1 use rustc_mir::interpret::InterpErrorInfo;
2 use std::cell::RefCell;
3
4 use crate::*;
5
6 /// Miri specific diagnostics
7 pub enum NonHaltingDiagnostic {
8     PoppedTrackedPointerTag(Item),
9     CreatedAlloc(AllocId),
10 }
11
12 /// Emit a custom diagnostic without going through the miri-engine machinery
13 pub fn report_diagnostic<'tcx, 'mir>(
14     ecx: &InterpCx<'mir, 'tcx, Evaluator<'tcx>>,
15     mut e: InterpErrorInfo<'tcx>,
16 ) -> Option<i64> {
17     // Special treatment for some error kinds
18     let msg = match e.kind {
19         InterpError::MachineStop(ref info) => {
20             let info = info.downcast_ref::<TerminationInfo>().expect("invalid MachineStop payload");
21             match info {
22                 TerminationInfo::Exit(code) => return Some(*code),
23                 TerminationInfo::Abort => format!("the evaluated program aborted execution"),
24             }
25         }
26         err_unsup!(NoMirFor(..)) => format!(
27             "{}. Did you set `MIRI_SYSROOT` to a Miri-enabled sysroot? You can prepare one with `cargo miri setup`.",
28             e
29         ),
30         InterpError::InvalidProgram(_) => bug!("This error should be impossible in Miri: {}", e),
31         _ => e.to_string(),
32     };
33     e.print_backtrace();
34     report_msg(ecx, msg, true)
35 }
36
37 /// Report an error or note (depending on the `error` argument) at the current frame's current statement.
38 /// Also emits a full stacktrace of the interpreter stack.
39 pub fn report_msg<'tcx, 'mir>(
40     ecx: &InterpCx<'mir, 'tcx, Evaluator<'tcx>>,
41     msg: String,
42     error: bool,
43 ) -> Option<i64> {
44     if let Some(frame) = ecx.stack().last() {
45         let span = frame.current_source_info().unwrap().span;
46
47         let mut err = if error {
48             let msg = format!("Miri evaluation error: {}", msg);
49             ecx.tcx.sess.struct_span_err(span, msg.as_str())
50         } else {
51             ecx.tcx.sess.diagnostic().span_note_diag(span, msg.as_str())
52         };
53         let frames = ecx.generate_stacktrace(None);
54         err.span_label(span, msg);
55         // We iterate with indices because we need to look at the next frame (the caller).
56         for idx in 0..frames.len() {
57             let frame_info = &frames[idx];
58             let call_site_is_local = frames
59                 .get(idx + 1)
60                 .map_or(false, |caller_info| caller_info.instance.def_id().is_local());
61             if call_site_is_local {
62                 err.span_note(frame_info.call_site, &frame_info.to_string());
63             } else {
64                 err.note(&frame_info.to_string());
65             }
66         }
67         err.emit();
68     } else {
69         ecx.tcx.sess.err(&msg);
70     }
71
72     for (i, frame) in ecx.stack().iter().enumerate() {
73         trace!("-------------------");
74         trace!("Frame {}", i);
75         trace!("    return: {:?}", frame.return_place.map(|p| *p));
76         for (i, local) in frame.locals.iter().enumerate() {
77             trace!("    local {}: {:?}", i, local.value);
78         }
79     }
80     // Let the reported error determine the return code.
81     return None;
82 }
83
84 thread_local! {
85     static DIAGNOSTICS: RefCell<Vec<NonHaltingDiagnostic>> = RefCell::new(Vec::new());
86 }
87
88 /// Schedule a diagnostic for emitting. This function works even if you have no `InterpCx` available.
89 /// The diagnostic will be emitted after the current interpreter step is finished.
90 pub fn register_diagnostic(e: NonHaltingDiagnostic) {
91     DIAGNOSTICS.with(|diagnostics| diagnostics.borrow_mut().push(e));
92 }
93
94 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
95 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
96     /// Emit all diagnostics that were registed with `register_diagnostics`
97     fn process_diagnostics(&self) {
98         let this = self.eval_context_ref();
99         DIAGNOSTICS.with(|diagnostics| {
100             for e in diagnostics.borrow_mut().drain(..) {
101                 use NonHaltingDiagnostic::*;
102                 let msg = match e {
103                     PoppedTrackedPointerTag(item) =>
104                         format!("popped tracked tag for item {:?}", item),
105                     CreatedAlloc(AllocId(id)) =>
106                         format!("created allocation with id {}", id),
107                 };
108                 report_msg(this, msg, false);
109             }
110         });
111     }
112 }