Skip to content

Commit

Permalink
Add C API
Browse files Browse the repository at this point in the history
  • Loading branch information
yurydelendik committed Jul 15, 2020
1 parent b3f74c2 commit faa08c0
Show file tree
Hide file tree
Showing 3 changed files with 244 additions and 3 deletions.
34 changes: 34 additions & 0 deletions crates/c-api/include/wasmtime.h
Original file line number Diff line number Diff line change
Expand Up @@ -893,6 +893,40 @@ WASM_API_EXTERN void wasmtime_externref_new_with_finalizer(
*/
WASM_API_EXTERN bool wasmtime_externref_data(wasm_val_t* val, void** datap);

/**
* \brief This function will compile a WebAssembly binary and saves artifacts
* as blob data.
*
* \param engine this is engine that will provide the compiler.
* \param binary this it the input buffer with the WebAssembly Binary Format inside of
* it. This will be parsed and converted to the binary format.
* \param ret if the conversion is successful, this byte vector is filled in with
* the serialized compiled module.
*
* \return a non-null error if parsing fails, or returns `NULL`. If parsing
* fails then `ret` isn't touched.
*
* This function does not take ownership of `binary` or `engine`, and the caller is
* expected to deallocate the returned #wasmtime_error_t and #wasm_byte_vec_t.
*/
WASM_API_EXTERN own wasmtime_error_t* wasmtime_compile_and_serialize(
wasm_engine_t* engine,
const wasm_byte_vec_t* binary,
own wasm_byte_vec_t *ret
);

/**
* \brief Build a module from serialized data.
* *
* This function does not take ownership of any of its arguments, but the
* returned error and module are owned by the caller.
*/
WASM_API_EXTERN own wasmtime_error_t *wasmtime_module_deserialize(
wasm_store_t *store,
const wasm_byte_vec_t *serialized,
own wasm_module_t **ret
);

#undef own

#ifdef __cplusplus
Expand Down
48 changes: 45 additions & 3 deletions crates/c-api/src/module.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use crate::{
handle_result, wasm_byte_vec_t, wasm_exporttype_t, wasm_exporttype_vec_t, wasm_importtype_t,
wasm_importtype_vec_t, wasm_store_t, wasmtime_error_t,
handle_result, wasm_byte_vec_t, wasm_engine_t, wasm_exporttype_t, wasm_exporttype_vec_t,
wasm_importtype_t, wasm_importtype_vec_t, wasm_store_t, wasmtime_error_t,
};
use std::ptr;
use wasmtime::{Engine, Module};
use wasmtime::{compile_and_serialize, Engine, Module};

#[repr(C)]
#[derive(Clone)]
Expand Down Expand Up @@ -128,3 +128,45 @@ pub extern "C" fn wasm_module_obtain(
exports,
}))
}

#[no_mangle]
pub extern "C" fn wasmtime_compile_and_serialize(
engine: &wasm_engine_t,
binary: &wasm_byte_vec_t,
ret: &mut wasm_byte_vec_t,
) -> Option<Box<wasmtime_error_t>> {
let mut result = Vec::new();
handle_result(
compile_and_serialize(&engine.engine, binary.as_slice(), &mut result),
|()| {
ret.set_buffer(result);
},
)
}

#[no_mangle]
pub unsafe extern "C" fn wasmtime_module_deserialize(
store: &wasm_store_t,
binary: &wasm_byte_vec_t,
ret: &mut *mut wasm_module_t,
) -> Option<Box<wasmtime_error_t>> {
handle_result(
Module::deserialize(&store.store.engine(), binary.as_slice()),
|module| {
let imports = module
.imports()
.map(|i| wasm_importtype_t::new(i.module().to_owned(), i.name().to_owned(), i.ty()))
.collect::<Vec<_>>();
let exports = module
.exports()
.map(|e| wasm_exporttype_t::new(e.name().to_owned(), e.ty()))
.collect::<Vec<_>>();
let module = Box::new(wasm_module_t {
module: module,
imports,
exports,
});
*ret = Box::into_raw(module);
},
)
}
165 changes: 165 additions & 0 deletions examples/serialize.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
/*
Example of instantiating of the WebAssembly module and invoking its exported
function.
You can compile and run this example on Linux with:
cargo build --release -p wasmtime
cc examples/hello.c \
-I crates/c-api/include \
-I crates/c-api/wasm-c-api/include \
target/release/libwasmtime.a \
-lpthread -ldl -lm \
-o hello
./hello
Note that on Windows and macOS the command will be similar, but you'll need
to tweak the `-lpthread` and such annotations as well as the name of the
`libwasmtime.a` file on Windows.
*/

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <wasm.h>
#include <wasmtime.h>

static void exit_with_error(const char *message, wasmtime_error_t *error, wasm_trap_t *trap);

static wasm_trap_t* hello_callback(const wasm_val_t args[], wasm_val_t results[]) {
printf("Calling back...\n");
printf("> Hello World!\n");
return NULL;
}

int serialize(wasm_byte_vec_t* buffer) {
// Set up our compilation context. Note that we could also work with a
// `wasm_config_t` here to configure what feature are enabled and various
// compilation settings.
printf("Initializing...\n");
wasm_engine_t *engine = wasm_engine_new();
assert(engine != NULL);

// Read our input file, which in this case is a wasm text file.
FILE* file = fopen("examples/hello.wat", "r");
assert(file != NULL);
fseek(file, 0L, SEEK_END);
size_t file_size = ftell(file);
fseek(file, 0L, SEEK_SET);
wasm_byte_vec_t wat;
wasm_byte_vec_new_uninitialized(&wat, file_size);
assert(fread(wat.data, file_size, 1, file) == 1);
fclose(file);

// Parse the wat into the binary wasm format
wasm_byte_vec_t wasm;
wasmtime_error_t *error = wasmtime_wat2wasm(&wat, &wasm);
if (error != NULL)
exit_with_error("failed to parse wat", error, NULL);
wasm_byte_vec_delete(&wat);

// Now that we've got our binary webassembly we can compile our module
// and serialize into buffer.
printf("Compiling and serializing module...\n");
wasm_module_t *module = NULL;
error = wasmtime_compile_and_serialize(engine, &wasm, buffer);
wasm_byte_vec_delete(&wasm);
if (error != NULL)
exit_with_error("failed to compile module", error, NULL);

printf("Serialized.\n");

wasm_engine_delete(engine);
return 0;
}

int deserialize(wasm_byte_vec_t* buffer) {
// Set up our compilation context. Note that we could also work with a
// `wasm_config_t` here to configure what feature are enabled and various
// compilation settings.
printf("Initializing...\n");
wasm_engine_t *engine = wasm_engine_new();
assert(engine != NULL);

// With an engine we can create a *store* which is a long-lived group of wasm
// modules.
wasm_store_t *store = wasm_store_new(engine);
assert(store != NULL);

// Deserialize compiled module.
printf("Deserialize module...\n");
wasm_module_t *module = NULL;
wasmtime_error_t *error = wasmtime_module_deserialize(store, buffer, &module);
if (error != NULL)
exit_with_error("failed to compile module", error, NULL);

// Next up we need to create the function that the wasm module imports. Here
// we'll be hooking up a thunk function to the `hello_callback` native
// function above.
printf("Creating callback...\n");
wasm_functype_t *hello_ty = wasm_functype_new_0_0();
wasm_func_t *hello = wasm_func_new(store, hello_ty, hello_callback);

// With our callback function we can now instantiate the compiled module,
// giving us an instance we can then execute exports from. Note that
// instantiation can trap due to execution of the `start` function, so we need
// to handle that here too.
printf("Instantiating module...\n");
wasm_trap_t *trap = NULL;
wasm_instance_t *instance = NULL;
const wasm_extern_t *imports[] = { wasm_func_as_extern(hello) };
error = wasmtime_instance_new(store, module, imports, 1, &instance, &trap);
if (instance == NULL)
exit_with_error("failed to instantiate", error, trap);

// Lookup our `run` export function
printf("Extracting export...\n");
wasm_extern_vec_t externs;
wasm_instance_exports(instance, &externs);
assert(externs.size == 1);
wasm_func_t *run = wasm_extern_as_func(externs.data[0]);
assert(run != NULL);

// And call it!
printf("Calling export...\n");
error = wasmtime_func_call(run, NULL, 0, NULL, 0, &trap);
if (error != NULL || trap != NULL)
exit_with_error("failed to call function", error, trap);

// Clean up after ourselves at this point
printf("All finished!\n");

wasm_extern_vec_delete(&externs);
wasm_instance_delete(instance);
wasm_module_delete(module);
wasm_store_delete(store);
wasm_engine_delete(engine);
return 0;
}

int main() {
wasm_byte_vec_t buffer;
if (serialize(&buffer)) {
return 1;
}
if (deserialize(&buffer)) {
return 1;
}
wasm_byte_vec_delete(&buffer);
return 0;
}

static void exit_with_error(const char *message, wasmtime_error_t *error, wasm_trap_t *trap) {
fprintf(stderr, "error: %s\n", message);
wasm_byte_vec_t error_message;
if (error != NULL) {
wasmtime_error_message(error, &error_message);
wasmtime_error_delete(error);
} else {
wasm_trap_message(trap, &error_message);
wasm_trap_delete(trap);
}
fprintf(stderr, "%.*s\n", (int) error_message.size, error_message.data);
wasm_byte_vec_delete(&error_message);
exit(1);
}

0 comments on commit faa08c0

Please sign in to comment.