1 use std::cell::RefCell;
3 use std::num::NonZeroU64;
8 use rustc_span::{source_map::DUMMY_SP, Span, SpanData, Symbol};
9 use rustc_target::abi::{Align, Size};
11 use crate::stacked_borrows::{diagnostics::TagHistory, AccessKind};
14 /// Details of premature program termination.
15 pub enum TerminationInfo {
18 UnsupportedInIsolation(String),
22 history: Option<TagHistory>,
24 Int2PtrWithStrictProvenance,
26 MultipleSymbolDefinitions {
39 impl fmt::Display for TerminationInfo {
40 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41 use TerminationInfo::*;
43 Exit(code) => write!(f, "the evaluated program completed with exit code {code}"),
44 Abort(msg) => write!(f, "{msg}"),
45 UnsupportedInIsolation(msg) => write!(f, "{msg}"),
46 Int2PtrWithStrictProvenance =>
49 "integer-to-pointer casts and `ptr::from_exposed_addr` are not supported with `-Zmiri-strict-provenance`"
51 StackedBorrowsUb { msg, .. } => write!(f, "{msg}"),
52 Deadlock => write!(f, "the evaluated program deadlocked"),
53 MultipleSymbolDefinitions { link_name, .. } =>
54 write!(f, "multiple definitions of symbol `{link_name}`"),
55 SymbolShimClashing { link_name, .. } =>
56 write!(f, "found `{link_name}` symbol definition that clashes with a built-in shim",),
61 impl MachineStopType for TerminationInfo {}
63 /// Miri specific diagnostics
64 pub enum NonHaltingDiagnostic {
65 CreatedPointerTag(NonZeroU64, Option<(AllocId, AllocRange)>),
66 /// This `Item` was popped from the borrow stack, either due to an access with the given tag or
67 /// a deallocation when the second argument is `None`.
68 PoppedPointerTag(Item, Option<(SbTagExtra, AccessKind)>),
69 CreatedCallId(CallId),
70 CreatedAlloc(AllocId, Size, Align, MemoryKind<MiriMemoryKind>),
72 RejectedIsolatedOp(String),
79 /// Level of Miri specific diagnostics
86 /// Attempts to prune a stacktrace to omit the Rust runtime, and returns a bool indicating if any
87 /// frames were pruned. If the stacktrace does not have any local frames, we conclude that it must
88 /// be pointing to a problem in the Rust runtime itself, and do not prune it at all.
89 fn prune_stacktrace<'mir, 'tcx>(
90 ecx: &InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
91 mut stacktrace: Vec<FrameInfo<'tcx>>,
92 ) -> (Vec<FrameInfo<'tcx>>, bool) {
93 match ecx.machine.backtrace_style {
94 BacktraceStyle::Off => {
95 // Remove all frames marked with `caller_location` -- that attribute indicates we
96 // usually want to point at the caller, not them.
97 stacktrace.retain(|frame| !frame.instance.def.requires_caller_location(*ecx.tcx));
98 // Retain one frame so that we can print a span for the error itself
99 stacktrace.truncate(1);
102 BacktraceStyle::Short => {
103 let original_len = stacktrace.len();
104 // Only prune frames if there is at least one local frame. This check ensures that if
105 // we get a backtrace that never makes it to the user code because it has detected a
106 // bug in the Rust runtime, we don't prune away every frame.
107 let has_local_frame = stacktrace.iter().any(|frame| ecx.machine.is_local(frame));
109 // Remove all frames marked with `caller_location` -- that attribute indicates we
110 // usually want to point at the caller, not them.
111 stacktrace.retain(|frame| !frame.instance.def.requires_caller_location(*ecx.tcx));
113 // This is part of the logic that `std` uses to select the relevant part of a
114 // backtrace. But here, we only look for __rust_begin_short_backtrace, not
115 // __rust_end_short_backtrace because the end symbol comes from a call to the default
117 stacktrace = stacktrace
119 .take_while(|frame| {
120 let def_id = frame.instance.def_id();
121 let path = ecx.tcx.tcx.def_path_str(def_id);
122 !path.contains("__rust_begin_short_backtrace")
124 .collect::<Vec<_>>();
126 // After we prune frames from the bottom, there are a few left that are part of the
127 // Rust runtime. So we remove frames until we get to a local symbol, which should be
129 // This len check ensures that we don't somehow remove every frame, as doing so breaks
130 // the primary error message.
131 while stacktrace.len() > 1
132 && stacktrace.last().map_or(false, |frame| !ecx.machine.is_local(frame))
137 let was_pruned = stacktrace.len() != original_len;
138 (stacktrace, was_pruned)
140 BacktraceStyle::Full => (stacktrace, false),
144 /// Emit a custom diagnostic without going through the miri-engine machinery
145 pub fn report_error<'tcx, 'mir>(
146 ecx: &InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
147 e: InterpErrorInfo<'tcx>,
151 let mut msg = vec![];
153 let (title, helps) = match &e.kind() {
154 MachineStop(info) => {
155 let info = info.downcast_ref::<TerminationInfo>().expect("invalid MachineStop payload");
156 use TerminationInfo::*;
157 let title = match info {
158 Exit(code) => return Some(*code),
159 Abort(_) => Some("abnormal termination"),
160 UnsupportedInIsolation(_) | Int2PtrWithStrictProvenance =>
161 Some("unsupported operation"),
162 StackedBorrowsUb { .. } => Some("Undefined Behavior"),
163 Deadlock => Some("deadlock"),
164 MultipleSymbolDefinitions { .. } | SymbolShimClashing { .. } => None,
167 let helps = match info {
168 UnsupportedInIsolation(_) =>
170 (None, format!("pass the flag `-Zmiri-disable-isolation` to disable isolation;")),
171 (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")),
173 StackedBorrowsUb { help, history, .. } => {
174 let url = "https://github.com/rust-lang/unsafe-code-guidelines/blob/master/wip/stacked-borrows.md";
175 msg.extend(help.clone());
176 let mut helps = vec![
177 (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")),
178 (None, format!("see {url} for further information")),
181 Some(TagHistory::Tagged {tag, created: (created_range, created_span), invalidated, protected }) => {
182 let msg = format!("{tag:?} was created by a retag at offsets {created_range:?}");
183 helps.push((Some(*created_span), msg));
184 if let Some((invalidated_range, invalidated_span)) = invalidated {
185 let msg = format!("{tag:?} was later invalidated at offsets {invalidated_range:?}");
186 helps.push((Some(*invalidated_span), msg));
188 if let Some((protecting_tag, protecting_tag_span, protection_span)) = protected {
189 helps.push((Some(*protecting_tag_span), format!("{tag:?} was protected due to {protecting_tag:?} which was created here")));
190 helps.push((Some(*protection_span), format!("this protector is live for this call")));
197 MultipleSymbolDefinitions { first, first_crate, second, second_crate, .. } =>
199 (Some(*first), format!("it's first defined here, in crate `{first_crate}`")),
200 (Some(*second), format!("then it's defined here again, in crate `{second_crate}`")),
202 SymbolShimClashing { link_name, span } =>
203 vec![(Some(*span), format!("the `{link_name}` symbol is defined here"))],
204 Int2PtrWithStrictProvenance =>
205 vec![(None, format!("use Strict Provenance APIs (https://doc.rust-lang.org/nightly/std/ptr/index.html#strict-provenance, https://crates.io/crates/sptr) instead"))],
212 let title = match e.kind() {
214 "unsupported operation",
215 UndefinedBehavior(_) =>
216 "Undefined Behavior",
217 ResourceExhaustion(_) =>
218 "resource exhaustion",
220 InvalidProgramInfo::AlreadyReported(_) |
221 InvalidProgramInfo::Layout(..) |
222 InvalidProgramInfo::ReferencedConstant
224 "post-monomorphization error",
226 bug!("This error should be impossible in Miri: {kind:?}"),
229 let helps = match e.kind() {
231 UnsupportedOpInfo::ThreadLocalStatic(_) |
232 UnsupportedOpInfo::ReadExternStatic(_)
234 panic!("Error should never be raised by Miri: {kind:?}", kind = e.kind()),
236 UnsupportedOpInfo::Unsupported(_) |
237 UnsupportedOpInfo::PartialPointerOverwrite(_) |
238 UnsupportedOpInfo::ReadPointerAsBytes
240 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"))],
241 UndefinedBehavior(UndefinedBehaviorInfo::AlignmentCheckFailed { .. })
242 if ecx.machine.check_alignment == AlignmentCheck::Symbolic
245 (None, format!("this usually indicates that your program performed an invalid operation and caused Undefined Behavior")),
246 (None, format!("but due to `-Zmiri-symbolic-alignment-check`, alignment errors can also be false positives")),
248 UndefinedBehavior(_) =>
250 (None, format!("this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior")),
251 (None, format!("see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information")),
253 InvalidProgram(_) | ResourceExhaustion(_) | MachineStop(_) =>
260 let stacktrace = ecx.generate_stacktrace();
261 let (stacktrace, was_pruned) = prune_stacktrace(ecx, stacktrace);
263 msg.insert(0, e.to_string());
267 &if let Some(title) = title { format!("{}: {}", title, msg[0]) } else { msg[0].clone() },
273 // Include a note like `std` does when we omit frames from a backtrace
275 ecx.tcx.sess.diagnostic().note_without_error(
276 "some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace",
280 // Debug-dump all locals.
281 for (i, frame) in ecx.active_thread_stack().iter().enumerate() {
282 trace!("-------------------");
283 trace!("Frame {}", i);
284 trace!(" return: {:?}", *frame.return_place);
285 for (i, local) in frame.locals.iter().enumerate() {
286 trace!(" local {}: {:?}", i, local.value);
290 // Extra output to help debug specific issues.
292 UndefinedBehavior(UndefinedBehaviorInfo::InvalidUninitBytes(Some((alloc_id, access)))) => {
294 "Uninitialized memory occurred at {alloc_id:?}{range:?}, in this allocation:",
295 range = access.uninit,
297 eprintln!("{:?}", ecx.dump_alloc(*alloc_id));
305 /// Report an error or note (depending on the `error` argument) with the given stacktrace.
306 /// Also emits a full stacktrace of the interpreter stack.
307 /// We want to present a multi-line span message for some errors. Diagnostics do not support this
308 /// directly, so we pass the lines as a `Vec<String>` and display each line after the first with an
309 /// additional `span_label` or `note` call.
310 fn report_msg<'mir, 'tcx>(
311 ecx: &InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
312 diag_level: DiagLevel,
314 span_msg: Vec<String>,
315 helps: Vec<(Option<SpanData>, String)>,
316 stacktrace: &[FrameInfo<'tcx>],
318 let span = stacktrace.first().map_or(DUMMY_SP, |fi| fi.span);
319 let sess = ecx.tcx.sess;
320 let mut err = match diag_level {
321 DiagLevel::Error => sess.struct_span_err(span, title).forget_guarantee(),
322 DiagLevel::Warning => sess.struct_span_warn(span, title),
323 DiagLevel::Note => sess.diagnostic().span_note_diag(span, title),
326 // Show main message.
327 if span != DUMMY_SP {
328 for line in span_msg {
329 err.span_label(span, line);
332 // Make sure we show the message even when it is a dummy span.
333 for line in span_msg {
336 err.note("(no span available)");
339 // Show help messages.
340 if !helps.is_empty() {
341 for (span_data, help) in helps {
342 if let Some(span_data) = span_data {
343 err.span_help(span_data.span(), &help);
348 // Add visual separator before backtrace.
349 err.note("backtrace:");
352 for (idx, frame_info) in stacktrace.iter().enumerate() {
353 let is_local = ecx.machine.is_local(frame_info);
354 // No span for non-local frames and the first frame (which is the error site).
355 if is_local && idx > 0 {
356 err.span_note(frame_info.span, &frame_info.to_string());
358 err.note(&frame_info.to_string());
366 static DIAGNOSTICS: RefCell<Vec<NonHaltingDiagnostic>> = RefCell::new(Vec::new());
369 /// Schedule a diagnostic for emitting. This function works even if you have no `InterpCx` available.
370 /// The diagnostic will be emitted after the current interpreter step is finished.
371 pub fn register_diagnostic(e: NonHaltingDiagnostic) {
372 DIAGNOSTICS.with(|diagnostics| diagnostics.borrow_mut().push(e));
375 /// Remember enough about the topmost frame so that we can restore the stack
376 /// after a step was taken.
377 pub struct TopFrameInfo<'tcx> {
379 instance: Option<ty::Instance<'tcx>>,
383 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
384 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
385 fn preprocess_diagnostics(&self) -> TopFrameInfo<'tcx> {
386 // Ensure we have no lingering diagnostics.
387 DIAGNOSTICS.with(|diagnostics| assert!(diagnostics.borrow().is_empty()));
389 let this = self.eval_context_ref();
390 if this.active_thread_stack().is_empty() {
391 // Diagnostics can happen even with the empty stack (e.g. deallocation of thread-local statics).
392 return TopFrameInfo { stack_size: 0, instance: None, span: DUMMY_SP };
394 let frame = this.frame();
397 stack_size: this.active_thread_stack().len(),
398 instance: Some(frame.instance),
399 span: frame.current_span(),
403 /// Emit all diagnostics that were registed with `register_diagnostics`
404 fn process_diagnostics(&self, info: TopFrameInfo<'tcx>) {
405 let this = self.eval_context_ref();
406 DIAGNOSTICS.with(|diagnostics| {
407 let mut diagnostics = diagnostics.borrow_mut();
408 if diagnostics.is_empty() {
411 // We need to fix up the stack trace, because the machine has already
412 // stepped to the next statement.
413 let mut stacktrace = this.generate_stacktrace();
414 // Remove newly pushed frames.
415 while stacktrace.len() > info.stack_size {
416 stacktrace.remove(0);
418 // Add popped frame back.
419 if stacktrace.len() < info.stack_size {
421 stacktrace.len() == info.stack_size - 1,
422 "we should never pop more than one frame at once"
424 let frame_info = FrameInfo {
425 instance: info.instance.unwrap(),
429 stacktrace.insert(0, frame_info);
430 } else if let Some(instance) = info.instance {
431 // Adjust topmost frame.
432 stacktrace[0].span = info.span;
434 stacktrace[0].instance, instance,
435 "we should not pop and push a frame in one step"
439 let (stacktrace, _was_pruned) = prune_stacktrace(this, stacktrace);
442 for e in diagnostics.drain(..) {
443 use NonHaltingDiagnostic::*;
445 CreatedPointerTag(tag, None) =>
446 format!("created tag {tag:?}"),
447 CreatedPointerTag(tag, Some((alloc_id, range))) =>
448 format!("created tag {tag:?} at {alloc_id:?}{range:?}"),
449 PoppedPointerTag(item, tag) =>
453 "popped tracked tag for item {item:?} due to deallocation",
455 Some((tag, access)) => {
457 "popped tracked tag for item {item:?} due to {access:?} access for {tag:?}",
462 format!("function call with id {id}"),
463 CreatedAlloc(AllocId(id), size, align, kind) =>
465 "created {kind} allocation of {size} bytes (alignment {align} bytes) with id {id}",
467 align = align.bytes(),
469 FreedAlloc(AllocId(id)) =>
470 format!("freed allocation with id {id}"),
471 RejectedIsolatedOp(ref op) =>
472 format!("{op} was made to return an error due to isolation"),
474 format!("progress report: current operation being executed is here"),
476 format!("integer-to-pointer cast"),
479 let (title, diag_level) = match e {
480 RejectedIsolatedOp(_) =>
481 ("operation rejected by isolation", DiagLevel::Warning),
482 Int2Ptr { .. } => ("integer-to-pointer cast", DiagLevel::Warning),
483 CreatedPointerTag(..)
484 | PoppedPointerTag(..)
488 | ProgressReport => ("tracking was triggered", DiagLevel::Note),
491 let helps = match e {
492 Int2Ptr { details: true } =>
494 (None, format!("This program is using integer-to-pointer casts or (equivalently) `ptr::from_exposed_addr`,")),
495 (None, format!("which means that Miri might miss pointer bugs in this program.")),
496 (None, format!("See https://doc.rust-lang.org/nightly/std/ptr/fn.from_exposed_addr.html for more details on that operation.")),
497 (None, format!("To ensure that Miri does not miss bugs in your program, use Strict Provenance APIs (https://doc.rust-lang.org/nightly/std/ptr/index.html#strict-provenance, https://crates.io/crates/sptr) instead.")),
498 (None, format!("You can then pass the `-Zmiri-strict-provenance` flag to Miri, to ensure you are not relying on `from_exposed_addr` semantics.")),
499 (None, format!("Alternatively, the `-Zmiri-permissive-provenance` flag disables this warning.")),
504 report_msg(this, diag_level, title, vec![msg], helps, &stacktrace);