1 use std::cell::RefCell;
3 use std::num::NonZeroU64;
7 use rustc_middle::ty::{self, TyCtxt};
8 use rustc_span::{source_map::DUMMY_SP, Span, SpanData, Symbol};
12 /// Details of premature program termination.
13 pub enum TerminationInfo {
16 UnsupportedInIsolation(String),
22 MultipleSymbolDefinitions {
35 impl fmt::Display for TerminationInfo {
36 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37 use TerminationInfo::*;
39 Exit(code) => write!(f, "the evaluated program completed with exit code {}", code),
40 Abort(msg) => write!(f, "{}", msg),
41 UnsupportedInIsolation(msg) => write!(f, "{}", msg),
42 ExperimentalUb { msg, .. } => write!(f, "{}", msg),
43 Deadlock => write!(f, "the evaluated program deadlocked"),
44 MultipleSymbolDefinitions { link_name, .. } =>
45 write!(f, "multiple definitions of symbol `{}`", link_name),
46 SymbolShimClashing { link_name, .. } =>
49 "found `{}` symbol definition that clashes with a built-in shim",
56 impl MachineStopType for TerminationInfo {}
58 /// Miri specific diagnostics
59 pub enum NonHaltingDiagnostic {
60 CreatedPointerTag(NonZeroU64),
61 PoppedPointerTag(Item),
62 CreatedCallId(CallId),
63 CreatedAlloc(AllocId),
65 RejectedIsolatedOp(String),
68 /// Level of Miri specific diagnostics
75 /// Emit a custom diagnostic without going through the miri-engine machinery
76 pub fn report_error<'tcx, 'mir>(
77 ecx: &InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
78 e: InterpErrorInfo<'tcx>,
82 let (title, helps) = match &e.kind() {
83 MachineStop(info) => {
84 let info = info.downcast_ref::<TerminationInfo>().expect("invalid MachineStop payload");
85 use TerminationInfo::*;
86 let title = match info {
87 Exit(code) => return Some(*code),
88 Abort(_) => Some("abnormal termination"),
89 UnsupportedInIsolation(_) => Some("unsupported operation"),
90 ExperimentalUb { .. } => Some("Undefined Behavior"),
91 Deadlock => Some("deadlock"),
92 MultipleSymbolDefinitions { .. } | SymbolShimClashing { .. } => None,
95 let helps = match info {
96 UnsupportedInIsolation(_) =>
98 (None, format!("pass the flag `-Zmiri-disable-isolation` to disable isolation;")),
99 (None, format!("or pass `-Zmiri-isolation-error=warn to configure Miri to return an error code from isolated operations (if supported for that operation) and continue with a warning")),
101 ExperimentalUb { url, .. } =>
103 (None, format!("this indicates a potential bug in the program: it performed an invalid operation, but the rules it violated are still experimental")),
104 (None, format!("see {} for further information", url)),
106 MultipleSymbolDefinitions { first, first_crate, second, second_crate, .. } =>
108 (Some(*first), format!("it's first defined here, in crate `{}`", first_crate)),
109 (Some(*second), format!("then it's defined here again, in crate `{}`", second_crate)),
111 SymbolShimClashing { link_name, span } =>
112 vec![(Some(*span), format!("the `{}` symbol is defined here", link_name))],
119 let title = match e.kind() {
121 "unsupported operation",
122 UndefinedBehavior(_) =>
123 "Undefined Behavior",
124 ResourceExhaustion(_) =>
125 "resource exhaustion",
126 InvalidProgram(InvalidProgramInfo::ReferencedConstant) =>
127 "post-monomorphization error",
128 InvalidProgram(InvalidProgramInfo::AlreadyReported(_)) =>
131 bug!("This error should be impossible in Miri: {:?}", kind),
134 let helps = match e.kind() {
135 Unsupported(UnsupportedOpInfo::NoMirFor(..)) =>
136 vec![(None, format!("make sure to use a Miri sysroot, which you can prepare with `cargo miri setup`"))],
137 Unsupported(UnsupportedOpInfo::ReadBytesAsPointer | UnsupportedOpInfo::ThreadLocalStatic(_) | UnsupportedOpInfo::ReadExternStatic(_)) =>
138 panic!("Error should never be raised by Miri: {:?}", e.kind()),
140 vec![(None, format!("this is likely not a bug in the program; it indicates that the program performed an operation that the interpreter does not support"))],
141 UndefinedBehavior(UndefinedBehaviorInfo::AlignmentCheckFailed { .. })
142 if ecx.memory.extra.check_alignment == AlignmentCheck::Symbolic
145 (None, format!("this usually indicates that your program performed an invalid operation and caused Undefined Behavior")),
146 (None, format!("but due to `-Zmiri-symbolic-alignment-check`, alignment errors can also be false positives")),
148 UndefinedBehavior(_) =>
150 (None, format!("this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior")),
151 (None, format!("see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information")),
160 let msg = e.to_string();
164 &if let Some(title) = title { format!("{}: {}", title, msg) } else { msg.clone() },
167 &ecx.generate_stacktrace(),
170 // Debug-dump all locals.
171 for (i, frame) in ecx.active_thread_stack().iter().enumerate() {
172 trace!("-------------------");
173 trace!("Frame {}", i);
174 trace!(" return: {:?}", frame.return_place.map(|p| *p));
175 for (i, local) in frame.locals.iter().enumerate() {
176 trace!(" local {}: {:?}", i, local.value);
180 // Extra output to help debug specific issues.
182 UndefinedBehavior(UndefinedBehaviorInfo::InvalidUninitBytes(Some((alloc_id, access)))) => {
184 "Uninitialized read occurred at offsets 0x{:x}..0x{:x} into this allocation:",
185 access.uninit_offset.bytes(),
186 access.uninit_offset.bytes() + access.uninit_size.bytes(),
188 eprintln!("{:?}", ecx.memory.dump_alloc(*alloc_id));
196 /// Report an error or note (depending on the `error` argument) with the given stacktrace.
197 /// Also emits a full stacktrace of the interpreter stack.
200 diag_level: DiagLevel,
203 mut helps: Vec<(Option<SpanData>, String)>,
204 stacktrace: &[FrameInfo<'tcx>],
206 let span = stacktrace.first().map_or(DUMMY_SP, |fi| fi.span);
207 let mut err = match diag_level {
208 DiagLevel::Error => tcx.sess.struct_span_err(span, title),
209 DiagLevel::Warning => tcx.sess.struct_span_warn(span, title),
210 DiagLevel::Note => tcx.sess.diagnostic().span_note_diag(span, title),
213 // Show main message.
214 if span != DUMMY_SP {
215 err.span_label(span, span_msg);
217 // Make sure we show the message even when it is a dummy span.
219 err.note("(no span available)");
221 // Show help messages.
222 if !helps.is_empty() {
223 // Add visual separator before backtrace.
224 helps.last_mut().unwrap().1.push_str("\n");
225 for (span_data, help) in helps {
226 if let Some(span_data) = span_data {
227 err.span_help(span_data.span(), &help);
234 for (idx, frame_info) in stacktrace.iter().enumerate() {
235 let is_local = frame_info.instance.def_id().is_local();
236 // No span for non-local frames and the first frame (which is the error site).
237 if is_local && idx > 0 {
238 err.span_note(frame_info.span, &frame_info.to_string());
240 err.note(&frame_info.to_string());
248 static DIAGNOSTICS: RefCell<Vec<NonHaltingDiagnostic>> = RefCell::new(Vec::new());
251 /// Schedule a diagnostic for emitting. This function works even if you have no `InterpCx` available.
252 /// The diagnostic will be emitted after the current interpreter step is finished.
253 pub fn register_diagnostic(e: NonHaltingDiagnostic) {
254 DIAGNOSTICS.with(|diagnostics| diagnostics.borrow_mut().push(e));
257 /// Remember enough about the topmost frame so that we can restore the stack
258 /// after a step was taken.
259 pub struct TopFrameInfo<'tcx> {
261 instance: Option<ty::Instance<'tcx>>,
265 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
266 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
267 fn preprocess_diagnostics(&self) -> TopFrameInfo<'tcx> {
268 // Ensure we have no lingering diagnostics.
269 DIAGNOSTICS.with(|diagnostics| assert!(diagnostics.borrow().is_empty()));
271 let this = self.eval_context_ref();
272 if this.active_thread_stack().is_empty() {
273 // Diagnostics can happen even with the empty stack (e.g. deallocation of thread-local statics).
274 return TopFrameInfo { stack_size: 0, instance: None, span: DUMMY_SP };
276 let frame = this.frame();
279 stack_size: this.active_thread_stack().len(),
280 instance: Some(frame.instance),
281 span: frame.current_span(),
285 /// Emit all diagnostics that were registed with `register_diagnostics`
286 fn process_diagnostics(&self, info: TopFrameInfo<'tcx>) {
287 let this = self.eval_context_ref();
288 DIAGNOSTICS.with(|diagnostics| {
289 let mut diagnostics = diagnostics.borrow_mut();
290 if diagnostics.is_empty() {
293 // We need to fix up the stack trace, because the machine has already
294 // stepped to the next statement.
295 let mut stacktrace = this.generate_stacktrace();
296 // Remove newly pushed frames.
297 while stacktrace.len() > info.stack_size {
298 stacktrace.remove(0);
300 // Add popped frame back.
301 if stacktrace.len() < info.stack_size {
303 stacktrace.len() == info.stack_size - 1,
304 "we should never pop more than one frame at once"
306 let frame_info = FrameInfo {
307 instance: info.instance.unwrap(),
311 stacktrace.insert(0, frame_info);
312 } else if let Some(instance) = info.instance {
313 // Adjust topmost frame.
314 stacktrace[0].span = info.span;
316 stacktrace[0].instance, instance,
317 "we should not pop and push a frame in one step"
322 for e in diagnostics.drain(..) {
323 use NonHaltingDiagnostic::*;
325 CreatedPointerTag(tag) => format!("created tag {:?}", tag),
326 PoppedPointerTag(item) => format!("popped tracked tag for item {:?}", item),
327 CreatedCallId(id) => format!("function call with id {}", id),
328 CreatedAlloc(AllocId(id)) => format!("created allocation with id {}", id),
329 FreedAlloc(AllocId(id)) => format!("freed allocation with id {}", id),
330 RejectedIsolatedOp(ref op) =>
331 format!("`{}` was made to return an error due to isolation", op),
334 let (title, diag_level) = match e {
335 RejectedIsolatedOp(_) =>
336 ("operation rejected by isolation", DiagLevel::Warning),
337 _ => ("tracking was triggered", DiagLevel::Note),
340 report_msg(*this.tcx, diag_level, title, msg, vec![], &stacktrace);