Finished middleware impl and made a CallTrace middleware

This commit is contained in:
losfair
2019-04-27 16:31:47 +08:00
parent eca8ccdbd4
commit 2262c8a6da
11 changed files with 266 additions and 109 deletions

View File

@ -1,30 +1,33 @@
use crate::{
backend::RunnableModule,
structures::Map,
types::{FuncIndex, FuncSig, SigIndex},
backend::{sys::Memory, Backend, CacheGen, Compiler, CompilerConfig, Token},
cache::{Artifact, Error as CacheError},
error::{CompileError, CompileResult},
module::{ModuleInfo, ModuleInner},
parse::LoadError,
structures::Map,
types::{FuncIndex, FuncSig, SigIndex},
};
use wasmparser::{Operator, Type as WpType};
use std::fmt::Debug;
use smallvec::SmallVec;
use std::fmt::Debug;
use std::marker::PhantomData;
use wasmparser::{Operator, Type as WpType};
pub enum Event<'a, 'b> {
Internal(InternalEvent),
Wasm(&'b Operator<'a>),
}
#[derive(Copy, Clone, Debug)]
pub enum InternalEvent {
FunctionBegin,
FunctionBegin(u32),
FunctionEnd,
Trace,
Bkpt(Box<Fn(BkptInfo) + Send + Sync + 'static>),
SetInternal(u32),
GetInternal(u32),
}
pub struct BkptInfo {}
pub trait ModuleCodeGenerator<FCG: FunctionCodeGenerator<E>, RM: RunnableModule, E: Debug> {
fn new() -> Self;
fn backend_id() -> Backend;
@ -36,10 +39,7 @@ pub trait ModuleCodeGenerator<FCG: FunctionCodeGenerator<E>, RM: RunnableModule,
fn feed_signatures(&mut self, signatures: Map<SigIndex, FuncSig>) -> Result<(), E>;
/// Sets function signatures.
fn feed_function_signatures(
&mut self,
assoc: Map<FuncIndex, SigIndex>,
) -> Result<(), E>;
fn feed_function_signatures(&mut self, assoc: Map<FuncIndex, SigIndex>) -> Result<(), E>;
/// Adds an import function.
fn feed_import_function(&mut self) -> Result<(), E>;
@ -72,23 +72,25 @@ pub struct SimpleStreamingCompilerGen<
}
impl<
MCG: ModuleCodeGenerator<FCG, RM, E>,
FCG: FunctionCodeGenerator<E>,
RM: RunnableModule + 'static,
E: Debug,
> SimpleStreamingCompilerGen<MCG, FCG, RM, E> {
MCG: ModuleCodeGenerator<FCG, RM, E>,
FCG: FunctionCodeGenerator<E>,
RM: RunnableModule + 'static,
E: Debug,
> SimpleStreamingCompilerGen<MCG, FCG, RM, E>
{
pub fn new() -> StreamingCompiler<MCG, FCG, RM, E, impl Fn() -> MiddlewareChain> {
StreamingCompiler::new(|| MiddlewareChain::new())
}
}
impl<
MCG: ModuleCodeGenerator<FCG, RM, E>,
FCG: FunctionCodeGenerator<E>,
RM: RunnableModule + 'static,
E: Debug,
CGEN: Fn() -> MiddlewareChain,
> StreamingCompiler<MCG, FCG, RM, E, CGEN> {
MCG: ModuleCodeGenerator<FCG, RM, E>,
FCG: FunctionCodeGenerator<E>,
RM: RunnableModule + 'static,
E: Debug,
CGEN: Fn() -> MiddlewareChain,
> StreamingCompiler<MCG, FCG, RM, E, CGEN>
{
pub fn new(chain_gen: CGEN) -> Self {
Self {
middleware_chain_generator: chain_gen,
@ -101,12 +103,13 @@ impl<
}
impl<
MCG: ModuleCodeGenerator<FCG, RM, E>,
FCG: FunctionCodeGenerator<E>,
RM: RunnableModule + 'static,
E: Debug,
CGEN: Fn() -> MiddlewareChain,
>Compiler for StreamingCompiler<MCG, FCG, RM, E, CGEN> {
MCG: ModuleCodeGenerator<FCG, RM, E>,
FCG: FunctionCodeGenerator<E>,
RM: RunnableModule + 'static,
E: Debug,
CGEN: Fn() -> MiddlewareChain,
> Compiler for StreamingCompiler<MCG, FCG, RM, E, CGEN>
{
fn compile(
&self,
wasm: &[u8],
@ -124,10 +127,18 @@ impl<
let mut mcg = MCG::new();
let mut chain = (self.middleware_chain_generator)();
let info = crate::parse::read_module(wasm, MCG::backend_id(), &mut mcg, &mut chain, &compiler_config)?;
let exec_context = mcg.finalize(&info).map_err(|x| CompileError::InternalError {
msg: format!("{:?}", x),
})?;
let info = crate::parse::read_module(
wasm,
MCG::backend_id(),
&mut mcg,
&mut chain,
&compiler_config,
)?;
let exec_context = mcg
.finalize(&info)
.map_err(|x| CompileError::InternalError {
msg: format!("{:?}", x),
})?;
Ok(ModuleInner {
cache_gen: Box::new(Placeholder),
runnable_module: Box::new(exec_context),
@ -143,7 +154,7 @@ impl<
}
pub struct EventSink<'a, 'b> {
buffer: SmallVec<[Event<'a, 'b>; 2]>
buffer: SmallVec<[Event<'a, 'b>; 2]>,
}
impl<'a, 'b> EventSink<'a, 'b> {
@ -158,16 +169,19 @@ pub struct MiddlewareChain {
impl MiddlewareChain {
pub fn new() -> MiddlewareChain {
MiddlewareChain {
chain: vec! [],
}
MiddlewareChain { chain: vec![] }
}
pub fn push<M: FunctionMiddleware + 'static>(&mut self, m: M) {
self.chain.push(Box::new(m));
}
pub(crate) fn run<E: Debug, FCG: FunctionCodeGenerator<E>>(&mut self, fcg: Option<&mut FCG>, ev: Event, module_info: &ModuleInfo) -> Result<(), String> {
pub(crate) fn run<E: Debug, FCG: FunctionCodeGenerator<E>>(
&mut self,
fcg: Option<&mut FCG>,
ev: Event,
module_info: &ModuleInfo,
) -> Result<(), String> {
let mut sink = EventSink {
buffer: SmallVec::new(),
};
@ -180,7 +194,8 @@ impl MiddlewareChain {
}
if let Some(fcg) = fcg {
for ev in sink.buffer {
fcg.feed_event(ev, module_info).map_err(|x| format!("{:?}", x))?;
fcg.feed_event(ev, module_info)
.map_err(|x| format!("{:?}", x))?;
}
}
@ -190,31 +205,32 @@ impl MiddlewareChain {
pub trait FunctionMiddleware {
type Error: Debug;
fn feed_event(
fn feed_event<'a, 'b: 'a>(
&mut self,
op: Event,
op: Event<'a, 'b>,
module_info: &ModuleInfo,
sink: &mut EventSink,
sink: &mut EventSink<'a, 'b>,
) -> Result<(), Self::Error>;
}
pub(crate) trait GenericFunctionMiddleware {
fn feed_event(
fn feed_event<'a, 'b: 'a>(
&mut self,
op: Event,
op: Event<'a, 'b>,
module_info: &ModuleInfo,
sink: &mut EventSink,
sink: &mut EventSink<'a, 'b>,
) -> Result<(), String>;
}
impl<E: Debug, T: FunctionMiddleware<Error = E>> GenericFunctionMiddleware for T {
fn feed_event(
fn feed_event<'a, 'b: 'a>(
&mut self,
op: Event,
op: Event<'a, 'b>,
module_info: &ModuleInfo,
sink: &mut EventSink,
sink: &mut EventSink<'a, 'b>,
) -> Result<(), String> {
<Self as FunctionMiddleware>::feed_event(self, op, module_info, sink).map_err(|x| format!("{:?}", x))
<Self as FunctionMiddleware>::feed_event(self, op, module_info, sink)
.map_err(|x| format!("{:?}", x))
}
}

View File

@ -14,6 +14,7 @@ pub mod backend;
mod backing;
pub mod cache;
pub mod codegen;
pub mod error;
pub mod export;
pub mod global;
@ -21,6 +22,7 @@ pub mod import;
pub mod instance;
pub mod memory;
pub mod module;
pub mod parse;
mod sig_registry;
pub mod structures;
mod sys;
@ -31,8 +33,6 @@ pub mod units;
pub mod vm;
#[doc(hidden)]
pub mod vmcalls;
pub mod codegen;
pub mod parse;
use self::error::CompileResult;
#[doc(inline)]

View File

@ -1,7 +1,7 @@
use crate::codegen::*;
use hashbrown::HashMap;
use crate::{
backend::{Backend, CompilerConfig, RunnableModule},
error::CompileError,
module::{
DataInitializer, ExportIndex, ImportName, ModuleInfo, StringTable, StringTableBuilder,
TableInitializer,
@ -13,14 +13,14 @@ use crate::{
TableIndex, Type, Value,
},
units::Pages,
error::CompileError,
};
use hashbrown::HashMap;
use std::fmt::Debug;
use wasmparser::{
BinaryReaderError, Data, DataKind, Element, ElementKind, Export, ExternalKind, FuncType,
Import, ImportSectionEntryType, InitExpr, ModuleReader, Operator, SectionCode, Type as WpType,
WasmDecoder,
};
use std::fmt::Debug;
#[derive(Debug)]
pub enum LoadError {
@ -122,7 +122,8 @@ pub fn read_module<
let sigindex = SigIndex::new(sigindex as usize);
info.imported_functions.push(import_name);
info.func_assoc.push(sigindex);
mcg.feed_import_function().map_err(|x| LoadError::Codegen(format!("{:?}", x)))?;
mcg.feed_import_function()
.map_err(|x| LoadError::Codegen(format!("{:?}", x)))?;
}
ImportSectionEntryType::Table(table_ty) => {
assert_eq!(table_ty.element_type, WpType::AnyFunc);
@ -192,13 +193,24 @@ pub fn read_module<
if func_count == 0 {
info.namespace_table = namespace_builder.take().unwrap().finish();
info.name_table = name_builder.take().unwrap().finish();
mcg.feed_signatures(info.signatures.clone()).map_err(|x| LoadError::Codegen(format!("{:?}", x)))?;
mcg.feed_function_signatures(info.func_assoc.clone()).map_err(|x| LoadError::Codegen(format!("{:?}", x)))?;
mcg.check_precondition(&info).map_err(|x| LoadError::Codegen(format!("{:?}", x)))?;
mcg.feed_signatures(info.signatures.clone())
.map_err(|x| LoadError::Codegen(format!("{:?}", x)))?;
mcg.feed_function_signatures(info.func_assoc.clone())
.map_err(|x| LoadError::Codegen(format!("{:?}", x)))?;
mcg.check_precondition(&info)
.map_err(|x| LoadError::Codegen(format!("{:?}", x)))?;
}
let fcg = mcg.next_function().map_err(|x| LoadError::Codegen(format!("{:?}", x)))?;
middlewares.run(Some(fcg), Event::Internal(InternalEvent::FunctionBegin), &info).map_err(|x| LoadError::Codegen(x))?;
let fcg = mcg
.next_function()
.map_err(|x| LoadError::Codegen(format!("{:?}", x)))?;
middlewares
.run(
Some(fcg),
Event::Internal(InternalEvent::FunctionBegin(id as u32)),
&info,
)
.map_err(|x| LoadError::Codegen(x))?;
let sig = info
.signatures
@ -210,10 +222,12 @@ pub fn read_module<
)
.unwrap();
for ret in sig.returns() {
fcg.feed_return(type_to_wp_type(*ret)).map_err(|x| LoadError::Codegen(format!("{:?}", x)))?;
fcg.feed_return(type_to_wp_type(*ret))
.map_err(|x| LoadError::Codegen(format!("{:?}", x)))?;
}
for param in sig.params() {
fcg.feed_param(type_to_wp_type(*param)).map_err(|x| LoadError::Codegen(format!("{:?}", x)))?;
fcg.feed_param(type_to_wp_type(*param))
.map_err(|x| LoadError::Codegen(format!("{:?}", x)))?;
}
let mut body_begun = false;
@ -224,22 +238,33 @@ pub fn read_module<
ParserState::Error(err) => return Err(LoadError::Parse(err)),
ParserState::FunctionBodyLocals { ref locals } => {
for &(count, ty) in locals.iter() {
fcg.feed_local(ty, count as usize).map_err(|x| LoadError::Codegen(format!("{:?}", x)))?;
fcg.feed_local(ty, count as usize)
.map_err(|x| LoadError::Codegen(format!("{:?}", x)))?;
}
}
ParserState::CodeOperator(ref op) => {
if !body_begun {
body_begun = true;
fcg.begin_body().map_err(|x| LoadError::Codegen(format!("{:?}", x)))?;
fcg.begin_body()
.map_err(|x| LoadError::Codegen(format!("{:?}", x)))?;
}
middlewares.run(Some(fcg), Event::Wasm(op), &info).map_err(|x| LoadError::Codegen(x))?;
middlewares
.run(Some(fcg), Event::Wasm(op), &info)
.map_err(|x| LoadError::Codegen(x))?;
}
ParserState::EndFunctionBody => break,
_ => unreachable!(),
}
}
middlewares.run(Some(fcg), Event::Internal(InternalEvent::FunctionEnd), &info).map_err(|x| LoadError::Codegen(x))?;
fcg.finalize().map_err(|x| LoadError::Codegen(format!("{:?}", x)))?;
middlewares
.run(
Some(fcg),
Event::Internal(InternalEvent::FunctionEnd),
&info,
)
.map_err(|x| LoadError::Codegen(x))?;
fcg.finalize()
.map_err(|x| LoadError::Codegen(format!("{:?}", x)))?;
}
ParserState::BeginActiveElementSectionEntry(table_index) => {
let table_index = TableIndex::new(table_index as usize);

View File

@ -22,7 +22,7 @@ pub struct Ctx {
local_backing: *mut LocalBacking,
import_backing: *mut ImportBacking,
pub(crate) module: *const ModuleInner,
pub module: *const ModuleInner,
pub data: *mut c_void,
pub data_finalizer: Option<fn(data: *mut c_void)>,