Add a wasmtime::Linker type (#1384)

* Add a `wasmtime::Linker` type

This commit adds a new type to the `wasmtime` crate, a `Linker`. This
linker is intended to vastly simplify calling `Instance::new` by easily
performing name resolution and incrementally defining state over time.
The goal here is to start down a path of making linking wasm modules in
`wasmtime` a first-class and ergonomic operation. This is highly likely
to evolve over time and get tweaked through releases as we iterate
towards a design well-suited for `wasmtime`, but this is intended to at
least be the initial foundation for such functionality.

This commit additionally also adds a C API for the linker and switches
the existing linking examples to using this linker in both Rust and C.

One piece of future work I'd like to tackle next is to integrate WASI
into the `wasmtime` crate in a more first-class manner. This [`Linker`]
type provides a great location to hook into the instantiation process to
easily instantiate modules with WASI imports. That's a relatively large
refactoring for now though and I figured it'd be best left for a
different time.

Closes #727
This commit is contained in:
Alex Crichton
2020-03-23 21:02:31 -05:00
committed by GitHub
parent 021ebb3748
commit 0d4bde4ab3
13 changed files with 630 additions and 110 deletions

View File

@@ -5,6 +5,7 @@
// TODO complete the C API
use anyhow::Result;
use std::cell::RefCell;
use std::panic::{self, AssertUnwindSafe};
use std::{mem, ptr, slice};
@@ -691,6 +692,15 @@ pub unsafe extern "C" fn wasm_instance_delete(instance: *mut wasm_instance_t) {
let _ = Box::from_raw(instance);
}
impl wasm_instance_t {
fn new(instance: Instance) -> wasm_instance_t {
wasm_instance_t {
instance: HostRef::new(instance),
exports_cache: RefCell::new(None),
}
}
}
#[no_mangle]
pub unsafe extern "C" fn wasm_instance_new(
store: *mut wasm_store_t,
@@ -722,12 +732,16 @@ pub unsafe extern "C" fn wasm_instance_new(
}
return ptr::null_mut();
}
match Instance::new(module, &externs) {
handle_instantiate(Instance::new(module, &externs), result)
}
unsafe fn handle_instantiate(
instance: Result<Instance>,
result: *mut *mut wasm_trap_t,
) -> *mut wasm_instance_t {
match instance {
Ok(instance) => {
let instance = Box::new(wasm_instance_t {
instance: HostRef::new(instance),
exports_cache: RefCell::new(None),
});
let instance = Box::new(wasm_instance_t::new(instance));
if !result.is_null() {
(*result) = ptr::null_mut();
}