wasm-wasmtime
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinesewasmtime — Server-Side WASM Runtime
wasmtime — 服务端WASM运行时
Purpose
用途
Guide agents through wasmtime: running WASM modules from the CLI, WASI APIs, the component model with WIT interfaces, embedding wasmtime in Rust applications, fuel metering for sandboxed execution, and debugging WASM with DWARF debug info.
指导使用者掌握wasmtime的相关操作:从CLI运行WASM模块、使用WASI API、基于WIT接口的组件模型、在Rust应用中嵌入wasmtime、用于沙箱执行的燃料计量,以及使用DWARF调试信息调试WASM。
Triggers
触发场景
- "How do I run a WASM file with wasmtime?"
- "How does WASI work with wasmtime?"
- "How do I embed wasmtime in my Rust application?"
- "What is the WebAssembly component model?"
- "How do I limit WASM execution with fuel?"
- "How do I debug a WASM module in wasmtime?"
- "如何使用wasmtime运行WASM文件?"
- "WASI如何与wasmtime配合使用?"
- "如何在我的Rust应用中嵌入wasmtime?"
- "什么是WebAssembly组件模型?"
- "如何通过燃料限制WASM的执行?"
- "如何在wasmtime中调试WASM模块?"
Workflow
操作流程
1. wasmtime CLI
1. wasmtime CLI
bash
undefinedbash
undefinedInstall
Install
curl https://wasmtime.dev/install.sh -sSf | bash
curl https://wasmtime.dev/install.sh -sSf | bash
Run a WASM module
Run a WASM module
wasmtime hello.wasm
wasmtime hello.wasm
Run with WASI arguments
Run with WASI arguments
wasmtime prog.wasm -- arg1 arg2
wasmtime prog.wasm -- arg1 arg2
Pre-open directories (WASI filesystem sandbox)
Pre-open directories (WASI filesystem sandbox)
wasmtime --dir /tmp::/ prog.wasm # map host /tmp to WASI root
wasmtime --dir /tmp::/ prog.wasm # map host /tmp to WASI root
Pass environment variables
Pass environment variables
wasmtime --env HOME=/home/user prog.wasm
wasmtime --env HOME=/home/user prog.wasm
Invoke specific exported function
Invoke specific exported function
wasmtime run --invoke add math.wasm 3 4
wasmtime run --invoke add math.wasm 3 4
Inspect exports
Inspect exports
wasmtime explore math.wasm # interactive explorer
wasmtime inspect math.wasm # show all exports/imports
wasmtime explore math.wasm # interactive explorer
wasmtime inspect math.wasm # show all exports/imports
Compile to native ahead-of-time
Compile to native ahead-of-time
wasmtime compile prog.wasm -o prog.cwasm
wasmtime run prog.cwasm
undefinedwasmtime compile prog.wasm -o prog.cwasm
wasmtime run prog.cwasm
undefined2. WASI preview2 APIs
2. WASI preview2 APIs
WASI preview2 provides a capability-based POSIX-like API set:
bash
undefinedWASI preview2提供一套基于能力的类POSIX API集合:
bash
undefinedwasmtime supports WASI p2 natively
wasmtime supports WASI p2 natively
wasmtime --wasi-modules experimental-wasi-http prog.wasm
wasmtime --wasi-modules experimental-wasi-http prog.wasm
Key WASI interfaces (WIT)
Key WASI interfaces (WIT)
wasi:filesystem — file and directory access
wasi:filesystem — file and directory access
wasi:sockets — TCP/UDP networking (preview2)
wasi:sockets — TCP/UDP networking (preview2)
wasi:http — HTTP client/server (experimental)
wasi:http — HTTP client/server (experimental)
wasi:cli — stdin/stdout/stderr, environment
wasi:cli — stdin/stdout/stderr, environment
wasi:random — secure random numbers
wasi:random — secure random numbers
wasi:clocks — system and monotonic clocks
wasi:clocks — system and monotonic clocks
undefinedundefined3. Embedding wasmtime in Rust
3. 在Rust中嵌入wasmtime
toml
undefinedtoml
undefinedCargo.toml
Cargo.toml
[dependencies]
wasmtime = "24"
wasmtime-wasi = "24"
anyhow = "1"
```rust
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(())
}[dependencies]
wasmtime = "24"
wasmtime-wasi = "24"
anyhow = "1"
```rust
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 metering — CPU limiting
4. 燃料计量 — CPU限制
Fuel metering limits the number of WASM instructions executed, preventing runaway or malicious code:
rust
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}"),
}燃料计量可以限制WASM指令的执行数量,防止失控或恶意代码的运行:
rust
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. Component model and WIT
5. 组件模型与WIT
The component model adds typed interface definitions (WIT) on top of core WASM:
wit
// math.wit — interface definition
package example:math@1.0.0;
interface calculator {
add: func(a: s32, b: s32) -> s32;
sqrt: func(x: f64) -> f64;
}
world math-world {
export calculator;
}bash
undefined组件模型在核心WASM之上添加了类型化接口定义(WIT):
wit
// math.wit — interface definition
package example:math@1.0.0;
interface calculator {
add: func(a: s32, b: s32) -> s32;
sqrt: func(x: f64) -> f64;
}
world math-world {
export calculator;
}bash
undefinedInstall component toolchain
Install component toolchain
cargo install wasm-tools cargo-component
cargo install wasm-tools cargo-component
Create a Rust component
Create a Rust component
cargo component new --lib math-component
cargo component new --lib math-component
Implement the WIT interface in src/lib.rs
Implement the WIT interface in src/lib.rs
Build component
Build component
cargo component build --release
cargo component build --release
Run with wasmtime component
Run with wasmtime component
wasmtime run math-component.wasm
```rust
// 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)?;wasmtime run math-component.wasm
```rust
// 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. WASM debugging with DWARF
6. 使用DWARF调试WASM
bash
undefinedbash
undefinedBuild WASM with debug info (Rust)
Build WASM with debug info (Rust)
cargo build --target wasm32-wasi # debug profile includes DWARF by default
cargo build --target wasm32-wasi # debug profile includes DWARF by default
Run with source-level debugging
Run with source-level debugging
WASMTIME_BACKTRACE_DETAILS=1 wasmtime prog.wasm
WASMTIME_BACKTRACE_DETAILS=1 wasmtime prog.wasm
Full DWARF stack traces
Full DWARF stack traces
wasmtime --debug-info prog.wasm 2>&1
wasmtime --debug-info prog.wasm 2>&1
GDB with WASM (wasmtime dev build)
GDB with WASM (wasmtime dev build)
wasmtime debug prog.wasm # experimental
wasmtime debug prog.wasm # experimental
wasm-tools for inspection
wasm-tools for inspection
wasm-tools print prog.wasm | head -50 # disassemble to WAT
wasm-tools validate prog.wasm # validate WASM binary
undefinedwasm-tools print prog.wasm | head -50 # disassemble to WAT
wasm-tools validate prog.wasm # validate WASM binary
undefined7. Performance configuration
7. 性能配置
rust
// 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")? };rust
// 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")? };Related skills
相关技能
- Use for compiling C/C++ to WASM for browser/WASI
skills/runtimes/wasm-emscripten - Use for async patterns in wasmtime Rust embedding
skills/rust/rust-async-internals - Use for sandboxing considerations with WASM
skills/runtimes/binary-hardening
- 若需将C/C++编译为适用于浏览器/WASI的WASM,请使用
skills/runtimes/wasm-emscripten - 若需在wasmtime Rust嵌入中使用异步模式,请使用
skills/rust/rust-async-internals - 若需了解WASM沙箱相关的加固措施,请使用
skills/runtimes/binary-hardening