Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reactor support. #1565

Merged
merged 18 commits into from
May 26, 2020
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions RELEASES.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,17 @@ Unreleased

### Added

* The [Commands and Reactors ABI] is now supported in the Rust API. `Linker::module`
loads a module and automatically handles Commands and Reactors semantics.

[Commands and Reactors ABI]: https://github.com/WebAssembly/WASI/blob/master/design/application-abi.md#current-unstable-abi

### Changed
sunfishcode marked this conversation as resolved.
Show resolved Hide resolved

* The wasm start function call is now separated out from `Instance::new`. `Instance::new`
now returns a `NewInstance`, call `.start` to run the wasm start function and return
the initialized `Instance`.

### Fixed

--------------------------------------------------------------------------------
Expand Down
12 changes: 12 additions & 0 deletions crates/c-api/include/wasmtime.h
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,18 @@ WASM_API_EXTERN own wasmtime_error_t* wasmtime_linker_instantiate(
own wasm_trap_t **trap
);

WASM_API_EXTERN own wasmtime_error_t* wasmtime_linker_module(
const wasmtime_linker_t *linker,
const wasm_name_t *name,
const wasm_module_t *module
);

WASM_API_EXTERN own wasmtime_error_t* wasmtime_linker_get_default(
const wasmtime_linker_t *linker,
const wasm_name_t *name,
own wasm_func_t **func
);

///////////////////////////////////////////////////////////////////////////////
//
// wasmtime_caller_t extension, binding the `Caller` type in the Rust API
Expand Down
7 changes: 5 additions & 2 deletions crates/c-api/src/instance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use crate::{wasm_store_t, wasmtime_error_t, ExternHost};
use anyhow::Result;
use std::cell::RefCell;
use std::ptr;
use wasmtime::{Extern, HostRef, Instance, Store, Trap};
use wasmtime::{Extern, HostRef, Instance, NewInstance, Store, Trap};

#[repr(C)]
#[derive(Clone)]
Expand Down Expand Up @@ -115,14 +115,17 @@ fn _wasmtime_instance_new(
}

pub fn handle_instantiate(
instance: Result<Instance>,
instance: Result<NewInstance>,
instance_ptr: &mut *mut wasm_instance_t,
trap_ptr: &mut *mut wasm_trap_t,
) -> Option<Box<wasmtime_error_t>> {
fn write<T>(ptr: &mut *mut T, val: T) {
*ptr = Box::into_raw(Box::new(val))
}

// Run the wasm start function.
let instance = instance.and_then(|new_instance| new_instance.start().map_err(Into::into));

match instance {
Ok(instance) => {
write(instance_ptr, wasm_instance_t::new(instance));
Expand Down
34 changes: 32 additions & 2 deletions crates/c-api/src/linker.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use crate::{bad_utf8, handle_result, wasmtime_error_t};
use crate::{wasm_extern_t, wasm_store_t, ExternHost};
use crate::{wasm_instance_t, wasm_module_t, wasm_name_t, wasm_trap_t};
use crate::{wasm_func_t, wasm_instance_t, wasm_module_t, wasm_name_t, wasm_trap_t};
use std::str;
use wasmtime::{Extern, Linker};
use wasmtime::{Extern, HostRef, Linker};

#[repr(C)]
pub struct wasmtime_linker_t {
Expand Down Expand Up @@ -89,3 +89,33 @@ pub unsafe extern "C" fn wasmtime_linker_instantiate(
let result = linker.linker.instantiate(&module.module.borrow());
super::instance::handle_instantiate(result, instance_ptr, trap_ptr)
}

#[no_mangle]
pub unsafe extern "C" fn wasmtime_linker_module(
linker: &mut wasmtime_linker_t,
name: &wasm_name_t,
module: &wasm_module_t,
) -> Option<Box<wasmtime_error_t>> {
let linker = &mut linker.linker;
let name = match str::from_utf8(name.as_slice()) {
Ok(s) => s,
Err(_) => return bad_utf8(),
};
handle_result(linker.module(name, &module.module.borrow()), |_linker| ())
}

#[no_mangle]
pub unsafe extern "C" fn wasmtime_linker_get_default(
linker: &mut wasmtime_linker_t,
name: &wasm_name_t,
func: &mut *mut wasm_func_t,
) -> Option<Box<wasmtime_error_t>> {
let linker = &mut linker.linker;
let name = match str::from_utf8(name.as_slice()) {
Ok(s) => s,
Err(_) => return bad_utf8(),
};
handle_result(linker.get_default(name), |f| {
*func = Box::into_raw(Box::new(HostRef::new(f).into()))
})
}
8 changes: 6 additions & 2 deletions crates/fuzzing/src/oracles.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,9 @@ pub fn differential_execution(
// aren't caught during validation or compilation. For example, an imported
// table might not have room for an element segment that we want to
// initialize into it.
let instance = match Instance::new(&module, &imports) {
let instance = match Instance::new(&module, &imports)
.and_then(|new_instance| new_instance.start().map_err(Into::into))
{
Ok(instance) => instance,
Err(e) => {
eprintln!(
Expand Down Expand Up @@ -338,7 +340,9 @@ pub fn make_api_calls(api: crate::generators::api::ApiCalls) {
// aren't caught during validation or compilation. For example, an imported
// table might not have room for an element segment that we want to
// initialize into it.
if let Ok(instance) = Instance::new(&module, &imports) {
if let Ok(instance) = Instance::new(&module, &imports)
.and_then(|new_instance| new_instance.start().map_err(Into::into))
{
instances.insert(id, instance);
}
}
Expand Down
4 changes: 0 additions & 4 deletions crates/runtime/src/instance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1330,8 +1330,4 @@ pub enum InstantiationError {
/// A trap ocurred during instantiation, after linking.
#[error("Trap occurred during instantiation")]
Trap(Trap),

/// A trap occurred while running the wasm start function.
#[error("Trap occurred while invoking start function")]
StartTrap(Trap),
}
41 changes: 12 additions & 29 deletions crates/test-programs/tests/wasm_tests/runtime.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use anyhow::{bail, Context};
use anyhow::Context;
use std::fs::File;
use std::path::Path;
use wasi_common::VirtualDirEntry;
use wasmtime::{Instance, Module, Store};
use wasmtime::{Linker, Module, Store};

#[derive(Clone, Copy, Debug)]
pub enum PreopenType {
Expand Down Expand Up @@ -48,36 +48,19 @@ pub fn instantiate(
let (reader, _writer) = os_pipe::pipe()?;
builder.stdin(reader_to_file(reader));
let snapshot1 = wasmtime_wasi::Wasi::new(&store, builder.build()?);
let module = Module::new(&store, &data).context("failed to create wasm module")?;
let imports = module
.imports()
.map(|i| {
let field_name = i.name();
if let Some(export) = snapshot1.get_export(field_name) {
Ok(export.clone().into())
} else {
bail!(
"import {} was not found in module {}",
field_name,
i.module()
)
}
})
.collect::<Result<Vec<_>, _>>()?;

let instance = Instance::new(&module, &imports).context(format!(
"error while instantiating Wasm module '{}'",
bin_name,
))?;
let mut linker = Linker::new(&store);

instance
.get_export("_start")
.context("expected a _start export")?
.into_func()
.context("expected export to be a func")?
.call(&[])?;
snapshot1.add_to_linker(&mut linker)?;

let module = Module::new(&store, &data).context("failed to create wasm module")?;

Ok(())
linker
.module("", &module)
.and_then(|m| m.get_default(""))
.and_then(|f| f.get0::<()>())
.and_then(|f| f().map_err(Into::into))
.context(format!("error while testing Wasm module '{}'", bin_name,))
}

#[cfg(unix)]
Expand Down
2 changes: 2 additions & 0 deletions crates/wasi-common/wig/src/wasi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,7 @@ pub fn define_struct(args: TokenStream) -> TokenStream {
let memory = match caller.get_export("memory") {
Some(wasmtime::Extern::Memory(m)) => m,
_ => {
log::warn!("callee does not export a memory as \"memory\"");
let e = wasi_common::old::snapshot_0::wasi::__WASI_ERRNO_INVAL;
#handle_early_error
}
Expand Down Expand Up @@ -463,6 +464,7 @@ pub fn define_struct_for_wiggle(args: TokenStream) -> TokenStream {
let mem = match caller.get_export("memory") {
Some(wasmtime::Extern::Memory(m)) => m,
_ => {
log::warn!("callee does not export a memory as \"memory\"");
let e = wasi_common::wasi::Errno::Inval;
#handle_early_error
}
Expand Down
6 changes: 3 additions & 3 deletions crates/wasmtime/src/externals.rs
Original file line number Diff line number Diff line change
Expand Up @@ -665,7 +665,7 @@ impl Memory {
/// let memory = Memory::new(&store, memory_ty);
///
/// let module = Module::new(&store, "(module (memory (import \"\" \"\") 1))")?;
/// let instance = Instance::new(&module, &[memory.into()])?;
/// let instance = Instance::new(&module, &[memory.into()])?.start()?;
/// // ...
/// # Ok(())
/// # }
Expand All @@ -688,7 +688,7 @@ impl Memory {
/// # fn main() -> anyhow::Result<()> {
/// let store = Store::default();
/// let module = Module::new(&store, "(module (memory (export \"mem\") 1))")?;
/// let instance = Instance::new(&module, &[])?;
/// let instance = Instance::new(&module, &[])?.start()?;
/// let memory = instance.get_memory("mem").unwrap();
/// let ty = memory.ty();
/// assert_eq!(ty.limits().min(), 1);
Expand Down Expand Up @@ -800,7 +800,7 @@ impl Memory {
/// # fn main() -> anyhow::Result<()> {
/// let store = Store::default();
/// let module = Module::new(&store, "(module (memory (export \"mem\") 1 2))")?;
/// let instance = Instance::new(&module, &[])?;
/// let instance = Instance::new(&module, &[])?.start()?;
/// let memory = instance.get_memory("mem").unwrap();
///
/// assert_eq!(memory.size(), 1);
Expand Down
14 changes: 7 additions & 7 deletions crates/wasmtime/src/func.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ use wasmtime_runtime::{Export, InstanceHandle, VMContext, VMFunctionBody};
/// # fn main() -> anyhow::Result<()> {
/// let store = Store::default();
/// let module = Module::new(&store, r#"(module (func (export "foo")))"#)?;
/// let instance = Instance::new(&module, &[])?;
/// let instance = Instance::new(&module, &[])?.start()?;
/// let foo = instance.get_func("foo").expect("export wasn't a function");
///
/// // Work with `foo` as a `Func` at this point, such as calling it
Expand Down Expand Up @@ -90,7 +90,7 @@ use wasmtime_runtime::{Export, InstanceHandle, VMContext, VMFunctionBody};
/// i32.add))
/// "#,
/// )?;
/// let instance = Instance::new(&module, &[add.into()])?;
/// let instance = Instance::new(&module, &[add.into()])?.start()?;
/// let call_add_twice = instance.get_func("call_add_twice").expect("export wasn't a function");
/// let call_add_twice = call_add_twice.get0::<i32>()?;
///
Expand Down Expand Up @@ -131,7 +131,7 @@ use wasmtime_runtime::{Export, InstanceHandle, VMContext, VMFunctionBody};
/// (start $start))
/// "#,
/// )?;
/// let instance = Instance::new(&module, &[double.into()])?;
/// let instance = Instance::new(&module, &[double.into()])?.start()?;
/// // .. work with `instance` if necessary
/// # Ok(())
/// # }
Expand Down Expand Up @@ -344,7 +344,7 @@ impl Func {
/// call $add))
/// "#,
/// )?;
/// let instance = Instance::new(&module, &[add.into()])?;
/// let instance = Instance::new(&module, &[add.into()])?.start()?;
/// let foo = instance.get_func("foo").unwrap().get2::<i32, i32, i32>()?;
/// assert_eq!(foo(1, 2)?, 3);
/// # Ok(())
Expand Down Expand Up @@ -375,7 +375,7 @@ impl Func {
/// call $add))
/// "#,
/// )?;
/// let instance = Instance::new(&module, &[add.into()])?;
/// let instance = Instance::new(&module, &[add.into()])?.start()?;
/// let foo = instance.get_func("foo").unwrap().get2::<i32, i32, i32>()?;
/// assert_eq!(foo(1, 2)?, 3);
/// assert!(foo(i32::max_value(), 1).is_err());
Expand Down Expand Up @@ -408,7 +408,7 @@ impl Func {
/// call $debug))
/// "#,
/// )?;
/// let instance = Instance::new(&module, &[debug.into()])?;
/// let instance = Instance::new(&module, &[debug.into()])?.start()?;
/// let foo = instance.get_func("foo").unwrap().get0::<()>()?;
/// foo()?;
/// # Ok(())
Expand Down Expand Up @@ -464,7 +464,7 @@ impl Func {
/// (data (i32.const 4) "Hello, world!"))
/// "#,
/// )?;
/// let instance = Instance::new(&module, &[log_str.into()])?;
/// let instance = Instance::new(&module, &[log_str.into()])?.start()?;
/// let foo = instance.get_func("foo").unwrap().get0::<()>()?;
/// foo()?;
/// # Ok(())
Expand Down
Loading