Skip to content

Commit 515287f

Browse files
committed
Auto merge of #1480 - RalfJung:diagnostic-stacktrace-fix, r=oli-obk
fix non-fatal diagnostics stacktraces Our non-fatal diagnostics are printed *after* completing the step that triggered them, which means the span and stacktrace used for them is that of the *next* MIR statement being executed. That's quite bad, obviously, as pointing to where in the source something happens is their entire point. Here's an example: ```rust use std::ptr; static mut PTR: *mut u8 = ptr::null_mut(); fn get_ptr() -> *const u8 { unsafe { PTR }} fn cause_ub() { unsafe { let _x = &*get_ptr(); } } fn main() { unsafe { let mut l = 0; PTR = &mut l; let r = &mut *PTR; cause_ub(); let _x = *r; } } ``` This example is UB; if you track the pointer tag that is given in the final error, it points to the entire body of `cause_ub` as a span, instead of the `&*get_ptr();`. I am not sure what the best way is to fix this. The cleanest way would be to capture a stack trace before the step and use it in case of a diagnostic, but that seems silly perf-wise. So instead I went with reconstructing the old stacktrace by going back one step in the MIR. This is however not possible if we were executing a `Terminator`... I think those cannot cause diagnostics but still, this is not great. Any ideas? r? @oli-obk
2 parents 0454dab + 545aa60 commit 515287f

File tree

3 files changed

+79
-28
lines changed

3 files changed

+79
-28
lines changed

src/diagnostics.rs

Lines changed: 74 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@ use std::fmt;
33

44
use log::trace;
55

6-
use rustc_span::DUMMY_SP;
6+
use rustc_middle::ty::{self, TyCtxt};
7+
use rustc_span::{source_map::DUMMY_SP, Span};
78

89
use crate::*;
910

@@ -116,7 +117,17 @@ pub fn report_error<'tcx, 'mir>(
116117

117118
e.print_backtrace();
118119
let msg = e.to_string();
119-
report_msg(ecx, &format!("{}: {}", title, msg), msg, helps, true);
120+
report_msg(*ecx.tcx, /*error*/true, &format!("{}: {}", title, msg), msg, helps, &ecx.generate_stacktrace());
121+
122+
// Debug-dump all locals.
123+
for (i, frame) in ecx.active_thread_stack().iter().enumerate() {
124+
trace!("-------------------");
125+
trace!("Frame {}", i);
126+
trace!(" return: {:?}", frame.return_place.map(|p| *p));
127+
for (i, local) in frame.locals.iter().enumerate() {
128+
trace!(" local {}: {:?}", i, local.value);
129+
}
130+
}
120131

121132
// Extra output to help debug specific issues.
122133
match e.kind {
@@ -135,24 +146,21 @@ pub fn report_error<'tcx, 'mir>(
135146
None
136147
}
137148

138-
/// Report an error or note (depending on the `error` argument) at the current frame's current statement.
149+
/// Report an error or note (depending on the `error` argument) with the given stacktrace.
139150
/// Also emits a full stacktrace of the interpreter stack.
140-
fn report_msg<'tcx, 'mir>(
141-
ecx: &InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
151+
fn report_msg<'tcx>(
152+
tcx: TyCtxt<'tcx>,
153+
error: bool,
142154
title: &str,
143155
span_msg: String,
144156
mut helps: Vec<String>,
145-
error: bool,
157+
stacktrace: &[FrameInfo<'tcx>],
146158
) {
147-
let span = if let Some(frame) = ecx.active_thread_stack().last() {
148-
frame.current_source_info().unwrap().span
149-
} else {
150-
DUMMY_SP
151-
};
159+
let span = stacktrace.first().map_or(DUMMY_SP, |fi| fi.span);
152160
let mut err = if error {
153-
ecx.tcx.sess.struct_span_err(span, title)
161+
tcx.sess.struct_span_err(span, title)
154162
} else {
155-
ecx.tcx.sess.diagnostic().span_note_diag(span, title)
163+
tcx.sess.diagnostic().span_note_diag(span, title)
156164
};
157165
err.span_label(span, span_msg);
158166
if !helps.is_empty() {
@@ -163,8 +171,7 @@ fn report_msg<'tcx, 'mir>(
163171
}
164172
}
165173
// Add backtrace
166-
let frames = ecx.generate_stacktrace();
167-
for (idx, frame_info) in frames.iter().enumerate() {
174+
for (idx, frame_info) in stacktrace.iter().enumerate() {
168175
let is_local = frame_info.instance.def_id().is_local();
169176
// No span for non-local frames and the first frame (which is the error site).
170177
if is_local && idx > 0 {
@@ -175,15 +182,6 @@ fn report_msg<'tcx, 'mir>(
175182
}
176183

177184
err.emit();
178-
179-
for (i, frame) in ecx.active_thread_stack().iter().enumerate() {
180-
trace!("-------------------");
181-
trace!("Frame {}", i);
182-
trace!(" return: {:?}", frame.return_place.map(|p| *p));
183-
for (i, local) in frame.locals.iter().enumerate() {
184-
trace!(" local {}: {:?}", i, local.value);
185-
}
186-
}
187185
}
188186

189187
thread_local! {
@@ -196,13 +194,62 @@ pub fn register_diagnostic(e: NonHaltingDiagnostic) {
196194
DIAGNOSTICS.with(|diagnostics| diagnostics.borrow_mut().push(e));
197195
}
198196

197+
/// Remember enough about the topmost frame so that we can restore the stack
198+
/// after a step was taken.
199+
pub struct TopFrameInfo<'tcx> {
200+
stack_size: usize,
201+
instance: ty::Instance<'tcx>,
202+
span: Span,
203+
}
204+
199205
impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
200206
pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
207+
fn preprocess_diagnostics(&self) -> TopFrameInfo<'tcx> {
208+
// Ensure we have no lingering diagnostics.
209+
DIAGNOSTICS.with(|diagnostics| assert!(diagnostics.borrow().is_empty()));
210+
211+
let this = self.eval_context_ref();
212+
let frame = this.frame();
213+
214+
TopFrameInfo {
215+
stack_size: this.active_thread_stack().len(),
216+
instance: frame.instance,
217+
span: frame.current_source_info().map_or(DUMMY_SP, |si| si.span),
218+
}
219+
}
220+
201221
/// Emit all diagnostics that were registed with `register_diagnostics`
202-
fn process_diagnostics(&self) {
222+
fn process_diagnostics(&self, info: TopFrameInfo<'tcx>) {
203223
let this = self.eval_context_ref();
204224
DIAGNOSTICS.with(|diagnostics| {
205-
for e in diagnostics.borrow_mut().drain(..) {
225+
let mut diagnostics = diagnostics.borrow_mut();
226+
if diagnostics.is_empty() {
227+
return;
228+
}
229+
// We need to fix up the stack trace, because the machine has already
230+
// stepped to the next statement.
231+
let mut stacktrace = this.generate_stacktrace();
232+
// Remove newly pushed frames.
233+
while stacktrace.len() > info.stack_size {
234+
stacktrace.remove(0);
235+
}
236+
// Add popped frame back.
237+
if stacktrace.len() < info.stack_size {
238+
assert!(stacktrace.len() == info.stack_size-1, "we should never pop more than one frame at once");
239+
let frame_info = FrameInfo {
240+
instance: info.instance,
241+
span: info.span,
242+
lint_root: None,
243+
};
244+
stacktrace.insert(0, frame_info);
245+
} else {
246+
// Adjust topmost frame.
247+
stacktrace[0].span = info.span;
248+
assert_eq!(stacktrace[0].instance, info.instance, "we should not pop and push a frame in one step");
249+
}
250+
251+
// Show diagnostics.
252+
for e in diagnostics.drain(..) {
206253
use NonHaltingDiagnostic::*;
207254
let msg = match e {
208255
PoppedPointerTag(item) =>
@@ -214,7 +261,7 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx
214261
FreedAlloc(AllocId(id)) =>
215262
format!("freed allocation with id {}", id),
216263
};
217-
report_msg(this, "tracking was triggered", msg, vec![], false);
264+
report_msg(*this.tcx, /*error*/false, "tracking was triggered", msg, vec![], &stacktrace);
218265
}
219266
});
220267
}

src/eval.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -212,7 +212,9 @@ pub fn eval_main<'tcx>(tcx: TyCtxt<'tcx>, main_id: DefId, config: MiriConfig) ->
212212
loop {
213213
match ecx.schedule()? {
214214
SchedulingAction::ExecuteStep => {
215+
let info = ecx.preprocess_diagnostics();
215216
assert!(ecx.step()?, "a terminated thread was scheduled for execution");
217+
ecx.process_diagnostics(info);
216218
}
217219
SchedulingAction::ExecuteTimeoutCallback => {
218220
assert!(ecx.machine.communicate,
@@ -230,7 +232,6 @@ pub fn eval_main<'tcx>(tcx: TyCtxt<'tcx>, main_id: DefId, config: MiriConfig) ->
230232
break;
231233
}
232234
}
233-
ecx.process_diagnostics();
234235
}
235236
let return_code = ecx.read_scalar(ret_place.into())?.not_undef()?.to_machine_isize(&ecx)?;
236237
Ok(return_code)

src/thread.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -373,6 +373,9 @@ impl<'mir, 'tcx: 'mir> ThreadManager<'mir, 'tcx> {
373373

374374
/// Change the active thread to some enabled thread.
375375
fn yield_active_thread(&mut self) {
376+
// We do not yield immediately, as swapping out the current stack while executing a MIR statement
377+
// could lead to all sorts of confusion.
378+
// We should only switch stacks between steps.
376379
self.yield_active_thread = true;
377380
}
378381

0 commit comments

Comments
 (0)