rust/src/diagnostics.rs

215 lines
8.1 KiB
Rust
Raw Normal View History

use std::cell::RefCell;
2020-03-24 08:24:36 +01:00
use std::fmt;
2019-12-24 00:11:40 +01:00
use log::trace;
2020-03-22 18:50:12 +01:00
use rustc_span::DUMMY_SP;
2019-12-24 00:11:40 +01:00
use crate::*;
/// Details of premature program termination.
pub enum TerminationInfo {
Exit(i64),
Abort(Option<String>),
UnsupportedInIsolation(String),
ExperimentalUb { msg: String, url: String },
Deadlock,
}
2020-03-24 08:24:36 +01:00
impl fmt::Debug for TerminationInfo {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use TerminationInfo::*;
match self {
Exit(code) =>
write!(f, "the evaluated program completed with exit code {}", code),
Abort(None) =>
write!(f, "the evaluated program aborted execution"),
Abort(Some(msg)) =>
write!(f, "the evaluated program aborted execution: {}", msg),
UnsupportedInIsolation(msg) =>
write!(f, "{}", msg),
ExperimentalUb { msg, .. } =>
write!(f, "{}", msg),
Deadlock =>
write!(f, "the evaluated program deadlocked"),
2020-03-24 08:24:36 +01:00
}
}
}
impl MachineStopType for TerminationInfo {}
2020-01-09 12:42:56 +01:00
/// Miri specific diagnostics
pub enum NonHaltingDiagnostic {
PoppedTrackedPointerTag(Item),
CreatedAlloc(AllocId),
2020-04-14 19:00:56 -04:00
FreedAlloc(AllocId),
}
2020-01-09 12:42:56 +01:00
/// Emit a custom diagnostic without going through the miri-engine machinery
pub fn report_error<'tcx, 'mir>(
ecx: &InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
2019-12-24 00:11:40 +01:00
mut e: InterpErrorInfo<'tcx>,
) -> Option<i64> {
2020-03-22 18:50:12 +01:00
use InterpError::*;
2020-04-12 10:08:12 +02:00
let (title, helps) = match &e.kind {
MachineStop(info) => {
2019-12-24 00:11:40 +01:00
let info = info.downcast_ref::<TerminationInfo>().expect("invalid MachineStop payload");
use TerminationInfo::*;
2020-03-24 08:24:36 +01:00
let title = match info {
Exit(code) => return Some(*code),
2020-03-24 08:24:36 +01:00
Abort(_) =>
"abnormal termination",
UnsupportedInIsolation(_) =>
"unsupported operation",
ExperimentalUb { .. } =>
"Undefined Behavior",
Deadlock => "deadlock",
};
let helps = match info {
UnsupportedInIsolation(_) =>
vec![format!("pass the flag `-Zmiri-disable-isolation` to disable isolation")],
ExperimentalUb { url, .. } =>
vec![
format!("this indicates a potential bug in the program: it performed an invalid operation, but the rules it violated are still experimental"),
format!("see {} for further information", url),
],
_ => vec![],
};
2020-03-24 08:24:36 +01:00
(title, helps)
}
_ => {
2020-03-24 08:24:36 +01:00
let title = match e.kind {
Unsupported(_) =>
2020-03-24 08:24:36 +01:00
"unsupported operation",
UndefinedBehavior(_) =>
2020-03-24 08:24:36 +01:00
"Undefined Behavior",
ResourceExhaustion(_) =>
2020-03-24 08:24:36 +01:00
"resource exhaustion",
_ =>
bug!("This error should be impossible in Miri: {}", e),
};
let helps = match e.kind {
Unsupported(UnsupportedOpInfo::NoMirFor(..)) =>
vec![format!("make sure to use a Miri sysroot, which you can prepare with `cargo miri setup`")],
2020-04-16 18:35:42 +02:00
Unsupported(UnsupportedOpInfo::ReadBytesAsPointer) =>
panic!("`ReadBytesAsPointer` cannot be raised by Miri"),
Unsupported(_) =>
vec![format!("this is likely not a bug in the program; it indicates that the program performed an operation that the interpreter does not support")],
UndefinedBehavior(UndefinedBehaviorInfo::AlignmentCheckFailed { .. }) =>
vec![
format!("this usually indicates that your program performed an invalid operation and caused Undefined Behavior"),
format!("but alignment errors can also be false positives, see https://github.com/rust-lang/miri/issues/1074"),
format!("you can disable the alignment check with `-Zmiri-disable-alignment-check`, but that could hide true bugs")
],
UndefinedBehavior(_) =>
vec![
format!("this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior"),
format!("see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information"),
],
_ => vec![],
};
2020-03-24 08:24:36 +01:00
(title, helps)
2019-12-24 00:11:40 +01:00
}
2020-03-22 18:50:12 +01:00
};
2020-03-24 08:24:36 +01:00
e.print_backtrace();
2020-04-22 17:41:06 -05:00
let msg = e.to_string();
2020-04-26 22:13:36 -05:00
report_msg(ecx, &format!("{}: {}", title, msg), msg, helps, true);
2020-04-22 17:41:06 -05:00
2020-04-26 22:13:36 -05:00
// Extra output to help debug specific issues.
if let UndefinedBehavior(UndefinedBehaviorInfo::InvalidUndefBytes(Some(ptr))) = e.kind {
2020-04-23 20:00:09 -05:00
eprintln!(
"Uninitialized read occurred at offset 0x{:x} into this allocation:",
ptr.offset.bytes(),
);
ecx.memory.dump_alloc(ptr.alloc_id);
2020-04-23 20:00:09 -05:00
eprintln!();
}
2020-04-22 17:41:06 -05:00
2020-04-26 22:13:36 -05:00
None
}
2020-01-09 12:42:56 +01:00
/// Report an error or note (depending on the `error` argument) at the current frame's current statement.
/// Also emits a full stacktrace of the interpreter stack.
fn report_msg<'tcx, 'mir>(
ecx: &InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
2020-03-22 18:50:12 +01:00
title: &str,
span_msg: String,
mut helps: Vec<String>,
error: bool,
2020-04-26 22:13:36 -05:00
) {
let span = if let Some(frame) = ecx.active_thread_stack().last() {
2020-03-22 18:50:12 +01:00
frame.current_source_info().unwrap().span
} else {
DUMMY_SP
};
let mut err = if error {
ecx.tcx.sess.struct_span_err(span, title)
} else {
ecx.tcx.sess.diagnostic().span_note_diag(span, title)
};
err.span_label(span, span_msg);
if !helps.is_empty() {
// Add visual separator before backtrace.
helps.last_mut().unwrap().push_str("\n");
for help in helps {
err.help(&help);
}
2020-03-22 18:50:12 +01:00
}
// Add backtrace
let frames = ecx.generate_stacktrace();
for (idx, frame_info) in frames.iter().enumerate() {
let is_local = frame_info.instance.def_id().is_local();
// No span for non-local frames and the first frame (which is the error site).
if is_local && idx > 0 {
err.span_note(frame_info.span, &frame_info.to_string());
} else {
2020-03-22 18:50:12 +01:00
err.note(&frame_info.to_string());
2019-12-24 00:11:40 +01:00
}
}
2020-03-22 18:50:12 +01:00
err.emit();
for (i, frame) in ecx.active_thread_stack().iter().enumerate() {
2019-12-24 00:11:40 +01:00
trace!("-------------------");
trace!("Frame {}", i);
trace!(" return: {:?}", frame.return_place.map(|p| *p));
for (i, local) in frame.locals.iter().enumerate() {
trace!(" local {}: {:?}", i, local.value);
}
}
}
thread_local! {
static DIAGNOSTICS: RefCell<Vec<NonHaltingDiagnostic>> = RefCell::new(Vec::new());
}
2020-01-09 12:42:56 +01:00
/// Schedule a diagnostic for emitting. This function works even if you have no `InterpCx` available.
/// The diagnostic will be emitted after the current interpreter step is finished.
pub fn register_diagnostic(e: NonHaltingDiagnostic) {
DIAGNOSTICS.with(|diagnostics| diagnostics.borrow_mut().push(e));
}
impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
2020-01-09 12:42:56 +01:00
/// Emit all diagnostics that were registed with `register_diagnostics`
fn process_diagnostics(&self) {
let this = self.eval_context_ref();
DIAGNOSTICS.with(|diagnostics| {
for e in diagnostics.borrow_mut().drain(..) {
use NonHaltingDiagnostic::*;
let msg = match e {
PoppedTrackedPointerTag(item) =>
format!("popped tracked tag for item {:?}", item),
CreatedAlloc(AllocId(id)) =>
format!("created allocation with id {}", id),
2020-04-14 19:00:56 -04:00
FreedAlloc(AllocId(id)) =>
format!("freed allocation with id {}", id),
};
report_msg(this, "tracking was triggered", msg, vec![], false);
}
});
}
}