Remove the Context type from wasmtime (#825)

* Remove the `Context` type from `wasmtime`

This hasn't really ended up being used in all that many places and the
dependencies on it were pretty minimal. This commit removes it in favor
of simplifying its various users a bit and/or leveraging the
`Engine`/`Store` structures where possible.

* Run rustfmt
This commit is contained in:
Alex Crichton
2020-01-15 16:54:57 -06:00
committed by GitHub
parent b4dccc0486
commit 0be3c2983c
6 changed files with 23 additions and 94 deletions

View File

@@ -141,8 +141,7 @@ impl WrappedCallable for WasmtimeFn {
// Get the trampoline to call for this function. // Get the trampoline to call for this function.
let exec_code_buf = self let exec_code_buf = self
.store .store
.context() .compiler_mut()
.compiler()
.get_published_trampoline(body, &signature, value_size) .get_published_trampoline(body, &signature, value_size)
.map_err(|e| Trap::new(format!("trampoline error: {:?}", e)))?; .map_err(|e| Trap::new(format!("trampoline error: {:?}", e)))?;

View File

@@ -1,53 +0,0 @@
use crate::Config;
use std::cell::{RefCell, RefMut};
use std::hash::{Hash, Hasher};
use std::rc::Rc;
use wasmtime_environ::settings;
use wasmtime_jit::{native, Compiler, Features};
#[derive(Clone)]
pub struct Context {
compiler: Rc<RefCell<Compiler>>,
features: Features,
debug_info: bool,
}
impl Context {
pub fn new(config: &Config) -> Context {
let isa = native::builder().finish(settings::Flags::new(config.flags.clone()));
Context::new_with_compiler(config, Compiler::new(isa, config.strategy))
}
pub fn new_with_compiler(config: &Config, compiler: Compiler) -> Context {
Context {
compiler: Rc::new(RefCell::new(compiler)),
features: config.features.clone(),
debug_info: config.debug_info,
}
}
pub(crate) fn debug_info(&self) -> bool {
self.debug_info
}
pub(crate) fn compiler(&self) -> RefMut<Compiler> {
self.compiler.borrow_mut()
}
}
impl Hash for Context {
fn hash<H>(&self, state: &mut H)
where
H: Hasher,
{
self.compiler.as_ptr().hash(state)
}
}
impl Eq for Context {}
impl PartialEq for Context {
fn eq(&self, other: &Context) -> bool {
Rc::ptr_eq(&self.compiler, &other.compiler)
}
}

View File

@@ -1,4 +1,3 @@
use crate::context::Context;
use crate::externals::Extern; use crate::externals::Extern;
use crate::module::Module; use crate::module::Module;
use crate::runtime::Store; use crate::runtime::Store;
@@ -6,9 +5,6 @@ use crate::trampoline::take_api_trap;
use crate::trap::Trap; use crate::trap::Trap;
use crate::types::{ExportType, ExternType}; use crate::types::{ExportType, ExternType};
use anyhow::{Error, Result}; use anyhow::{Error, Result};
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::rc::Rc;
use wasmtime_jit::{CompiledModule, Resolver}; use wasmtime_jit::{CompiledModule, Resolver};
use wasmtime_runtime::{Export, InstanceHandle, InstantiationError}; use wasmtime_runtime::{Export, InstanceHandle, InstantiationError};
@@ -29,19 +25,15 @@ fn instantiate_in_context(
data: &[u8], data: &[u8],
imports: &[Extern], imports: &[Extern],
module_name: Option<&str>, module_name: Option<&str>,
context: Context, ) -> Result<InstanceHandle> {
exports: Rc<RefCell<HashMap<String, Option<wasmtime_runtime::Export>>>>,
) -> Result<(InstanceHandle, HashSet<Context>), Error> {
let mut contexts = HashSet::new();
let debug_info = context.debug_info();
let mut resolver = SimpleResolver { imports }; let mut resolver = SimpleResolver { imports };
let mut compiled_module = CompiledModule::new( let mut compiled_module = CompiledModule::new(
&mut context.compiler(), &mut store.compiler_mut(),
data, data,
module_name, module_name,
&mut resolver, &mut resolver,
exports, store.global_exports().clone(),
debug_info, store.engine().config().debug_info,
)?; )?;
// Register all module signatures // Register all module signatures
@@ -58,34 +50,24 @@ fn instantiate_in_context(
e.into() e.into()
} }
})?; })?;
contexts.insert(context); Ok(instance)
Ok((instance, contexts))
} }
#[derive(Clone)] #[derive(Clone)]
pub struct Instance { pub struct Instance {
instance_handle: InstanceHandle, instance_handle: InstanceHandle,
module: Module, module: Module,
// We need to keep CodeMemory alive.
contexts: HashSet<Context>,
exports: Box<[Extern]>, exports: Box<[Extern]>,
} }
impl Instance { impl Instance {
pub fn new(module: &Module, externs: &[Extern]) -> Result<Instance, Error> { pub fn new(module: &Module, externs: &[Extern]) -> Result<Instance, Error> {
let store = module.store(); let store = module.store();
let context = store.context().clone(); let mut instance_handle = instantiate_in_context(
let exports = store.global_exports().clone(); store,
let (mut instance_handle, contexts) = instantiate_in_context(
module.store(),
module.binary().expect("binary"), module.binary().expect("binary"),
externs, externs,
module.name(), module.name(),
context,
exports,
)?; )?;
let exports = { let exports = {
@@ -104,7 +86,6 @@ impl Instance {
Ok(Instance { Ok(Instance {
instance_handle, instance_handle,
module: module.clone(), module: module.clone(),
contexts,
exports, exports,
}) })
} }
@@ -141,8 +122,6 @@ impl Instance {
} }
pub fn from_handle(store: &Store, instance_handle: InstanceHandle) -> Instance { pub fn from_handle(store: &Store, instance_handle: InstanceHandle) -> Instance {
let contexts = HashSet::new();
let mut exports = Vec::new(); let mut exports = Vec::new();
let mut exports_types = Vec::new(); let mut exports_types = Vec::new();
let mut mutable = instance_handle.clone(); let mut mutable = instance_handle.clone();
@@ -175,7 +154,6 @@ impl Instance {
Instance { Instance {
instance_handle, instance_handle,
module, module,
contexts,
exports: exports.into_boxed_slice(), exports: exports.into_boxed_slice(),
} }
} }

View File

@@ -7,7 +7,6 @@
//! itself for consumption from other languages. //! itself for consumption from other languages.
mod callable; mod callable;
mod context;
mod externals; mod externals;
mod instance; mod instance;
mod module; mod module;

View File

@@ -196,7 +196,7 @@ impl Module {
/// ///
/// [binary]: https://webassembly.github.io/spec/core/binary/index.html /// [binary]: https://webassembly.github.io/spec/core/binary/index.html
pub fn validate(store: &Store, binary: &[u8]) -> Result<()> { pub fn validate(store: &Store, binary: &[u8]) -> Result<()> {
let features = store.engine().config.features.clone(); let features = store.engine().config().features.clone();
let config = ValidatingParserConfig { let config = ValidatingParserConfig {
operator_config: OperatorValidatorConfig { operator_config: OperatorValidatorConfig {
enable_threads: features.threads, enable_threads: features.threads,

View File

@@ -1,4 +1,3 @@
use crate::context::Context;
use anyhow::Result; use anyhow::Result;
use std::cell::RefCell; use std::cell::RefCell;
use std::collections::HashMap; use std::collections::HashMap;
@@ -8,7 +7,7 @@ use wasmtime_environ::{
ir, ir,
settings::{self, Configurable}, settings::{self, Configurable},
}; };
use wasmtime_jit::{CompilationStrategy, Features}; use wasmtime_jit::{native, CompilationStrategy, Compiler, Features};
// Runtime Environment // Runtime Environment
@@ -297,7 +296,7 @@ pub enum OptLevel {
/// default settings. /// default settings.
#[derive(Default, Clone)] #[derive(Default, Clone)]
pub struct Engine { pub struct Engine {
pub(crate) config: Arc<Config>, config: Arc<Config>,
} }
impl Engine { impl Engine {
@@ -308,6 +307,11 @@ impl Engine {
config: Arc::new(config.clone()), config: Arc::new(config.clone()),
} }
} }
/// Returns the configuration settings that this engine is using.
pub fn config(&self) -> &Config {
&self.config
}
} }
// Store // Store
@@ -337,7 +341,7 @@ pub struct Store {
struct StoreInner { struct StoreInner {
engine: Engine, engine: Engine,
context: Context, compiler: RefCell<Compiler>,
global_exports: Rc<RefCell<HashMap<String, Option<wasmtime_runtime::Export>>>>, global_exports: Rc<RefCell<HashMap<String, Option<wasmtime_runtime::Export>>>>,
signature_cache: RefCell<HashMap<wasmtime_runtime::VMSharedSignatureIndex, ir::Signature>>, signature_cache: RefCell<HashMap<wasmtime_runtime::VMSharedSignatureIndex, ir::Signature>>,
} }
@@ -345,10 +349,12 @@ struct StoreInner {
impl Store { impl Store {
/// Creates a new store to be associated with the given [`Engine`]. /// Creates a new store to be associated with the given [`Engine`].
pub fn new(engine: &Engine) -> Store { pub fn new(engine: &Engine) -> Store {
let isa = native::builder().finish(settings::Flags::new(engine.config.flags.clone()));
let compiler = Compiler::new(isa, engine.config.strategy);
Store { Store {
inner: Rc::new(StoreInner { inner: Rc::new(StoreInner {
engine: engine.clone(), engine: engine.clone(),
context: Context::new(&engine.config), compiler: RefCell::new(compiler),
global_exports: Rc::new(RefCell::new(HashMap::new())), global_exports: Rc::new(RefCell::new(HashMap::new())),
signature_cache: RefCell::new(HashMap::new()), signature_cache: RefCell::new(HashMap::new()),
}), }),
@@ -360,8 +366,8 @@ impl Store {
&self.inner.engine &self.inner.engine
} }
pub(crate) fn context(&self) -> &Context { pub(crate) fn compiler_mut(&self) -> std::cell::RefMut<'_, Compiler> {
&self.inner.context self.inner.compiler.borrow_mut()
} }
// Specific to wasmtime: hack to pass memory around to wasi // Specific to wasmtime: hack to pass memory around to wasi
@@ -377,7 +383,7 @@ impl Store {
signature: &ir::Signature, signature: &ir::Signature,
) -> wasmtime_runtime::VMSharedSignatureIndex { ) -> wasmtime_runtime::VMSharedSignatureIndex {
use std::collections::hash_map::Entry; use std::collections::hash_map::Entry;
let index = self.context().compiler().signatures().register(signature); let index = self.compiler_mut().signatures().register(signature);
match self.inner.signature_cache.borrow_mut().entry(index) { match self.inner.signature_cache.borrow_mut().entry(index) {
Entry::Vacant(v) => { Entry::Vacant(v) => {
v.insert(signature.clone()); v.insert(signature.clone());