A lightweight WebAssembly runtime that is fast, secure, and standards-compliant
[docs] Add C++ chapter and missing examples (#11569)
Till Schneidereiteaa01d7b8221
diff --git a/README.md b/README.mdindex cc1b1b2635..8d54b8ee05 100644--- a/README.md+++ b/README.md@@ -139,8 +139,8 @@ the implementation.Languages supported by the Bytecode Alliance:* **[Rust]** - the [`wasmtime` crate]-* **[C]** - the [`wasm.h`, `wasi.h`, and `wasmtime.h` headers][c-headers], [CMake](crates/c-api/CMakeLists.txt) or [`wasmtime` Conan package]-* **C++** - the [`wasmtime.hh` header][c-headers] or the [`wasmtime-cpp` Conan package]+* **[C]** - the [`wasm.h`, `wasi.h`, and `wasmtime.h` headers][c-headers], [CMake](crates/c-api/CMakeLists.txt)+* **C++** - the [`wasmtime.hh` header][c-headers]* **[Python]** - the [`wasmtime` PyPI package]* **[.NET]** - the [`Wasmtime` NuGet package]* **[Go]** - the [`wasmtime-go` repository]@@ -161,8 +161,6 @@ Languages supported by the community:[`Wasmtime` NuGet package]: https://www.nuget.org/packages/Wasmtime[Go]: https://bytecodealliance.github.io/wasmtime/lang-go.html[`wasmtime-go` repository]: https://pkg.go.dev/github.com/bytecodealliance/wasmtime-go-[`wasmtime` Conan package]: https://conan.io/center/wasmtime-[`wasmtime-cpp` Conan package]: https://conan.io/center/wasmtime-cpp[Ruby]: https://bytecodealliance.github.io/wasmtime/lang-ruby.html[`wasmtime` gem]: https://rubygems.org/gems/wasmtime[Elixir]: https://docs.wasmtime.dev/lang-elixir.htmldiff --git a/crates/c-api/include/wasmtime.hh b/crates/c-api/include/wasmtime.hhindex a779ce25cd..9a7c11cb4a 100644--- a/crates/c-api/include/wasmtime.hh+++ b/crates/c-api/include/wasmtime.hh@@ -19,8 +19,13 @@* \example gcd.cc* \example linking.cc* \example memory.cc+ * \example multimemory.cc* \example interrupt.cc+ * \example multi.cc+ * \example anyref.cc* \example externref.cc+ * \example serialize.cc+ * \example threads.cc*//**diff --git a/crates/c-api/include/wasmtime/func.hh b/crates/c-api/include/wasmtime/func.hhindex 58f2b92ceb..29ef2b6323 100644--- a/crates/c-api/include/wasmtime/func.hh+++ b/crates/c-api/include/wasmtime/func.hh@@ -63,9 +63,11 @@ template <typename T> struct WasmType {static const ValKind kind = ValKind::valkind; \static void store(Store::Context cx, wasmtime_val_raw_t *p, \const native &t) { \+ (void)cx; \p->field = t; \} \static native load(Store::Context cx, wasmtime_val_raw_t *p) { \+ (void)cx; \return p->field; \} \};@@ -108,9 +110,13 @@ template <> struct WasmType<V128> {static const bool valid = true;static const ValKind kind = ValKind::V128;static void store(Store::Context cx, wasmtime_val_raw_t *p, const V128 &t) {+ (void)cx;memcpy(&p->v128[0], &t.v128[0], sizeof(wasmtime_v128));}- static V128 load(Store::Context cx, wasmtime_val_raw_t *p) { return p->v128; }+ static V128 load(Store::Context cx, wasmtime_val_raw_t *p) {+ (void)cx;+ return p->v128;+ }};/// A "trait" for a list of types and operations on them, used for `Func::wrap`@@ -139,8 +145,14 @@ template <> struct WasmTypeList<std::monostate> {static const size_t size = 0;static bool matches(ValType::ListRef types) { return types.size() == 0; }static void store(Store::Context cx, wasmtime_val_raw_t *storage,- const std::monostate &t) {}+ const std::monostate &t) {+ (void)cx;+ (void)storage;+ (void)t;+ }static std::monostate load(Store::Context cx, wasmtime_val_raw_t *storage) {+ (void)cx;+ (void)storage;return std::monostate();}static std::vector<ValType> types() { return {}; }@@ -167,8 +179,8 @@ template <typename... T> struct WasmTypeList<std::tuple<T...>> {t);}static std::tuple<T...> load(Store::Context cx, wasmtime_val_raw_t *storage) {- size_t n = 0;- return std::tuple<T...>{WasmType<T>::load(cx, &storage[n++])...}; // NOLINT+ (void)cx;+ return std::tuple<T...>{WasmType<T>::load(cx, storage++)...}; // NOLINT}static std::vector<ValType> types() { return {WasmType<T>::kind...}; }};@@ -195,6 +207,8 @@ template <> struct WasmHostRet<void> {template <typename F, typename... A>static std::optional<Trap> invoke(F f, Caller cx, wasmtime_val_raw_t *raw,A... args) {+ (void)cx;+ (void)raw;f(args...);return std::nullopt;}@@ -331,6 +345,7 @@ class Func {raw_callback_unchecked(void *env, wasmtime_caller_t *caller,wasmtime_val_raw_t *args_and_results,size_t nargs_and_results) {+ (void)nargs_and_results;using HostFunc = WasmHostFunc<F>;Caller cx(caller);F *func = reinterpret_cast<F *>(env); // NOLINTdiff --git a/crates/c-api/include/wasmtime/global.hh b/crates/c-api/include/wasmtime/global.hhindex faa00aa2e2..cbc9ee1ff6 100644--- a/crates/c-api/include/wasmtime/global.hh+++ b/crates/c-api/include/wasmtime/global.hh@@ -61,7 +61,7 @@ public:Val get(Store::Context cx) const {Val val;wasmtime_global_get(cx.ptr, &global, &val.val);- return std::move(val);+ return val;}/// Sets this global to a new value.diff --git a/docs/SUMMARY.md b/docs/SUMMARY.mdindex d5e2ba189d..d9b0bbab4d 100644--- a/docs/SUMMARY.md+++ b/docs/SUMMARY.md@@ -11,19 +11,43 @@- [Hello, world!](./examples-rust-hello-world.md)- [Calculating the GCD](./examples-rust-gcd.md)- [Using Linear Memory](./examples-rust-memory.md)- - [WASI](./examples-rust-wasi.md)+ - [WASIp2](./examples-rust-wasip2.md)- [Linking Modules](./examples-rust-linking.md)- [Debugging](./examples-rust-debugging.md)- [Core Dumps](./examples-rust-core-dumps.md)- [Using Multi-Value](./examples-rust-multi-value.md)+ - [`anyref` Reference Type](./examples-rust-anyref.md)+ - [`externref` Reference Type](./examples-rust-externref.md)+ - [Multiple Memories](./examples-rust-multimemory.md)+ - [Serializing Modules](./examples-rust-serialize.md)+ - [Multithreaded Embedding](./examples-rust-multithreaded-embedding.md)+ - [Memory Protection Keys](./examples-rust-mpk.md)- [C](./lang-c.md)- [Hello, World!](./examples-c-hello-world.md)- [Calculating the GCD](./examples-c-gcd.md)- [Using Linear Memory](./examples-c-memory.md)- - [WASI](./examples-c-wasi.md)+ - [WASIp1](./examples-c-wasi.md)- [Linking Modules](./examples-c-linking.md)- [Debugging](./examples-c-debugging.md)- [Using Multi-Value](./examples-c-multi-value.md)+ - [`anyref` Reference Type](./examples-c-anyref.md)+ - [`externref` Reference Type](./examples-c-externref.md)+ - [Multiple Memories](./examples-c-multimemory.md)+ - [Serializing Modules](./examples-c-serialize.md)+ - [Multithreaded Embedding](./examples-c-multithreaded-embedding.md)+ - [C++](./lang-cpp.md)+ - [Hello, World!](./examples-cpp-hello-world.md)+ - [Calculating the GCD](./examples-cpp-gcd.md)+ - [Using Linear Memory](./examples-cpp-memory.md)+ - [WASIp1](./examples-cpp-wasi.md)+ - [Linking Modules](./examples-cpp-linking.md)+ - [Using Multi-Value](./examples-cpp-multi-value.md)+ - [`anyref` Reference Type](./examples-cpp-anyref.md)+ - [`externref` Reference Type](./examples-cpp-externref.md)+ - [Multiple Memories](./examples-cpp-multimemory.md)+ - [Serializing Modules](./examples-cpp-serialize.md)+ - [Multithreaded Embedding](./examples-cpp-multithreaded-embedding.md)+ - [Async Host Functions](./examples-cpp-async.md)- [Python](./lang-python.md)- [.NET](./lang-dotnet.md)- [Go](./lang-go.md)diff --git a/docs/examples-c-anyref.md b/docs/examples-c-anyref.mdnew file mode 100644index 0000000000..a69a0cbcfa--- /dev/null+++ b/docs/examples-c-anyref.md@@ -0,0 +1,20 @@+# Working with `anyref`++You can also [browse this source code online][code] and clone the wasmtime+repository to run the example locally.++[code]: https://github.com/bytecodealliance/wasmtime/blob/main/examples/anyref.c++This example demonstrates using `anyref` values.++## `anyref.wat`++```wat+{{#include ../examples/anyref.wat}}+```++## `anyref.c`++```c+{{#include ../examples/anyref.c}}+```diff --git a/docs/examples-c-embed.md b/docs/examples-c-embed.mddeleted file mode 100644index 57b88955ad..0000000000--- a/docs/examples-c-embed.md+++ /dev/null@@ -1 +0,0 @@-# Cdiff --git a/docs/examples-c-externref.md b/docs/examples-c-externref.mdnew file mode 100644index 0000000000..26708b8a7f--- /dev/null+++ b/docs/examples-c-externref.md@@ -0,0 +1,20 @@+# Working with `externref`++You can also [browse this source code online][code] and clone the wasmtime+repository to run the example locally.++[code]: https://github.com/bytecodealliance/wasmtime/blob/main/examples/externref.c++This example shows how to pass opaque host references into and out of WebAssembly using `externref`.++## `externref.wat`++```wat+{{#include ../examples/externref.wat}}+```++## `externref.c`++```c+{{#include ../examples/externref.c}}+```diff --git a/docs/examples-c-multimemory.md b/docs/examples-c-multimemory.mdnew file mode 100644index 0000000000..d112941cc0--- /dev/null+++ b/docs/examples-c-multimemory.md@@ -0,0 +1,20 @@+# Working with Multiple Memories++You can also [browse this source code online][code] and clone the wasmtime+repository to run the example locally.++[code]: https://github.com/bytecodealliance/wasmtime/blob/main/examples/multimemory.c++This example demonstrates instantiating and interacting with a module that has multiple linear memories.++## `multimemory.wat`++```wat+{{#include ../examples/multimemory.wat}}+```++## `multimemory.c`++```c+{{#include ../examples/multimemory.c}}+```diff --git a/docs/examples-c-multithreaded-embedding.md b/docs/examples-c-multithreaded-embedding.mdnew file mode 100644index 0000000000..a586794218--- /dev/null+++ b/docs/examples-c-multithreaded-embedding.md@@ -0,0 +1,20 @@+# Multithreaded Embedding++You can also [browse this source code online][code] and clone the wasmtime+repository to run the example locally.++[code]: https://github.com/bytecodealliance/wasmtime/blob/main/examples/threads.c++This example demonstrates using Wasmtime in multithreaded runtimes.++## `threads.wat`++```wat+{{#include ../examples/threads.wat}}+```++## `threads.c`++```c+{{#include ../examples/threads.c}}+```diff --git a/docs/examples-c-serialize.md b/docs/examples-c-serialize.mdnew file mode 100644index 0000000000..9f7bd027cb--- /dev/null+++ b/docs/examples-c-serialize.md@@ -0,0 +1,14 @@+# Serializing and Deserializing Modules++You can also [browse this source code online][code] and clone the wasmtime+repository to run the example locally.++[code]: https://github.com/bytecodealliance/wasmtime/blob/main/examples/serialize.c++This example shows how to serialize a compiled module to disk and later deserialize it to skip compilation on the critical path.++## `serialize.c`++```c+{{#include ../examples/serialize.c}}+```diff --git a/docs/examples-c-wasi.md b/docs/examples-c-wasi.mdindex c8b842d3b4..8906562cd8 100644--- a/docs/examples-c-wasi.md+++ b/docs/examples-c-wasi.md@@ -3,7 +3,7 @@You can also [browse this source code online][code] and clone the wasmtimerepository to run the example locally.-[code]: https://github.com/bytecodealliance/wasmtime/blob/main/examples/wasi/main.c+[code]: https://github.com/bytecodealliance/wasmtime/blob/main/examples/wasip1/main.cThis example shows off how to instantiate a wasm module using WASI imports.diff --git a/docs/examples-cpp-anyref.md b/docs/examples-cpp-anyref.mdnew file mode 100644index 0000000000..11186b2050--- /dev/null+++ b/docs/examples-cpp-anyref.md@@ -0,0 +1,20 @@+# Working with `anyref`++You can also [browse this source code online][code] and clone the wasmtime+repository to run the example locally.++[code]: https://github.com/bytecodealliance/wasmtime/blob/main/examples/anyref.cc++This example demonstrates using `anyref` values.++## `anyref.wat`++```wat+{{#include ../examples/anyref.wat}}+```++## `anyref.cc`++```cpp+{{#include ../examples/anyref.cc}}+```diff --git a/docs/examples-cpp-async.md b/docs/examples-cpp-async.mdnew file mode 100644index 0000000000..62ac756c79--- /dev/null+++ b/docs/examples-cpp-async.md@@ -0,0 +1,20 @@+# Asynchronous Host Functions++You can also [browse this source code online][code] and clone the wasmtime+repository to run the example locally.++[code]: https://github.com/bytecodealliance/wasmtime/blob/main/examples/async.cpp++This example demonstrates configuring Wasmtime for asynchronous operation and calling async host functions from wasm.++## `async.wat`++```wat+{{#include ../examples/async.wat}}+```++## `async.cpp`++```cpp+{{#include ../examples/async.cpp}}+```diff --git a/docs/examples-cpp-externref.md b/docs/examples-cpp-externref.mdnew file mode 100644index 0000000000..dc7f17f840--- /dev/null+++ b/docs/examples-cpp-externref.md@@ -0,0 +1,20 @@+# Working with `externref`++You can also [browse this source code online][code] and clone the wasmtime+repository to run the example locally.++[code]: https://github.com/bytecodealliance/wasmtime/blob/main/examples/externref.cc++This example shows how to pass opaque host references into and out of WebAssembly using `externref`.++## `externref.wat`++```wat+{{#include ../examples/externref.wat}}+```++## `externref.cc`++```cpp+{{#include ../examples/externref.cc}}+```diff --git a/docs/examples-cpp-gcd.md b/docs/examples-cpp-gcd.mdnew file mode 100644index 0000000000..2ac579856d--- /dev/null+++ b/docs/examples-cpp-gcd.md@@ -0,0 +1,20 @@+# Calculating the GCD++You can also [browse this source code online][code] and clone the wasmtime+repository to run the example locally.++[code]: https://github.com/bytecodealliance/wasmtime/blob/main/examples/gcd.cc++This example shows off how to run a wasm program which calculates the GCD of two numbers.++## `gcd.wat`++```wat+{{#include ../examples/gcd.wat}}+```++## `gcd.cc`++```cpp+{{#include ../examples/gcd.cc}}+```diff --git a/docs/examples-cpp-hello-world.md b/docs/examples-cpp-hello-world.mdnew file mode 100644index 0000000000..00d136b6a4--- /dev/null+++ b/docs/examples-cpp-hello-world.md@@ -0,0 +1,20 @@+# Hello, world!++You can also [browse this source code online][code] and clone the wasmtime+repository to run the example locally.++[code]: https://github.com/bytecodealliance/wasmtime/blob/main/examples/hello.cc++This example shows off how to instantiate a simple wasm module with a host function import and call an exported function.++## `hello.wat`++```wat+{{#include ../examples/hello.wat}}+```++## `hello.cc`++```cpp+{{#include ../examples/hello.cc}}+```diff --git a/docs/examples-cpp-linking.md b/docs/examples-cpp-linking.mdnew file mode 100644index 0000000000..312695d6f2--- /dev/null+++ b/docs/examples-cpp-linking.md@@ -0,0 +1,26 @@+# Linking modules together++You can also [browse this source code online][code] and clone the wasmtime+repository to run the example locally.++[code]: https://github.com/bytecodealliance/wasmtime/blob/main/examples/linking.cc++This example shows off how to link multiple wasm modules together, where one module imports functions exported by another.++## `linking1.wat`++```wat+{{#include ../examples/linking1.wat}}+```++## `linking2.wat`++```wat+{{#include ../examples/linking2.wat}}+```++## `linking.cc`++```cpp+{{#include ../examples/linking.cc}}+```diff --git a/docs/examples-cpp-memory.md b/docs/examples-cpp-memory.mdnew file mode 100644index 0000000000..780ad09c0d--- /dev/null+++ b/docs/examples-cpp-memory.md@@ -0,0 +1,20 @@+# Working with Memory++You can also [browse this source code online][code] and clone the wasmtime+repository to run the example locally.++[code]: https://github.com/bytecodealliance/wasmtime/blob/main/examples/memory.cc++This example shows off how to interact with wasm memory from the host, reading and writing data directly.++## `memory.wat`++```wat+{{#include ../examples/memory.wat}}+```++## `memory.cc`++```cpp+{{#include ../examples/memory.cc}}+```diff --git a/docs/examples-cpp-multi-value.md b/docs/examples-cpp-multi-value.mdnew file mode 100644index 0000000000..a4e4afe935--- /dev/null+++ b/docs/examples-cpp-multi-value.md@@ -0,0 +1,22 @@+# Using multi-value++You can also [browse this source code online][code] and clone the wasmtime+repository to run the example locally.++[code]: https://github.com/bytecodealliance/wasmtime/blob/main/examples/multi.cc++This example shows off how to interact with a wasm module that uses multi-value+exports and imports.++## `multi.wat`++```wat+{{#include ../examples/multi.wat}}+```+++## `multi.cc`++```c+{{#include ../examples/multi.cc}}+```diff --git a/docs/examples-cpp-multimemory.md b/docs/examples-cpp-multimemory.mdnew file mode 100644index 0000000000..30ccddc865--- /dev/null+++ b/docs/examples-cpp-multimemory.md@@ -0,0 +1,20 @@+# Working with Multiple Memories++You can also [browse this source code online][code] and clone the wasmtime+repository to run the example locally.++[code]: https://github.com/bytecodealliance/wasmtime/blob/main/examples/multimemory.cc++This example demonstrates using a module with multiple linear memories.++## `multimemory.wat`++```wat+{{#include ../examples/multimemory.wat}}+```++## `multimemory.cc`++```cpp+{{#include ../examples/multimemory.cc}}+```diff --git a/docs/examples-cpp-multithreaded-embedding.md b/docs/examples-cpp-multithreaded-embedding.mdnew file mode 100644index 0000000000..6293b22c45--- /dev/null+++ b/docs/examples-cpp-multithreaded-embedding.md@@ -0,0 +1,20 @@+# Multithreaded Embedding++You can also [browse this source code online][code] and clone the wasmtime+repository to run the example locally.++[code]: https://github.com/bytecodealliance/wasmtime/blob/main/examples/threads.cc++This example demonstrates using Wasmtime in multithreaded runtimes.++## `threads.wat`++```wat+{{#include ../examples/threads.wat}}+```++## `threads.cc`++```cpp+{{#include ../examples/threads.cc}}+```diff --git a/docs/examples-cpp-serialize.md b/docs/examples-cpp-serialize.mdnew file mode 100644index 0000000000..57ecfad80d--- /dev/null+++ b/docs/examples-cpp-serialize.md@@ -0,0 +1,14 @@+# Serializing and Deserializing Modules++You can also [browse this source code online][code] and clone the wasmtime+repository to run the example locally.++[code]: https://github.com/bytecodealliance/wasmtime/blob/main/examples/serialize.cc++This example shows how to serialize a compiled module to disk and later deserialize it to skip compilation on the critical path.++## `serialize.cc`++```cpp+{{#include ../examples/serialize.cc}}+```diff --git a/docs/examples-cpp-wasi.md b/docs/examples-cpp-wasi.mdnew file mode 100644index 0000000000..e889b833bf--- /dev/null+++ b/docs/examples-cpp-wasi.md@@ -0,0 +1,21 @@+# WASI++You can also [browse this source code online][code] and clone the wasmtime+repository to run the example locally.++[code]: https://github.com/bytecodealliance/wasmtime/blob/main/examples/wasip1/main.cc++This example shows off how to instantiate a wasm module using WASI imports.++## Wasm Source code++```rust,ignore+{{#include ../examples/wasm/wasi.rs}}+```+++## `wasi.cc`++```c+{{#include ../examples/wasip1/main.cc}}+```diff --git a/docs/examples-rust-anyref.md b/docs/examples-rust-anyref.mdnew file mode 100644index 0000000000..b28812aba3--- /dev/null+++ b/docs/examples-rust-anyref.md@@ -0,0 +1,20 @@+# Working with `anyref`++You can also [browse this source code online][code] and clone the wasmtime+repository to run the example locally.++[code]: https://github.com/bytecodealliance/wasmtime/blob/main/examples/anyref.rs++This example demonstrates using `anyref` values.++## `anyref.wat`++```wat+{{#include ../examples/anyref.wat}}+```++## `anyref.rs`++```rust,ignore+{{#include ../examples/anyref.rs}}+```diff --git a/docs/examples-rust-externref.md b/docs/examples-rust-externref.mdnew file mode 100644index 0000000000..99e336d1f2--- /dev/null+++ b/docs/examples-rust-externref.md@@ -0,0 +1,20 @@+# Working with `externref`++You can also [browse this source code online][code] and clone the wasmtime+repository to run the example locally.++[code]: https://github.com/bytecodealliance/wasmtime/blob/main/examples/externref.rs++This example shows how to pass opaque host references into and out of WebAssembly using `externref`.++## `externref.wat`++```wat+{{#include ../examples/externref.wat}}+```++## `externref.rs`++```rust,ignore+{{#include ../examples/externref.rs}}+```diff --git a/docs/examples-rust-mpk.md b/docs/examples-rust-mpk.mdnew file mode 100644index 0000000000..9f0764c12e--- /dev/null+++ b/docs/examples-rust-mpk.md@@ -0,0 +1,14 @@+# Memory Protection Keys (MPK)++You can also [browse this source code online][code] and clone the wasmtime+repository to run the example locally.++[code]: https://github.com/bytecodealliance/wasmtime/blob/main/examples/mpk.rs++This example demonstrates using the [Memory Protection Keys](https://www.man7.org/linux/man-pages/man7/pkeys.7.html) feature on supported platforms.++## `mpk.rs`++```rust,ignore+{{#include ../examples/mpk.rs}}+```diff --git a/docs/examples-rust-multimemory.md b/docs/examples-rust-multimemory.mdnew file mode 100644index 0000000000..f22dd7a3d0--- /dev/null+++ b/docs/examples-rust-multimemory.md@@ -0,0 +1,20 @@+# Working with Multiple Memories++You can also [browse this source code online][code] and clone the wasmtime+repository to run the example locally.++[code]: https://github.com/bytecodealliance/wasmtime/blob/main/examples/multimemory.rs++This example demonstrates using the multiple memories proposal, instantiating a module that imports and exports more than one linear memory.++## `multimemory.wat`++```wat+{{#include ../examples/multimemory.wat}}+```++## `multimemory.rs`++```rust,ignore+{{#include ../examples/multimemory.rs}}+```diff --git a/docs/examples-rust-multithreaded-embedding.md b/docs/examples-rust-multithreaded-embedding.mdnew file mode 100644index 0000000000..86ba29f3f3--- /dev/null+++ b/docs/examples-rust-multithreaded-embedding.md@@ -0,0 +1,20 @@+# Multithreaded Embedding++You can also [browse this source code online][code] and clone the wasmtime+repository to run the example locally.++[code]: https://github.com/bytecodealliance/wasmtime/blob/main/examples/threads.rs++This example demonstrates using Wasmtime in multithreaded runtimes.++## `threads.wat`++```wat+{{#include ../examples/threads.wat}}+```++## `threads.rs`++```rust,ignore+{{#include ../examples/threads.rs}}+```diff --git a/docs/examples-rust-serialize.md b/docs/examples-rust-serialize.mdnew file mode 100644index 0000000000..9c11020284--- /dev/null+++ b/docs/examples-rust-serialize.md@@ -0,0 +1,14 @@+# Serializing and Deserializing Modules++You can also [browse this source code online][code] and clone the wasmtime+repository to run the example locally.++[code]: https://github.com/bytecodealliance/wasmtime/blob/main/examples/serialize.rs++This example shows how to compile a module once and serialize its compiled representation to disk and later deserialize it to skip compilation on the critical path. See also the [pre-compilation example](examples-pre-compiling-wasm.md) for ahead-of-time compilation.++## `serialize.rs`++```rust,ignore+{{#include ../examples/serialize.rs}}+```diff --git a/docs/examples-rust-wasi.md b/docs/examples-rust-wasip2.mdsimilarity index 100%rename from docs/examples-rust-wasi.mdrename to docs/examples-rust-wasip2.mddiff --git a/docs/lang-cpp.md b/docs/lang-cpp.mdnew file mode 100644index 0000000000..65138c8e1b--- /dev/null+++ b/docs/lang-cpp.md@@ -0,0 +1,3 @@+# Using WebAssembly from C++++The examples in this chapter show how to embed Wasmtime using the C++ API to execute wasm programs with various features. Consult the [API docs](https://docs.wasmtime.dev/c-api/) for the full C++ API.diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txtindex 4d6c1ea56d..605e921f6c 100644--- a/examples/CMakeLists.txt+++ b/examples/CMakeLists.txt@@ -51,6 +51,7 @@ create_rust_wasm(resource-component wasm32-wasip2)# C/C++ examples/testscreate_target(anyref anyref.c)+create_target(anyref-cpp anyref.cc)create_target(async async.cpp)create_target(externref externref.c)create_target(externref-cpp externref.cc)@@ -68,10 +69,15 @@ create_target(linking-cpp linking.cc)create_target(memory memory.c)create_target(memory-cpp memory.cc)create_target(multi multi.c)+create_target(multi-cpp multi.cc)create_target(multimemory multimemory.c)+create_target(multimemory-cpp multimemory.cc)create_target(serialize serialize.c)+create_target(serialize-cpp serialize.cc)create_target(threads threads.c)+create_target(threads-cpp threads.cc)create_target(wasip1 wasip1/main.c)+create_target(wasip1-cpp wasip1/main.cc)# Rust examples/testscreate_rust_test(anyref)diff --git a/examples/README.md b/examples/README.mdindex e37175bf24..af3951760a 100644--- a/examples/README.md+++ b/examples/README.md@@ -1,17 +1,18 @@# Examples of the `wasmtime` APIThis directory contains a number of examples of using the `wasmtime` API from-different languages. Currently examples are all in Rust and C using the-`wasmtime` crate or the wasmtime embedding API.+different languages.-Each example is available in both C and in Rust. Examples are accompanied with a+Most examples are available in Rust, C, and C++, using the `wasmtime` crate or the+[C/C++ embedding API](https://docs.wasmtime.dev/c-api/). Examples are accompanied by a`*.wat` file which is the wasm input, or a Rust project in a `wasm` folder whichis the source code for the original wasm file.-Rust examples can be executed with `cargo run --example $name`. C examples can-be built with `mkdir build && cd build && cmake ..`. You can run-`cmake --build .` to build all examples or-`cmake --build . --target wasmtime-$name`, replacing the name as you wish. They-can also be [built manually](https://docs.wasmtime.dev/c-api/).+Rust examples can be executed with `cargo run --example $name`. C and C++ examples can+be built with `mkdir build && cd build && cmake $name`, where for C `$name` is the+basename of the example, and for C++ it is `[basename]-cpp`. You can run+`cmake --build .` to build all examples or `cmake --build . --target wasmtime-$name`,+replacing the name as you wish.+They can also be [built manually](https://docs.wasmtime.dev/c-api/).For more information see the examples themselves!diff --git a/examples/anyref.cc b/examples/anyref.ccnew file mode 100644index 0000000000..112b267593--- /dev/null+++ b/examples/anyref.cc@@ -0,0 +1,102 @@+/*+Example of using `anyref` values.++You can build the example using CMake:++mkdir build && (cd build && cmake .. && \+ cmake --build . --target wasmtime-anyref-cpp)++And then run it:++build/wasmtime-anyref-cpp+*/++#include <fstream>+#include <iostream>+#include <sstream>+#include <wasmtime.hh>++using namespace wasmtime;++std::string readFile(const char *name) {+ std::ifstream watFile;+ watFile.open(name);+ std::stringstream strStream;+ strStream << watFile.rdbuf();+ return strStream.str();+}++int main() {+ std::cout << "Initializing...\n";+ Config config;+ config.wasm_reference_types(true);+ config.wasm_function_references(true);+ config.wasm_gc(true);+ Engine engine(std::move(config));+ Store store(engine);++ std::cout << "Compiling module...\n";+ auto wat = readFile("examples/anyref.wat");+ Module module = Module::compile(engine, wat).unwrap();++ std::cout << "Instantiating module...\n";+ Instance instance = Instance::create(store, module, {}).unwrap();++ std::cout << "Creating new `anyref` from i31...\n";+ // Create an i31ref wrapping 1234+ auto cx = store.context();+ AnyRef i31 = AnyRef::i31(cx, 1234);+ Val anyref_val(i31);+ auto opt_any = anyref_val.anyref(cx);+ if (!opt_any || !opt_any->u31(cx) || *opt_any->u31(cx) != 1234) {+ std::cerr << "> Error creating i31 anyref\n";+ return 1;+ }++ std::cout << "Touching `anyref` table...\n";+ Table table = std::get<Table>(*instance.get(store, "table"));+ table.set(store, 3, anyref_val).unwrap();+ auto elem_opt = table.get(store, 3);+ if (!elem_opt) {+ std::cerr << "> Error getting table element\n";+ return 1;+ }+ auto elem_any = elem_opt->anyref(cx);+ if (!elem_any || !elem_any->u31(cx) || *elem_any->u31(cx) != 1234) {+ std::cerr << "> Error verifying table element\n";+ return 1;+ }++ std::cout << "Touching `anyref` global...\n";+ Global global = std::get<Global>(*instance.get(store, "global"));+ global.set(store, anyref_val).unwrap();+ Val global_val = global.get(store);+ auto global_any = global_val.anyref(cx);+ if (!global_any || !global_any->u31(cx) || *global_any->u31(cx) != 1234) {+ std::cerr << "> Error verifying global value\n";+ return 1;+ }++ std::cout << "Passing `anyref` into func...\n";+ Func take_anyref = std::get<Func>(*instance.get(store, "take_anyref"));+ take_anyref.call(store, {anyref_val}).unwrap();++ std::cout << "Getting `anyref` from func...\n";+ Func return_anyref = std::get<Func>(*instance.get(store, "return_anyref"));+ auto results = return_anyref.call(store, {}).unwrap();+ if (results.size() != 1) {+ std::cerr << "> Unexpected number of results\n";+ return 1;+ }+ auto ret_any = results[0].anyref(cx);+ if (!ret_any || !ret_any->u31(cx) || *ret_any->u31(cx) != 42) {+ std::cerr << "> Error verifying returned anyref\n";+ return 1;+ }++ std::cout << "GCing within the store...\n";+ store.context().gc();++ std::cout << "Done.\n";+ return 0;+}diff --git a/examples/multi.cc b/examples/multi.ccnew file mode 100644index 0000000000..34a20e481f--- /dev/null+++ b/examples/multi.cc@@ -0,0 +1,78 @@+/*+Example of instantiating of the WebAssembly module and invoking its exported+function.++You can build the example using CMake:++mkdir build && (cd build && cmake .. && \+ cmake --build . --target wasmtime-multi-cpp)++And then run it:++build/wasmtime-multi-cpp+*/++#include <fstream>+#include <iostream>+#include <sstream>+#include <wasmtime.hh>++using namespace wasmtime;++std::string readFile(const char *name) {+ std::ifstream watFile;+ watFile.open(name);+ std::stringstream strStream;+ strStream << watFile.rdbuf();+ return strStream.str();+}++int main() {+ std::cout << "Initializing...\n";+ Engine engine;+ Store store(engine);++ std::cout << "Compiling module...\n";+ auto wat = readFile("examples/multi.wat");+ Module module = Module::compile(engine, wat).unwrap();++ std::cout << "Creating callback...\n";+ Func callback_func = Func::wrap(+ store, [](int32_t a, int64_t b) -> std::tuple<int64_t, int32_t> {+ // Rust example adds 1 to each argument but flips order.+ return std::make_tuple(b + 1, a + 1);+ });++ std::cout << "Instantiating module...\n";+ Instance instance = Instance::create(store, module, {callback_func}).unwrap();++ std::cout << "Extracting export...\n";+ Func g = std::get<Func>(*instance.get(store, "g"));++ std::cout << "Calling export \"g\"...\n";+ // Provide (i32=1, i64=3) like the Rust example+ auto results = g.call(store, {Val(int32_t(1)), Val(int64_t(3))}).unwrap();++ std::cout << "Printing result...\n";+ std::cout << "> " << results[0].i64() << " " << results[1].i32() << "\n";++ std::cout << "Calling export \"round_trip_many\"...\n";+ Func round_trip_many =+ std::get<Func>(*instance.get(store, "round_trip_many"));+ auto many_results =+ round_trip_many+ .call(store, {Val(int64_t(0)), Val(int64_t(1)), Val(int64_t(2)),+ Val(int64_t(3)), Val(int64_t(4)), Val(int64_t(5)),+ Val(int64_t(6)), Val(int64_t(7)), Val(int64_t(8)),+ Val(int64_t(9))})+ .unwrap();+ std::cout << "Printing result...\n";+ std::cout << "> (";+ for (size_t i = 0; i < many_results.size(); i++) {+ if (i)+ std::cout << ", ";+ std::cout << many_results[i].i64();+ }+ std::cout << ")\n";+ return 0;+}diff --git a/examples/multimemory.cc b/examples/multimemory.ccnew file mode 100644index 0000000000..e208b2002e--- /dev/null+++ b/examples/multimemory.cc@@ -0,0 +1,61 @@+/*+An example of how to interact with multiple memories.++You can build the example using CMake:++mkdir build && (cd build && cmake .. && \+ cmake --build . --target wasmtime-multimemory-cpp)++And then run it:++build/wasmtime-multimemory-cpp+*/++#include <fstream>+#include <iostream>+#include <sstream>+#include <wasmtime.hh>++using namespace wasmtime;++std::string readFile(const char *name) {+ std::ifstream watFile;+ watFile.open(name);+ std::stringstream strStream;+ strStream << watFile.rdbuf();+ return strStream.str();+}++int main() {+ std::cout << "Initializing...\n";+ Config config;+ config.wasm_multi_memory(true);+ Engine engine(std::move(config));+ Store store(engine);++ std::cout << "Compiling module...\n";+ auto wat = readFile("examples/multimemory.wat");+ Module module = Module::compile(engine, wat).unwrap();++ std::cout << "Instantiating module...\n";+ Instance instance = Instance::create(store, module, {}).unwrap();+ Memory memory0 = std::get<Memory>(*instance.get(store, "memory0"));+ Memory memory1 = std::get<Memory>(*instance.get(store, "memory1"));++ std::cout << "Checking memory...\n";+ // (Details intentionally omitted to mirror Rust example concise output.)++ std::cout << "Mutating memory...\n";+ auto d0 = memory0.data(store);+ if (d0.size() >= 0x1004)+ d0[0x1003] = 5;+ auto d1 = memory1.data(store);+ if (d1.size() >= 0x1004)+ d1[0x1003] = 7;++ std::cout << "Growing memory...\n";+ memory0.grow(store, 1).unwrap();+ memory1.grow(store, 2).unwrap();++ return 0;+}diff --git a/examples/serialize.cc b/examples/serialize.ccnew file mode 100644index 0000000000..4b39ebc833--- /dev/null+++ b/examples/serialize.cc@@ -0,0 +1,77 @@+/*+Small example of how to serialize compiled wasm module to the disk,+and then instantiate it from the compilation artifacts.++You can build the example using CMake:++mkdir build && (cd build && cmake .. && \+ cmake --build . --target wasmtime-serialize-cpp)++And then run it:++build/wasmtime-serialize-cpp+*/++#include <fstream>+#include <iostream>+#include <sstream>+#include <vector>+#include <wasmtime.hh>++using namespace wasmtime;++std::string readFile(const char *name) {+ std::ifstream watFile;+ watFile.open(name);+ std::stringstream strStream;+ strStream << watFile.rdbuf();+ return strStream.str();+}++std::vector<uint8_t> serialize() {+ std::cout << "Initializing...\n";+ Engine engine;++ std::cout << "Compiling module...\n";+ auto wat = readFile("examples/hello.wat");+ Module module = Module::compile(engine, wat).unwrap();++ auto serialized = module.serialize().unwrap();++ std::cout << "Serialized.\n";+ return serialized;+}++void deserialize(std::vector<uint8_t> buffer) {+ std::cout << "Initializing...\n";+ Engine engine;+ Store store(engine);++ std::cout << "Deserialize module...\n";+ Module module =+ Module::deserialize(engine, Span<uint8_t>(buffer.data(), buffer.size()))+ .unwrap();++ std::cout << "Creating callback...\n";+ Func hello_func = Func::wrap(store, []() {+ std::cout << "Calling back...\n";+ std::cout << "> Hello World!\n";+ });++ std::cout << "Instantiating module...\n";+ Instance instance = Instance::create(store, module, {hello_func}).unwrap();++ std::cout << "Extracting export...\n";+ Func run = std::get<Func>(*instance.get(store, "run"));++ std::cout << "Calling export...\n";+ run.call(store, {}).unwrap();++ std::cout << "Done.\n";+}++int main() {+ auto buffer = serialize();+ deserialize(buffer);+ return 0;+}diff --git a/examples/threads.cc b/examples/threads.ccnew file mode 100644index 0000000000..f03b0b2f15--- /dev/null+++ b/examples/threads.cc@@ -0,0 +1,99 @@+/*+Example of instantiating of the WebAssembly module and invoking its exported+function in a separate thread.++You can build the example using CMake:++mkdir build && (cd build && cmake .. && \+ cmake --build . --target wasmtime-threads-cpp)++And then run it:++build/wasmtime-threads-cpp+*/++#include <fstream>+#include <iostream>+#include <mutex>+#include <sstream>+#include <thread>+#include <unordered_map>+#include <vector>+#include <wasmtime.hh>++using namespace wasmtime;++std::string readFile(const char *name) {+ std::ifstream watFile;+ watFile.open(name);+ std::stringstream strStream;+ strStream << watFile.rdbuf();+ return strStream.str();+}++const int N_THREADS = 10;+const int N_REPS = 3;++std::mutex print_mutex;++void run_worker(Engine engine, Module module) {+ std::thread::id id = std::this_thread::get_id();+ Store store(engine);+ for (int i = 0; i < N_REPS; i++) {+ {+ std::lock_guard<std::mutex> lock(print_mutex);+ std::cout << "Instantiating module...\n";+ }+ Func hello_func = Func::wrap(store, []() {+ std::lock_guard<std::mutex> lock(print_mutex);+ std::thread::id id = std::this_thread::get_id();+ std::cout << "> Hello from ThreadId(" << id << ")\n";+ });+ auto instance_res = Instance::create(store, module, {hello_func});+ if (!instance_res) {+ std::cout << "> Error instantiating module!\n";+ return;+ }+ Instance instance = instance_res.unwrap();+ Func run = std::get<Func>(*instance.get(store, "run"));+ {+ std::lock_guard<std::mutex> lock(print_mutex);+ std::cout << "Executing...\n";+ }+ run.call(store, {}).unwrap();+ std::this_thread::sleep_for(std::chrono::milliseconds(100));+ }++ // Move store to a new thread once.+ {+ std::lock_guard<std::mutex> lock(print_mutex);+ std::cout << "> Moving (" << id << ") to a new thread\n";+ }+ auto handle = std::thread([store = std::move(store), module]() mutable {+ Func hello_func = Func::wrap(store, []() {+ std::lock_guard<std::mutex> lock(print_mutex);+ std::thread::id id = std::this_thread::get_id();+ std::cout << "> Hello from ThreadId(" << id << ")\n";+ });+ Instance instance = Instance::create(store, module, {hello_func}).unwrap();+ Func run = std::get<Func>(*instance.get(store, "run"));+ run.call(store, {}).unwrap();+ });+ handle.join();+}++int main() {+ std::cout << "Initializing...\n";++ Engine engine;+ auto wat = readFile("examples/threads.wat");+ Module module = Module::compile(engine, wat).unwrap();++ std::vector<std::thread> threads;+ threads.reserve(N_THREADS);+ for (int i = 0; i < N_THREADS; i++)+ threads.emplace_back(run_worker, engine, module);+ for (auto &t : threads)+ t.join();+ return 0;+}diff --git a/examples/wasip1/main.c b/examples/wasip1/main.cindex c933be4dc5..0e1ccf4ec8 100644--- a/examples/wasip1/main.c+++ b/examples/wasip1/main.c@@ -5,19 +5,19 @@ You can compile and run this example on Linux with:cmake examples/cargo build --release -p wasmtime-c-api- cc examples/wasi/main.c \+ cc examples/wasip1/main.c \-I crates/c-api/include \target/release/libwasmtime.a \-lpthread -ldl -lm \- -o wasi- ./wasi+ -o wasip1+ ./wasip1Note that on Windows and macOS the command will be similar, but you'll needto tweak the `-lpthread` and such annotations.You can also build using cmake:-mkdir build && cd build && cmake .. && cmake --build . --target wasmtime-wasi+mkdir build && cd build && cmake .. && cmake --build . --target wasmtime-wasip1*/#include <assert.h>diff --git a/examples/wasip1/main.cc b/examples/wasip1/main.ccnew file mode 100644index 0000000000..62b8ebcbe5--- /dev/null+++ b/examples/wasip1/main.cc@@ -0,0 +1,65 @@+/*+Example of instantiating a wasm module which uses WASI imports.++You can build the example using CMake:++mkdir build && (cd build && cmake .. && \+ cmake --build . --target wasmtime-wasip1-cpp)++And then run it:++build/wasmtime-wasip1-cpp+*/++#include <fstream>+#include <iostream>+#include <sstream>+#include <vector>+#include <wasmtime.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() {+ // Define the WASI functions globally on the `Config`.+ Engine engine;+ Linker linker(engine);+ linker.define_wasi().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_stdin();+ wasi.inherit_stdout();+ wasi.inherit_stderr();++ Store store(engine);+ store.context().set_wasi(std::move(wasi)).unwrap();++ // Load and compile the wasm module.+ auto bytes = read_binary_file("target/wasm32-wasip1/debug/wasi.wasm");+ auto module =+ Module::compile(engine, Span<uint8_t>(bytes.data(), bytes.size()))+ .unwrap();++ // Define the module in the linker (anonymous name matches Rust example+ // usage).+ linker.module(store.context(), "", module).unwrap();++ // Get the default export (command entrypoint) and invoke it.+ Func default_func = linker.get_default(store.context(), "").unwrap();+ default_func.call(store, {}).unwrap();++ return 0;+}