2 use std::num::NonZeroU64;
6 use rustc_span::{source_map::DUMMY_SP, SpanData, Symbol};
7 use rustc_target::abi::{Align, Size};
9 use crate::stacked_borrows::{diagnostics::TagHistory, AccessKind};
12 /// Details of premature program termination.
13 pub enum TerminationInfo {
16 UnsupportedInIsolation(String),
20 history: Option<TagHistory>,
22 Int2PtrWithStrictProvenance,
24 MultipleSymbolDefinitions {
37 impl fmt::Display for TerminationInfo {
38 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
39 use TerminationInfo::*;
41 Exit(code) => write!(f, "the evaluated program completed with exit code {code}"),
42 Abort(msg) => write!(f, "{msg}"),
43 UnsupportedInIsolation(msg) => write!(f, "{msg}"),
44 Int2PtrWithStrictProvenance =>
47 "integer-to-pointer casts and `ptr::from_exposed_addr` are not supported with `-Zmiri-strict-provenance`"
49 StackedBorrowsUb { msg, .. } => write!(f, "{msg}"),
50 Deadlock => write!(f, "the evaluated program deadlocked"),
51 MultipleSymbolDefinitions { link_name, .. } =>
52 write!(f, "multiple definitions of symbol `{link_name}`"),
53 SymbolShimClashing { link_name, .. } =>
54 write!(f, "found `{link_name}` symbol definition that clashes with a built-in shim",),
59 impl MachineStopType for TerminationInfo {}
61 /// Miri specific diagnostics
62 pub enum NonHaltingDiagnostic {
63 /// (new_tag, new_kind, (alloc_id, base_offset, orig_tag))
65 /// new_kind is `None` for base tags.
66 CreatedPointerTag(NonZeroU64, Option<String>, Option<(AllocId, AllocRange, ProvenanceExtra)>),
67 /// This `Item` was popped from the borrow stack, either due to an access with the given tag or
68 /// a deallocation when the second argument is `None`.
69 PoppedPointerTag(Item, Option<(ProvenanceExtra, AccessKind)>),
70 CreatedCallId(CallId),
71 CreatedAlloc(AllocId, Size, Align, MemoryKind<MiriMemoryKind>),
73 RejectedIsolatedOp(String),
75 block_count: u64, // how many basic blocks have been run so far
80 WeakMemoryOutdatedLoad,
83 /// Level of Miri specific diagnostics
90 /// Attempts to prune a stacktrace to omit the Rust runtime, and returns a bool indicating if any
91 /// frames were pruned. If the stacktrace does not have any local frames, we conclude that it must
92 /// be pointing to a problem in the Rust runtime itself, and do not prune it at all.
93 fn prune_stacktrace<'tcx>(
94 mut stacktrace: Vec<FrameInfo<'tcx>>,
95 machine: &MiriMachine<'_, 'tcx>,
96 ) -> (Vec<FrameInfo<'tcx>>, bool) {
97 match machine.backtrace_style {
98 BacktraceStyle::Off => {
99 // Remove all frames marked with `caller_location` -- that attribute indicates we
100 // usually want to point at the caller, not them.
101 stacktrace.retain(|frame| !frame.instance.def.requires_caller_location(machine.tcx));
102 // Retain one frame so that we can print a span for the error itself
103 stacktrace.truncate(1);
106 BacktraceStyle::Short => {
107 let original_len = stacktrace.len();
108 // Only prune frames if there is at least one local frame. This check ensures that if
109 // we get a backtrace that never makes it to the user code because it has detected a
110 // bug in the Rust runtime, we don't prune away every frame.
111 let has_local_frame = stacktrace.iter().any(|frame| machine.is_local(frame));
113 // Remove all frames marked with `caller_location` -- that attribute indicates we
114 // usually want to point at the caller, not them.
116 .retain(|frame| !frame.instance.def.requires_caller_location(machine.tcx));
118 // This is part of the logic that `std` uses to select the relevant part of a
119 // backtrace. But here, we only look for __rust_begin_short_backtrace, not
120 // __rust_end_short_backtrace because the end symbol comes from a call to the default
122 stacktrace = stacktrace
124 .take_while(|frame| {
125 let def_id = frame.instance.def_id();
126 let path = machine.tcx.def_path_str(def_id);
127 !path.contains("__rust_begin_short_backtrace")
129 .collect::<Vec<_>>();
131 // After we prune frames from the bottom, there are a few left that are part of the
132 // Rust runtime. So we remove frames until we get to a local symbol, which should be
134 // This len check ensures that we don't somehow remove every frame, as doing so breaks
135 // the primary error message.
136 while stacktrace.len() > 1
137 && stacktrace.last().map_or(false, |frame| !machine.is_local(frame))
142 let was_pruned = stacktrace.len() != original_len;
143 (stacktrace, was_pruned)
145 BacktraceStyle::Full => (stacktrace, false),
149 /// Emit a custom diagnostic without going through the miri-engine machinery
150 pub fn report_error<'tcx, 'mir>(
151 ecx: &InterpCx<'mir, 'tcx, MiriMachine<'mir, 'tcx>>,
152 e: InterpErrorInfo<'tcx>,
156 let mut msg = vec![];
158 let (title, helps) = match &e.kind() {
159 MachineStop(info) => {
160 let info = info.downcast_ref::<TerminationInfo>().expect("invalid MachineStop payload");
161 use TerminationInfo::*;
162 let title = match info {
163 Exit(code) => return Some(*code),
164 Abort(_) => Some("abnormal termination"),
165 UnsupportedInIsolation(_) | Int2PtrWithStrictProvenance =>
166 Some("unsupported operation"),
167 StackedBorrowsUb { .. } => Some("Undefined Behavior"),
168 Deadlock => Some("deadlock"),
169 MultipleSymbolDefinitions { .. } | SymbolShimClashing { .. } => None,
172 let helps = match info {
173 UnsupportedInIsolation(_) =>
175 (None, format!("pass the flag `-Zmiri-disable-isolation` to disable isolation;")),
176 (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")),
178 StackedBorrowsUb { help, history, .. } => {
179 let url = "https://github.com/rust-lang/unsafe-code-guidelines/blob/master/wip/stacked-borrows.md";
180 msg.extend(help.clone());
181 let mut helps = vec![
182 (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")),
183 (None, format!("see {url} for further information")),
185 if let Some(TagHistory {created, invalidated, protected}) = history.clone() {
186 helps.push((Some(created.1), created.0));
187 if let Some((msg, span)) = invalidated {
188 helps.push((Some(span), msg));
190 if let Some((protector_msg, protector_span)) = protected {
191 helps.push((Some(protector_span), protector_msg));
196 MultipleSymbolDefinitions { first, first_crate, second, second_crate, .. } =>
198 (Some(*first), format!("it's first defined here, in crate `{first_crate}`")),
199 (Some(*second), format!("then it's defined here again, in crate `{second_crate}`")),
201 SymbolShimClashing { link_name, span } =>
202 vec![(Some(*span), format!("the `{link_name}` symbol is defined here"))],
203 Int2PtrWithStrictProvenance =>
204 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"))],
211 let title = match e.kind() {
213 "unsupported operation",
214 UndefinedBehavior(_) =>
215 "Undefined Behavior",
216 ResourceExhaustion(_) =>
217 "resource exhaustion",
219 InvalidProgramInfo::AlreadyReported(_) |
220 InvalidProgramInfo::Layout(..) |
221 InvalidProgramInfo::ReferencedConstant
223 "post-monomorphization error",
225 bug!("This error should be impossible in Miri: {kind:?}"),
228 let helps = match e.kind() {
230 UnsupportedOpInfo::ThreadLocalStatic(_) |
231 UnsupportedOpInfo::ReadExternStatic(_) |
232 UnsupportedOpInfo::PartialPointerOverwrite(_) | // we make memory uninit instead
233 UnsupportedOpInfo::ReadPointerAsBytes
235 panic!("Error should never be raised by Miri: {kind:?}", kind = e.kind()),
237 UnsupportedOpInfo::Unsupported(_) |
238 UnsupportedOpInfo::PartialPointerCopy(_)
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(stacktrace, &ecx.machine);
263 msg.insert(0, e.to_string());
266 &if let Some(title) = title { format!("{}: {}", title, msg[0]) } else { msg[0].clone() },
274 // Include a note like `std` does when we omit frames from a backtrace
276 ecx.tcx.sess.diagnostic().note_without_error(
277 "some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace",
281 // Debug-dump all locals.
282 for (i, frame) in ecx.active_thread_stack().iter().enumerate() {
283 trace!("-------------------");
284 trace!("Frame {}", i);
285 trace!(" return: {:?}", *frame.return_place);
286 for (i, local) in frame.locals.iter().enumerate() {
287 trace!(" local {}: {:?}", i, local.value);
291 // Extra output to help debug specific issues.
293 UndefinedBehavior(UndefinedBehaviorInfo::InvalidUninitBytes(Some((alloc_id, access)))) => {
295 "Uninitialized memory occurred at {alloc_id:?}{range:?}, in this allocation:",
296 range = access.uninit,
298 eprintln!("{:?}", ecx.dump_alloc(*alloc_id));
306 /// Report an error or note (depending on the `error` argument) with the given stacktrace.
307 /// Also emits a full stacktrace of the interpreter stack.
308 /// We want to present a multi-line span message for some errors. Diagnostics do not support this
309 /// directly, so we pass the lines as a `Vec<String>` and display each line after the first with an
310 /// additional `span_label` or `note` call.
312 diag_level: DiagLevel,
314 span_msg: Vec<String>,
315 notes: Vec<(Option<SpanData>, String)>,
316 helps: Vec<(Option<SpanData>, String)>,
317 stacktrace: &[FrameInfo<'tcx>],
318 machine: &MiriMachine<'_, 'tcx>,
320 let span = stacktrace.first().map_or(DUMMY_SP, |fi| fi.span);
321 let sess = machine.tcx.sess;
322 let mut err = match diag_level {
323 DiagLevel::Error => sess.struct_span_err(span, title).forget_guarantee(),
324 DiagLevel::Warning => sess.struct_span_warn(span, title),
325 DiagLevel::Note => sess.diagnostic().span_note_diag(span, title),
328 // Show main message.
329 if span != DUMMY_SP {
330 for line in span_msg {
331 err.span_label(span, line);
334 // Make sure we show the message even when it is a dummy span.
335 for line in span_msg {
338 err.note("(no span available)");
341 // Show note and help messages.
342 for (span_data, note) in ¬es {
343 if let Some(span_data) = span_data {
344 err.span_note(span_data.span(), note);
349 for (span_data, help) in &helps {
350 if let Some(span_data) = span_data {
351 err.span_help(span_data.span(), help);
356 if notes.len() + helps.len() > 0 {
357 // Add visual separator before backtrace.
358 err.note("BACKTRACE:");
361 for (idx, frame_info) in stacktrace.iter().enumerate() {
362 let is_local = machine.is_local(frame_info);
363 // No span for non-local frames and the first frame (which is the error site).
364 if is_local && idx > 0 {
365 err.span_note(frame_info.span, &frame_info.to_string());
367 err.note(&frame_info.to_string());
374 impl<'mir, 'tcx> MiriMachine<'mir, 'tcx> {
375 pub fn emit_diagnostic(&self, e: NonHaltingDiagnostic) {
376 use NonHaltingDiagnostic::*;
379 MiriInterpCx::generate_stacktrace_from_stack(self.threads.active_thread_stack());
380 let (stacktrace, _was_pruned) = prune_stacktrace(stacktrace, self);
382 let (title, diag_level) = match &e {
383 RejectedIsolatedOp(_) => ("operation rejected by isolation", DiagLevel::Warning),
384 Int2Ptr { .. } => ("integer-to-pointer cast", DiagLevel::Warning),
385 CreatedPointerTag(..)
386 | PoppedPointerTag(..)
390 | ProgressReport { .. }
391 | WeakMemoryOutdatedLoad => ("tracking was triggered", DiagLevel::Note),
395 CreatedPointerTag(tag, None, _) => format!("created base tag {tag:?}"),
396 CreatedPointerTag(tag, Some(kind), None) => format!("created {tag:?} for {kind}"),
397 CreatedPointerTag(tag, Some(kind), Some((alloc_id, range, orig_tag))) =>
399 "created tag {tag:?} for {kind} at {alloc_id:?}{range:?} derived from {orig_tag:?}"
401 PoppedPointerTag(item, tag) =>
403 None => format!("popped tracked tag for item {item:?} due to deallocation",),
404 Some((tag, access)) => {
406 "popped tracked tag for item {item:?} due to {access:?} access for {tag:?}",
410 CreatedCallId(id) => format!("function call with id {id}"),
411 CreatedAlloc(AllocId(id), size, align, kind) =>
413 "created {kind} allocation of {size} bytes (alignment {align} bytes) with id {id}",
415 align = align.bytes(),
417 FreedAlloc(AllocId(id)) => format!("freed allocation with id {id}"),
418 RejectedIsolatedOp(ref op) =>
419 format!("{op} was made to return an error due to isolation"),
420 ProgressReport { .. } =>
421 format!("progress report: current operation being executed is here"),
422 Int2Ptr { .. } => format!("integer-to-pointer cast"),
423 WeakMemoryOutdatedLoad =>
424 format!("weak memory emulation: outdated value returned from load"),
427 let notes = match &e {
428 ProgressReport { block_count } => {
429 // It is important that each progress report is slightly different, since
430 // identical diagnostics are being deduplicated.
431 vec![(None, format!("so far, {block_count} basic blocks have been executed"))]
436 let helps = match &e {
437 Int2Ptr { details: true } =>
442 "This program is using integer-to-pointer casts or (equivalently) `ptr::from_exposed_addr`,"
447 format!("which means that Miri might miss pointer bugs in this program."),
452 "See https://doc.rust-lang.org/nightly/std/ptr/fn.from_exposed_addr.html for more details on that operation."
458 "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."
464 "You can then pass the `-Zmiri-strict-provenance` flag to Miri, to ensure you are not relying on `from_exposed_addr` semantics."
470 "Alternatively, the `-Zmiri-permissive-provenance` flag disables this warning."
477 report_msg(diag_level, title, vec![msg], notes, helps, &stacktrace, self);
481 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriInterpCx<'mir, 'tcx> {}
482 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> {
483 fn emit_diagnostic(&self, e: NonHaltingDiagnostic) {
484 let this = self.eval_context_ref();
485 this.machine.emit_diagnostic(e);
488 /// We had a panic in Miri itself, try to print something useful.
489 fn handle_ice(&self) {
492 "Miri caused an ICE during evaluation. Here's the interpreter backtrace at the time of the panic:"
494 let this = self.eval_context_ref();
495 let stacktrace = this.generate_stacktrace();
498 "the place in the program where the ICE was triggered",