Add Wasmtime-specific C API functions to return errors (#1467)

* Add Wasmtime-specific C API functions to return errors

This commit adds new `wasmtime_*` symbols to the C API, many of which
mirror the existing counterparts in the `wasm.h` header. These APIs are
enhanced in a number of respects:

* Detailed error information is now available through a
  `wasmtime_error_t`. Currently this only exposes one function which is
  to extract a string version of the error.

* There is a distinction now between traps and errors during
  instantiation and function calling. Traps only happen if wasm traps,
  and errors can happen for things like runtime type errors when
  interacting with the API.

* APIs have improved safety with respect to embedders where the lengths
  of arrays are now taken as explicit parameters rather than assumed
  from other parameters.

* Handle trap updates

* Update C examples

* Fix memory.c compile on MSVC

* Update test assertions

* Refactor C slightly

* Bare-bones .NET update

* Remove bogus nul handling
This commit is contained in:
Alex Crichton
2020-04-06 15:13:06 -05:00
committed by GitHub
parent 78c548dc8f
commit bd374fd6fc
30 changed files with 817 additions and 403 deletions

View File

@@ -12,6 +12,18 @@ extern "C" {
#define own
#define WASMTIME_DECLARE_OWN(name) \
typedef struct wasmtime_##name##_t wasmtime_##name##_t; \
\
WASM_API_EXTERN void wasmtime_##name##_delete(own wasmtime_##name##_t*);
WASMTIME_DECLARE_OWN(error)
WASM_API_EXTERN void wasmtime_error_message(
const wasmtime_error_t *error,
own wasm_name_t *message
);
typedef uint8_t wasmtime_strategy_t;
enum wasmtime_strategy_enum { // Strategy
WASMTIME_STRATEGY_AUTO,
@@ -42,10 +54,10 @@ WASMTIME_CONFIG_PROP(void, wasm_reference_types, bool)
WASMTIME_CONFIG_PROP(void, wasm_simd, bool)
WASMTIME_CONFIG_PROP(void, wasm_bulk_memory, bool)
WASMTIME_CONFIG_PROP(void, wasm_multi_value, bool)
WASMTIME_CONFIG_PROP(bool, strategy, wasmtime_strategy_t)
WASMTIME_CONFIG_PROP(wasmtime_error_t*, strategy, wasmtime_strategy_t)
WASMTIME_CONFIG_PROP(void, cranelift_debug_verifier, bool)
WASMTIME_CONFIG_PROP(void, cranelift_opt_level, wasmtime_opt_level_t)
WASMTIME_CONFIG_PROP(bool, profiler, wasmtime_profiling_strategy_t)
WASMTIME_CONFIG_PROP(wasmtime_error_t*, profiler, wasmtime_profiling_strategy_t)
///////////////////////////////////////////////////////////////////////////////
@@ -55,53 +67,46 @@ WASMTIME_CONFIG_PROP(bool, profiler, wasmtime_profiling_strategy_t)
// it. This will be parsed and converted to the binary format.
// * `ret` - if the conversion is successful, this byte vector is filled in with
// the WebAssembly binary format.
// * `error_message` - if the conversion fails, this is filled in with a
// descriptive error message of why parsing failed. This parameter is
// optional.
//
// Returns `true` if conversion succeeded, or `false` if it failed.
WASM_API_EXTERN bool wasmtime_wat2wasm(
// Returns a non-null error if parsing fails, or returns `NULL`. If parsing
// fails then `ret` isn't touched.
WASM_API_EXTERN own wasmtime_error_t* wasmtime_wat2wasm(
const wasm_byte_vec_t *wat,
own wasm_byte_vec_t *ret,
own wasm_byte_vec_t *error_message
own wasm_byte_vec_t *ret
);
///////////////////////////////////////////////////////////////////////////////
//
// wasmtime_linker_t extension type, binding the `Linker` type in the Rust API
#define WASMTIME_DECLARE_OWN(name) \
typedef struct wasmtime_##name##_t wasmtime_##name##_t; \
\
WASM_API_EXTERN void wasmtime_##name##_delete(own wasmtime_##name##_t*);
WASMTIME_DECLARE_OWN(linker)
WASM_API_EXTERN own wasmtime_linker_t* wasmtime_linker_new(wasm_store_t* store);
WASM_API_EXTERN void wasmtime_linker_allow_shadowing(wasmtime_linker_t* linker, bool allow_shadowing);
WASM_API_EXTERN bool wasmtime_linker_define(
WASM_API_EXTERN own wasmtime_error_t* wasmtime_linker_define(
wasmtime_linker_t *linker,
const wasm_name_t *module,
const wasm_name_t *name,
const wasm_extern_t *item
);
WASM_API_EXTERN bool wasmtime_linker_define_wasi(
WASM_API_EXTERN own wasmtime_error_t* wasmtime_linker_define_wasi(
wasmtime_linker_t *linker,
const wasi_instance_t *instance
);
WASM_API_EXTERN bool wasmtime_linker_define_instance(
WASM_API_EXTERN own wasmtime_error_t* wasmtime_linker_define_instance(
wasmtime_linker_t *linker,
const wasm_name_t *name,
const wasm_instance_t *instance
);
WASM_API_EXTERN wasm_instance_t* wasmtime_linker_instantiate(
WASM_API_EXTERN own wasmtime_error_t* wasmtime_linker_instantiate(
const wasmtime_linker_t *linker,
const wasm_module_t *module,
own wasm_instance_t **instance,
own wasm_trap_t **trap
);
@@ -133,6 +138,98 @@ WASM_API_EXTERN own wasm_extern_t* wasmtime_caller_export_get(const wasmtime_cal
WASM_API_EXTERN const wasm_name_t *wasmtime_frame_func_name(const wasm_frame_t*);
WASM_API_EXTERN const wasm_name_t *wasmtime_frame_module_name(const wasm_frame_t*);
///////////////////////////////////////////////////////////////////////////////
//
// Extensions to the C API which augment existing functionality with extra
// error reporting, safety, etc.
// Similar to `wasm_func_call`, but with a few tweaks:
//
// * `args` and `results` have a size parameter saying how big the arrays are
// * An error *and* a trap can be returned
// * Errors are returned if `args` have the wrong types, if the args/results
// arrays have the wrong lengths, or if values come from the wrong store.
//
// The are three possible return states from this function:
//
// 1. The returned error is non-null. This means `results`
// wasn't written to and `trap` will have `NULL` written to it. This state
// means that programmer error happened when calling the function (e.g. the
// size of the args/results were wrong)
// 2. The trap pointer is filled in. This means the returned error is `NULL` and
// `results` was not written to. This state means that the function was
// executing but hit a wasm trap while executing.
// 3. The error and trap returned are both `NULL` and `results` are written to.
// This means that the function call worked and the specified results were
// produced.
//
// The `trap` pointer cannot be `NULL`. The `args` and `results` pointers may be
// `NULL` if the corresponding length is zero.
WASM_API_EXTERN own wasmtime_error_t *wasmtime_func_call(
wasm_func_t *func,
const wasm_val_t *args,
size_t num_args,
wasm_val_t *results,
size_t num_results,
own wasm_trap_t **trap
);
// Similar to `wasm_global_new`, but with a few tweaks:
//
// * An error is returned instead of `wasm_global_t`, which is taken as an
// out-parameter
// * An error happens when the `type` specified does not match the type of the
// value `val`, or if it comes from a different store than `store`.
WASM_API_EXTERN own wasmtime_error_t *wasmtime_global_new(
wasm_store_t *store,
const wasm_globaltype_t *type,
const wasm_val_t *val,
own wasm_global_t **ret
);
// Similar to `wasm_global_set`, but with an error that can be returned if the
// specified value does not come from the same store as this global, if the
// global is immutable, or if the specified value has the wrong type.
WASM_API_EXTERN own wasmtime_error_t *wasmtime_global_set(
wasm_global_t *global,
const wasm_val_t *val
);
// Similar to `wasm_instance_new`, but with tweaks:
//
// * An error message can be returned from this function.
// * The number of imports specified is passed as an argument
// * The `trap` pointer is required to not be NULL.
// * No `wasm_store_t` argument is required.
//
// The states of return values from this function are similar to
// `wasmtime_func_call` where an error can be returned meaning something like a
// link error in this context. A trap can be returned (meaning no error or
// instance is returned), or an instance can be returned (meaning no error or
// trap is returned).
WASM_API_EXTERN own wasmtime_error_t *wasmtime_instance_new(
const wasm_module_t *module,
const wasm_extern_t* const imports[],
size_t num_imports,
own wasm_instance_t **instance,
own wasm_trap_t **trap
);
// Similar to `wasm_module_new`, but an error is returned to return a
// descriptive error message in case compilation fails.
WASM_API_EXTERN own wasmtime_error_t *wasmtime_module_new(
wasm_store_t *store,
const wasm_byte_vec_t *binary,
own wasm_module_t **ret
);
// Similar to `wasm_module_validate`, but an error is returned to return a
// descriptive error message in case compilation fails.
WASM_API_EXTERN own wasmtime_error_t *wasmtime_module_validate(
wasm_store_t *store,
const wasm_byte_vec_t *binary
);
#undef own
#ifdef __cplusplus

View File

@@ -1,3 +1,4 @@
use crate::{handle_result, wasmtime_error_t};
use wasmtime::{Config, OptLevel, ProfilingStrategy, Strategy};
#[repr(C)]
@@ -72,15 +73,14 @@ pub extern "C" fn wasmtime_config_wasm_multi_value_set(c: &mut wasm_config_t, en
pub extern "C" fn wasmtime_config_strategy_set(
c: &mut wasm_config_t,
strategy: wasmtime_strategy_t,
) -> bool {
) -> Option<Box<wasmtime_error_t>> {
use wasmtime_strategy_t::*;
c.config
.strategy(match strategy {
WASMTIME_STRATEGY_AUTO => Strategy::Auto,
WASMTIME_STRATEGY_CRANELIFT => Strategy::Cranelift,
WASMTIME_STRATEGY_LIGHTBEAM => Strategy::Lightbeam,
})
.is_ok()
let result = c.config.strategy(match strategy {
WASMTIME_STRATEGY_AUTO => Strategy::Auto,
WASMTIME_STRATEGY_CRANELIFT => Strategy::Cranelift,
WASMTIME_STRATEGY_LIGHTBEAM => Strategy::Lightbeam,
});
handle_result(result, |_cfg| {})
}
#[no_mangle]
@@ -108,12 +108,11 @@ pub extern "C" fn wasmtime_config_cranelift_opt_level_set(
pub extern "C" fn wasmtime_config_profiler_set(
c: &mut wasm_config_t,
strategy: wasmtime_profiling_strategy_t,
) -> bool {
) -> Option<Box<wasmtime_error_t>> {
use wasmtime_profiling_strategy_t::*;
c.config
.profiler(match strategy {
WASMTIME_PROFILING_STRATEGY_NONE => ProfilingStrategy::None,
WASMTIME_PROFILING_STRATEGY_JITDUMP => ProfilingStrategy::JitDump,
})
.is_ok()
let result = c.config.profiler(match strategy {
WASMTIME_PROFILING_STRATEGY_NONE => ProfilingStrategy::None,
WASMTIME_PROFILING_STRATEGY_JITDUMP => ProfilingStrategy::JitDump,
});
handle_result(result, |_cfg| {})
}

46
crates/c-api/src/error.rs Normal file
View File

@@ -0,0 +1,46 @@
use crate::{wasm_name_t, wasm_trap_t};
use anyhow::{anyhow, Error, Result};
use wasmtime::Trap;
#[repr(C)]
pub struct wasmtime_error_t {
error: Error,
}
wasmtime_c_api_macros::declare_own!(wasmtime_error_t);
impl wasmtime_error_t {
pub(crate) fn to_trap(&self) -> Box<wasm_trap_t> {
Box::new(wasm_trap_t::new(Trap::new(format!("{:?}", self.error))))
}
}
impl From<Error> for wasmtime_error_t {
fn from(error: Error) -> wasmtime_error_t {
wasmtime_error_t { error }
}
}
pub(crate) fn handle_result<T>(
result: Result<T>,
ok: impl FnOnce(T),
) -> Option<Box<wasmtime_error_t>> {
match result {
Ok(value) => {
ok(value);
None
}
Err(error) => Some(Box::new(wasmtime_error_t { error })),
}
}
pub(crate) fn bad_utf8() -> Option<Box<wasmtime_error_t>> {
Some(Box::new(wasmtime_error_t {
error: anyhow!("input was not valid utf-8"),
}))
}
#[no_mangle]
pub extern "C" fn wasmtime_error_message(error: &wasmtime_error_t, message: &mut wasm_name_t) {
message.set_buffer(format!("{:?}", error.error).into_bytes());
}

View File

@@ -1,5 +1,6 @@
use crate::{wasm_extern_t, wasm_functype_t, wasm_store_t, wasm_val_t};
use crate::{wasm_name_t, wasm_trap_t, ExternHost};
use crate::{wasm_name_t, wasm_trap_t, wasmtime_error_t, ExternHost};
use anyhow::anyhow;
use std::ffi::c_void;
use std::panic::{self, AssertUnwindSafe};
use std::ptr;
@@ -160,16 +161,54 @@ pub extern "C" fn wasmtime_func_new_with_env(
#[no_mangle]
pub unsafe extern "C" fn wasm_func_call(
func: &wasm_func_t,
wasm_func: &wasm_func_t,
args: *const wasm_val_t,
results: *mut wasm_val_t,
) -> *mut wasm_trap_t {
let func = func.func().borrow();
let mut params = Vec::with_capacity(func.param_arity());
for i in 0..func.param_arity() {
let val = &(*args.add(i));
params.push(val.val());
let func = wasm_func.func().borrow();
let mut trap = ptr::null_mut();
let error = wasmtime_func_call(
wasm_func,
args,
func.param_arity(),
results,
func.result_arity(),
&mut trap,
);
match error {
Some(err) => Box::into_raw(err.to_trap()),
None => trap,
}
}
#[no_mangle]
pub unsafe extern "C" fn wasmtime_func_call(
func: &wasm_func_t,
args: *const wasm_val_t,
num_args: usize,
results: *mut wasm_val_t,
num_results: usize,
trap_ptr: &mut *mut wasm_trap_t,
) -> Option<Box<wasmtime_error_t>> {
_wasmtime_func_call(
func,
std::slice::from_raw_parts(args, num_args),
std::slice::from_raw_parts_mut(results, num_results),
trap_ptr,
)
}
fn _wasmtime_func_call(
func: &wasm_func_t,
args: &[wasm_val_t],
results: &mut [wasm_val_t],
trap_ptr: &mut *mut wasm_trap_t,
) -> Option<Box<wasmtime_error_t>> {
let func = func.func().borrow();
if results.len() != func.result_arity() {
return Some(Box::new(anyhow!("wrong number of results provided").into()));
}
let params = args.iter().map(|i| i.val()).collect::<Vec<_>>();
// We're calling arbitrary code here most of the time, and we in general
// want to try to insulate callers against bugs in wasmtime/wasi/etc if we
@@ -178,18 +217,18 @@ pub unsafe extern "C" fn wasm_func_call(
let result = panic::catch_unwind(AssertUnwindSafe(|| func.call(&params)));
match result {
Ok(Ok(out)) => {
for i in 0..func.result_arity() {
let val = &mut (*results.add(i));
*val = wasm_val_t::from_val(&out[i]);
for (slot, val) in results.iter_mut().zip(out.iter()) {
*slot = wasm_val_t::from_val(val);
}
ptr::null_mut()
}
Ok(Err(trap)) => {
let trap = Box::new(wasm_trap_t {
trap: HostRef::new(trap),
});
Box::into_raw(trap)
None
}
Ok(Err(trap)) => match trap.downcast::<Trap>() {
Ok(trap) => {
*trap_ptr = Box::into_raw(Box::new(wasm_trap_t::new(trap)));
None
}
Err(err) => Some(Box::new(err.into())),
},
Err(panic) => {
let trap = if let Some(msg) = panic.downcast_ref::<String>() {
Trap::new(msg)
@@ -198,10 +237,9 @@ pub unsafe extern "C" fn wasm_func_call(
} else {
Trap::new("rust panic happened")
};
let trap = Box::new(wasm_trap_t {
trap: HostRef::new(trap),
});
Box::into_raw(trap)
let trap = Box::new(wasm_trap_t::new(trap));
*trap_ptr = Box::into_raw(trap);
None
}
}
}

View File

@@ -1,4 +1,6 @@
use crate::{handle_result, wasmtime_error_t};
use crate::{wasm_extern_t, wasm_globaltype_t, wasm_store_t, wasm_val_t, ExternHost};
use std::ptr;
use wasmtime::{Global, HostRef};
#[derive(Clone)]
@@ -35,13 +37,31 @@ pub extern "C" fn wasm_global_new(
gt: &wasm_globaltype_t,
val: &wasm_val_t,
) -> Option<Box<wasm_global_t>> {
let global =
HostRef::new(Global::new(&store.store.borrow(), gt.ty().ty.clone(), val.val()).ok()?);
Some(Box::new(wasm_global_t {
ext: wasm_extern_t {
which: ExternHost::Global(global),
},
}))
let mut global = ptr::null_mut();
match wasmtime_global_new(store, gt, val, &mut global) {
Some(_err) => None,
None => {
assert!(!global.is_null());
Some(unsafe { Box::from_raw(global) })
}
}
}
#[no_mangle]
pub extern "C" fn wasmtime_global_new(
store: &wasm_store_t,
gt: &wasm_globaltype_t,
val: &wasm_val_t,
ret: &mut *mut wasm_global_t,
) -> Option<Box<wasmtime_error_t>> {
let global = Global::new(&store.store.borrow(), gt.ty().ty.clone(), val.val());
handle_result(global, |global| {
*ret = Box::into_raw(Box::new(wasm_global_t {
ext: wasm_extern_t {
which: ExternHost::Global(HostRef::new(global)),
},
}));
})
}
#[no_mangle]
@@ -66,3 +86,11 @@ pub extern "C" fn wasm_global_set(g: &wasm_global_t, val: &wasm_val_t) {
// FIXME(WebAssembly/wasm-c-api#131) should communicate the error here
drop(result);
}
#[no_mangle]
pub extern "C" fn wasmtime_global_set(
g: &wasm_global_t,
val: &wasm_val_t,
) -> Option<Box<wasmtime_error_t>> {
handle_result(g.global().borrow().set(val.val()), |()| {})
}

View File

@@ -1,5 +1,5 @@
use crate::{wasm_extern_t, wasm_extern_vec_t, wasm_module_t, wasm_trap_t};
use crate::{wasm_store_t, ExternHost};
use crate::{wasm_store_t, wasmtime_error_t, ExternHost};
use anyhow::Result;
use std::cell::RefCell;
use std::ptr;
@@ -15,7 +15,7 @@ pub struct wasm_instance_t {
wasmtime_c_api_macros::declare_ref!(wasm_instance_t);
impl wasm_instance_t {
fn new(instance: Instance) -> wasm_instance_t {
pub(crate) fn new(instance: Instance) -> wasm_instance_t {
wasm_instance_t {
instance: HostRef::new(instance),
exports_cache: RefCell::new(None),
@@ -30,59 +30,111 @@ impl wasm_instance_t {
#[no_mangle]
pub unsafe extern "C" fn wasm_instance_new(
store: &wasm_store_t,
module: &wasm_module_t,
wasm_module: &wasm_module_t,
imports: *const Box<wasm_extern_t>,
result: Option<&mut *mut wasm_trap_t>,
) -> Option<Box<wasm_instance_t>> {
let mut externs: Vec<Extern> = Vec::with_capacity((*module).imports.len());
for i in 0..(*module).imports.len() {
let import = &*imports.add(i);
externs.push(match &import.which {
ExternHost::Func(e) => Extern::Func(e.borrow().clone()),
ExternHost::Table(e) => Extern::Table(e.borrow().clone()),
ExternHost::Global(e) => Extern::Global(e.borrow().clone()),
ExternHost::Memory(e) => Extern::Memory(e.borrow().clone()),
});
}
let store = &(*store).store.borrow();
let module = &(*module).module.borrow();
let store = &store.store.borrow();
let module = &wasm_module.module.borrow();
if !Store::same(&store, module.store()) {
if let Some(result) = result {
let trap = Trap::new("wasm_store_t must match store in wasm_module_t");
let trap = Box::new(wasm_trap_t {
trap: HostRef::new(trap),
});
let trap = Box::new(wasm_trap_t::new(trap));
*result = Box::into_raw(trap);
}
return None;
}
handle_instantiate(Instance::new(module, &externs), result)
let mut instance = ptr::null_mut();
let mut trap = ptr::null_mut();
let err = wasmtime_instance_new(
wasm_module,
imports,
wasm_module.imports.len(),
&mut instance,
&mut trap,
);
match err {
Some(err) => {
assert!(trap.is_null());
assert!(instance.is_null());
if let Some(result) = result {
*result = Box::into_raw(err.to_trap());
}
None
}
None => {
if instance.is_null() {
assert!(!trap.is_null());
if let Some(result) = result {
*result = trap;
} else {
drop(Box::from_raw(trap))
}
None
} else {
assert!(trap.is_null());
Some(Box::from_raw(instance))
}
}
}
}
#[no_mangle]
pub unsafe extern "C" fn wasmtime_instance_new(
module: &wasm_module_t,
imports: *const Box<wasm_extern_t>,
num_imports: usize,
instance_ptr: &mut *mut wasm_instance_t,
trap_ptr: &mut *mut wasm_trap_t,
) -> Option<Box<wasmtime_error_t>> {
_wasmtime_instance_new(
module,
std::slice::from_raw_parts(imports, num_imports),
instance_ptr,
trap_ptr,
)
}
fn _wasmtime_instance_new(
module: &wasm_module_t,
imports: &[Box<wasm_extern_t>],
instance_ptr: &mut *mut wasm_instance_t,
trap_ptr: &mut *mut wasm_trap_t,
) -> Option<Box<wasmtime_error_t>> {
let imports = imports
.iter()
.map(|import| match &import.which {
ExternHost::Func(e) => Extern::Func(e.borrow().clone()),
ExternHost::Table(e) => Extern::Table(e.borrow().clone()),
ExternHost::Global(e) => Extern::Global(e.borrow().clone()),
ExternHost::Memory(e) => Extern::Memory(e.borrow().clone()),
})
.collect::<Vec<_>>();
let module = &module.module.borrow();
handle_instantiate(Instance::new(module, &imports), instance_ptr, trap_ptr)
}
pub fn handle_instantiate(
instance: Result<Instance>,
result: Option<&mut *mut wasm_trap_t>,
) -> Option<Box<wasm_instance_t>> {
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))
}
match instance {
Ok(instance) => {
if let Some(result) = result {
*result = ptr::null_mut();
}
Some(Box::new(wasm_instance_t::new(instance)))
}
Err(trap) => {
if let Some(result) = result {
let trap = match trap.downcast::<Trap>() {
Ok(trap) => trap,
Err(e) => Trap::new(format!("{:?}", e)),
};
let trap = Box::new(wasm_trap_t {
trap: HostRef::new(trap),
});
*result = Box::into_raw(trap);
}
write(instance_ptr, wasm_instance_t::new(instance));
None
}
Err(e) => match e.downcast::<Trap>() {
Ok(trap) => {
write(trap_ptr, wasm_trap_t::new(trap));
None
}
Err(e) => Some(Box::new(e.into())),
},
}
}

View File

@@ -7,6 +7,7 @@
mod config;
mod engine;
mod error;
mod r#extern;
mod func;
mod global;
@@ -24,6 +25,7 @@ mod vec;
pub use crate::config::*;
pub use crate::engine::*;
pub use crate::error::*;
pub use crate::func::*;
pub use crate::global::*;
pub use crate::instance::*;

View File

@@ -1,3 +1,4 @@
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 std::str;
@@ -32,15 +33,15 @@ pub extern "C" fn wasmtime_linker_define(
module: &wasm_name_t,
name: &wasm_name_t,
item: &wasm_extern_t,
) -> bool {
) -> Option<Box<wasmtime_error_t>> {
let linker = &mut linker.linker;
let module = match str::from_utf8(module.as_slice()) {
Ok(s) => s,
Err(_) => return false,
Err(_) => return bad_utf8(),
};
let name = match str::from_utf8(name.as_slice()) {
Ok(s) => s,
Err(_) => return false,
Err(_) => return bad_utf8(),
};
let item = match &item.which {
ExternHost::Func(e) => Extern::Func(e.borrow().clone()),
@@ -48,7 +49,7 @@ pub extern "C" fn wasmtime_linker_define(
ExternHost::Global(e) => Extern::Global(e.borrow().clone()),
ExternHost::Memory(e) => Extern::Memory(e.borrow().clone()),
};
linker.define(module, name, item).is_ok()
handle_result(linker.define(module, name, item), |_linker| ())
}
#[cfg(feature = "wasi")]
@@ -56,9 +57,9 @@ pub extern "C" fn wasmtime_linker_define(
pub extern "C" fn wasmtime_linker_define_wasi(
linker: &mut wasmtime_linker_t,
instance: &crate::wasi_instance_t,
) -> bool {
) -> Option<Box<wasmtime_error_t>> {
let linker = &mut linker.linker;
instance.add_to_linker(linker).is_ok()
handle_result(instance.add_to_linker(linker), |_linker| ())
}
#[no_mangle]
@@ -66,22 +67,25 @@ pub extern "C" fn wasmtime_linker_define_instance(
linker: &mut wasmtime_linker_t,
name: &wasm_name_t,
instance: &wasm_instance_t,
) -> bool {
) -> Option<Box<wasmtime_error_t>> {
let linker = &mut linker.linker;
let name = match str::from_utf8(name.as_slice()) {
Ok(s) => s,
Err(_) => return false,
Err(_) => return bad_utf8(),
};
linker.instance(name, &instance.instance.borrow()).is_ok()
handle_result(
linker.instance(name, &instance.instance.borrow()),
|_linker| (),
)
}
#[no_mangle]
pub unsafe extern "C" fn wasmtime_linker_instantiate(
linker: &wasmtime_linker_t,
module: &wasm_module_t,
trap: Option<&mut *mut wasm_trap_t>,
) -> Option<Box<wasm_instance_t>> {
let linker = &linker.linker;
let result = linker.instantiate(&module.module.borrow());
super::instance::handle_instantiate(result, trap)
instance_ptr: &mut *mut wasm_instance_t,
trap_ptr: &mut *mut wasm_trap_t,
) -> Option<Box<wasmtime_error_t>> {
let result = linker.linker.instantiate(&module.module.borrow());
super::instance::handle_instantiate(result, instance_ptr, trap_ptr)
}

View File

@@ -1,5 +1,7 @@
use crate::{handle_result, wasmtime_error_t};
use crate::{wasm_byte_vec_t, wasm_exporttype_vec_t, wasm_importtype_vec_t};
use crate::{wasm_exporttype_t, wasm_importtype_t, wasm_store_t};
use std::ptr;
use wasmtime::{HostRef, Module};
#[repr(C)]
@@ -23,31 +25,57 @@ pub extern "C" fn wasm_module_new(
store: &wasm_store_t,
binary: &wasm_byte_vec_t,
) -> Option<Box<wasm_module_t>> {
let mut ret = ptr::null_mut();
match wasmtime_module_new(store, binary, &mut ret) {
Some(_err) => None,
None => {
assert!(!ret.is_null());
Some(unsafe { Box::from_raw(ret) })
}
}
}
#[no_mangle]
pub extern "C" fn wasmtime_module_new(
store: &wasm_store_t,
binary: &wasm_byte_vec_t,
ret: &mut *mut wasm_module_t,
) -> Option<Box<wasmtime_error_t>> {
let binary = binary.as_slice();
let store = &store.store.borrow();
let module = Module::from_binary(store, binary).ok()?;
let imports = module
.imports()
.iter()
.map(|i| wasm_importtype_t::new(i.clone()))
.collect::<Vec<_>>();
let exports = module
.exports()
.iter()
.map(|e| wasm_exporttype_t::new(e.clone()))
.collect::<Vec<_>>();
Some(Box::new(wasm_module_t {
module: HostRef::new(module),
imports,
exports,
}))
handle_result(Module::from_binary(store, binary), |module| {
let imports = module
.imports()
.iter()
.map(|i| wasm_importtype_t::new(i.clone()))
.collect::<Vec<_>>();
let exports = module
.exports()
.iter()
.map(|e| wasm_exporttype_t::new(e.clone()))
.collect::<Vec<_>>();
let module = Box::new(wasm_module_t {
module: HostRef::new(module),
imports,
exports,
});
*ret = Box::into_raw(module);
})
}
#[no_mangle]
pub extern "C" fn wasm_module_validate(store: &wasm_store_t, binary: &wasm_byte_vec_t) -> bool {
wasmtime_module_validate(store, binary).is_none()
}
#[no_mangle]
pub extern "C" fn wasmtime_module_validate(
store: &wasm_store_t,
binary: &wasm_byte_vec_t,
) -> Option<Box<wasmtime_error_t>> {
let binary = binary.as_slice();
let store = &store.store.borrow();
Module::validate(store, binary).is_ok()
handle_result(Module::validate(store, binary), |()| {})
}
#[no_mangle]

View File

@@ -11,6 +11,12 @@ pub struct wasm_trap_t {
wasmtime_c_api_macros::declare_ref!(wasm_trap_t);
impl wasm_trap_t {
pub(crate) fn new(trap: Trap) -> wasm_trap_t {
wasm_trap_t {
trap: HostRef::new(trap),
}
}
fn anyref(&self) -> wasmtime::AnyRef {
self.trap.anyref()
}

View File

@@ -1,30 +1,15 @@
use crate::wasm_byte_vec_t;
use crate::{bad_utf8, handle_result, wasm_byte_vec_t, wasmtime_error_t};
#[no_mangle]
pub extern "C" fn wasmtime_wat2wasm(
wat: &wasm_byte_vec_t,
ret: &mut wasm_byte_vec_t,
error: Option<&mut wasm_byte_vec_t>,
) -> bool {
) -> Option<Box<wasmtime_error_t>> {
let wat = match std::str::from_utf8(wat.as_slice()) {
Ok(s) => s,
Err(_) => {
if let Some(error) = error {
error.set_buffer(b"input was not valid utf-8".to_vec());
}
return false;
}
Err(_) => return bad_utf8(),
};
match wat::parse_str(wat) {
Ok(bytes) => {
ret.set_buffer(bytes.into());
true
}
Err(e) => {
if let Some(error) = error {
error.set_buffer(e.to_string().into_bytes());
}
false
}
}
handle_result(wat::parse_str(wat).map_err(|e| e.into()), |bytes| {
ret.set_buffer(bytes.into())
})
}