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

@@ -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())
})
}