]> git.lizzy.rs Git - rust.git/blob - src/diagnostics.rs
2e4023e0b5bf89ee1a832b4087493130aa723bc5
[rust.git] / src / diagnostics.rs
1 use std::cell::RefCell;
2 use std::fmt;
3
4 use rustc_span::DUMMY_SP;
5
6 use crate::*;
7
8 /// Details of premature program termination.
9 pub enum TerminationInfo {
10     Exit(i64),
11     Abort(Option<String>),
12     UnsupportedInIsolation(String),
13     ExperimentalUb { msg: String, url: String }
14 }
15
16 impl fmt::Debug for TerminationInfo {
17     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
18         use TerminationInfo::*;
19         match self {
20             Exit(code) =>
21                 write!(f, "the evaluated program completed with exit code {}", code),
22             Abort(None) =>
23                 write!(f, "the evaluated program aborted execution"),
24             Abort(Some(msg)) =>
25                 write!(f, "the evaluated program aborted execution: {}", msg),
26             UnsupportedInIsolation(msg) =>
27                 write!(f, "{}", msg),
28             ExperimentalUb { msg, .. } =>
29                 write!(f, "{}", msg),
30         }
31     }
32 }
33
34 impl MachineStopType for TerminationInfo {}
35
36 /// Miri specific diagnostics
37 pub enum NonHaltingDiagnostic {
38     PoppedTrackedPointerTag(Item),
39     CreatedAlloc(AllocId),
40 }
41
42 /// Emit a custom diagnostic without going through the miri-engine machinery
43 pub fn report_error<'tcx, 'mir>(
44     ecx: &InterpCx<'mir, 'tcx, Evaluator<'tcx>>,
45     mut e: InterpErrorInfo<'tcx>,
46 ) -> Option<i64> {
47     use InterpError::*;
48
49     let (title, helps) = match e.kind {
50         MachineStop(ref info) => {
51             let info = info.downcast_ref::<TerminationInfo>().expect("invalid MachineStop payload");
52             use TerminationInfo::*;
53             let title = match info {
54                 Exit(code) => return Some(*code),
55                 Abort(_) =>
56                     "abnormal termination",
57                 UnsupportedInIsolation(_) =>
58                     "unsupported operation",
59                 ExperimentalUb { .. } =>
60                     "Undefined Behavior",
61             };
62             let helps = match info {
63                 UnsupportedInIsolation(_) =>
64                     vec![format!("pass the flag `-Zmiri-disable-isolation` to disable isolation")],
65                 ExperimentalUb { url, .. } =>
66                     vec![
67                         format!("this indicates a potential bug in the program: it performed an invalid operation, but the rules it violated are still experimental"),
68                         format!("see {} for further information", url),
69                     ],
70                 _ => vec![],
71             };
72             (title, helps)
73         }
74         _ => {
75             let title = match e.kind {
76                 Unsupported(_) =>
77                     "unsupported operation",
78                 UndefinedBehavior(_) =>
79                     "Undefined Behavior",
80                 ResourceExhaustion(_) =>
81                     "resource exhaustion",
82                 _ =>
83                     bug!("This error should be impossible in Miri: {}", e),
84             };
85             let helps = match e.kind {
86                 Unsupported(UnsupportedOpInfo::NoMirFor(..)) =>
87                     vec![format!("make sure to use a Miri sysroot, which you can prepare with `cargo miri setup`")],
88                 Unsupported(_) =>
89                     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")],
90                 UndefinedBehavior(_) =>
91                     vec![
92                         format!("this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior"),
93                         format!("see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information"),
94                     ],
95                 _ => vec![],
96             };
97             (title, helps)
98         }
99     };
100
101     e.print_backtrace();
102     let msg = e.to_string();
103     report_msg(ecx, &format!("{}: {}", title, msg), msg, &helps, true)
104 }
105
106 /// Report an error or note (depending on the `error` argument) at the current frame's current statement.
107 /// Also emits a full stacktrace of the interpreter stack.
108 fn report_msg<'tcx, 'mir>(
109     ecx: &InterpCx<'mir, 'tcx, Evaluator<'tcx>>,
110     title: &str,
111     span_msg: String,
112     helps: &[String],
113     error: bool,
114 ) -> Option<i64> {
115     let span = if let Some(frame) = ecx.stack().last() {
116         frame.current_source_info().unwrap().span
117     } else {
118         DUMMY_SP
119     };
120     let mut err = if error {
121         ecx.tcx.sess.struct_span_err(span, title)
122     } else {
123         ecx.tcx.sess.diagnostic().span_note_diag(span, title)
124     };
125     err.span_label(span, span_msg);
126     for help in helps {
127         err.help(help);
128     }
129     // Add backtrace
130     let frames = ecx.generate_stacktrace(None);
131     // We iterate with indices because we need to look at the next frame (the caller).
132     for idx in 0..frames.len() {
133         let frame_info = &frames[idx];
134         let call_site_is_local = frames
135             .get(idx + 1)
136             .map_or(false, |caller_info| caller_info.instance.def_id().is_local());
137         if call_site_is_local {
138             err.span_note(frame_info.call_site, &frame_info.to_string());
139         } else {
140             err.note(&frame_info.to_string());
141         }
142     }
143
144     err.emit();
145
146     for (i, frame) in ecx.stack().iter().enumerate() {
147         trace!("-------------------");
148         trace!("Frame {}", i);
149         trace!("    return: {:?}", frame.return_place.map(|p| *p));
150         for (i, local) in frame.locals.iter().enumerate() {
151             trace!("    local {}: {:?}", i, local.value);
152         }
153     }
154     // Let the reported error determine the return code.
155     return None;
156 }
157
158 thread_local! {
159     static DIAGNOSTICS: RefCell<Vec<NonHaltingDiagnostic>> = RefCell::new(Vec::new());
160 }
161
162 /// Schedule a diagnostic for emitting. This function works even if you have no `InterpCx` available.
163 /// The diagnostic will be emitted after the current interpreter step is finished.
164 pub fn register_diagnostic(e: NonHaltingDiagnostic) {
165     DIAGNOSTICS.with(|diagnostics| diagnostics.borrow_mut().push(e));
166 }
167
168 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
169 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
170     /// Emit all diagnostics that were registed with `register_diagnostics`
171     fn process_diagnostics(&self) {
172         let this = self.eval_context_ref();
173         DIAGNOSTICS.with(|diagnostics| {
174             for e in diagnostics.borrow_mut().drain(..) {
175                 use NonHaltingDiagnostic::*;
176                 let msg = match e {
177                     PoppedTrackedPointerTag(item) =>
178                         format!("popped tracked tag for item {:?}", item),
179                     CreatedAlloc(AllocId(id)) =>
180                         format!("created allocation with id {}", id),
181                 };
182                 report_msg(this, "tracking was triggered", msg, &[], false);
183             }
184         });
185     }
186 }