Preserve full native stack traces in errors (#823)

* Preserve full native stack traces in errors

This commit builds on #759 by performing a few refactorings:

* The `backtrace` crate is updated to 0.3.42 which incorporates the
  Windows-specific stack-walking code, so that's no longer needed.
* A full `backtrace::Backtrace` type is held in a trap at all times.
* The trap structures in the `wasmtime-*` internal crates were
  refactored a bit to preserve more information and deal with raw
  values rather than converting between various types and strings.
* The `wasmtime::Trap` type has been updated with these various changes.

Eventually I think we'll want to likely render full stack traces (and/or
partial wasm ones) into error messages, but for now that's left as-is
and we can always improve it later. I suspect the most relevant thing we
need to do is to implement function name symbolication for wasm
functions first, and then afterwards we can incorporate native function
names!

* Fix some test suite assertions
This commit is contained in:
Alex Crichton
2020-01-15 15:30:17 -06:00
committed by GitHub
parent b8e4354efc
commit e7e08f162d
12 changed files with 89 additions and 239 deletions

View File

@@ -20,7 +20,7 @@ indexmap = "1.0.2"
thiserror = "1.0.4"
more-asserts = "0.2.1"
cfg-if = "0.1.9"
backtrace = "0.3.40"
backtrace = "0.3.42"
[target.'cfg(target_os = "windows")'.dependencies]
winapi = { version = "0.3.7", features = ["winbase", "memoryapi"] }

View File

@@ -1,148 +0,0 @@
//! Backtrace object and utilities.
use crate::jit_function_registry;
use std::sync::Arc;
/// Information about backtrace frame.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct BacktraceFrame {
pc: usize,
}
impl Default for BacktraceFrame {
fn default() -> Self {
Self { pc: 0 }
}
}
impl BacktraceFrame {
/// Current PC or IP pointer for the frame.
pub fn pc(&self) -> usize {
self.pc
}
/// Additinal frame information.
pub fn tag(&self) -> Option<Arc<jit_function_registry::JITFunctionTag>> {
jit_function_registry::find(self.pc)
}
}
const BACKTRACE_LIMIT: usize = 32;
/// Backtrace during WebAssembly trap.
#[derive(Copy, Clone, PartialEq, Eq)]
pub struct Backtrace {
len: usize,
frames: [BacktraceFrame; BACKTRACE_LIMIT],
}
impl Backtrace {
fn new() -> Self {
Self {
len: 0,
frames: [Default::default(); BACKTRACE_LIMIT],
}
}
fn full(&self) -> bool {
self.len >= BACKTRACE_LIMIT
}
fn push(&mut self, frame: BacktraceFrame) {
assert!(self.len < BACKTRACE_LIMIT);
self.frames[self.len] = frame;
self.len += 1;
}
/// Amount of the backtrace frames.
pub fn len(&self) -> usize {
self.len
}
}
impl std::ops::Index<usize> for Backtrace {
type Output = BacktraceFrame;
fn index(&self, index: usize) -> &Self::Output {
assert!(index < self.len);
&self.frames[index]
}
}
impl std::fmt::Debug for Backtrace {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
writeln!(f, "Backtrace![")?;
for i in 0..self.len() {
let frame = &self.frames[i];
writeln!(f, " {:x}: {:?}", frame.pc(), frame.tag())?;
}
write!(f, "]")?;
Ok(())
}
}
#[cfg(not(all(target_os = "windows", target_arch = "x86_64")))]
fn capture_stack<F>(mut f: F)
where
F: FnMut(usize) -> bool,
{
use backtrace::trace;
trace(|frame| {
let pc = frame.ip() as usize;
f(pc)
});
}
#[cfg(all(target_os = "windows", target_arch = "x86_64"))]
fn capture_stack<F>(mut f: F)
where
F: FnMut(usize) -> bool,
{
use std::mem::MaybeUninit;
use std::ptr;
use winapi::um::winnt::{
RtlCaptureContext, RtlLookupFunctionEntry, RtlVirtualUnwind, CONTEXT, UNW_FLAG_NHANDLER,
};
#[repr(C, align(16))]
struct WrappedContext(CONTEXT);
unsafe {
let mut ctx = WrappedContext(MaybeUninit::uninit().assume_init());
RtlCaptureContext(&mut ctx.0);
let mut unwind_history_table = MaybeUninit::zeroed().assume_init();
while ctx.0.Rip != 0 {
let cont = f(ctx.0.Rip as usize);
if !cont {
break;
}
let mut image_base: u64 = 0;
let mut handler_data: *mut core::ffi::c_void = ptr::null_mut();
let mut establisher_frame: u64 = 0;
let rf = RtlLookupFunctionEntry(ctx.0.Rip, &mut image_base, &mut unwind_history_table);
if rf.is_null() {
ctx.0.Rip = ptr::read(ctx.0.Rsp as *const u64);
ctx.0.Rsp += 8;
} else {
RtlVirtualUnwind(
UNW_FLAG_NHANDLER,
image_base,
ctx.0.Rip,
rf,
&mut ctx.0,
&mut handler_data,
&mut establisher_frame,
ptr::null_mut(),
);
}
}
}
}
/// Returns current backtrace. Only registered wasmtime functions will be listed.
pub fn get_backtrace() -> Backtrace {
let mut frames = Backtrace::new();
capture_stack(|pc| {
if let Some(_) = jit_function_registry::find(pc) {
frames.push(BacktraceFrame { pc });
}
!frames.full()
});
frames
}

View File

@@ -9,7 +9,7 @@ use crate::memory::LinearMemory;
use crate::mmap::Mmap;
use crate::signalhandlers::{wasmtime_init_eager, wasmtime_init_finish};
use crate::table::Table;
use crate::traphandlers::{wasmtime_call, TrapMessageAndStack};
use crate::traphandlers::{wasmtime_call, Trap};
use crate::vmcontext::{
VMBuiltinFunctionsArray, VMCallerCheckedAnyfunc, VMContext, VMFunctionBody, VMFunctionImport,
VMGlobalDefinition, VMGlobalImport, VMMemoryDefinition, VMMemoryImport, VMSharedSignatureIndex,
@@ -568,7 +568,7 @@ impl Instance {
// Make the call.
unsafe { wasmtime_call(callee_vmctx, callee_address) }
.map_err(|TrapMessageAndStack(msg, _)| InstantiationError::StartTrap(msg))
.map_err(InstantiationError::StartTrap)
}
/// Invoke the WebAssembly start function of the instance, if one is present.
@@ -1398,6 +1398,6 @@ pub enum InstantiationError {
Link(#[from] LinkError),
/// A compilation error occured.
#[error("Trap occurred while invoking start function: {0}")]
StartTrap(String),
#[error("Trap occurred while invoking start function")]
StartTrap(#[source] Trap),
}

View File

@@ -21,7 +21,6 @@
)
)]
mod backtrace;
mod export;
mod imports;
mod instance;
@@ -38,7 +37,6 @@ mod vmcontext;
pub mod jit_function_registry;
pub mod libcalls;
pub use crate::backtrace::{get_backtrace, Backtrace, BacktraceFrame};
pub use crate::export::Export;
pub use crate::imports::Imports;
pub use crate::instance::{InstanceHandle, InstantiationError, LinkError};
@@ -47,7 +45,7 @@ pub use crate::mmap::Mmap;
pub use crate::sig_registry::SignatureRegistry;
pub use crate::signalhandlers::{wasmtime_init_eager, wasmtime_init_finish};
pub use crate::trap_registry::{get_mut_trap_registry, get_trap_registry, TrapRegistrationGuard};
pub use crate::traphandlers::{wasmtime_call, wasmtime_call_trampoline, TrapMessageAndStack};
pub use crate::traphandlers::{wasmtime_call, wasmtime_call_trampoline, Trap};
pub use crate::vmcontext::{
VMCallerCheckedAnyfunc, VMContext, VMFunctionBody, VMFunctionImport, VMGlobalDefinition,
VMGlobalImport, VMInvokeArgument, VMMemoryDefinition, VMMemoryImport, VMSharedSignatureIndex,

View File

@@ -1,11 +1,12 @@
//! WebAssembly trap handling, which is built on top of the lower-level
//! signalhandling mechanisms.
use crate::backtrace::{get_backtrace, Backtrace};
use crate::trap_registry::get_trap_registry;
use crate::trap_registry::TrapDescription;
use crate::vmcontext::{VMContext, VMFunctionBody};
use backtrace::Backtrace;
use std::cell::Cell;
use std::fmt;
use std::ptr;
use wasmtime_environ::ir;
@@ -19,7 +20,7 @@ extern "C" {
}
thread_local! {
static RECORDED_TRAP: Cell<Option<(TrapDescription, Backtrace)>> = Cell::new(None);
static RECORDED_TRAP: Cell<Option<Trap>> = Cell::new(None);
static JMP_BUF: Cell<*const u8> = Cell::new(ptr::null());
static RESET_GUARD_PAGE: Cell<bool> = Cell::new(false);
}
@@ -44,26 +45,26 @@ pub extern "C" fn CheckIfTrapAtAddress(_pc: *const u8) -> i8 {
pub extern "C" fn RecordTrap(pc: *const u8, reset_guard_page: bool) {
// TODO: please see explanation in CheckIfTrapAtAddress.
let registry = get_trap_registry();
let trap_desc = registry
.get_trap(pc as usize)
.unwrap_or_else(|| TrapDescription {
source_loc: ir::SourceLoc::default(),
trap_code: ir::TrapCode::StackOverflow,
});
let trap_backtrace = get_backtrace();
let trap = Trap {
desc: registry
.get_trap(pc as usize)
.unwrap_or_else(|| TrapDescription {
source_loc: ir::SourceLoc::default(),
trap_code: ir::TrapCode::StackOverflow,
}),
backtrace: Backtrace::new_unresolved(),
};
if reset_guard_page {
RESET_GUARD_PAGE.with(|v| v.set(true));
}
RECORDED_TRAP.with(|data| {
assert_eq!(
data.get(),
None,
let prev = data.replace(Some(trap));
assert!(
prev.is_none(),
"Only one trap per thread can be recorded at a moment!"
);
data.set(Some((trap_desc, trap_backtrace)))
});
}
@@ -113,21 +114,31 @@ fn reset_guard_page() {}
/// Stores trace message with backtrace.
#[derive(Debug)]
pub struct TrapMessageAndStack(pub String, pub Backtrace);
pub struct Trap {
/// What sort of trap happened, as well as where in the original wasm module
/// it happened.
pub desc: TrapDescription,
/// Native stack backtrace at the time the trap occurred
pub backtrace: Backtrace,
}
fn trap_message_and_stack() -> TrapMessageAndStack {
let trap_desc = RECORDED_TRAP
.with(|data| data.replace(None))
.expect("trap_message must be called after trap occurred");
TrapMessageAndStack(
format!(
impl fmt::Display for Trap {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"wasm trap: {}, source location: {}",
trap_code_to_expected_string(trap_desc.0.trap_code),
trap_desc.0.source_loc,
),
trap_desc.1,
)
trap_code_to_expected_string(self.desc.trap_code),
self.desc.source_loc
)
}
}
impl std::error::Error for Trap {}
fn last_trap() -> Trap {
RECORDED_TRAP
.with(|data| data.replace(None))
.expect("trap_message must be called after trap occurred")
}
fn trap_code_to_expected_string(trap_code: ir::TrapCode) -> String {
@@ -156,9 +167,9 @@ pub unsafe extern "C" fn wasmtime_call_trampoline(
vmctx: *mut VMContext,
callee: *const VMFunctionBody,
values_vec: *mut u8,
) -> Result<(), TrapMessageAndStack> {
) -> Result<(), Trap> {
if WasmtimeCallTrampoline(vmctx as *mut u8, callee, values_vec) == 0 {
Err(trap_message_and_stack())
Err(last_trap())
} else {
Ok(())
}
@@ -170,9 +181,9 @@ pub unsafe extern "C" fn wasmtime_call_trampoline(
pub unsafe extern "C" fn wasmtime_call(
vmctx: *mut VMContext,
callee: *const VMFunctionBody,
) -> Result<(), TrapMessageAndStack> {
) -> Result<(), Trap> {
if WasmtimeCall(vmctx as *mut u8, callee) == 0 {
Err(trap_message_and_stack())
Err(last_trap())
} else {
Ok(())
}