Skip to content

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

docs: Add an example application that embeds Wasmtime in order to use plugins (#11848)

Tim Chevalier63f094dfc2b0
diff --git a/.github/actions/install-plugins-prerequisites/action.yml b/.github/actions/install-plugins-prerequisites/action.yml
new file mode 100644
index 0000000000..d3cd404cfd
--- /dev/null
+++ b/.github/actions/install-plugins-prerequisites/action.yml
@@ -0,0 +1,19 @@
+name: 'Install prerequisites for plugins example'
+description: 'Install prerequisites for plugins example'
+
+runs:
+ using: composite
+ steps:
+ - name: Install WASI SDK (Linux)
+ run: wget https://github.com/WebAssembly/wasi-sdk/releases/download/wasi-sdk-27/wasi-sdk-27.0-x86_64-linux.tar.gz -P ${{ runner.temp }} && tar xf ${{ runner.temp }}/wasi-sdk-27.0-x86_64-linux.tar.gz -C ${{ runner.temp }} && echo WASI_SDK_PATH=${{ runner.temp }}/wasi-sdk-27.0-x86_64-linux >> $GITHUB_ENV
+ if: runner.os == 'Linux'
+ shell: bash
+ - name: Install wit-bindgen (Linux)
+ run: cargo install [email protected]
+ if: runner.os == 'Linux'
+ shell: bash
+ - name: Install jco (Linux)
+ run: npm install --global @bytecodealliance/[email protected] && npm install --global @bytecodealliance/[email protected]
+ if: runner.os == 'Linux'
+ shell: bash
+
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml
index a2fc5dd508..c650765e7c 100644
--- a/.github/workflows/main.yml
+++ b/.github/workflows/main.yml
@@ -298,6 +298,7 @@ jobs:
--exclude wasmtime-wasi-nn \
--exclude wasmtime-fuzzing \
--exclude wasm-spec-interpreter \
+ --exclude calculator \
--all-features
env:
RUSTDOCFLAGS: --cfg=docsrs
@@ -642,7 +643,8 @@ jobs:
#
# Run this on windows/mac/linux
- os: ubuntu-24.04
- flags: -DBUILD_SHARED_LIBS=ON -DBUILD_TESTS=ON -DBUILD_RUST_EXAMPLES=ON
+ # Only run the "plugins" example on Linux
+ flags: -DBUILD_SHARED_LIBS=ON -DBUILD_TESTS=ON -DBUILD_RUST_EXAMPLES=ON -DBUILD_RUST_PLUGINS_EXAMPLE=ON
name: Linux
- os: macos-15
flags: -DBUILD_SHARED_LIBS=ON -DBUILD_TESTS=ON -DBUILD_RUST_EXAMPLES=ON
@@ -672,6 +674,9 @@ jobs:
- uses: ./.github/actions/install-rust
- run: rustup target add wasm32-wasip2
+ - uses: ./.github/actions/install-plugins-prerequisites
+ if: runner.os == 'Linux'
+
- uses: ilammy/msvc-dev-cmd@0b201ec74fa43914dc39ae48a89fd1d8cb592756
# An ode to MinGW: man you're a pain to work around sometimes
- run: rm /usr/bin/link
diff --git a/Cargo.lock b/Cargo.lock
index 7ac64028d6..f8d9e69267 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -337,6 +337,16 @@ dependencies = [
"pkg-config",
]
+[[package]]
+name = "calculator"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "clap",
+ "wasmtime",
+ "wasmtime-wasi",
+]
+
[[package]]
name = "camino"
version = "1.1.4"
diff --git a/Cargo.toml b/Cargo.toml
index 2e9fc2b78a..f489e16aca 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -172,6 +172,7 @@ members = [
"examples/resource-component/wasm",
"examples/min-platform",
"examples/min-platform/embedding",
+ "examples/wasip2-plugins",
"fuzz",
"winch/codegen",
]
diff --git a/ci/run-tests.py b/ci/run-tests.py
index 8f354788d6..b6a28454b9 100755
--- a/ci/run-tests.py
+++ b/ci/run-tests.py
@@ -16,6 +16,8 @@
# - wasm-spec-interpreter: brings in OCaml which is a pain to configure for all
# targets, tested as part of the wastime-fuzzing CI job.
#
+# - calculator (under examples/wasip2-plugins): an example that's tested separately.
+#
# - veri_engine: requires an SMT solver (z3)
import subprocess
@@ -28,6 +30,7 @@ args.append('--exclude=wasmtime-wasi-tls-nativetls')
args.append('--exclude=wasmtime-fuzzing')
args.append('--exclude=wasm-spec-interpreter')
args.append('--exclude=veri_engine')
+args.append('--exclude=calculator')
args.extend(sys.argv[1:])
result = subprocess.run(args)
diff --git a/docs/SUMMARY.md b/docs/SUMMARY.md
index 2ee46ed707..9990f3b346 100644
--- a/docs/SUMMARY.md
+++ b/docs/SUMMARY.md
@@ -19,6 +19,7 @@
- [Multithreaded Embedding](./examples-multithreaded-embedding.md)
- [WASIp1](./examples-wasip1.md)
- [WASIp2](./examples-wasip2.md)
+ - [An Application with Plugins](./wasip2-plugins.md)
- [Core Dumps](./examples-core-dumps.md)
- [Memory Protection Keys](./examples-mpk.md)
- [Async Host Functions](./examples-async.md)
diff --git a/docs/wasip2-plugins.md b/docs/wasip2-plugins.md
new file mode 100644
index 0000000000..fbc6db3a92
--- /dev/null
+++ b/docs/wasip2-plugins.md
@@ -0,0 +1,292 @@
+# Calculator with WebAssembly Plugins
+
+This example demonstrates how to embed Wasmtime
+to create an application that uses plugins.
+The plugins are WebAssembly components.
+
+You can [browse this source code online](https://github.com/bytecodealliance/wasmtime/blob/main/examples/wasip2-plugins)
+and clone the wasmtime repository to run this example locally.
+
+This application is a simplified version of the application presented
+in Sy Brand's blog post
+["Building Native Plugin Systems with WebAssembly Components "](https://tartanllama.xyz/posts/wasm-plugins/).
+Consult that blog post for a more complex example of embedding Wasmtime
+and using plugins.
+
+## The calculator
+
+The calculator being implemented is very simple;
+it takes an expression represented in prefix form, without parentheses,
+on the command line. For example:
+
+```
+target/release/calculator --plugins plugins/ add 1 2
+```
+
+or
+
+```
+target/release/calculator --plugins plugins/ subtract -1 -2
+```
+
+The set of operations available is defined by the set of plugins present in
+the `plugins/` directory.
+
+Each plugin is a component that supports two operations:
+* `get_plugin_name`: Returns the name of the arithmetic operation
+ that this plugin implements.
+* `evaluate`: Takes two signed integer arguments and returns the result
+ of evaluating the operation on the arguments.
+
+Two example plugins are included: an `add` plugin implemented in C,
+and a `subtract` plugin implemented in JavaScript.
+Running `cargo build --release` will generate the plugins:
+`c-plugin/add.wasm` and `js-plugin/subtract.wasm`.
+To run the code, you should copy both of these files into the
+`plugins/` directory that you provide with the `--plugins` option.
+
+> To build the plugins, you must install `wit-bindgen` and the WASI SDK
+> (for building the C plugin) and `jco` (for building the JavaScript
+> plugin). For instructions, see [the C/C++ section](https://component-model.bytecodealliance.org/language-support/c.html)
+> and [the JavaScript section](https://component-model.bytecodealliance.org/language-support/javascript.html)
+> of the [Component Model documentation](https://component-model.bytecodealliance.org/).
+
+There are no nested expressions.
+
+## WIT bindings
+
+To define the interface for the plugins, we have to create a `.wit` file.
+The contents of this file are:
+
+```wit
+package docs:calculator;
+
+interface host {}
+
+world plugin {
+ import host;
+
+ export get-plugin-name: func() -> string;
+ export evaluate: func(x: s32, y: s32) -> s32;
+}
+```
+
+The WIT file defines a world that the plugin must implement,
+as well as any imports it can expect its host to provide.
+In this case, the `host` interface is empty, indicating that
+there is no functionality in the host that a plugin can call.
+
+The world has two exports, indicating that the plugin must implement
+two functions: a `get-plugin-name` function that returns the name
+of the operation that this plugin implements, and an `evaluate` function
+that does computation specific to this plugin.
+
+In the calculator code, we write:
+
+```wit
+bindgen!("plugin");
+```
+
+which uses a macro provided by Wasmtime that automatically runs
+the `wit-bindgen` tool to generate bindings for the world.
+
+## `CalculatorState`
+
+We use the `CalculatorState` type to represent the global state of the program,
+which in this case is just a mapping from strings that represent operation names
+to `PluginDesc`s. A `PluginDesc` represents the information needed in order
+to execute a plugin given arguments.
+
+## Loading plugins
+
+The application takes a directory as a command-line argument,
+which is expected to contain plugins (as .wasm files).
+All plugins in the directory are loaded eagerly.
+
+The `load_plugins()` function starts by calling the Wasmtime library's
+`Engine::default()` function to create an `Engine`:
+
+```rust
+let engine = Engine::default();
+```
+
+An `Engine` is an environment for executing WebAssembly programs.
+Only one `Engine` is needed regardless of how many plugins
+may be executed. For more details, see the [Wasmtime crate documentation](https://docs.rs/wasmtime/latest/wasmtime/#core-concepts).
+
+Next, it passes the engine to the Wasmtime library's `Linker::new()`
+function to create a `Linker`. A `Linker` is parameterized over a state
+type.
+In this application, we don't need per-plugin state
+(plugins implement pure functions), so the state type is `()` (the unit type).
+
+```rust
+let linker: Linker<()> = Linker::new(&engine);
+```
+
+As with the `Engine`, only one `Linker` is needed for the whole application.
+A `Linker` can be used to define functions in the host (in this case, the
+calculator application) that can be called by guests (in this case, plugins
+loaded by the calculator). We don't define any such functions in our host,
+so the linker is only used as an argument to the `instantiate()` function
+(which we'll see a little bit later).
+
+The remaining code checks that the provided path for the plugins directory
+exists and is really a directory, and if so, calls `load_plugin()` on
+each file in the directory that has the `.wasm` extension:
+
+```rust
+ if !plugins_dir.is_dir() {
+ anyhow::bail!("plugins directory does not exist");
+ }
+
+ for entry in fs::read_dir(plugins_dir)? {
+ let path = entry?.path();
+ if path.is_file() && path.extension().and_then(OsStr::to_str) == Some("wasm") {
+ load_plugin(state, &engine, &linker, path)?;
+ }
+ }
+```
+
+Next let's look at the `load_plugin()` function, which loads a single plugin.
+The function begins by calling the Wasmtime library's `Component::from_file()`
+function, which takes an `Engine` and the name of a binary WebAssembly file.
+
+```rust
+let component = Component::from_file(engine, &path)?;
+```
+
+`from_file()` loads and compiles WebAssembly code and creates
+the in-memory representation of a component, which we assign to
+the variable `component`.
+
+The next block of code creates the dynamic representation
+of the component, which has all the resources it needs and can have its
+functions called:
+
+```rust
+ let (plugin_name, plugin, store) = {
+ let mut store = Store::new(engine, ());
+ let plugin = Plugin::instantiate(&mut store, &component, linker)?;
+ (plugin.call_get_plugin_name(&mut store)?, plugin, store)
+ };
+```
+
+First, it calls the Wasmtime library's `Store::new` function to create a `Store`.
+A [`Store`](https://docs.rs/wasmtime/latest/wasmtime/#core-concepts)
+represents the state of a particular component. Unlike an `Engine`, it's specific
+to each unit of code and so it can't be re-used across different plugins.
+The `Store` type is parameterized with a state type `T`, and the third argument
+to `Store::new` must have type `T`.
+Since we don't use host state in this example,
+we pass in `()`, which has type `()`; so we get a `Store<()>` back.
+
+Next, it calls the `Plugin::instantiate()` function, which was generated
+automatically by the `bindgen!("plugin")` macro.
+The function takes the `Store` we just created,
+the `Component` that represents the code for the plugin,
+and the `Linker` that was passed in to `load_plugin()`.
+`instantiate()` returns a `Plugin`.
+The `Plugin` type corresponds to the `plugin` world from our `.wit` file,
+and was also automatically generated by the `bindgen!` macro.
+
+Now that we have a fully instantiated plugin, we can call its
+`get-plugin-name` function. The `call_get_plugin_name` method was
+generated by the `bindgen!` macro; notice that the name
+`call_get_plugin_name` is the same as `get-plugin-name` from the `.wit` file,
+but with underscores in place of hyphens, and is prefixed by `call_`.
+This method takes a `Store`, which in general allows use of host state
+by the implementation of the method in the plugin, though not in this case
+(since we have a `Store<()>`).
+
+Finally, we update the calculator's state by associating the plugin name
+with a structure containing the plugin and store:
+
+```rust
+ state
+ .plugin_descs
+ .insert(plugin_name, PluginDesc { plugin, store });
+```
+
+## Running the code
+
+Finally, this line of code is responsible for actually evaluating the
+expression that was provided on the command line:
+
+```rust
+args.op.run(&mut state)
+```
+
+The `BinaryOperation` struct has a `run` method that looks like this:
+
+```rust
+ fn run(self, state: &mut CalculatorState) -> anyhow::Result<()> {
+ let desc = lookup_plugin(state, self.op.as_ref())?;
+ let result = desc.plugin.call_evaluate(&mut desc.store, self.x, self.y)?;
+ println!("{}({}, {}) = {}", self.op, self.x, self.y, result);
+ Ok(())
+ }
+```
+
+First, it calls `lookup_plugin`, which simply looks up the operation
+name (`self.op`, which is just the name that was given on the command line)
+in the hash table that was created by `load_plugins()`.
+This returns a `PluginDesc`, which is defined as:
+
+```rust
+pub struct PluginDesc {
+ pub plugin: Plugin,
+ pub store: wasmtime::Store<()>,
+}
+```
+
+Remember, the type `Plugin` corresponds to the `plugin` world and was
+generated automatically by the `bindgen!` macro.
+
+The next line of code:
+
+```rust
+let result = desc.plugin.call_evaluate(&mut desc.store, self.x, self.y)?;
+```
+
+is the one that actually calls into the plugin to do the computation.
+The bindings generator guarantees that a `Plugin` has an `evaluate`
+method, which we call using `call_evaluate` (the name it was given
+by the bindings generator).
+Like `call_get_plugin_name`, it takes a `Store` as the first argument.
+The other two arguments are the ones given on the command line.
+`result` is a 32-bit integer (`i32`) because that's the return type
+of `call_evaluate()`.
+
+Finally, we print the result to `stdout`.
+
+## Writing the plugins
+
+So far we've assumed that the `plugins` directory is populated
+with plugins for all the arithmetic operations we want.
+How do we actually write the plugins?
+The [component model documentation](https://component-model.bytecodealliance.org)
+documents how to generate WebAssembly components from various programming languages.
+
+As part of this sample application, two plugins are provided,
+one in `c-plugin/` (implementing the `add` operation), and one in `js-plugin/`
+(implementing the `subtract`) operation.
+The `build.rs` script shows how the code is built.
+
+Any number of plugins could be added, compiled from any language that
+has a toolchain with WebAssembly support, implementing any other arithmetic
+operations.
+
+## Wrapping up
+
+This is a minimal example showing how to embed Wasmtime to create an
+application with dynamically loaded plugins.
+The application could be extended in various ways:
+
+* Allow nested expressions (like `add(subtract(1, 2), 3)`)
+* Add floating-point operations
+* Add unary expressions (like `sqrt(2)`)
+
+The basic mechanism for loading plugins would still be the same,
+with only the application-specific logic changing.
+
diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt
index f8494b9319..ee083133df 100644
--- a/examples/CMakeLists.txt
+++ b/examples/CMakeLists.txt
@@ -115,3 +115,7 @@ if (BUILD_RUST_EXAMPLES)
create_rust_test(component)
create_rust_test(resource-component)
endif()
+
+if (BUILD_RUST_PLUGINS_EXAMPLE)
+ add_test(NAME wasip2-plugins-rust COMMAND cargo build --features build-plugins WORKING_DIRECTORY ../../examples/wasip2-plugins)
+endif()
diff --git a/examples/wasip2-plugins/.gitignore b/examples/wasip2-plugins/.gitignore
new file mode 100644
index 0000000000..b5deb5244a
--- /dev/null
+++ b/examples/wasip2-plugins/.gitignore
@@ -0,0 +1,4 @@
+*.wasm
+c-plugin/plugin.c
+c-plugin/plugin.h
+c-plugin/plugin_component_type.o
diff --git a/examples/wasip2-plugins/Cargo.toml b/examples/wasip2-plugins/Cargo.toml
new file mode 100644
index 0000000000..7652628b92
--- /dev/null
+++ b/examples/wasip2-plugins/Cargo.toml
@@ -0,0 +1,18 @@
+[package]
+name = "calculator"
+version = "0.1.0"
+edition = "2024"
+description = """
+Example Rust-based WebAssembly host that implements a calculator
+with plugins for arithmetic operations.
+"""
+publish = false
+
+[dependencies]
+anyhow = { workspace = true }
+clap = { workspace = true, features = ["derive"] }
+wasmtime = { workspace = true, features = ['std', 'cranelift'] }
+wasmtime-wasi = { workspace = true }
+
+[features]
+build-plugins = []
diff --git a/examples/wasip2-plugins/README.md b/examples/wasip2-plugins/README.md
new file mode 100644
index 0000000000..daf80f3460
--- /dev/null
+++ b/examples/wasip2-plugins/README.md
@@ -0,0 +1,13 @@
+Build with `cargo build --release`
+
+Then, create a plugins directory (e.g. `plugins`) and copy `c-plugin/add.wasm`
+and `js-plugin/subtract.wasm` into that directory.
+
+Finally, run (for example):
+
+`target/release/calculator --plugins plugins add 1 2`
+or
+`target/release/calculator --plugins plugins subtract 1 2`
+
+For more details, see the ["Calculator with WebAssembly Plugins"](http://docs.wasmtime.dev/wasip2-plugins.html)
+section of the documentation.
diff --git a/examples/wasip2-plugins/build.rs b/examples/wasip2-plugins/build.rs
new file mode 100644
index 0000000000..7cdff827b8
--- /dev/null
+++ b/examples/wasip2-plugins/build.rs
@@ -0,0 +1,81 @@
+use std::env;
+use std::path::Path;
+use std::process::Command;
+use std::process::exit;
+
+#[allow(dead_code)]
+fn build_c_plugin() {
+ // Run wit-bindgen
+ let mut status = Command::new("wit-bindgen")
+ .args(["c", "../wit/calculator.wit"])
+ .current_dir("c-plugin")
+ .status()
+ .expect("wit-bindgen c ../wit/calculator.wit failed (cwd = c-plugin)");
+ if !status.success() {
+ println!(
+ "wit-bindgen c ../wit/calculator.wit failed (cwd = c-plugin): status {}",
+ status
+ );
+ exit(1);
+ }
+
+ // Check that wasi-sdk is installed
+ let wasi_sdk_path = env::var("WASI_SDK_PATH");
+ if wasi_sdk_path.is_err() {
+ println!("You must set WASI_SDK_PATH to the location where you installed the WASI SDK");
+ exit(1);
+ }
+ // Compile the plugin
+ let clang_path = Path::new(&wasi_sdk_path.unwrap()).join("bin/wasm32-wasip2-clang");
+ status = Command::new(&clang_path)
+ .args([
+ "-o",
+ "add.wasm",
+ "-mexec-model=reactor",
+ "add.c",
+ "plugin.c",
+ "plugin_component_type.o",
+ ])
+ .current_dir("c-plugin")
+ .status()
+ .unwrap_or_else(|_| {
+ panic!(
+ "{} failed to compile the plugin (cwd = c-plugin)",
+ clang_path.display()
+ )
+ });
+ if !status.success() {
+ println!(
+ "{} failed to compile the plugin (cwd = c-plugin): status {}",
+ clang_path.display(),
+ status
+ );
+ exit(1);
+ }
+}
+
+#[allow(dead_code)]
+fn build_js_plugin() {
+ Command::new("jco")
+ .args([
+ "componentize",
+ "--wit",
+ "../wit/calculator.wit",
+ "--world-name",
+ "plugin",
+ "--out",
+ "subtract.wasm",
+ "--disable=all",
+ "subtract.js",
+ ])
+ .current_dir("js-plugin")
+ .status()
+ .expect("jco componentize failed (is jco installed?) (cwd = js-plugin)");
+}
+
+fn main() {
+ #[cfg(feature = "build-plugins")]
+ build_c_plugin();
+ #[cfg(feature = "build-plugins")]
+ build_js_plugin();
+}
diff --git a/examples/wasip2-plugins/c-plugin/add.c b/examples/wasip2-plugins/c-plugin/add.c
new file mode 100644
index 0000000000..ee9e362962
--- /dev/null
+++ b/examples/wasip2-plugins/c-plugin/add.c
@@ -0,0 +1,7 @@
+#include "plugin.h"
+
+void exports_plugin_get_plugin_name(plugin_string_t *ret) {
+ plugin_string_set(ret, "add");
+}
+
+int32_t exports_plugin_evaluate(int32_t x, int32_t y) { return x + y; }
diff --git a/examples/wasip2-plugins/js-plugin/subtract.js b/examples/wasip2-plugins/js-plugin/subtract.js
new file mode 100644
index 0000000000..33811d9228
--- /dev/null
+++ b/examples/wasip2-plugins/js-plugin/subtract.js
@@ -0,0 +1,9 @@
+export function evaluate(x, y) {
+ return x - y;
+}
+
+
+export function getPluginName(x, y) {
+ return "subtract";
+}
+
diff --git a/examples/wasip2-plugins/src/main.rs b/examples/wasip2-plugins/src/main.rs
new file mode 100644
index 0000000000..1195ff48c5
--- /dev/null
+++ b/examples/wasip2-plugins/src/main.rs
@@ -0,0 +1,137 @@
+use anyhow::anyhow;
+use clap::Parser;
+use std::collections::HashMap;
+use std::ffi::OsStr;
+use std::fs;
+use std::path::{Path, PathBuf};
+use wasmtime::component::{Component, Linker, bindgen};
+use wasmtime::{Engine, Store};
+
+// Generates bindings for the plugin world defined in the wit/calculator.wit file.
+bindgen!("plugin");
+
+/// A CLI that implements a plugin-based calculator whose
+/// operations are implemented by independent WebAssembly components.
+
+#[derive(Parser)]
+struct BinaryOperation {
+ /// The name of the operation
+ op: String,
+ /// The first operand
+ x: i32,
+ /// The second operand
+ y: i32,
+}
+
+fn lookup_plugin<'a>(
+ state: &'a mut CalculatorState,
+ op: &str,
+) -> anyhow::Result<&'a mut PluginDesc> {
+ state
+ .plugin_descs
+ .get_mut(op)
+ .ok_or(anyhow!("unknown operation {}", op))
+}
+
+impl BinaryOperation {
+ fn run(self, state: &mut CalculatorState) -> anyhow::Result<()> {
+ let desc = lookup_plugin(state, self.op.as_ref())?;
+ let result = desc.plugin.call_evaluate(&mut desc.store, self.x, self.y)?;
+ println!("{}({}, {}) = {}", self.op, self.x, self.y, result);
+ Ok(())
+ }
+}
+
+pub struct CalculatorState {
+ // Mapping from operation names to descriptors for the plugins
+ pub plugin_descs: HashMap<String, PluginDesc>,
+}
+
+impl Default for CalculatorState {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl CalculatorState {
+ pub fn new() -> Self {
+ CalculatorState {
+ plugin_descs: HashMap::new(),
+ }
+ }
+}
+
+pub struct PluginDesc {
+ pub plugin: Plugin,
+ pub store: wasmtime::Store<()>,
+}
+
+fn load_plugin(
+ state: &mut CalculatorState,
+ engine: &Engine,
+ linker: &Linker<()>,
+ path: PathBuf,
+) -> wasmtime::Result<()> {
+ println!("Loading plugin from file {:?}", path);
+
+ // Creates a component from a .wasm file
+ let component = Component::from_file(engine, &path)?;
+
+ let (plugin_name, plugin, store) = {
+ // Creates a Store for each plugin.
+ // A Store represents dynamic state, so each plugin
+ // has its own Store.
+ let mut store = Store::new(engine, ());
+ // Instantiate the plugin to the store we just created.
+ let plugin = Plugin::instantiate(&mut store, &component, linker)?;
+ (plugin.call_get_plugin_name(&mut store)?, plugin, store)
+ };
+
+ state
+ .plugin_descs
+ .insert(plugin_name, PluginDesc { plugin, store });
+
+ Ok(())
+}
+
+fn load_plugins(state: &mut CalculatorState, plugins_dir: &Path) -> wasmtime::Result<()> {
+ let engine = Engine::default();
+ let linker: Linker<()> = Linker::new(&engine);
+
+ if !plugins_dir.is_dir() {
+ anyhow::bail!("plugins directory does not exist");
+ }
+
+ for entry in fs::read_dir(plugins_dir)? {
+ let path = entry?.path();
+ if path.is_file() && path.extension().and_then(OsStr::to_str) == Some("wasm") {
+ load_plugin(state, &engine, &linker, path)?;
+ }
+ }
+ Ok(())
+}
+
+#[derive(Parser)]
+#[command(name = "calculator-host", version = env!("CARGO_PKG_VERSION"))]
+#[command(about = "A calculator with plugin support")]
+struct Args {
+ #[command(flatten)]
+ op: BinaryOperation,
+
+ #[arg(long, help = "Plugin directory")]
+ plugins: PathBuf,
+}
+
+fn main() -> anyhow::Result<()> {
+ // Get plugins directory
+ let args = Args::parse();
+
+ // Initialize mapping from plugin names to plugins
+ let mut state = CalculatorState::new();
+
+ // Load plugins from plugins directory
+ load_plugins(&mut state, args.plugins.as_path())?;
+
+ // Evaluate the expression given on the command line
+ args.op.run(&mut state)
+}
diff --git a/examples/wasip2-plugins/wit/calculator.wit b/examples/wasip2-plugins/wit/calculator.wit
new file mode 100644
index 0000000000..908aeacc1a
--- /dev/null
+++ b/examples/wasip2-plugins/wit/calculator.wit
@@ -0,0 +1,10 @@
+package docs:calculator;
+
+interface host {}
+
+world plugin {
+ import host;
+
+ export get-plugin-name: func() -> string;
+ export evaluate: func(x: s32, y: s32) -> s32;
+}
\ No newline at end of file