Dumping stack through import.

This commit is contained in:
losfair
2019-06-12 13:38:58 +08:00
parent ddd0653a25
commit 00b6bf632a
9 changed files with 259 additions and 41 deletions

View File

@ -4,7 +4,7 @@ use crate::{
typed_func::Wasm,
types::{LocalFuncIndex, SigIndex},
vm,
state::FunctionStateMap,
state::ModuleStateMap,
};
use crate::{
@ -85,10 +85,9 @@ pub trait RunnableModule: Send + Sync {
local_func_index: LocalFuncIndex,
) -> Option<NonNull<vm::Func>>;
fn get_func_statemap(
fn get_module_state_map(
&self,
_local_func_index: LocalFuncIndex,
) -> Option<FunctionStateMap> { None }
) -> Option<ModuleStateMap> { None }
/// A wasm trampoline contains the necesarry data to dynamically call an exported wasm function.
/// Given a particular signature index, we are returned a trampoline that is matched with that

View File

@ -1,3 +1,6 @@
use std::collections::BTreeMap;
use std::ops::Bound::{Included, Unbounded};
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
pub struct RegisterIndex(pub usize);
@ -30,6 +33,26 @@ pub struct FunctionStateMap {
pub initial: MachineState,
pub shadow_size: usize, // for single-pass backend, 32 bytes on x86-64
pub diffs: Vec<MachineStateDiff>,
pub loop_offsets: BTreeMap<usize, usize>, /* offset -> diff_id */
pub call_offsets: BTreeMap<usize, usize>, /* offset -> diff_id */
}
#[derive(Clone, Debug)]
pub struct ModuleStateMap {
pub local_functions: BTreeMap<usize, FunctionStateMap>,
pub total_size: usize,
}
impl ModuleStateMap {
pub fn lookup_call_ip(&self, ip: usize, base: usize) -> Option<(&FunctionStateMap, MachineState)> {
if ip < base || ip - base >= self.total_size {
None
} else {
//println!("lookup ip: {} in {:?}", ip - base, self.local_functions);
let fsm = self.local_functions.range((Unbounded, Included(&(ip - base)))).last().map(|x| x.1).unwrap();
Some((fsm, fsm.call_offsets.get(&(ip - base)).map(|x| fsm.diffs[*x].build_state(fsm)).unwrap()))
}
}
}
impl FunctionStateMap {
@ -38,6 +61,8 @@ impl FunctionStateMap {
initial,
shadow_size,
diffs: vec![],
loop_offsets: BTreeMap::new(),
call_offsets: BTreeMap::new(),
}
}
}
@ -99,6 +124,34 @@ pub mod x64 {
}
}
pub fn read_stack(msm: &ModuleStateMap, code_base: usize, mut stack: *const u64) {
for i in 0.. {
unsafe {
let ret_addr = *stack;
stack = stack.offset(1);
let (fsm, state) = match msm.lookup_call_ip(ret_addr as usize, code_base) {
Some(x) => x,
_ => break
};
let mut found_shadow = false;
for v in &state.stack_values {
match *v {
MachineValue::ExplicitShadow => {
stack = stack.offset((fsm.shadow_size / 8) as isize);
found_shadow = true;
}
_ => {
stack = stack.offset(1);
}
}
}
assert_eq!(found_shadow, true);
stack = stack.offset(1); // RBP
println!("Frame #{}: {:p} {:?}", i, ret_addr as *const u8, state);
}
}
}
#[repr(u8)]
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum GPR {

View File

@ -8,6 +8,8 @@
use crate::loader::CodeMemory;
use std::{mem, slice};
use crate::vm::Ctx;
use std::fmt;
lazy_static! {
/// Reads the context pointer from `mm0`.
@ -98,6 +100,31 @@ impl TrampolineBufferBuilder {
idx
}
pub fn add_context_rsp_trampoline(
&mut self,
target: unsafe extern "C" fn (&mut Ctx, *const CallContext, *const u64),
context: *const CallContext,
) -> usize {
let idx = self.offsets.len();
self.offsets.push(self.code.len());
self.code.extend_from_slice(&[
0x48, 0xbe, // movabsq ?, %rsi
]);
self.code.extend_from_slice(value_to_bytes(&context));
self.code.extend_from_slice(&[
0x48, 0x89, 0xe2, // mov %rsp, %rdx
]);
self.code.extend_from_slice(&[
0x48, 0xb8, // movabsq ?, %rax
]);
self.code.extend_from_slice(value_to_bytes(&target));
self.code.extend_from_slice(&[
0xff, 0xe0, // jmpq *%rax
]);
idx
}
/// Adds a callinfo trampoline.
///
/// This generates a trampoline function that collects `num_params` parameters into an array
@ -196,6 +223,12 @@ impl TrampolineBuffer {
}
}
impl fmt::Debug for TrampolineBuffer {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "TrampolineBuffer {{}}")
}
}
#[cfg(test)]
mod tests {
use super::*;

View File

@ -364,30 +364,35 @@ macro_rules! impl_traits {
impl< $( $x: WasmExternType, )* Rets: WasmTypeList, Trap: TrapEarly<Rets>, FN: Fn( &mut Ctx $( ,$x )* ) -> Trap> ExternalFunction<($( $x ),*), Rets> for FN {
#[allow(non_snake_case)]
fn to_raw(&self) -> NonNull<vm::Func> {
assert_eq!(mem::size_of::<Self>(), 0, "you cannot use a closure that captures state for `Func`.");
if mem::size_of::<Self>() == 0 {
/// This is required for the llvm backend to be able to unwind through this function.
#[cfg_attr(nightly, unwind(allowed))]
extern fn wrap<$( $x: WasmExternType, )* Rets: WasmTypeList, Trap: TrapEarly<Rets>, FN: Fn( &mut Ctx $( ,$x )* ) -> Trap>( ctx: &mut Ctx $( ,$x: <$x as WasmExternType>::Native )* ) -> Rets::CStruct {
let f: FN = unsafe { mem::transmute_copy(&()) };
/// This is required for the llvm backend to be able to unwind through this function.
#[cfg_attr(nightly, unwind(allowed))]
extern fn wrap<$( $x: WasmExternType, )* Rets: WasmTypeList, Trap: TrapEarly<Rets>, FN: Fn( &mut Ctx $( ,$x )* ) -> Trap>( ctx: &mut Ctx $( ,$x: <$x as WasmExternType>::Native )* ) -> Rets::CStruct {
let f: FN = unsafe { mem::transmute_copy(&()) };
let err = match panic::catch_unwind(panic::AssertUnwindSafe(|| {
f( ctx $( ,WasmExternType::from_native($x) )* ).report()
})) {
Ok(Ok(returns)) => return returns.into_c_struct(),
Ok(Err(err)) => {
let b: Box<_> = err.into();
b as Box<dyn Any>
},
Err(err) => err,
};
let err = match panic::catch_unwind(panic::AssertUnwindSafe(|| {
f( ctx $( ,WasmExternType::from_native($x) )* ).report()
})) {
Ok(Ok(returns)) => return returns.into_c_struct(),
Ok(Err(err)) => {
let b: Box<_> = err.into();
b as Box<dyn Any>
},
Err(err) => err,
};
unsafe {
(&*ctx.module).runnable_module.do_early_trap(err)
unsafe {
(&*ctx.module).runnable_module.do_early_trap(err)
}
}
}
NonNull::new(wrap::<$( $x, )* Rets, Trap, Self> as *mut vm::Func).unwrap()
NonNull::new(wrap::<$( $x, )* Rets, Trap, Self> as *mut vm::Func).unwrap()
} else {
assert_eq!(mem::size_of::<Self>(), mem::size_of::<usize>(), "you cannot use a closure that captures state for `Func`.");
NonNull::new(unsafe {
::std::mem::transmute_copy::<_, *mut vm::Func>(self)
}).unwrap()
}
}
}