1 use std::cell::RefCell;
3 use std::num::NonZeroU64;
8 use rustc_span::{source_map::DUMMY_SP, Span, SpanData, Symbol};
10 use crate::helpers::HexRange;
11 use crate::stacked_borrows::{diagnostics::TagHistory, AccessKind, SbTag};
14 /// Details of premature program termination.
15 pub enum TerminationInfo {
18 UnsupportedInIsolation(String),
22 history: Option<TagHistory>,
25 MultipleSymbolDefinitions {
38 impl fmt::Display for TerminationInfo {
39 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40 use TerminationInfo::*;
42 Exit(code) => write!(f, "the evaluated program completed with exit code {}", code),
43 Abort(msg) => write!(f, "{}", msg),
44 UnsupportedInIsolation(msg) => write!(f, "{}", msg),
45 StackedBorrowsUb { msg, .. } => write!(f, "{}", msg),
46 Deadlock => write!(f, "the evaluated program deadlocked"),
47 MultipleSymbolDefinitions { link_name, .. } =>
48 write!(f, "multiple definitions of symbol `{}`", link_name),
49 SymbolShimClashing { link_name, .. } =>
52 "found `{}` symbol definition that clashes with a built-in shim",
59 impl MachineStopType for TerminationInfo {}
61 /// Miri specific diagnostics
62 pub enum NonHaltingDiagnostic {
63 CreatedPointerTag(NonZeroU64),
64 /// This `Item` was popped from the borrow stack, either due to a grant of
65 /// `AccessKind` to `SbTag` or a deallocation when the second argument is `None`.
66 PoppedPointerTag(Item, Option<(SbTag, AccessKind)>),
67 CreatedCallId(CallId),
68 CreatedAlloc(AllocId),
70 RejectedIsolatedOp(String),
73 /// Level of Miri specific diagnostics
80 /// Attempts to prune a stacktrace to omit the Rust runtime, and returns a bool indicating if any
81 /// frames were pruned. If the stacktrace does not have any local frames, we conclude that it must
82 /// be pointing to a problem in the Rust runtime itself, and do not prune it at all.
83 fn prune_stacktrace<'mir, 'tcx>(
84 ecx: &InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
85 mut stacktrace: Vec<FrameInfo<'tcx>>,
86 ) -> (Vec<FrameInfo<'tcx>>, bool) {
87 match ecx.machine.backtrace_style {
88 BacktraceStyle::Off => {
89 // Retain one frame so that we can print a span for the error itself
90 stacktrace.truncate(1);
93 BacktraceStyle::Short => {
94 let original_len = stacktrace.len();
95 // Only prune frames if there is at least one local frame. This check ensures that if
96 // we get a backtrace that never makes it to the user code because it has detected a
97 // bug in the Rust runtime, we don't prune away every frame.
98 let has_local_frame = stacktrace.iter().any(|frame| ecx.machine.is_local(frame));
100 // This is part of the logic that `std` uses to select the relevant part of a
101 // backtrace. But here, we only look for __rust_begin_short_backtrace, not
102 // __rust_end_short_backtrace because the end symbol comes from a call to the default
104 stacktrace = stacktrace
106 .take_while(|frame| {
107 let def_id = frame.instance.def_id();
108 let path = ecx.tcx.tcx.def_path_str(def_id);
109 !path.contains("__rust_begin_short_backtrace")
111 .collect::<Vec<_>>();
113 // After we prune frames from the bottom, there are a few left that are part of the
114 // Rust runtime. So we remove frames until we get to a local symbol, which should be
116 // This len check ensures that we don't somehow remove every frame, as doing so breaks
117 // the primary error message.
118 while stacktrace.len() > 1
119 && stacktrace.last().map_or(false, |frame| !ecx.machine.is_local(frame))
124 let was_pruned = stacktrace.len() != original_len;
125 (stacktrace, was_pruned)
127 BacktraceStyle::Full => (stacktrace, false),
131 /// Emit a custom diagnostic without going through the miri-engine machinery
132 pub fn report_error<'tcx, 'mir>(
133 ecx: &InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
134 e: InterpErrorInfo<'tcx>,
138 let mut msg = vec![];
140 let (title, helps) = match &e.kind() {
141 MachineStop(info) => {
142 let info = info.downcast_ref::<TerminationInfo>().expect("invalid MachineStop payload");
143 use TerminationInfo::*;
144 let title = match info {
145 Exit(code) => return Some(*code),
146 Abort(_) => Some("abnormal termination"),
147 UnsupportedInIsolation(_) => Some("unsupported operation"),
148 StackedBorrowsUb { .. } => Some("Undefined Behavior"),
149 Deadlock => Some("deadlock"),
150 MultipleSymbolDefinitions { .. } | SymbolShimClashing { .. } => None,
153 let helps = match info {
154 UnsupportedInIsolation(_) =>
156 (None, format!("pass the flag `-Zmiri-disable-isolation` to disable isolation;")),
157 (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")),
159 StackedBorrowsUb { help, history, .. } => {
160 let url = "https://github.com/rust-lang/unsafe-code-guidelines/blob/master/wip/stacked-borrows.md";
161 msg.extend(help.clone());
162 let mut helps = vec![
163 (None, format!("this indicates a potential bug in the program: it performed an invalid operation, but the Stacked Borrows rules it violated are still experimental")),
164 (None, format!("see {url} for further information")),
167 Some(TagHistory::Tagged {tag, created: (created_range, created_span), invalidated, protected }) => {
168 let msg = format!("{:?} was created by a retag at offsets {}", tag, HexRange(*created_range));
169 helps.push((Some(*created_span), msg));
170 if let Some((invalidated_range, invalidated_span)) = invalidated {
171 let msg = format!("{:?} was later invalidated at offsets {}", tag, HexRange(*invalidated_range));
172 helps.push((Some(*invalidated_span), msg));
174 if let Some((protecting_tag, protecting_tag_span, protection_span)) = protected {
175 helps.push((Some(*protecting_tag_span), format!("{:?} was protected due to {:?} which was created here", tag, protecting_tag)));
176 helps.push((Some(*protection_span), "this protector is live for this call".to_string()));
179 Some(TagHistory::Untagged{ recently_created, recently_invalidated, matching_created, protected }) => {
180 if let Some((range, span)) = recently_created {
181 let msg = format!("tag was most recently created at offsets {}", HexRange(*range));
182 helps.push((Some(*span), msg));
184 if let Some((range, span)) = recently_invalidated {
185 let msg = format!("tag was later invalidated at offsets {}", HexRange(*range));
186 helps.push((Some(*span), msg));
188 if let Some((range, span)) = matching_created {
189 let msg = format!("this tag was also created here at offsets {}", HexRange(*range));
190 helps.push((Some(*span), msg));
192 if let Some((protecting_tag, protecting_tag_span, protection_span)) = protected {
193 helps.push((Some(*protecting_tag_span), format!("{:?} was protected due to a tag which was created here", protecting_tag)));
194 helps.push((Some(*protection_span), "this protector is live for this call".to_string()));
201 MultipleSymbolDefinitions { first, first_crate, second, second_crate, .. } =>
203 (Some(*first), format!("it's first defined here, in crate `{}`", first_crate)),
204 (Some(*second), format!("then it's defined here again, in crate `{}`", second_crate)),
206 SymbolShimClashing { link_name, span } =>
207 vec![(Some(*span), format!("the `{}` symbol is defined here", link_name))],
214 let title = match e.kind() {
216 "unsupported operation",
217 UndefinedBehavior(_) =>
218 "Undefined Behavior",
219 ResourceExhaustion(_) =>
220 "resource exhaustion",
222 InvalidProgramInfo::AlreadyReported(_) |
223 InvalidProgramInfo::Layout(..) |
224 InvalidProgramInfo::ReferencedConstant
226 "post-monomorphization error",
228 bug!("This error should be impossible in Miri: {:?}", kind),
231 let helps = match e.kind() {
233 UnsupportedOpInfo::ThreadLocalStatic(_) |
234 UnsupportedOpInfo::ReadExternStatic(_)
236 panic!("Error should never be raised by Miri: {:?}", e.kind()),
238 UnsupportedOpInfo::Unsupported(_) |
239 UnsupportedOpInfo::PartialPointerOverwrite(_) |
240 UnsupportedOpInfo::ReadPointerAsBytes
242 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"))],
243 UndefinedBehavior(UndefinedBehaviorInfo::AlignmentCheckFailed { .. })
244 if ecx.machine.check_alignment == AlignmentCheck::Symbolic
247 (None, format!("this usually indicates that your program performed an invalid operation and caused Undefined Behavior")),
248 (None, format!("but due to `-Zmiri-symbolic-alignment-check`, alignment errors can also be false positives")),
250 UndefinedBehavior(_) =>
252 (None, format!("this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior")),
253 (None, format!("see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information")),
255 InvalidProgram(_) | ResourceExhaustion(_) | MachineStop(_) =>
262 let stacktrace = ecx.generate_stacktrace();
263 let (stacktrace, was_pruned) = prune_stacktrace(ecx, stacktrace);
265 msg.insert(0, e.to_string());
269 &if let Some(title) = title { format!("{}: {}", title, msg[0]) } else { msg[0].clone() },
275 // Include a note like `std` does when we omit frames from a backtrace
277 ecx.tcx.sess.diagnostic().note_without_error(
278 "some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace",
282 // Debug-dump all locals.
283 for (i, frame) in ecx.active_thread_stack().iter().enumerate() {
284 trace!("-------------------");
285 trace!("Frame {}", i);
286 trace!(" return: {:?}", *frame.return_place);
287 for (i, local) in frame.locals.iter().enumerate() {
288 trace!(" local {}: {:?}", i, local.value);
292 // Extra output to help debug specific issues.
294 UndefinedBehavior(UndefinedBehaviorInfo::InvalidUninitBytes(Some((alloc_id, access)))) => {
296 "Uninitialized read occurred at offsets 0x{:x}..0x{:x} into this allocation:",
297 access.uninit_offset.bytes(),
298 access.uninit_offset.bytes() + access.uninit_size.bytes(),
300 eprintln!("{:?}", ecx.dump_alloc(*alloc_id));
308 /// Report an error or note (depending on the `error` argument) with the given stacktrace.
309 /// Also emits a full stacktrace of the interpreter stack.
310 /// We want to present a multi-line span message for some errors. Diagnostics do not support this
311 /// directly, so we pass the lines as a `Vec<String>` and display each line after the first with an
312 /// additional `span_label` or `note` call.
313 fn report_msg<'mir, 'tcx>(
314 ecx: &InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
315 diag_level: DiagLevel,
317 span_msg: Vec<String>,
318 mut helps: Vec<(Option<SpanData>, String)>,
319 stacktrace: &[FrameInfo<'tcx>],
321 let span = stacktrace.first().map_or(DUMMY_SP, |fi| fi.span);
322 let sess = ecx.tcx.sess;
323 let mut err = match diag_level {
324 DiagLevel::Error => sess.struct_span_err(span, title).forget_guarantee(),
325 DiagLevel::Warning => sess.struct_span_warn(span, title),
326 DiagLevel::Note => sess.diagnostic().span_note_diag(span, title),
329 // Show main message.
330 if span != DUMMY_SP {
331 for line in span_msg {
332 err.span_label(span, line);
335 // Make sure we show the message even when it is a dummy span.
336 for line in span_msg {
339 err.note("(no span available)");
342 // Show help messages.
343 if !helps.is_empty() {
344 // Add visual separator before backtrace.
345 helps.last_mut().unwrap().1.push('\n');
346 for (span_data, help) in helps {
347 if let Some(span_data) = span_data {
348 err.span_help(span_data.span(), &help);
355 for (idx, frame_info) in stacktrace.iter().enumerate() {
356 let is_local = ecx.machine.is_local(frame_info);
357 // No span for non-local frames and the first frame (which is the error site).
358 if is_local && idx > 0 {
359 err.span_note(frame_info.span, &frame_info.to_string());
361 err.note(&frame_info.to_string());
369 static DIAGNOSTICS: RefCell<Vec<NonHaltingDiagnostic>> = RefCell::new(Vec::new());
372 /// Schedule a diagnostic for emitting. This function works even if you have no `InterpCx` available.
373 /// The diagnostic will be emitted after the current interpreter step is finished.
374 pub fn register_diagnostic(e: NonHaltingDiagnostic) {
375 DIAGNOSTICS.with(|diagnostics| diagnostics.borrow_mut().push(e));
378 /// Remember enough about the topmost frame so that we can restore the stack
379 /// after a step was taken.
380 pub struct TopFrameInfo<'tcx> {
382 instance: Option<ty::Instance<'tcx>>,
386 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
387 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
388 fn preprocess_diagnostics(&self) -> TopFrameInfo<'tcx> {
389 // Ensure we have no lingering diagnostics.
390 DIAGNOSTICS.with(|diagnostics| assert!(diagnostics.borrow().is_empty()));
392 let this = self.eval_context_ref();
393 if this.active_thread_stack().is_empty() {
394 // Diagnostics can happen even with the empty stack (e.g. deallocation of thread-local statics).
395 return TopFrameInfo { stack_size: 0, instance: None, span: DUMMY_SP };
397 let frame = this.frame();
400 stack_size: this.active_thread_stack().len(),
401 instance: Some(frame.instance),
402 span: frame.current_span(),
406 /// Emit all diagnostics that were registed with `register_diagnostics`
407 fn process_diagnostics(&self, info: TopFrameInfo<'tcx>) {
408 let this = self.eval_context_ref();
409 DIAGNOSTICS.with(|diagnostics| {
410 let mut diagnostics = diagnostics.borrow_mut();
411 if diagnostics.is_empty() {
414 // We need to fix up the stack trace, because the machine has already
415 // stepped to the next statement.
416 let mut stacktrace = this.generate_stacktrace();
417 // Remove newly pushed frames.
418 while stacktrace.len() > info.stack_size {
419 stacktrace.remove(0);
421 // Add popped frame back.
422 if stacktrace.len() < info.stack_size {
424 stacktrace.len() == info.stack_size - 1,
425 "we should never pop more than one frame at once"
427 let frame_info = FrameInfo {
428 instance: info.instance.unwrap(),
432 stacktrace.insert(0, frame_info);
433 } else if let Some(instance) = info.instance {
434 // Adjust topmost frame.
435 stacktrace[0].span = info.span;
437 stacktrace[0].instance, instance,
438 "we should not pop and push a frame in one step"
442 let (stacktrace, _was_pruned) = prune_stacktrace(this, stacktrace);
445 for e in diagnostics.drain(..) {
446 use NonHaltingDiagnostic::*;
448 CreatedPointerTag(tag) => format!("created tag {:?}", tag),
449 PoppedPointerTag(item, tag) =>
453 "popped tracked tag for item {:?} due to deallocation",
456 Some((tag, access)) => {
458 "popped tracked tag for item {:?} due to {:?} access for {:?}",
463 CreatedCallId(id) => format!("function call with id {id}"),
464 CreatedAlloc(AllocId(id)) => format!("created allocation with id {id}"),
465 FreedAlloc(AllocId(id)) => format!("freed allocation with id {id}"),
466 RejectedIsolatedOp(ref op) =>
467 format!("{op} was made to return an error due to isolation"),
470 let (title, diag_level) = match e {
471 RejectedIsolatedOp(_) =>
472 ("operation rejected by isolation", DiagLevel::Warning),
473 _ => ("tracking was triggered", DiagLevel::Note),
476 report_msg(this, diag_level, title, vec![msg], vec![], &stacktrace);