mcpField
W
wasm-wasmtime

wasm-wasmtime

github.com/mohitmishra786開発269499 回インストール18 週間前に更新
リポジトリ

wasm-wasmtime について

wasmtime の実行と組み込みをエージェント向けに案内する WebAssembly スキルです。WASI、コンポーネント、実行制限、デバッグを扱い、CLI の利用者や Rust アプリにランタイムを組み込む開発者を対象とします。

主な機能

  1. 01CLI から WASM モジュールを実行
  2. 02WASI API の利用
  3. 03WIT によるコンポーネントインターフェース定義
  4. 04Rust への wasmtime 組み込み
  5. 05fuel による実行制限
  6. 06DWARF 情報を使ったデバッグ

活用シーン

  1. 01CLI 引数を指定した WASM モジュールの実行
  2. 02WASI によるファイルシステムやネットワークアクセス
  3. 03Rust アプリへのコンポーネント実行の組み込み
  4. 04信頼できないモジュールの実行制限と障害調査

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/mohitmishra786/low-level-dev-skills --skill wasm-wasmtime

インストール後、Claude Code で/wasm-wasmtimeを入力して読み込まれたか確認します。

詳細

wasmtime — サーバーサイド WASM ランタイム

目的

CLI からの WASM モジュールの実行、WASI API、WIT インターフェースを使ったコンポーネントモデル、wasmtime の Rust アプリケーションへの組み込み、サンドボックス実行のための燃料計測、DWARF デバッグ情報を使った WASM のデバッグについて、エージェントをガイドします。

トリガー

  • 「wasmtime で WASM ファイルを実行するにはどうすればよいですか?」
  • 「wasmtime で WASI はどのように動作しますか?」
  • 「wasmtime を Rust アプリケーションに組み込むにはどうすればよいですか?」
  • 「WebAssembly コンポーネントモデルとは何ですか?」
  • 「燃料を使って 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. wasmtime を Rust に組み込む
# 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. 燃料計測 — CPU の制限

燃料計測は実行される 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/コンポーネントのビルドでは、gc サポートのための wasmtime の機能フラグを確認してください。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 で、longjmp 形式の Emscripten パターンをネイティブの try/catch/throw に置き換えます。組み込みで必要な場合は、明示的に有効にしてください。

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

WIT パッケージと cargo component を使ってバインディングを再生成し、WASI p1(wasi_snapshot_preview1)から移行してください。

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")? };

関連スキル

  • ブラウザー/WASI 向けに C/C++ を WASM にコンパイルする場合は、skills/runtimes/wasm-emscripten を使用してください
  • wasmtime の Rust 組み込みにおける非同期パターンについては、skills/rust/rust-async-internals を使用してください
  • WASM のサンドボックス化に関する考慮事項については、skills/runtimes/binary-hardening を使用してください

コメント