关于 wasm-wasmtime
为 Agent 提供使用和嵌入 wasmtime 的 WebAssembly 指南,涵盖 WASI、组件、执行限制与调试。适用于使用命令行或将运行时集成到 Rust 应用的开发者。
主要功能
- 01通过命令行运行 WASM 模块
- 02使用 WASI API
- 03用 WIT 定义组件接口
- 04在 Rust 中嵌入 wasmtime
- 05通过 fuel 限制执行
- 06使用 DWARF 信息调试
适用场景
- 01通过命令行参数运行 WASM 模块
- 02提供 WASI 文件系统或网络访问
- 03在 Rust 应用中嵌入组件执行
- 04限制不可信模块并检查运行故障
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ mohitmishra786/ low-level-dev-skills --skill wasm-wasmtime安装后在 Claude Code 中输入/wasm-wasmtime确认已加载。
详细介绍
wasmtime —— 服务端 WASM 运行时
用途
指导 Agent 使用 wasmtime:通过 CLI 运行 WASM 模块、使用 WASI API、通过 WIT 接口使用组件模型、在 Rust 应用中嵌入 wasmtime、使用 fuel 计量对执行进行沙箱限制,以及使用 DWARF 调试信息调试 WASM。
触发条件
-“如何使用 wasmtime 运行 WASM 文件?” -“WASI 如何与 wasmtime 配合使用?” -“如何在 Rust 应用中嵌入 wasmtime?” -“什么是 WebAssembly 组件模型?” -“如何使用 fuel 限制 WASM 执行?” -“如何在 wasmtime 中调试 WASM 模块?”
工作流
1. wasmtime CLI
# Install
curl https://wasmtime.dev/install.sh -sSf | bash
# Run a WASM module
wasmtime hello.wasm
# Run with WASI arguments
wasmtime prog.wasm -- arg1 arg2
# Pre-open directories (WASI filesystem sandbox)
wasmtime --dir /tmp::/ prog.wasm # map host /tmp to WASI root
# Pass environment variables
wasmtime --env HOME=/home/user prog.wasm
# Invoke specific exported function
wasmtime run --invoke add math.wasm 3 4
# Inspect exports
wasmtime explore math.wasm # interactive explorer
wasmtime inspect math.wasm # show all exports/imports
# Compile to native ahead-of-time
wasmtime compile prog.wasm -o prog.cwasm
wasmtime run prog.cwasm
2. WASI preview2 API
WASI preview2 提供基于能力的类 POSIX API 集:
# wasmtime supports WASI p2 natively
wasmtime --wasi-modules experimental-wasi-http prog.wasm
# Key WASI interfaces (WIT)
# wasi:filesystem — file and directory access
# wasi:sockets — TCP/UDP networking (preview2)
# wasi:http — HTTP client/server (experimental)
# wasi:cli — stdin/stdout/stderr, environment
# wasi:random — secure random numbers
# wasi:clocks — system and monotonic clocks
3. 在 Rust 中嵌入 wasmtime
# Cargo.toml
[dependencies]
wasmtime = "24"
wasmtime-wasi = "24"
anyhow = "1"
use wasmtime::*;
use wasmtime_wasi::WasiCtxBuilder;
fn main() -> anyhow::Result<()> {
// Create engine with default config
let engine = Engine::default();
// Load and compile WASM module
let module = Module::from_file(&engine, "prog.wasm")?;
// Set up WASI context
let wasi = WasiCtxBuilder::new()
.inherit_stdio()
.inherit_env()
.preopened_dir("/tmp", "/")?
.build();
// Create a store (holds WASM state)
let mut store = Store::new(&engine, wasi);
// Instantiate the module
let instance = Instance::new(&mut store, &module, &[])?;
// Call an exported function
let add = instance.get_typed_func::<(i32, i32), i32>(&mut store, "add")?;
let result = add.call(&mut store, (3, 4))?;
println!("Result: {result}");
Ok(())
}
4. Fuel 计量 —— 限制 CPU 使用
Fuel 计量会限制执行的 WASM 指令数量,防止代码失控或具有恶意行为:
use wasmtime::*;
let mut config = Config::default();
config.consume_fuel(true); // enable fuel consumption
let engine = Engine::new(&config)?;
let module = Module::from_file(&engine, "untrusted.wasm")?;
let mut store = Store::new(&engine, ());
store.set_fuel(1_000_000)?; // allow 1M instructions
let instance = Instance::new(&mut store, &module, &[])?;
let run = instance.get_typed_func::<(), ()>(&mut store, "run")?;
match run.call(&mut store, ()) {
Ok(_) => println!("Completed, fuel remaining: {}", store.get_fuel()?),
Err(e) if e.to_string().contains("all fuel consumed") => {
println!("Timed out (fuel exhausted)");
}
Err(e) => eprintln!("Error: {e}"),
}
5. 组件模型和 WIT
组件模型在核心 WASM 之上增加了类型化接口定义(WIT):
// math.wit — interface definition
package example:[email protected];
interface calculator {
add: func(a: s32, b: s32) -> s32;
sqrt: func(x: f64) -> f64;
}
world math-world {
export calculator;
}
# Install component toolchain
cargo install wasm-tools cargo-component
# Create a Rust component
cargo component new --lib math-component
# Implement the WIT interface in src/lib.rs
# Build component
cargo component build --release
# Run with wasmtime component
wasmtime run math-component.wasm
// Embed a component in Rust
use wasmtime::component::*;
wasmtime::component::bindgen!({
world: "math-world",
path: "math.wit",
});
let component = Component::from_file(&engine, "math.wasm")?;
let (calculator, _) = MathWorld::instantiate(&mut store, &component, &linker)?;
let result = calculator.call_add(&mut store, 3, 4)?;
6. 使用 DWARF 调试 WASM
# Build WASM with debug info (Rust)
cargo build --target wasm32-wasi # debug profile includes DWARF by default
# Run with source-level debugging
WASMTIME_BACKTRACE_DETAILS=1 wasmtime prog.wasm
# Full DWARF stack traces
wasmtime --debug-info prog.wasm 2>&1
# GDB with WASM (wasmtime dev build)
wasmtime debug prog.wasm # experimental
# wasm-tools for inspection
wasm-tools print prog.wasm | head -50 # disassemble to WAT
wasm-tools validate prog.wasm # validate WASM binary
7. WASM GC(垃圾回收对象)
WASM GC 提案增加了具有托管分配机制的结构体和数组类型:
;; GC-enabled module (toolchain dependent)
(struct $point (field (mut f32) x) (field (mut f32) y))
# wasm-tools with GC support
wasm-tools validate --features gc module.wasm
wasmtime run --wasm gc module.wasm
在 Rust/组件构建中,请检查 wasmtime 的功能标志是否支持 gc。在 WAT 或编译输出中使用 struct.new、array.new、struct.get、array.get 指令。
8. WASM 线程和共享内存
# Requires SharedArrayBuffer in JS hosts; WASI pthreads in native hosts
# Compile with threading enabled (Clang/Rust wasm32-wasi-threads)
clang --target=wasm32-wasi -pthread -matomics -mbulk-memory -o prog.wasm prog.c
# Current wasmtime enables threads + shared-memory by default (see stability-wasm-proposals)
wasmtime run prog.wasm
原子操作(i32.atomic.*)和 memory.atomic.wait/notify 需要 bulk-memory 和 threads 提案。如果运行的是较旧的构建版本,请查看 wasmtime --help 中的 -W/-S 覆盖选项。
9. WASM 异常处理
(try (do $exn)
(throw $exn)
(catch $exn (local.get 0) (return)))
# Exception handling enabled by default in current wasmtime releases
wasmtime run module.wasm
它用 WASM 原生的 try/catch/throw 替代了 Emscripten 的 longjmp 风格模式。对于嵌入场景,如有需要,请显式启用:
config.wasm_exceptions(true); // usually on by default in recent wasmtime
10. WASI Preview 2(p2)稳定化
WASIp2 使用带类型的接口和组件模型,而不是原始系统调用导入:
# wasmtime 17+ supports component model / WASI p2 (see examples-wasip2.html)
wasmtime run component.wasm
# wit-bindgen generates host/guest bindings from WIT files
wit-bindgen rust ./deps/wasi-cli.wit
从 WASI p1(wasi_snapshot_preview1)迁移时,请使用 cargo component 和 WIT 包重新生成绑定。
11. 性能配置
// High-performance embedding config
let mut config = Config::default();
config.cranelift_opt_level(OptLevel::SpeedAndSize);
config.parallel_compilation(true);
config.cache_config_load_default()?; // disk cache for compiled modules
// Ahead-of-time compilation for production
// 1. Pre-compile in build pipeline
let serialized = module.serialize()?;
std::fs::write("prog.cwasm", &serialized)?;
// 2. Load pre-compiled at runtime (zero compilation cost)
let module = unsafe { Module::deserialize_file(&engine, "prog.cwasm")? };
相关技能
- 使用
skills/runtimes/wasm-emscripten将 C/C++ 编译为适用于浏览器/WASI 的 WASM - 使用
skills/rust/rust-async-internals了解在 Rust 中嵌入 wasmtime 时的异步模式 - 使用
skills/runtimes/binary-hardening了解 WASM 沙箱注意事项