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::ThreadLocalStatic(_) | UnsupportedOpInfo::ReadExternStatic(_)) =>
136 panic!("Error should never be raised by Miri: {:?}", e.kind()),
138 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"))],
139 UndefinedBehavior(UndefinedBehaviorInfo::AlignmentCheckFailed { .. })
140 if ecx.memory.extra.check_alignment == AlignmentCheck::Symbolic
143 (None, format!("this usually indicates that your program performed an invalid operation and caused Undefined Behavior")),
144 (None, format!("but due to `-Zmiri-symbolic-alignment-check`, alignment errors can also be false positives")),
146 UndefinedBehavior(_) =>
148 (None, format!("this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior")),
149 (None, format!("see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information")),
158 let msg = e.to_string();
162 &if let Some(title) = title { format!("{}: {}", title, msg) } else { msg.clone() },
165 &ecx.generate_stacktrace(),
168 // Debug-dump all locals.
169 for (i, frame) in ecx.active_thread_stack().iter().enumerate() {
170 trace!("-------------------");
171 trace!("Frame {}", i);
172 trace!(" return: {:?}", frame.return_place.map(|p| *p));
173 for (i, local) in frame.locals.iter().enumerate() {
174 trace!(" local {}: {:?}", i, local.value);
178 // Extra output to help debug specific issues.
180 UndefinedBehavior(UndefinedBehaviorInfo::InvalidUninitBytes(Some((alloc_id, access)))) => {
182 "Uninitialized read occurred at offsets 0x{:x}..0x{:x} into this allocation:",
183 access.uninit_offset.bytes(),
184 access.uninit_offset.bytes() + access.uninit_size.bytes(),
186 eprintln!("{:?}", ecx.memory.dump_alloc(*alloc_id));
194 /// Report an error or note (depending on the `error` argument) with the given stacktrace.
195 /// Also emits a full stacktrace of the interpreter stack.
198 diag_level: DiagLevel,
201 mut helps: Vec<(Option<SpanData>, String)>,
202 stacktrace: &[FrameInfo<'tcx>],
204 let span = stacktrace.first().map_or(DUMMY_SP, |fi| fi.span);
205 let mut err = match diag_level {
206 DiagLevel::Error => tcx.sess.struct_span_err(span, title),
207 DiagLevel::Warning => tcx.sess.struct_span_warn(span, title),
208 DiagLevel::Note => tcx.sess.diagnostic().span_note_diag(span, title),
211 // Show main message.
212 if span != DUMMY_SP {
213 err.span_label(span, span_msg);
215 // Make sure we show the message even when it is a dummy span.
217 err.note("(no span available)");
219 // Show help messages.
220 if !helps.is_empty() {
221 // Add visual separator before backtrace.
222 helps.last_mut().unwrap().1.push_str("\n");
223 for (span_data, help) in helps {
224 if let Some(span_data) = span_data {
225 err.span_help(span_data.span(), &help);
232 for (idx, frame_info) in stacktrace.iter().enumerate() {
233 let is_local = frame_info.instance.def_id().is_local();
234 // No span for non-local frames and the first frame (which is the error site).
235 if is_local && idx > 0 {
236 err.span_note(frame_info.span, &frame_info.to_string());
238 err.note(&frame_info.to_string());
246 static DIAGNOSTICS: RefCell<Vec<NonHaltingDiagnostic>> = RefCell::new(Vec::new());
249 /// Schedule a diagnostic for emitting. This function works even if you have no `InterpCx` available.
250 /// The diagnostic will be emitted after the current interpreter step is finished.
251 pub fn register_diagnostic(e: NonHaltingDiagnostic) {
252 DIAGNOSTICS.with(|diagnostics| diagnostics.borrow_mut().push(e));
255 /// Remember enough about the topmost frame so that we can restore the stack
256 /// after a step was taken.
257 pub struct TopFrameInfo<'tcx> {
259 instance: Option<ty::Instance<'tcx>>,
263 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
264 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
265 fn preprocess_diagnostics(&self) -> TopFrameInfo<'tcx> {
266 // Ensure we have no lingering diagnostics.
267 DIAGNOSTICS.with(|diagnostics| assert!(diagnostics.borrow().is_empty()));
269 let this = self.eval_context_ref();
270 if this.active_thread_stack().is_empty() {
271 // Diagnostics can happen even with the empty stack (e.g. deallocation of thread-local statics).
272 return TopFrameInfo { stack_size: 0, instance: None, span: DUMMY_SP };
274 let frame = this.frame();
277 stack_size: this.active_thread_stack().len(),
278 instance: Some(frame.instance),
279 span: frame.current_span(),
283 /// Emit all diagnostics that were registed with `register_diagnostics`
284 fn process_diagnostics(&self, info: TopFrameInfo<'tcx>) {
285 let this = self.eval_context_ref();
286 DIAGNOSTICS.with(|diagnostics| {
287 let mut diagnostics = diagnostics.borrow_mut();
288 if diagnostics.is_empty() {
291 // We need to fix up the stack trace, because the machine has already
292 // stepped to the next statement.
293 let mut stacktrace = this.generate_stacktrace();
294 // Remove newly pushed frames.
295 while stacktrace.len() > info.stack_size {
296 stacktrace.remove(0);
298 // Add popped frame back.
299 if stacktrace.len() < info.stack_size {
301 stacktrace.len() == info.stack_size - 1,
302 "we should never pop more than one frame at once"
304 let frame_info = FrameInfo {
305 instance: info.instance.unwrap(),
309 stacktrace.insert(0, frame_info);
310 } else if let Some(instance) = info.instance {
311 // Adjust topmost frame.
312 stacktrace[0].span = info.span;
314 stacktrace[0].instance, instance,
315 "we should not pop and push a frame in one step"
320 for e in diagnostics.drain(..) {
321 use NonHaltingDiagnostic::*;
323 CreatedPointerTag(tag) => format!("created tag {:?}", tag),
324 PoppedPointerTag(item) => format!("popped tracked tag for item {:?}", item),
325 CreatedCallId(id) => format!("function call with id {}", id),
326 CreatedAlloc(AllocId(id)) => format!("created allocation with id {}", id),
327 FreedAlloc(AllocId(id)) => format!("freed allocation with id {}", id),
328 RejectedIsolatedOp(ref op) =>
329 format!("{} was made to return an error due to isolation", op),
332 let (title, diag_level) = match e {
333 RejectedIsolatedOp(_) =>
334 ("operation rejected by isolation", DiagLevel::Warning),
335 _ => ("tracking was triggered", DiagLevel::Note),
338 report_msg(*this.tcx, diag_level, title, msg, vec![], &stacktrace);