Rename Instance to InstanceHandle.

This commit is contained in:
Dan Gohman
2019-02-22 14:11:02 -08:00
parent 21abecb158
commit 5f201f6d73
13 changed files with 82 additions and 79 deletions

View File

@@ -7,7 +7,7 @@ use core::{fmt, mem, ptr, slice};
use cranelift_codegen::ir;
use std::string::String;
use std::vec::Vec;
use wasmtime_runtime::{wasmtime_call_trampoline, Export, Instance};
use wasmtime_runtime::{wasmtime_call_trampoline, Export, InstanceHandle};
/// A runtime value.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
@@ -125,10 +125,10 @@ pub enum ActionError {
Type(String),
}
/// Invoke a function in an `Instance` identified by an export name.
/// Invoke a function through an `InstanceHandle` identified by an export name.
pub fn invoke(
compiler: &mut Compiler,
instance: &mut Instance,
instance: &mut InstanceHandle,
function_name: &str,
args: &[RuntimeValue],
) -> Result<ActionOutcome, ActionError> {
@@ -220,7 +220,7 @@ pub fn invoke(
/// Returns a slice of the contents of allocated linear memory.
pub fn inspect_memory<'instance>(
instance: &'instance Instance,
instance: &'instance InstanceHandle,
memory_name: &str,
start: usize,
len: usize,
@@ -251,8 +251,8 @@ pub fn inspect_memory<'instance>(
})
}
/// Read a global in this `Instance` identified by an export name.
pub fn get(instance: &Instance, global_name: &str) -> Result<RuntimeValue, ActionError> {
/// Read a global in the given instance identified by an export name.
pub fn get(instance: &InstanceHandle, global_name: &str) -> Result<RuntimeValue, ActionError> {
let (definition, global) = match unsafe { instance.lookup_immutable(global_name) } {
Some(Export::Global {
definition,

View File

@@ -1,6 +1,6 @@
use crate::action::{get, inspect_memory, invoke};
use crate::{
instantiate, ActionError, ActionOutcome, Compiler, Instance, Namespace, RuntimeValue,
instantiate, ActionError, ActionOutcome, Compiler, InstanceHandle, Namespace, RuntimeValue,
SetupError,
};
use cranelift_codegen::isa::TargetIsa;
@@ -86,7 +86,7 @@ impl Context {
}
}
fn instantiate(&mut self, data: &[u8]) -> Result<Instance, SetupError> {
fn instantiate(&mut self, data: &[u8]) -> Result<InstanceHandle, SetupError> {
self.validate(&data).map_err(SetupError::Validate)?;
instantiate(
@@ -98,7 +98,10 @@ impl Context {
}
/// Return the instance associated with the given name.
pub fn get_instance(&mut self, instance_name: &str) -> Result<&mut Instance, UnknownInstance> {
pub fn get_instance(
&mut self,
instance_name: &str,
) -> Result<&mut InstanceHandle, UnknownInstance> {
self.namespace
.get_instance(instance_name)
.ok_or_else(|| UnknownInstance {
@@ -111,21 +114,21 @@ impl Context {
&mut self,
instance_name: Option<String>,
data: &[u8],
) -> Result<Instance, ActionError> {
) -> Result<InstanceHandle, ActionError> {
let instance = self.instantiate(data).map_err(ActionError::Setup)?;
self.optionally_name_instance(instance_name, instance.clone());
Ok(instance)
}
/// If `name` isn't None, register it for the given instance.
pub fn optionally_name_instance(&mut self, name: Option<String>, instance: Instance) {
pub fn optionally_name_instance(&mut self, name: Option<String>, instance: InstanceHandle) {
if let Some(name) = name {
self.namespace.name_instance(name, instance);
}
}
/// Register a name for the given instance.
pub fn name_instance(&mut self, name: String, instance: Instance) {
pub fn name_instance(&mut self, name: String, instance: InstanceHandle) {
self.namespace.name_instance(name, instance);
}
@@ -154,7 +157,7 @@ impl Context {
/// Invoke an exported function from an instance.
pub fn invoke(
&mut self,
instance: &mut Instance,
instance: &mut InstanceHandle,
field: &str,
args: &[RuntimeValue],
) -> Result<ActionOutcome, ActionError> {
@@ -175,7 +178,11 @@ impl Context {
}
/// Get the value of an exported global variable from an instance.
pub fn get(&mut self, instance: &Instance, field: &str) -> Result<ActionOutcome, ActionError> {
pub fn get(
&mut self,
instance: &InstanceHandle,
field: &str,
) -> Result<ActionOutcome, ActionError> {
get(instance, field).map(|value| ActionOutcome::Returned {
values: vec![value],
})
@@ -184,7 +191,7 @@ impl Context {
/// Get a slice of memory from an instance.
pub fn inspect_memory<'instance>(
&self,
instance: &'instance Instance,
instance: &'instance InstanceHandle,
field_name: &str,
start: usize,
len: usize,

View File

@@ -18,7 +18,7 @@ use wasmtime_environ::{
CompileError, DataInitializer, DataInitializerLocation, Module, ModuleEnvironment,
};
use wasmtime_runtime::{
Export, Imports, Instance, InstantiationError, VMFunctionBody, VMSharedSignatureIndex,
Export, Imports, InstanceHandle, InstantiationError, VMFunctionBody, VMSharedSignatureIndex,
};
/// An error condition while setting up a wasm instance, be it validation,
@@ -160,12 +160,12 @@ impl CompiledModule {
}
}
/// Crate an `Instance` from this `CompiledModule`.
/// Crate an `InstanceContents` from this `CompiledModule`.
///
/// Note that if only one instance of this module is needed, it may be more
/// efficient to call the top-level `instantiate`, since that avoids copying
/// the data initializers.
pub fn instantiate(&mut self) -> Result<Instance, InstantiationError> {
pub fn instantiate(&mut self) -> Result<InstanceHandle, InstantiationError> {
let data_initializers = self
.data_initializers
.iter()
@@ -174,7 +174,7 @@ impl CompiledModule {
data: &*init.data,
})
.collect::<Vec<_>>();
Instance::new(
InstanceHandle::new(
Rc::clone(&self.module),
Rc::clone(&self.global_exports),
self.finished_functions.clone(),
@@ -205,7 +205,7 @@ impl OwnedDataInitializer {
}
}
/// Create a new `Instance` by compiling the wasm module in `data` and instatiating it.
/// Create a new wasm instance by compiling the wasm module in `data` and instatiating it.
///
/// This is equivalent to createing a `CompiledModule` and calling `instantiate()` on it,
/// but avoids creating an intermediate copy of the data initializers.
@@ -214,10 +214,10 @@ pub fn instantiate(
data: &[u8],
resolver: &mut dyn Resolver,
global_exports: Rc<RefCell<HashMap<String, Option<Export>>>>,
) -> Result<Instance, SetupError> {
) -> Result<InstanceHandle, SetupError> {
let raw = RawCompiledModule::new(compiler, data, resolver)?;
Instance::new(
InstanceHandle::new(
Rc::new(raw.module),
global_exports,
raw.finished_functions,

View File

@@ -36,8 +36,6 @@ use hashbrown::{hash_map, HashMap};
#[cfg(feature = "std")]
use std::collections::{hash_map, HashMap};
#[macro_use]
extern crate cranelift_entity;
#[macro_use]
extern crate failure_derive;
@@ -60,9 +58,9 @@ pub use crate::namespace::Namespace;
pub use crate::resolver::{NullResolver, Resolver};
pub use crate::target_tunables::target_tunables;
// Re-export `Instance` so that users won't need to separately depend on
// Re-export `InstanceHandle` so that users won't need to separately depend on
// wasmtime-runtime in common cases.
pub use wasmtime_runtime::{Instance, InstantiationError};
pub use wasmtime_runtime::{InstanceHandle, InstantiationError};
/// Version number of this crate.
pub const VERSION: &str = env!("CARGO_PKG_VERSION");

View File

@@ -12,7 +12,7 @@ use wasmtime_environ::{
};
use wasmtime_runtime::libcalls;
use wasmtime_runtime::{
Export, Imports, Instance, LinkError, VMFunctionBody, VMFunctionImport, VMGlobalImport,
Export, Imports, InstanceHandle, LinkError, VMFunctionBody, VMFunctionImport, VMGlobalImport,
VMMemoryImport, VMTableImport,
};
@@ -44,7 +44,7 @@ pub fn link_module(
signature, import_signature)
));
}
dependencies.insert(Instance::from_vmctx(vmctx));
dependencies.insert(InstanceHandle::from_vmctx(vmctx));
function_imports.push(VMFunctionImport {
body: address,
vmctx,
@@ -82,7 +82,7 @@ pub fn link_module(
module_name, field,
)));
}
dependencies.insert(Instance::from_vmctx(vmctx));
dependencies.insert(InstanceHandle::from_vmctx(vmctx));
table_imports.push(VMTableImport {
from: definition,
vmctx,
@@ -136,7 +136,7 @@ pub fn link_module(
}
assert!(memory.offset_guard_size >= import_memory.offset_guard_size);
dependencies.insert(Instance::from_vmctx(vmctx));
dependencies.insert(InstanceHandle::from_vmctx(vmctx));
memory_imports.push(VMMemoryImport {
from: definition,
vmctx,
@@ -180,7 +180,7 @@ pub fn link_module(
module_name, field
)));
}
dependencies.insert(Instance::from_vmctx(vmctx));
dependencies.insert(InstanceHandle::from_vmctx(vmctx));
global_imports.push(VMGlobalImport { from: definition });
}
},

View File

@@ -5,7 +5,7 @@
use super::HashMap;
use crate::resolver::Resolver;
use std::string::String;
use wasmtime_runtime::{Export, Instance};
use wasmtime_runtime::{Export, InstanceHandle};
/// A namespace containing instances keyed by name.
///
@@ -13,7 +13,7 @@ use wasmtime_runtime::{Export, Instance};
/// imports using defined exports.
pub struct Namespace {
/// Mapping from identifiers to indices in `self.instances`.
names: HashMap<String, Instance>,
names: HashMap<String, InstanceHandle>,
}
impl Namespace {
@@ -24,14 +24,14 @@ impl Namespace {
}
}
/// Install a new `Instance` in this `Namespace`, optionally with the
/// given name, and return its index.
pub fn name_instance(&mut self, name: String, instance: Instance) {
/// Install a new `InstanceHandle` in this `Namespace`, optionally with the
/// given name.
pub fn name_instance(&mut self, name: String, instance: InstanceHandle) {
self.names.insert(name, instance);
}
/// Get the instance index registered with the given `instance_name`.
pub fn get_instance(&mut self, name: &str) -> Option<&mut Instance> {
/// Get the instance registered with the given `instance_name`.
pub fn get_instance(&mut self, name: &str) -> Option<&mut InstanceHandle> {
self.names.get_mut(name)
}
}

View File

@@ -1,4 +1,4 @@
use crate::instance::Instance;
use crate::instance::InstanceHandle;
use crate::vmcontext::{VMFunctionImport, VMGlobalImport, VMMemoryImport, VMTableImport};
use cranelift_entity::{BoxedSlice, PrimaryMap};
use cranelift_wasm::{FuncIndex, GlobalIndex, MemoryIndex, TableIndex};
@@ -8,7 +8,7 @@ use std::collections::HashSet;
#[derive(Clone)]
pub struct Imports {
/// The set of instances that the imports depend on.
pub dependencies: HashSet<Instance>,
pub dependencies: HashSet<InstanceHandle>,
/// Resolved addresses for imported functions.
pub functions: BoxedSlice<FuncIndex, VMFunctionImport>,
@@ -26,7 +26,7 @@ pub struct Imports {
impl Imports {
/// Construct a new `Imports` instance.
pub fn new(
dependencies: HashSet<Instance>,
dependencies: HashSet<InstanceHandle>,
function_imports: PrimaryMap<FuncIndex, VMFunctionImport>,
table_imports: PrimaryMap<TableIndex, VMTableImport>,
memory_imports: PrimaryMap<MemoryIndex, VMMemoryImport>,

View File

@@ -1,5 +1,6 @@
//! An `Instance` contains all the runtime state used by execution of a wasm
//! module.
//! An `InstanceContents` contains all the runtime state used by execution
//! of a wasm module. An `InstanceHandle` is a reference-counting handle
//! for an `InstanceContents`.
use crate::export::Export;
use crate::imports::Imports;
@@ -177,25 +178,23 @@ fn global_mut<'vmctx>(
/// The actual contents of an instance.
///
/// `Instance` is just a handle containing a pointer to an `InstanceContents`,
/// which is specially allocated.
/// `InstanceContents` instances are specially allocated.
///
/// This is repr(C) to ensure that the vmctx field is last.
/// FIXME: Should this be pub(crate)?
#[repr(C)]
pub struct InstanceContents {
pub(crate) struct InstanceContents {
/// The number of references to this `InstanceContents`.
refcount: usize,
/// Instances from which this `InstanceContents` imports. These won't
/// create reference cycles because wasm instances can't cyclically
/// import from each other.
dependencies: HashSet<Instance>,
dependencies: HashSet<InstanceHandle>,
/// The allocated contents.
mmap: Mmap,
/// The `Module` this `Instance` was instantiated from.
/// The `Module` this `InstanceContents` was instantiated from.
module: Rc<Module>,
/// Offsets in the `vmctx` region.
@@ -497,7 +496,7 @@ impl InstanceContents {
}
}
/// Return the offset from the vmctx pointer to its containing Instance.
/// Return the offset from the vmctx pointer to its containing InstanceContents.
pub(crate) fn vmctx_offset() -> isize {
offset_of!(Self, vmctx) as isize
}
@@ -611,17 +610,14 @@ impl InstanceContents {
}
}
/// An Instance of a WebAssembly module.
///
/// Note that compiled wasm code passes around raw pointers to `Instance`, so
/// this shouldn't be moved.
/// A handle holding an `InstanceContents` of a WebAssembly module.
#[derive(Hash, PartialEq, Eq)]
pub struct Instance {
pub struct InstanceHandle {
instance: *mut InstanceContents,
}
impl Instance {
/// Create a new `Instance`.
impl InstanceHandle {
/// Create a new `InstanceHandle` pointing at a new `InstanceContents`.
pub fn new(
module: Rc<Module>,
global_exports: Rc<RefCell<HashMap<String, Option<Export>>>>,
@@ -753,7 +749,7 @@ impl Instance {
}
// Ensure that our signal handlers are ready for action.
// TODO: Move these calls out of `Instance`.
// TODO: Move these calls out of `InstanceHandle`.
wasmtime_init_eager();
wasmtime_init_finish(contents.vmctx_mut());
@@ -834,28 +830,28 @@ impl Instance {
}
}
impl Instance {
impl InstanceHandle {
/// Return the contained contents.
pub fn contents(&self) -> &InstanceContents {
fn contents(&self) -> &InstanceContents {
unsafe { &*(self.instance as *const InstanceContents) }
}
/// Return the contained contents.
pub fn contents_mut(&mut self) -> &mut InstanceContents {
fn contents_mut(&mut self) -> &mut InstanceContents {
unsafe { &mut *(self.instance as *mut InstanceContents) }
}
}
impl Clone for Instance {
impl Clone for InstanceHandle {
fn clone(&self) -> Self {
unsafe { &mut *(self.instance as *mut InstanceContents) }.refcount += 1;
Instance {
InstanceHandle {
instance: self.instance,
}
}
}
impl Drop for Instance {
impl Drop for InstanceHandle {
fn drop(&mut self) {
let contents = self.contents_mut();
contents.refcount -= 1;

View File

@@ -46,7 +46,7 @@ pub mod libcalls;
pub use crate::export::Export;
pub use crate::imports::Imports;
pub use crate::instance::{Instance, InstanceContents, InstantiationError, LinkError};
pub use crate::instance::{InstanceHandle, InstantiationError, LinkError};
pub use crate::mmap::Mmap;
pub use crate::sig_registry::SignatureRegistry;
pub use crate::signalhandlers::{wasmtime_init_eager, wasmtime_init_finish};

View File

@@ -478,21 +478,20 @@ impl Default for VMCallerCheckedAnyfunc {
pub struct VMContext {}
impl VMContext {
/// Return a mutable reference to the associated `Instance`.
/// Return a mutable reference to the associated `InstanceContents`.
///
/// This is unsafe because it doesn't work on just any `VMContext`, it must
/// be a `VMContext` allocated as part of an `Instance`.
/// FIXME: make this pub(crate)?
/// be a `VMContext` allocated as part of an `InstanceContents`.
#[allow(clippy::cast_ptr_alignment)]
pub unsafe fn instance_contents(&mut self) -> &mut InstanceContents {
pub(crate) unsafe fn instance_contents(&mut self) -> &mut InstanceContents {
&mut *((self as *mut Self as *mut u8).offset(-InstanceContents::vmctx_offset())
as *mut InstanceContents)
}
/// Return a mutable reference to the host state associated with `Instance`.
/// Return a mutable reference to the host state associated with `InstanceContents`.
///
/// This is unsafe because it doesn't work on just any `VMContext`, it must
/// be a `VMContext` allocated as part of an `Instance`.
/// be a `VMContext` allocated as part of an `InstanceContents`.
pub unsafe fn host_state(&mut self) -> &mut Any {
self.instance_contents().host_state()
}

View File

@@ -8,7 +8,7 @@ use std::rc::Rc;
use target_lexicon::HOST;
use wasmtime_environ::{translate_signature, Export, MemoryPlan, Module, TablePlan};
use wasmtime_jit::target_tunables;
use wasmtime_runtime::{Imports, Instance, InstantiationError, VMContext, VMFunctionBody};
use wasmtime_runtime::{Imports, InstanceHandle, InstantiationError, VMContext, VMFunctionBody};
extern "C" fn spectest_print() {}
@@ -46,7 +46,7 @@ extern "C" fn spectest_print_f64_f64(_vmctx: &mut VMContext, x: f64, y: f64) {
/// Return an instance implementing the "spectest" interface used in the
/// spec testsuite.
pub fn instantiate_spectest() -> Result<Instance, InstantiationError> {
pub fn instantiate_spectest() -> Result<InstanceHandle, InstantiationError> {
let call_conv = isa::CallConv::triple_default(&HOST);
let pointer_type = types::Type::triple_pointer_type(&HOST);
let mut module = Module::new();
@@ -216,7 +216,7 @@ pub fn instantiate_spectest() -> Result<Instance, InstantiationError> {
let data_initializers = Vec::new();
let signatures = PrimaryMap::new();
Instance::new(
InstanceHandle::new(
Rc::new(module),
Rc::new(RefCell::new(HashMap::new())),
finished_functions.into_boxed_slice(),

View File

@@ -4,8 +4,8 @@ use std::path::Path;
use std::{fmt, fs, io, str};
use wabt::script::{Action, Command, CommandKind, ModuleBinary, ScriptParser, Value};
use wasmtime_jit::{
ActionError, ActionOutcome, Compiler, Context, Instance, InstantiationError, RuntimeValue,
UnknownInstance,
ActionError, ActionOutcome, Compiler, Context, InstanceHandle, InstantiationError,
RuntimeValue, UnknownInstance,
};
/// Translate from a `script::Value` to a `RuntimeValue`.
@@ -71,7 +71,7 @@ pub struct WastFileError {
pub struct WastContext {
/// Wast files have a concept of a "current" module, which is the most
/// recently defined.
current: Option<Instance>,
current: Option<InstanceHandle>,
context: Context,
}
@@ -85,7 +85,10 @@ impl WastContext {
}
}
fn get_instance(&mut self, instance_name: Option<&str>) -> Result<&mut Instance, WastError> {
fn get_instance(
&mut self,
instance_name: Option<&str>,
) -> Result<&mut InstanceHandle, WastError> {
let instance = if let Some(instance_name) = instance_name {
self.context
.get_instance(instance_name)

View File

@@ -154,7 +154,7 @@ fn handle_module(context: &mut Context, args: &Args, path: &Path) -> Result<(),
// Read the wasm module binary.
let data = read_wasm(path.to_path_buf())?;
// Create a new `Instance` by compiling and instantiating a wasm module.
// Compile and instantiating a wasm module.
let mut instance = context
.instantiate_module(None, &data)
.map_err(|e| e.to_string())?;