Refactor and fill out wasmtime's C API (#1415)
* Refactor and improve safety of C API This commit is intended to be a relatively large refactoring of the C API which is targeted at improving the safety of our C API definitions. Not all of the APIs have been updated yet but this is intended to be the start. The goal here is to make as many functions safe as we can, expressing inputs/outputs as native Rust types rather than raw pointers wherever possible. For example instead of `*const wasm_foo_t` we'd take `&wasm_foo_t`. Instead of returning `*mut wasm_foo_t` we'd return `Box<wasm_foo_t>`. No ABI/API changes are intended from this commit, it's supposed to only change how we define all these functions internally. This commit also additionally implements a few more API bindings for exposed vector types by unifying everything into one macro. Finally, this commit moves many internal caches in the C API to the `OnceCell` type which provides a safe interface for one-time initialization. * Split apart monolithic C API `lib.rs` This commit splits the monolithic `src/lib.rs` in the C API crate into lots of smaller files. The goal here is to make this a bit more readable and digestable. Each module now contains only API bindings for a particular type, roughly organized around the grouping in the wasm.h header file already. A few more extensions were added, such as filling out `*_as_*` conversions with both const and non-const versions. Additionally many APIs were made safer in the same style as the previous commit, generally preferring Rust types rather than raw pointer types. Overall no functional change is intended here, it should be mostly just code movement and minor refactorings! * Make a few wasi C bindings safer Use safe Rust types where we can and touch up a few APIs here and there. * Implement `wasm_*type_as_externtype*` APIs This commit restructures `wasm_externtype_t` to be similar to `wasm_extern_t` so type conversion between the `*_extern_*` variants to the concrete variants are all simple casts. (checked in the case of general to concrete, of course). * Consistently imlpement host info functions in the API This commit adds a small macro crate which is then used to consistently define the various host-info-related functions in the C API. The goal here is to try to mirror what the `wasm.h` header provides to provide a full implementation of the header.
This commit is contained in:
111
crates/c-api/src/instance.rs
Normal file
111
crates/c-api/src/instance.rs
Normal file
@@ -0,0 +1,111 @@
|
||||
use crate::{wasm_extern_t, wasm_extern_vec_t, wasm_module_t, wasm_trap_t};
|
||||
use crate::{wasm_store_t, ExternHost};
|
||||
use anyhow::Result;
|
||||
use std::cell::RefCell;
|
||||
use std::ptr;
|
||||
use wasmtime::{Extern, HostRef, Instance, Store, Trap};
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Clone)]
|
||||
pub struct wasm_instance_t {
|
||||
pub(crate) instance: HostRef<Instance>,
|
||||
exports_cache: RefCell<Option<Vec<ExternHost>>>,
|
||||
}
|
||||
|
||||
wasmtime_c_api_macros::declare_ref!(wasm_instance_t);
|
||||
|
||||
impl wasm_instance_t {
|
||||
fn new(instance: Instance) -> wasm_instance_t {
|
||||
wasm_instance_t {
|
||||
instance: HostRef::new(instance),
|
||||
exports_cache: RefCell::new(None),
|
||||
}
|
||||
}
|
||||
|
||||
fn anyref(&self) -> wasmtime::AnyRef {
|
||||
self.instance.anyref()
|
||||
}
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn wasm_instance_new(
|
||||
store: &wasm_store_t,
|
||||
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();
|
||||
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),
|
||||
});
|
||||
*result = Box::into_raw(trap);
|
||||
}
|
||||
return None;
|
||||
}
|
||||
handle_instantiate(Instance::new(module, &externs), result)
|
||||
}
|
||||
|
||||
pub fn handle_instantiate(
|
||||
instance: Result<Instance>,
|
||||
result: Option<&mut *mut wasm_trap_t>,
|
||||
) -> Option<Box<wasm_instance_t>> {
|
||||
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);
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub extern "C" fn wasm_instance_exports(instance: &wasm_instance_t, out: &mut wasm_extern_vec_t) {
|
||||
let mut cache = instance.exports_cache.borrow_mut();
|
||||
let exports = cache.get_or_insert_with(|| {
|
||||
let instance = &instance.instance.borrow();
|
||||
instance
|
||||
.exports()
|
||||
.iter()
|
||||
.map(|e| match e {
|
||||
Extern::Func(f) => ExternHost::Func(HostRef::new(f.clone())),
|
||||
Extern::Global(f) => ExternHost::Global(HostRef::new(f.clone())),
|
||||
Extern::Memory(f) => ExternHost::Memory(HostRef::new(f.clone())),
|
||||
Extern::Table(f) => ExternHost::Table(HostRef::new(f.clone())),
|
||||
})
|
||||
.collect()
|
||||
});
|
||||
let mut buffer = Vec::with_capacity(exports.len());
|
||||
for e in exports {
|
||||
let ext = Box::new(wasm_extern_t { which: e.clone() });
|
||||
buffer.push(Some(ext));
|
||||
}
|
||||
out.set_buffer(buffer);
|
||||
}
|
||||
Reference in New Issue
Block a user