Skip to content

A lightweight WebAssembly runtime that is fast, secure, and standards-compliant

Fill out wasip2 C/C++ examples, migrate tokio example to wasip2 (#14422)

Alex Crichton356e8bae3dae
diff --git a/crates/c-api/include/wasmtime/component/func.h b/crates/c-api/include/wasmtime/component/func.h
index a2b48a2987..9a3f3e9930 100644
--- a/crates/c-api/include/wasmtime/component/func.h
+++ b/crates/c-api/include/wasmtime/component/func.h
@@ -51,10 +51,11 @@ wasmtime_component_func_type(const wasmtime_component_func_t *func,
*
* The \p args provided must match the parameters that this function takes in
* terms of their types and the number of parameters. Results will be written to
- * the \p results provided if the call completes successfully. The initial types
- * of the values in \p results are ignored and values are overwritten to write
- * the result. It's required that the \p results_size exactly matches the number
- * of results that this function produces.
+ * the \p results provided if the call completes successfully. It's required
+ * that the \p results_size exactly matches the number of results that this
+ * function produces. It's additionally required that \p results is all entirely
+ * initialize (cannot be uninitialized memory). The types of values do not
+ * matter, and #WASMTIME_COMPONENT_BOOL can be used to cheaply initialize.
*/
WASM_API_EXTERN wasmtime_error_t *wasmtime_component_func_call(
const wasmtime_component_func_t *func, wasmtime_context_t *context,
diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt
index 5959fa3e81..7b91fa2bf4 100644
--- a/examples/CMakeLists.txt
+++ b/examples/CMakeLists.txt
@@ -1,7 +1,7 @@
cmake_minimum_required(VERSION 3.10)
project(wasmtime-examples)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
-set(CMAKE_CXX_STANDARD 17)
+set(CMAKE_CXX_STANDARD 20)
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/../crates/c-api ${CMAKE_CURRENT_BINARY_DIR}/wasmtime)
@@ -54,7 +54,7 @@ enable_testing()
# Wasm files required by tests, but only built if tests are actually being run.
create_rust_wasm(fib-debug wasm32-unknown-unknown)
-create_rust_wasm(tokio wasm32-wasip1)
+create_rust_wasm(tokio wasm32-wasip2)
create_rust_wasm(wasi wasm32-wasip1)
create_rust_wasm(wasi wasm32-wasip2)
create_rust_wasm(component wasm32-unknown-unknown)
@@ -89,6 +89,8 @@ create_target(threads threads.c)
create_target(threads-cpp threads.cc)
create_target(wasip1 wasip1/main.c)
create_target(wasip1-cpp wasip1/main.cc)
+create_target(wasip2 wasip2/main.c)
+create_target(wasip2-cpp wasip2/main.cc)
# Rust examples/tests
if (BUILD_RUST_EXAMPLES)
diff --git a/examples/tokio/main.rs b/examples/tokio/main.rs
index 9feca556e1..4ae8f10a33 100644
--- a/examples/tokio/main.rs
+++ b/examples/tokio/main.rs
@@ -1,13 +1,14 @@
use std::sync::Arc;
use tokio::time::Duration;
-use wasmtime::Error;
-use wasmtime::{Config, Engine, Linker, Module, Store};
-use wasmtime_wasi::{WasiCtx, p1::WasiP1Ctx};
+use wasmtime::component::{Component, Linker, ResourceTable};
+use wasmtime::{Config, Engine, Error, Store};
+use wasmtime_wasi::p2::bindings::Command;
+use wasmtime_wasi::{WasiCtx, WasiCtxView, WasiView};
#[tokio::main]
async fn main() -> Result<(), Error> {
// Create an environment shared by all wasm execution. This contains
- // the `Engine` and the `Module` we are executing.
+ // the `Engine` and the `Component` we are executing.
let env = Environment::new()?;
// The inputs to run_wasm are `Send`: we can create them here and send
@@ -35,11 +36,27 @@ async fn main() -> Result<(), Error> {
Ok(())
}
+/// The per-store host state: a WASI context plus the resource table that
+/// host resources (including WASI) live ni.
+struct ComponentRunStates {
+ wasi_ctx: WasiCtx,
+ resource_table: ResourceTable,
+}
+
+impl WasiView for ComponentRunStates {
+ fn ctx(&mut self) -> WasiCtxView<'_> {
+ WasiCtxView {
+ ctx: &mut self.wasi_ctx,
+ table: &mut self.resource_table,
+ }
+ }
+}
+
#[derive(Clone)]
struct Environment {
engine: Engine,
- module: Module,
- linker: Arc<Linker<WasiP1Ctx>>,
+ component: Component,
+ linker: Arc<Linker<ComponentRunStates>>,
}
impl Environment {
@@ -50,18 +67,19 @@ impl Environment {
config.consume_fuel(true);
let engine = Engine::new(&config)?;
- let module = Module::from_file(&engine, "target/wasm32-wasip1/debug/tokio-wasi.wasm")?;
+ let component =
+ Component::from_file(&engine, "target/wasm32-wasip2/debug/tokio-wasi.wasm")?;
// A `Linker` is shared in the environment amongst all stores, and this
- // linker is used to instantiate the `module` above. This example only
- // adds WASI functions to the linker, notably the async versions built
- // on tokio.
+ // linker is used to instantiate the `component` above. This example
+ // only adds WASI functions to the linker, notably the async versions
+ // built on tokio.
let mut linker = Linker::new(&engine);
- wasmtime_wasi::p1::add_to_linker_async(&mut linker, |cx| cx)?;
+ wasmtime_wasi::p2::add_to_linker_async(&mut linker)?;
Ok(Self {
engine,
- module,
+ component,
linker: Arc::new(linker),
})
}
@@ -87,8 +105,12 @@ async fn run_wasm(inputs: Inputs) -> Result<(), Error> {
.inherit_stdout()
// Set an environment variable so the wasm knows its name.
.env("NAME", &inputs.name)
- .build_p1();
- let mut store = Store::new(&inputs.env.engine, wasi);
+ .build();
+ let state = ComponentRunStates {
+ wasi_ctx: wasi,
+ resource_table: ResourceTable::new(),
+ };
+ let mut store = Store::new(&inputs.env.engine, state);
// Put effectively unlimited fuel so it can run forever.
store.set_fuel(u64::MAX)?;
@@ -97,16 +119,14 @@ async fn run_wasm(inputs: Inputs) -> Result<(), Error> {
store.fuel_async_yield_interval(Some(10000))?;
// Instantiate into our own unique store using the shared linker, afterwards
- // acquiring the `_start` function for the module and executing it.
- let instance = inputs
- .env
- .linker
- .instantiate_async(&mut store, &inputs.env.module)
- .await?;
- instance
- .get_typed_func::<(), ()>(&mut store, "_start")?
- .call_async(&mut store, ())
- .await?;
+ // acquiring the `wasi:cli/run` export of the component and executing it.
+ let command =
+ Command::instantiate_async(&mut store, &inputs.env.component, &inputs.env.linker).await?;
+ command
+ .wasi_cli_run()
+ .call_run(&mut store)
+ .await?
+ .map_err(|()| wasmtime::format_err!("{} exited with an error", inputs.name))?;
Ok(())
}
diff --git a/examples/wasip2/main.c b/examples/wasip2/main.c
new file mode 100644
index 0000000000..dce3044590
--- /dev/null
+++ b/examples/wasip2/main.c
@@ -0,0 +1,158 @@
+/*
+Example of instantiating a WebAssembly component which uses WASIp2 imports.
+
+You can compile and run this example on Linux with:
+
+ cargo build --target wasm32-wasip2 -p example-wasi-wasm
+ cargo build --release -p wasmtime-c-api
+ cc examples/wasip2/main.c \
+ -I crates/c-api/include \
+ target/release/libwasmtime.a \
+ -lpthread -ldl -lm \
+ -o wasip2
+ ./wasip2
+
+Note that on Windows and macOS the command will be similar, but you'll need
+to tweak the `-lpthread` and such annotations.
+
+You can also build and run this example using cmake:
+
+ cargo build --target wasm32-wasip2 -p example-wasi-wasm
+ cmake -B build -S examples
+ cmake --build build --target wasmtime-wasip2
+ ./build/wasmtime-wasip2
+*/
+
+#include <assert.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <wasi.h>
+#include <wasm.h>
+#include <wasmtime.h>
+
+static void exit_with_error(const char *message, wasmtime_error_t *error,
+ wasm_trap_t *trap);
+
+int main() {
+ // Set up our context
+ wasm_engine_t *engine = wasm_engine_new();
+ assert(engine != NULL);
+ wasmtime_store_t *store = wasmtime_store_new(engine, NULL, NULL);
+ assert(store != NULL);
+ wasmtime_context_t *context = wasmtime_store_context(store);
+
+ // Create a component linker with WASIp2 functions defined
+ wasmtime_component_linker_t *linker = wasmtime_component_linker_new(engine);
+ wasmtime_error_t *error = wasmtime_component_linker_add_wasip2(linker);
+ if (error != NULL)
+ exit_with_error("failed to link wasi", error, NULL);
+
+ wasm_byte_vec_t wasm;
+ // Load our input file to parse it next
+ FILE *file = fopen("target/wasm32-wasip2/debug/wasi.wasm", "rb");
+ if (!file) {
+ printf("> Error loading file!\n");
+ exit(1);
+ }
+ fseek(file, 0L, SEEK_END);
+ size_t file_size = ftell(file);
+ wasm_byte_vec_new_uninitialized(&wasm, file_size);
+ fseek(file, 0L, SEEK_SET);
+ if (fread(wasm.data, file_size, 1, file) != 1) {
+ printf("> Error loading component!\n");
+ exit(1);
+ }
+ fclose(file);
+
+ // Compile our component
+ wasmtime_component_t *component = NULL;
+ error = wasmtime_component_new(engine, (uint8_t *)wasm.data, wasm.size,
+ &component);
+ if (!component)
+ exit_with_error("failed to compile component", error, NULL);
+ wasm_byte_vec_delete(&wasm);
+
+ // Create a WASI context and put it in the store; all instances in the store
+ // share this context. `wasi_config_t` provides a number of ways to configure
+ // what the target program will have access to.
+ wasi_config_t *wasi_config = wasi_config_new();
+ assert(wasi_config);
+ wasi_config_inherit_argv(wasi_config);
+ wasi_config_inherit_env(wasi_config);
+ wasi_config_inherit_stdin(wasi_config);
+ wasi_config_inherit_stdout(wasi_config);
+ wasi_config_inherit_stderr(wasi_config);
+ error = wasmtime_context_set_wasi(context, wasi_config);
+ if (error != NULL)
+ exit_with_error("failed to instantiate WASI", error, NULL);
+
+ // Instantiate the component
+ wasmtime_component_instance_t instance;
+ error = wasmtime_component_linker_instantiate(linker, context, component,
+ &instance);
+ if (error != NULL)
+ exit_with_error("failed to instantiate component", error, NULL);
+
+ // Look up the `run` function in the exported `wasi:cli/[email protected]` interface.
+ // First look up the interface itself, then the function within it.
+ const char *interface_name = "wasi:cli/[email protected]";
+ wasmtime_component_export_index_t *interface_idx =
+ wasmtime_component_instance_get_export_index(
+ &instance, context, NULL, interface_name, strlen(interface_name));
+ if (interface_idx == NULL) {
+ fprintf(stderr, "error: cannot find `%s` interface\n", interface_name);
+ exit(1);
+ }
+ wasmtime_component_export_index_t *func_idx =
+ wasmtime_component_instance_get_export_index(&instance, context,
+ interface_idx, "run", 3);
+ if (func_idx == NULL) {
+ fprintf(stderr, "error: cannot find `run` function in `%s` interface\n",
+ interface_name);
+ exit(1);
+ }
+ wasmtime_component_func_t func;
+ bool found =
+ wasmtime_component_instance_get_func(&instance, context, func_idx, &func);
+ assert(found);
+ wasmtime_component_export_index_delete(func_idx);
+ wasmtime_component_export_index_delete(interface_idx);
+
+ // Run it. The `run` function takes no arguments and returns a single
+ // `result<(), ()>` value indicating whether the program succeeded.
+ wasmtime_component_val_t result = {.kind = WASMTIME_COMPONENT_BOOL};
+ error = wasmtime_component_func_call(&func, context, NULL, 0, &result, 1);
+ if (error != NULL)
+ exit_with_error("error calling `run`", error, NULL);
+ assert(result.kind == WASMTIME_COMPONENT_RESULT);
+ bool ok = result.of.result.is_ok;
+ wasmtime_component_val_delete(&result);
+ if (!ok) {
+ fprintf(stderr, "error: program returned an error\n");
+ exit(1);
+ }
+
+ // Clean up after ourselves at this point
+ wasmtime_component_linker_delete(linker);
+ wasmtime_component_delete(component);
+ wasmtime_store_delete(store);
+ wasm_engine_delete(engine);
+ 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);
+}
diff --git a/examples/wasip2/main.cc b/examples/wasip2/main.cc
new file mode 100644
index 0000000000..e867c46429
--- /dev/null
+++ b/examples/wasip2/main.cc
@@ -0,0 +1,86 @@
+/*
+Example of instantiating a WebAssembly component which uses WASIp2 imports.
+
+You can build and run the example using CMake:
+
+ cargo build --target wasm32-wasip2 -p example-wasi-wasm
+ cmake -B build -S examples
+ cmake --build build --target wasmtime-wasip2-cpp
+ ./build/wasmtime-wasip2-cpp
+*/
+
+#include <array>
+#include <fstream>
+#include <iostream>
+#include <vector>
+#include <wasmtime.hh>
+#include <wasmtime/component.hh>
+
+using namespace wasmtime;
+
+static std::vector<uint8_t> read_binary_file(const char *path) {
+ std::ifstream file(path, std::ios::in | std::ios::binary);
+ if (!file.is_open()) {
+ throw std::runtime_error(std::string("failed to open wasm file: ") + path);
+ }
+ std::vector<uint8_t> data((std::istreambuf_iterator<char>(file)),
+ std::istreambuf_iterator<char>());
+ return data;
+}
+
+int main() {
+ // Create a component linker with the WASIp2 functions defined.
+ Engine engine;
+ component::Linker linker(engine);
+ linker.add_wasip2().unwrap();
+
+ // Create a WASI context and put it in a Store; all instances in the store
+ // share this context. `WasiConfig` provides a number of ways to
+ // configure what the target program will have access to.
+ WasiConfig wasi;
+ wasi.inherit_argv();
+ wasi.inherit_env();
+ wasi.inherit_stdin();
+ wasi.inherit_stdout();
+ wasi.inherit_stderr();
+
+ Store store(engine);
+ auto context = store.context();
+ context.set_wasi(std::move(wasi)).unwrap();
+
+ // Load and compile the wasm component.
+ auto bytes = read_binary_file("target/wasm32-wasip2/debug/wasi.wasm");
+ auto component = component::Component::compile(
+ engine, Span<uint8_t>(bytes.data(), bytes.size()))
+ .unwrap();
+
+ // Instantiate the component with the imports we've defined in the linker.
+ auto instance = linker.instantiate(context, component).unwrap();
+
+ // Look up the `run` function in the exported `wasi:cli/[email protected]` interface.
+ // First look up the interface itself, then the function within it.
+ auto interface_idx =
+ instance.get_export_index(context, nullptr, "wasi:cli/[email protected]");
+ if (!interface_idx) {
+ std::cerr << "error: cannot find `wasi:cli/[email protected]` interface\n";
+ return 1;
+ }
+ auto func_idx = instance.get_export_index(context, &*interface_idx, "run");
+ if (!func_idx) {
+ std::cerr << "error: cannot find `run` function in "
+ "`wasi:cli/[email protected]` interface\n";
+ return 1;
+ }
+ auto func = *instance.get_func(context, *func_idx);
+
+ // Run it. The `run` function takes no arguments and returns a single
+ // `result<(), ()>` value indicating whether the program succeeded.
+ auto results = std::array<component::Val, 1>{false};
+ func.call(context, {}, results).unwrap();
+ if (!results[0].get_result().is_ok()) {
+ std::cerr << "error: program returned an error\n";
+ return 1;
+ }
+
+ return 0;
+}