Skip to content

WebAssembly チートシート

Web 上で高速に実行するためのバイナリ命令形式。

01

はじめに

JS での Wasm のロード

WebAssembly(Wasm)はブラウザでネイティブに近い速度で動くバイナリ形式です。instantiateStreaming は .wasm ファイルを読み込んでコンパイルします。エクスポートされた関数は JavaScript から呼び出せます。

webassembly
// Load and instantiate a .wasm module
WebAssembly.instantiateStreaming(fetch('module.wasm'))
  .then(result => {
    const { instance } = result;
    // call exported functions
    console.log(instance.exports.add(2, 3)); // 5
  });

// Alternative: from ArrayBuffer
const bytes = new Uint8Array([0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00]);
WebAssembly.instantiate(bytes).then(result => {
  console.log(result.instance.exports);
});

WebAssembly の Module と Instance

WebAssembly.Module はコンパイル済みで状態を持たない表現です — 複数のインスタンスで安全に再利用できます。WebAssembly.Instance は実行時の状態(memory、globals)を保持します。1 回コンパイルして何度もインスタンス化するのは、並列ワーカーの生成に効率的です。

webassembly
// Two-step: compile then instantiate
const module = await WebAssembly.compile(bytes);
const instance = await WebAssembly.instantiate(module, importObject);
console.log(instance.exports.add(1, 2));

// Module is stateless & shareable across instances
const instance2 = await WebAssembly.instantiate(module, importObject);
// Each instance has its own memory and globals

ブラウザ対応と機能検出

WebAssembly 1.0 はすべてのモダンブラウザでサポートされています。新しい提案(SIMD、exceptions、threads、GC)には機能検出が必要です。WebAssembly.validate はコンパイルせずにバイト列が有効なモジュールかチェックします。

webassembly
// Check basic WebAssembly support
if (typeof WebAssembly !== 'undefined') {
  console.log('WebAssembly is supported');
}

// Verify the engine can actually compile
WebAssembly.validate(new Uint8Array([
  0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00
])); // true if valid module

// Feature-detect newer proposals
const hasSIMD = typeof WebAssembly.Module !== 'undefined';
const hasExceptions = 'exceptions' in WebAssembly;

ストリーミング vs 非ストリーミング

instantiateStreaming はネットワークから流れてくるモジュールをその場でコンパイルするので — 起動が速いです。サーバーは必ず 'Content-Type: application/wasm' を送らなければなりません。そのヘッダーを付けない CDN や静的ホストでは、ArrayBuffer のパスにフォールバックしましょう。

webassembly
// Streaming (preferred): compiles while downloading
WebAssembly.instantiateStreaming(fetch('m.wasm'), imports);

// Non-streaming: must download fully first
const res = await fetch('m.wasm');
const buf = await res.arrayBuffer();
WebAssembly.instantiate(buf, imports);

// Streaming requires correct MIME type:
//   Content-Type: application/wasm

Wasm のマジックナンバーとヘッダー

Wasm バイナリのマジックナンバーは ASCII 文字列の '\0asm' で、その後に 4 バイトのリトルエンディアンのバージョンが続きます。このヘッダーで、コンパイル前にファイルが Wasm かどうか検証できます。形式はセクション(Type、Import、Function、Memory など)で構成されます。

webassembly
// Every .wasm file starts with this 8-byte header:
//   0x00 0x61 0x73 0x6d  -> "\0asm"
//   0x01 0x00 0x00 0x00  -> version 1
const magic = [0x00, 0x61, 0x73, 0x6d];
const version = [0x01, 0x00, 0x00, 0x00];

// Quick validity check
function isWasm(bytes) {
  return bytes[0] === 0x00 && bytes[1] === 0x61
      && bytes[2] === 0x73 && bytes[3] === 0x6d;
}

Hello Wasm(最小の例)

最小の Wasm アプリ: モジュールは JS から 'log' 関数をインポートし、それを呼ぶ 'greet' をエクスポートします。WAT(WebAssembly Text)形式は人間が読める表現で、wat2wasm でバイナリへコンパイルされます。ブラウザが実行するのはバイナリ形式だけです。

webassembly
<!-- index.html -->
<script>
  WebAssembly.instantiateStreaming(fetch('hello.wasm'))
    .then(({ instance }) => {
      instance.exports.greet(); // logs "Hello, Wasm!"
    });
</script>

;; hello.wat (compiled to hello.wasm via wat2wasm)
(module
  (import "console" "log" (func $log (param i32)))
  (func (export "greet")
    i32.const 72   ;; 'H'
    call $log
  )
)
02

WAT テキスト形式

module と S 式

WAT(WebAssembly Text 形式)は Wasm のテキスト表現です。すべてが (module ...) の S 式で包まれます。命令はスタックベースの順で書きます: オペランドを先にプッシュし、その後に演算が消費します。

webassembly
;; WAT uses s-expressions: (keyword args...)
(module
  ;; function definitions, exports, etc. go here
)

;; Nested expressions form the instruction sequence
(module
  (func $add (param $a i32) (param $b i32) (result i32)
    local.get $a
    local.get $b
    i32.add
  )
  (export "add" (func $add))
)

WAT のコメント

WAT は 2 つのコメント形式をサポートします: ';;' は 1 行、'(; ... ;)' はブロックコメントです。ブロックコメントはネストでき複数行にまたがれます — 開発中にコードの塊を無効化するのに便利です。

webassembly
;; Single-line comment (starts with ;;)
(func (export "f")
  i32.const 1  ;; push 1
  drop         ;; discard
)

(; Block comment
   can span
   multiple lines ;)
(func (export "g")
  nop
)

関数定義の構文

関数は (func ...) で宣言します。パラメータは (param $name type)、結果は (result type) です。'$name' は省略でき — 省略すると関数/ローカル変数は数値インデックスで参照されます。複数戻り値には multi-value 提案が必要です(広くサポートされています)。

webassembly
;; Named function with params and result
(func $name (param $p1 i32) (param $p2 f64) (result i32)
  ;; body
)

;; Anonymous function (referenced by index)
(func (param i32) (result i32)
  local.get 0
)

;; Multiple results (multi-value proposal)
(func $swap (param i32 i32) (result i32 i32)
  local.get 1
  local.get 0
)

インラインの export と import

WAT は関数、memory、table、global にインラインの (export "name") と (import "module" "field") の注釈を付けられます — 展開形の (export ...) / (import ...) のショートハンドです。どちらも同じバイナリにコンパイルされます。

webassembly
;; Inline export on a function
(func (export "add") (param i32 i32) (result i32)
  local.get 0
  local.get 1
  i32.add
)

;; Inline import
(func $log (import "env" "log") (param i32))

;; Inline export on memory
(memory (export "mem") 1)

;; Expanded form (equivalent)
(func $add (param i32 i32) (result i32) ...)
(export "add" (func $add))

データセグメント

データセグメントは、インスタンス化時に線形メモリを初期化する(active)か、memory.init で遅延初期化する(passive)ものです。文字列には \00(null 終端)や \n(改行)のようなエスケープシーケンスを含められます。data.drop はコピー後にセグメントのストレージを解放します。

webassembly
;; Initialize memory with bytes at offset 0
(memory 1)
(data (i32.const 0) "Hello, Wasm!\00")

;; Named data segment (active)
(data $msg (i32.const 0) "Hello\00")

;; Passive data segment (used with memory.init)
(data $passive "lazy-loaded bytes")

;; Drop a data segment to free its memory
(data.drop $msg)

wat2wasm と wasm2wat の変換

WABT(WebAssembly Binary Toolkit)は wat2wasm(テキスト→バイナリ)、wasm2wat(バイナリ→テキスト)、wasm-validate、wasm-objdump を提供します。Wasm モジュールの検査、デバッグ、手書きに不可欠なツールです。.wat 形式は人間用、.wasm 形式はブラウザが実行するものです。

webassembly
# Install the WebAssembly Binary Toolkit (WABT)
# macOS:  brew install wabt
# Ubuntu: apt install wabt

# Convert text -> binary
wat2wasm hello.wat -o hello.wasm

# Convert binary -> text (disassemble)
wasm2wat hello.wasm -o hello.wat

# Validate a .wasm file
wasm-validate hello.wasm

# Print module structure
wasm-objdump -x hello.wasm
03

値型

基本の値型(i32/i64/f32/f64)

Wasm の基本の値型は 4 つだけです: i32、i64、f32、f64。整数の符号の有無は型ではなく演算で決まります(例: i32.div_s vs i32.div_u)。このため型システムは最小限で予測可能です。

webassembly
;; Wasm has exactly four basic value types:
;;   i32  - 32-bit integer
;;   i64  - 64-bit integer
;;   f32  - 32-bit float
;;   f64  - 64-bit float

(func (param i32) (param i64) (param f32) (param f64)
  (result f64)
  local.get 2   ;; f32
  f64.promote_f32
)

;; Integers are signed or unsigned PER OPERATION,
;; not per type. Use i32.add_s / i32.div_u etc.

WAT の数値リテラル

WAT の数値リテラルは 10 進、16 進(0x)、2 進(0b)をサポートします。浮動小数点は科学表記、無限大(inf)、NaN に対応です。WAT のリテラルはデフォルトで符号なしです — 負の整数は先頭の '-' でエンコードします。

webassembly
;; Integer literals
i32.const 42
i32.const -7
i32.const 0xff       ;; hex
i32.const 0b1010     ;; binary

;; Float literals
f64.const 3.14
f64.const 1e10
f64.const -0.0
f64.const inf
f64.const nan

;; 64-bit
i64.const 9007199254740992  ;; 2^53

型変換

変換には一貫した命名規則があります: extend(小→大)、wrap(大→小)、convert(整数↔浮動小数点)、reinterpret(ビットレベルのキャスト)、demote/promote(浮動小数点の精度)。符号付きは _s、符号なしは _u です。

webassembly
;; Extend i32 to i64
i64.extend_i32_s      ;; sign-extend
i64.extend_i32_u      ;; zero-extend

;; Wrap i64 to i32
i32.wrap_i64

;; Integer <-> Float
f32.convert_i32_s
f64.convert_i64_u
i32.trunc_f32_s       ;; truncate (toward zero)
i32.reinterpret_f32   ;; bit-level reinterpret

;; Demote / promote floats
f32.demote_f64
f64.promote_f32

v128 SIMD 型

v128 型は 16 バイトを 1 つの SIMD レジスタに詰め込みます。レーンは i32x4(4×int32)、f32x4(4×float32)、i16x8、i8x16、f64x2 として扱えます。SIMD は 1 命令で複数の値を処理するため、画像/音声/暗号のワークロードを高速化します。

webassembly
;; SIMD: 128-bit vector type (fixed-width SIMD proposal)
(module
  (func (param v128) (result v128)
    local.get 0
    v128.not            ;; bitwise NOT
  )
  (func (result v128)
    v128.const i32x4 1 2 3 4
  )
)

;; Vector operations: i32x4, i16x8, i8x16, f32x4, f64x2
v128.const f32x4 1.0 2.0 3.0 4.0
i32x4.add

参照型(funcref/externref)

参照型の提案は funcref(関数ポインタ)と externref(不透明なホスト参照)を追加します。externref は強力です: Wasm が JS オブジェクトをコピーもシリアライズもせず保持できます。テーブルと組み合わせると、柔軟なコールバックパターンが可能になります。

webassembly
;; Reference types proposal adds:
;;   funcref   - reference to a function (in a table)
;;   externref - opaque reference to a host (JS) object

(module
  (table 1 funcref)
  (func (param externref) (result externref)
    local.get 0    ;; pass through a JS object
  )
)

;; In JS, externref lets you pass arbitrary objects
;; through Wasm without serialization:
instance.exports.store({ hello: 'world' });
04

関数

関数の定義と呼び出し

関数はコードの基本単位です。call は名前/インデックスで関数を呼びます。引数は呼び出しの前にスタックに積み、結果は関数が戻るときスタックに残ります。スタックは (result ...) の宣言と一致しなければなりません。

webassembly
(module
  (func $add (param $a i32) (param $b i32) (result i32)
    local.get $a
    local.get $b
    i32.add
  )
  (func $double (param $x i32) (result i32)
    local.get $x
    local.get $x
    i32.add      ;; or: i32.const 2  i32.mul
  )
  (func (export "use")
    i32.const 5
    i32.const 7
    call $add     ;; -> 12 on stack
    drop
  )
)

パラメータとローカル変数

パラメータは 0 起点のインデックスを持つ不変のローカルです。宣言したローカル(local $name type)はゼロ初期化され、可変です。local.get、local.set、local.tee(set +スタックに残す)を使います。ローカル変数は memory/global の外では Wasm 唯一の可変ストレージです。

webassembly
(func $f (param $a i32) (param $b i32) (result i32)
  (local $sum i32)         ;; mutable local
  (local $i i32)
  local.get $a
  local.get $b
  i32.add
  local.set $sum           ;; store into local
  i32.const 0
  local.set $i
  local.get $sum
)

;; tee: set and keep on stack
local.tee $sum             ;; $sum = top; stays on stack

複数の戻り値

multi-value 提案により、関数は複数の値を返せ(0 個も受け付け)、2020 年以降すべての主要エンジニアリングでサポートされています。これにより memory 経由の出力パラメータが不要になり、swap/minmax のようなイディオムが自然に書けます。

webassembly
;; Multi-value: return two i32 values
(func $minmax (param $a i32) (param $b i32) (result i32 i32)
  local.get $a
  local.get $b
  i32.lt_s
  if (result i32 i32)
    local.get $a
    local.get $b
  else
    local.get $b
    local.get $a
  end
)

;; Caller receives both on the stack
(func (export "use")
  i32.const 3
  i32.const 8
  call $minmax
  ;; stack: [min=3, max=8]
  drop drop
)

再帰

Wasm は直接再帰をサポートします — 関数は自分自身を呼べます。MVP の Wasm には末尾呼び出し最適化がありません(tail-call 提案が return_call を追加します)。深い再帰はスタックオーバーフローのリスクがあるため、本番コードでは反復ループが推奨です。

webassembly
(module
  (func $fact (param $n i32) (result i32)
    local.get $n
    i32.const 1
    i32.le_s
    if (result i32)
      i32.const 1
    else
      local.get $n
      local.get $n
      i32.const 1
      i32.sub
      call $fact     ;; recursive call
      i32.mul
    end
  )
  (export "factorial" (func $fact))
)

インライン export と名前付き呼び出し

関数定義に付けたインラインの (export "name") は、独立した (export ...) 宣言のショートハンドです。call_ref(参照型の提案)は funcref 経由で直接関数を呼び出し、テーブル参照なしで第一級の関数値を可能にします。

webassembly
(module
  ;; Inline export on definition
  (func $add (export "add") (param i32 i32) (result i32)
    local.get 0
    local.get 1
    i32.add
  )

  ;; call_ref: call via funcref (reference types)
  (func $caller (param $f funcref) (param i32) (result i32)
    local.get 1
    local.get 0
    call_ref (param i32) (result i32)
  )
)

start 関数

モジュールは 1 つの (start $func) 関数を宣言でき、インスタンス化時に自動で実行されます — 初期化に便利です。引数を取らず何も返しません。start 関数はモジュールに 1 つしか許されません。

webassembly
(module
  (func $init
    ;; runs once at instantiation
    i32.const 0
    i32.const 42
    i32.store
  )
  (start $init)        ;; declare as start function
  (memory (export "mem") 1)
)

;; The start function runs automatically after
;; instantiation, before instantiate() resolves.
;; It takes no params and returns nothing.
05

Memory

線形メモリの宣言

線形メモリは連続した ArrayBuffer のような領域で、64KiB ページ単位で成長します。(memory 1 10) は初期=1、最大=10 を宣言します。memory は Wasm と JS の間でまとまったデータ(文字列、配列)を渡す唯一の手段です。JS からアクセスするにはエクスポートしましょう。

webassembly
(module
  ;; 1 page = 64KiB. Declare 1 page, max 10.
  (memory $mem 1 10)
  (export "memory" (memory $mem))

  ;; JS-side: read/write the exported memory
  ;; const buf = new Uint8Array(instance.exports.memory.buffer);
)

memory.grow

memory.grow はページを追加し、前のサイズ(ページ数)を返します。失敗時は -1 です。重要なのは、成長させると基の ArrayBuffer が切り離されること — 既存のすべての TypedArray ビューが使えなくなります。grow の呼び出しの後は必ずビューを作り直しましょう。

webassembly
(func $grow (result i32)
  i32.const 1            ;; request 1 more page
  memory.grow            ;; returns previous size (or -1)
)

;; In JS, growing detaches the old buffer!
const prev = instance.exports.grow();
const buf = new Uint8Array(instance.exports.memory.buffer);
// OLD buf references are now detached — re-create views!

load と store の操作

load/store にはサイズ(8/16/32/64 ビット)と符号拡張(_s/_u)のバリエーションがあります。offset=N はアドレスのオペランドに定数を加え、align= はヒントです(サイズ以下でなければならない)。すべてのアドレスは線形メモリへのバイトオフセットです。

webassembly
;; Load: read from memory at address (top of stack)
i32.load  offset=0 align=2     ;; 4-byte aligned load
i32.load8_u                    ;; 1 byte, zero-extended
i32.load16_s                   ;; 2 bytes, sign-extended
f64.load                       ;; 8-byte float load

;; Store: write value at address
i32.const 100        ;; address
i32.const 42         ;; value
i32.store            ;; mem[100] = 42

i32.const 100
i32.const 0xFF
i32.store8           ;; write 1 byte

メモリサイズとアライメント

Wasm のアライメントはパフォーマンスのヒントであって、正しさの制約ではありません — アラインされていないアクセスも常に動作します。'align' の値は演算の自然なサイズを超えてはいけません。memory.size は現在のページ数(各 64KiB)を返します。

webassembly
;; Each load/store has a natural alignment:
;;   i32.load   -> 4 bytes
;;   i64.load   -> 8 bytes
;;   f32.load   -> 4 bytes
;;   i32.load8  -> 1 byte

;; Explicit alignment hint (does not affect correctness)
i32.load align=2    ;; may be slower but still works

;; memory.size returns current pages
(func $pages (result i32)
  memory.size
)

共有メモリとアトミック

共有メモリ(threads 提案)は複数の Wasm インスタンス/Worker が 1 つの memory を共有し、並列性を実現します。アトミック操作(i32.atomic.load/store/rmw.add/cmpxchg)が同期を提供します。ブラウザではクロスオリジン分離(COOP/COEP ヘッダー)が必要です。

webassembly
(module
  ;; Shared memory (threads proposal)
  (memory 1 1 shared)
  (export "memory" (memory 0))

  ;; Atomic operations
  (func (param i32 i32)
    local.get 0       ;; address
    local.get 1       ;; value
    i32.atomic.store
  )
  (func (param i32) (result i32)
    local.get 0
    i32.atomic.load
  )
  (func (param i32) (result i32)
    local.get 0
    i32.const 1
    i32.atomic.rmw.add   ;; atomic read-modify-write
  )
)

メモリからの文字列の読み取り

Wasm には文字列型がありません — 文字列は線形メモリ内のバイト列で、たいてい (ポインタ, 長さ) のペアとして渡します。UTF-8 の変換は TextEncoder/TextDecoder が担います。書き込む前に、メモリ領域が十分に大きいことを必ず確認しましょう。

webassembly
// Wasm has no string type — strings live in linear memory.
// Decode UTF-8 from a (ptr, len) pair returned by Wasm:

function readString(memory, ptr, len) {
  const bytes = new Uint8Array(memory.buffer, ptr, len);
  return new TextDecoder('utf-8').decode(bytes);
}

// Writing a string into Wasm memory:
function writeString(memory, str, ptr) {
  const bytes = new TextEncoder().encode(str);
  const view = new Uint8Array(memory.buffer, ptr, bytes.length);
  view.set(bytes);
  return bytes.length; // return length
}
06

Table

テーブルの宣言

テーブルは参照(たいてい funcref)の配列で、間接呼び出しと動的ディスパッチに使われます。バイトを保持する memory と違い、テーブルは Wasm が偽造できない不透明な参照を保持します。(elem ...) セグメントはインスタンス化時にテーブルのスロットを初期化します。

webassembly
(module
  ;; A table of function references, initial size 1
  (table 1 funcref)
  (export "table" (table 0))

  ;; With max size
  (table $t 4 16 funcref)

  ;; elem segment: initialize table slots
  (elem (i32.const 0) $fn1 $fn2 $fn3)
  (func $fn1)
  (func $fn2)
  (func $fn3)
)

funcref テーブルと call_indirect

call_indirect はテーブルのエントリ経由でインデックスにより呼び出しを振り分けます。(type ...) 宣言は必須で — Wasm は実行時に関数のシグネチャが一致するかチェックします(不一致は trap)。これが Wasm での vtable と OO ディスパッチの基盤です。

webassembly
(module
  (type $bin (func (param i32 i32) (result i32)))
  (table 3 funcref)

  (func $add (param i32 i32) (result i32)
    local.get 0  local.get 1  i32.add)
  (func $sub (param i32 i32) (result i32)
    local.get 0  local.get 1  i32.sub)
  (func $mul (param i32 i32) (result i32)
    local.get 0  local.get 1  i32.mul)

  (elem (i32.const 0) $add $sub $mul)

  (func (export "dispatch") (param i32 i32 i32) (result i32)
    local.get 0      ;; arg a
    local.get 1      ;; arg b
    local.get 2      ;; table index
    call_indirect (type $bin)
  )
)

テーブルの grow、get、set

table.grow はスロットを追加し、前のサイズ(または -1)を返します。table.get/table.set はインデックスでエントリを読み書きします。テーブルを成長させると、コールバックの実行時登録が可能になります。暴走した割り当てを防ぐため、初期サイズ+最大の境界で成長を制限しましょう。

webassembly
(func $addSlot (param funcref) (result i32)
  local.get 0
  i32.const 1            ;; grow by 1
  table.grow             ;; returns old size, or -1
)

(func $read (param i32) (result funcref)
  local.get 0
  table.get
)

(func $write (param i32 funcref)
  local.get 0     ;; index
  local.get 1     ;; funcref
  table.set
)

ホストオブジェクトのための externref テーブル

externref のテーブルはホスト(JS)オブジェクトへの不透明な参照を保存します — Wasm はそれを保持し受け渡しはできますが、中身を検査はできません。コールバックの登録、JS のハンドルテーブル、オブジェクト指向の JS API を Wasm へ橋渡しするのに理想的です。

webassembly
(module
  ;; Table holding opaque JS objects
  (table 8 externref)
  (export "table" (table 0))

  (func $store (param i32 externref)
    local.get 0
    local.get 1
    table.set
  )
  (func $load (param i32) (result externref)
    local.get 0
    table.get
  )
)

// JS: pass arbitrary objects
instance.exports.store(2, { callback: () => 42 });

動的ディスパッチのパターン

動的ディスパッチのパターン: 操作をテーブルに保存し、call_indirect でインデックスにより呼び出します。必須の型チェックと組み合わせると、安全な vtable 風のポリモーフィズムになります。Rust の enum、C++ の仮想関数、インタプリタがディスパッチを実装する方法です。

webassembly
(module
  (type $op (func (param i32 i32) (result i32)))
  (table 4 funcref)
  (elem (i32.const 0) $add $sub $mul $div)

  (func $add (param i32 i32) (result i32)
    local.get 0  local.get 1  i32.add)
  (func $sub (param i32 i32) (result i32)
    local.get 0  local.get 1  i32.sub)
  (func $mul (param i32 i32) (result i32)
    local.get 0  local.get 1  i32.mul)
  (func $div (param i32 i32) (result i32)
    local.get 0  local.get 1  i32.div_s)

  (func (export "apply") (param $op i32) (param $a i32) (param $b i32)
    (result i32)
    local.get $a
    local.get $b
    local.get $op
    call_indirect (type $op)
  )
)
07

Global

グローバルの宣言

グローバルはモジュールレベルの単一の値で、不変(デフォルト)か可変(mut)です。関数呼び出しをまたいで残るため、カウンター、設定フラグ、定数に便利です。可変のグローバルは memory/table の外で唯一の共有可能な可変状態です。

webassembly
(module
  ;; Immutable global (const)
  (global $counter (mut i32) (i32.const 0))

  ;; Read-only global
  (global $pi f64 (f64.const 3.14159265))

  (func $increment
    global.get $counter
    i32.const 1
    i32.add
    global.set $counter
  )
)

可変 vs 不変のグローバル

'mut' がなければグローバルは不変で、global.set はコンパイルエラーになります。初期化子は定数式でなければなりません(例: i32.const、ref.null、インポートした不変グローバルの global.get)。安全のためデフォルトは不変にしましょう。

webassembly
(module
  ;; (global $name type init)        -> immutable
  ;; (global $name (mut type) init)  -> mutable

  (global $version i32 (i32.const 3))
  ;; global.set $version  ;; ERROR: immutable

  (global $state (mut i32) (i32.const 0))
  (func (export "toggle")
    global.get $state
    i32.eqz
    if
      i32.const 1  global.set $state
    else
      i32.const 0  global.set $state
    end
  )
)

グローバルのインポート

グローバルのインポートにより、ホストがインスタンス化時に設定値(または WebAssembly.Global オブジェクト)をモジュールへ注入できます。不変のインポートグローバルは他のグローバルの初期化に使えます。WebAssembly.Global は、可変で共有されるグローバルの JS から見えるラッパーです。

webassembly
(module
  ;; Import a global from JS
  (global $env (import "env" "version") i32)

  ;; Mutable imported global
  (global $flag (import "env" "flag") (mut i32))

  (func (export "ver") (result i32)
    global.get $env
  )
)

// JS side
const imports = {
  env: {
    version: 3,
    flag: new WebAssembly.Global({ value: 'i32', mutable: true }, 0)
  }
};

グローバルのエクスポートと共有

エクスポートされたグローバルは JS から、.value プロパティ(取得でき、可変なら設定も可能)を持つ WebAssembly.Global オブジェクトとしてアクセスできます。Global オブジェクトを複数のモジュールインスタンス間で共有すれば、memory に触れずに状態を協調させるきれいな方法になります。

webassembly
(module
  (global $g (export "counter") (mut i32) (i32.const 0))
  (func (export "inc")
    global.get $g
    i32.const 1
    i32.add
    global.set $g
  )
)

// JS reads/writes the global directly
const g = instance.exports.counter;
g.value;        // 0
instance.exports.inc();
g.value;        // 1
g.value = 100;  // write directly

グローバルのユースケース

グローバルが向く 3 つのパターン: (1) インポートした設定の定数、(2) インスタンス間で共有される永続的なカウンター/状態、(3) 計算結果のキャッシュ。単一の値には memory よりシンプルで、JS 経由で共有すれば複数のインスタンスから見えます。

webassembly
(module
  ;; Configuration constants
  (global $maxSize (import "config" "maxSize") i32)
  (global $debug   (import "config" "debug")   i32)

  ;; Persistent counters
  (global $calls (mut i32) (i32.const 0))

  (func (export "handle") (result i32)
    global.get $calls
    i32.const 1
    i32.add
    global.set $calls
    global.get $calls
  )
)
08

インポートとエクスポート

関数のインポート

インポートにより、Wasm がホスト(JS)の関数を呼べます。各インポートは 2 段の名前(module、field)で識別されます。instantiate に渡す import オブジェクトはこれらの名前と一致しなければなりません。インポートは、Wasm が外界(I/O、ログ、スケジューリング)へ手を伸ばす方法です。

webassembly
(module
  ;; Import a function under module.field naming
  (func $log (import "console" "log") (param i32))
  (func $now (import "env" "now") (result f64))

  (func (export "run")
    i32.const 42
    call $log        ;; -> console.log(42)
    call $now
    drop
  )
)

// JS
WebAssembly.instantiateStreaming(fetch('m.wasm'), {
  console: { log: x => console.log('wasm:', x) },
  env:     { now: () => performance.now() }
});

memory のインポート

memory のインポートにより、複数の Wasm モジュール(と JS)が 1 つのメモリ領域を共有できます — Wasm「ライブラリ」の基盤です。1 つのモジュールが確保して書き込み、別のモジュールが読み取ります。データをコピーせずにモジュールを組み合わせられ、component model の先駆けです。

webassembly
(module
  (memory (import "env" "memory") 1)
  (func (export "writeHi")
    i32.const 0
    i32.const 72     ;; 'H'
    i32.store8
  )
)

// Shared memory across multiple modules:
const memory = new WebAssembly.Memory({ initial: 1 });
WebAssembly.instantiateStreaming(fetch('a.wasm'), { env: { memory } });
WebAssembly.instantiateStreaming(fetch('b.wasm'), { env: { memory } });
// Both modules read/write the SAME memory

グローバルとテーブルのインポート

グローバルとテーブルもインポートでき、モジュール間で共有の状態や関数ポインタのテーブルが実現します。JS のコンストラクタは WebAssembly.Table です。可変のインポートグローバルは、モジュールを再ビルドせずにホストが Wasm の挙動に動的に影響を与えられます。

webassembly
(module
  (global $seed (import "env" "seed") i32)
  (table (import "env" "table") 4 funcref)

  (func (export "rand") (result i32)
    global.get $seed
    i32.const 1103515245
    i32.mul
    i32.const 12345
    i32.add
    ;; (truncated LCG step)
  )
)

// JS provides the imports
const imports = {
  env: {
    seed: 42,
    table: new WebAssembly.Table({
      element: 'funcref', initial: 4, maximum: 16
    })
  }
};

関数、memory、テーブルのエクスポート

モジュール内で宣言されたものは何でもエクスポートできます: 関数、memory、テーブル、グローバル。エクスポートは instance.exports のプロパティになります。memory のエクスポートは JS に線形ヒープのビューを与え、グローバルのエクスポートは WebAssembly.Global オブジェクトを、テーブルのエクスポートは関数参照を公開します。

webassembly
(module
  (memory 1)
  (table 2 funcref)
  (global $c (mut i32) (i32.const 0))

  (func (export "add") (param i32 i32) (result i32)
    local.get 0  local.get 1  i32.add)
  (export "memory" (memory 0))
  (export "table"  (table 0))
  (export "counter" (global $c))
)

// JS usage
const { add, memory, table, counter } = instance.exports;
add(2, 3);                              // 5
new Uint8Array(memory.buffer);          // raw bytes
table.get(0);                           // funcref
counter.value;                          // 0

インラインのインポートとエクスポート

インラインの (import "m" "f") と (export "name") の注釈は構文糖衣です — 独立した (import ...)/(export ...) 形式と同じバイナリにコンパイルされます。1 つの定義にインラインのエクスポートを付けられますが、インポートする項目については、インポートとエクスポートは別々に宣言します。

webassembly
(module
  ;; Inline import (compact form)
  (func $log (import "env" "log") (param i32))

  ;; Inline export on function
  (func (export "add") (param i32 i32) (result i32)
    local.get 0  local.get 1  i32.add
  )

  ;; Inline export on memory
  (memory (export "mem") 1)

  ;; Inline import + export combined is NOT allowed;
  ;; a definition imports OR exports, not both.
)

import オブジェクトのベストプラクティス

import オブジェクトは、モジュールの (module, field) の名前に合わせて構成しましょう。分かりやすいエラーを出すため、インスタンス化の前に必須のインポートを検証します。適切な場所ではホスト関数を try/catch で包みましょう — インポート内部の捕捉されない throw は Wasm の呼び出し元を trap させます。

webassembly
// Build a typed import object
const imports = {
  env: {
    log:       (i) => console.log('[wasm]', i),
    now:       () => performance.now(),
    abort:     () => { throw new Error('wasm abort'); },
    memory:    new WebAssembly.Memory({ initial: 1 }),
    seed:      42,
  }
};

// Validate imports before instantiation:
function checkImports(imports, required) {
  for (const [mod, fields] of Object.entries(required)) {
    for (const f of fields) {
      if (!imports[mod]?.[f] === undefined) {
        throw new Error(`Missing import: ${mod}.${f}`);
      }
    }
  }
}
09

制御フロー

block

block はラベル付きのスコープを作り、分岐(br)がそこから抜けます。Wasm の分岐は構造化されています — 囲んでいる block/loop/if の末尾にしかジャンプできません。(result ...) を持つ block は、分岐で入っても流れ落ちても、その値をスタックに残します。

webassembly
;; block: a labeled group with a single exit
(block $b
  i32.const 1
  i32.const 2
  i32.add
  ;; br $b exits the block (with optional value)
  br $b
  ;; unreachable code
)
;; stack now has the result of the block

;; Blocks can produce a value (multi-value):
(block $b (result i32)
  i32.const 42
  br $b
)

loop

loop は block に似ていますが、br $loop は末尾ではなくループの先頭へジャンプします(反復の続行)— block とは逆です。Wasm には for/while のキーワードがなく、反復は loop +条件付きの br_if で組み立てます。

webassembly
;; loop: a block whose br jumps back to the TOP
(func $count (param $n i32) (result i32)
  (local $i i32) (local $sum i32)
  i32.const 0  local.set $i
  i32.const 0  local.set $sum
  (loop $loop
    local.get $i
    local.get $n
    i32.lt_s
    if
      local.get $sum
      local.get $i
      i32.add
      local.set $sum
      local.get $i
      i32.const 1
      i32.add
      local.set $i
      br $loop        ;; jump back to loop start
    end
  )
  local.get $sum
)

if / else

if はスタックから i32 を消費します(非ゼロ=真)。(result ...) 句を付けると、両分岐の型が一致するとき if が値を産み出します。else のない if も許され、分岐は空でも構いません。if は block + br_if の糖衣です。

webassembly
;; if consumes a condition from the stack
(func $abs (param $x i32) (result i32)
  local.get $x
  if (result i32)
    local.get $x
  else
    i32.const 0
    local.get $x
    i32.sub       ;; negate
  end
)

;; if without else (no result)
(func (param i32)
  local.get 0
  if
    ;; do something only if non-zero
  end
)

br と br_if

br $label は名前付きの block/if の末尾(または loop の先頭)へジャンプします。br_if は条件付きで同じことをします。ラベルは数値でも構いません(br 0 = 最も内側)。値を伴う分岐はその値をスタックに残します — Wasm の慣用的な早期 return の方法です。

webassembly
;; br: unconditional branch to a label
(block $outer
  (block $inner
    br $inner       ;; exits inner
    br $outer       ;; exits outer (unreachable here)
  )
)

;; br_if: branch only if top of stack is non-zero
(func $clamp (param $x i32) (result i32)
  (block $done (result i32)
    local.get $x
    i32.const 100
    i32.gt_s
    br_if $done          ;; if x > 100, branch with...
    i32.const 100        ;; ...100 on the stack
    local.get $x
    i32.const 0
    i32.lt_s
    br_if $done          ;; if x < 0, branch with...
    i32.const 0          ;; ...0
    local.get $x         ;; else x
  )
)

br_table(switch)

br_table は switch を実装します: i32 のインデックスを消費し、列挙されたラベルのどれか、範囲外なら最後(デフォルト)のラベルへジャンプします。各 case が値を返せるよう、ブロックは最も外側からネストしましょう。タグによるディスパッチで最も効率的な方法です。

webassembly
;; br_table: jump table (like a C switch)
(func $dayName (param $d i32) (result i32)
  (block $default
    (block $sat
      (block $sun
        local.get $d
        br_table $sun $sat $default
      )
      i32.const 0  ;; Sunday
      return
    )
    i32.const 6   ;; Saturday
    return
  )
  i32.const -1    ;; default
)

;; br_table $l0 $l1 $l2 ... $default
;; index 0 -> $l0, 1 -> $l1, ... out-of-range -> $default

return と unreachable

return はスタック上の値とともに即座に関数を抜けます。unreachable は常に trap します(実行時例外を投げる)— 実行されるはずのないコードパスの印で、assert(false) に似ています。どちらも構造化されたブロックモデルの外に出るための逃し口です。

webassembly
(func $find (param $arr i32) (param $len i32) (param $key i32)
  (result i32)
  (local $i i32)
  i32.const 0  local.set $i
  (block $notFound
    (loop $loop
      local.get $i
      local.get $len
      i32.ge_s
      br_if $notFound
      ;; load arr[i] and compare...
      local.get $i
      i32.const 1
      i32.add
      local.set $i
      br $loop
    )
  )
  unreachable        ;; traps if reached
)

;; return: early exit from the function
;; unreachable: always traps (used to mark bugs)
10

JS との相互運用

数値の受け渡し

i32/f32/f64 は JS の number に直接対応します。i64 は JS の BigInt に対応します(大きな整数は Number の安全な範囲を超えます)。i64 のパラメータ/戻り値には常に BigInt を使いましょう。境界での変換はゼロコピーですが、頻繁に跨ぐとオーバーヘッドになります — まとまった操作は Wasm 内で実行しましょう。

webassembly
// Numbers pass directly across the Wasm/JS boundary.
const exports = instance.exports;

exports.add(2, 3);          // 5  (i32 -> JS number)
exports.square(4);          // 16
exports.compute(1.5, 2.5);  // f64 -> JS number

// i64 caveat: before BigInt integration, i64 returns
// caused problems. Now Wasm i64 maps to JS BigInt:
const big = exports.bigResult();  // 9007199254740993n

// Passing a BigInt to an i64 param:
exports.takeBigInt(123n);

文字列の受け渡し

文字列は境界を UTF-8 のバイト列として渡ります: JS が Wasm のメモリへエンコードし、(ポインタ, 長さ) を渡します。多くの場合、Wasm 側が alloc/free のヘルパーをエクスポートするか、両方を 1 つの i64 に詰めます(下位 32 ビット=ptr、上位 32 ビット=len)。リークを避けるため、バッファは必ず解放するか再利用しましょう。

webassembly
// Wasm has no string type. Encode UTF-8 into memory,
// pass (ptr, len) to Wasm:

function passString(memory, str) {
  const bytes = new TextEncoder().encode(str);
  const ptr = instance.exports.alloc(bytes.length);
  new Uint8Array(memory.buffer, ptr, bytes.length).set(bytes);
  instance.exports.processString(ptr, bytes.length);
  instance.exports.dealloc(ptr, bytes.length);
}

// Receiving a string back:
function recvString(memory, ptrLen) {
  const ptr = ptrLen >>> 0;
  const len = ptrLen >>> 32;
  const bytes = new Uint8Array(memory.buffer, ptr, len);
  return new TextDecoder().decode(bytes);
}

配列とまとまったデータの受け渡し

まとまった数値データには、Wasm のメモリを適切な型の TypedArray(Float32Array、Int32Array など)として見て、.set() でコピーします。これが最速の経路です — memcpy のようなもの。ポインタのアライメントに注意し(i32/f32 は 4 バイト、i64/f64 は 8 バイト)、メモリは必ず解放しましょう。

webassembly
// Write a JS array into Wasm memory:
function passArray(memory, arr) {
  const view = new Float32Array(memory.buffer);
  const ptr = instance.exports.alloc(arr.length * 4);
  const offset = ptr / 4;
  for (let i = 0; i < arr.length; i++) view[offset + i] = arr[i];
  return ptr;
}

// Faster: use TypedArray.set with a subarray
function passArrayFast(memory, arr) {
  const ptr = instance.exports.alloc(arr.length * 4);
  new Float32Array(memory.buffer, ptr, arr.length).set(arr);
  return ptr;
}

境界をまたぐメモリ管理

Wasm のメモリは手動管理です — ガベージコレクタはありません。Wasm が alloc/free をエクスポートするなら(または malloc 風のヘルパーを使うなら)、JS 側のアクセスは try/finally で包み、解放を保証しましょう。memory.grow が ArrayBuffer のビューを切り離すことにも注意 — 成長後はビューを作り直します。

webassembly
// Wasm has no GC — JS must manage allocations.
// Pattern: Wasm exports alloc/free, JS uses them:

const { memory, alloc, free, process } = instance.exports;

function withBuffer(size, fn) {
  const ptr = alloc(size);
  try {
    return fn(new Uint8Array(memory.buffer, ptr, size));
  } finally {
    free(ptr, size);
  }
}

// CAUTION: TypedArray views become detached after
// memory.grow — re-create them after any grow call.

WebAssembly.Global

WebAssembly.Global は Wasm のグローバル値を包む JS のラッパーです。1 つ作って複数のモジュールインスタンスに渡せば、memory に触れずに可変の状態をきれいに共有できます。.value プロパティが基の i32/i64/f32/f64(または v128/externref)を読み書きします。

webassembly
// Create a global on the JS side
const counter = new WebAssembly.Global(
  { value: 'i32', mutable: true },
  0
);

// Pass to Wasm at instantiation
WebAssembly.instantiateStreaming(fetch('m.wasm'), {
  env: { counter }
});

// Read/write from JS
counter.value;        // 0
counter.value = 10;   // set
counter.value++;      // 11

// Share across multiple instances
WebAssembly.instantiateStreaming(fetch('m2.wasm'), {
  env: { counter }    // same Global object
});

WebAssembly.Table とエラー

WebAssembly.Table は JS と Wasm の両方からアクセスできる関数参照を保存します — コールバックのレジストリやディスパッチテーブルに便利です。Wasm の trap(ゼロ除算、範囲外メモリ、スタックオーバーフロー)は、JS では WebAssembly.RuntimeError として現れます — 危険な呼び出しは try/catch で包みましょう。

webassembly
// Table of function references, callable from JS indirectly
const table = new WebAssembly.Table({
  element: 'funcref',
  initial: 4,
  maximum: 16
});

// Set a slot to a Wasm-exported function
table.set(0, instance.exports.add);
table.get(0)(2, 3);  // 5

// Errors propagate as 'RuntimeError' across the boundary:
try {
  instance.exports.divide(1, 0);
} catch (e) {
  // e instanceof WebAssembly.RuntimeError
  console.error('Wasm trapped:', e.message);
}
11

C/C++ から Wasm へのコンパイル

Emscripten のセットアップ

Emscripten は C/C++(と LLVM 系言語)を Wasm へコンパイルする定番のツールチェーンです。Clang、Binaryen、ブラウザ向けに移植された libc/libstdc++ を同梱します。各シェルセッションで emsdk_env により環境を有効化しましょう。更新が頻繁なので、定期的に再インストールします。

webassembly
# Install the Emscripten SDK
git clone https://github.com/emscripten-core/emsdk.git
cd emsdk
./emsdk install latest
./emsdk activate latest
source ./emsdk_env.sh   # Linux/macOS
# Windows: emsdk_env.bat

# Verify
emcc --version
# emcc (Emscripten gcc/clang-like replacement)

C の Hello World

標準の C はそのまま動きます — printf は Emscripten が提供する仮想ターミナルへ書き込みます。main() はモジュールのロード時に自動で呼ばれます。JS から呼ぶ関数は、EMSCRIPTEN_KEEPALIVE か -s EXPORTED_FUNCTIONS フラグでエクスポートしましょう。

webassembly
// hello.c
#include <stdio.h>

int add(int a, int b) {
    return a + b;
}

int main() {
    printf("Hello from C!\n");
    printf("2 + 3 = %d\n", add(2, 3));
    return 0;
}

emcc でのコンパイル

emcc がコンパイルを駆動します。-O3 は積極的な最適化(インライン化、デッドコード除去)を有効にします。EXPORTED_FUNCTIONS は公開する C のシンボル(先頭に _)を列挙します。MODULARIZE はローダーをファクトリとして包み、バンドラで使いやすくします。出力形式: .wasm のみ、.js の接着+.wasm、または .html のデモです。

webassembly
# Standalone .wasm (no main, exported functions only)
emcc add.c -O3 -o add.wasm \
  -s EXPORTED_FUNCTIONS='["_add"]' \
  -s ALLOW_MEMORY_GROWTH=1

# HTML + JS + Wasm bundle (auto-runs main)
emcc hello.c -o hello.html

# With optimizations and a specific output
emcc hello.c -O3 -s WASM=1 -o hello.js

# Common flags:
#   -O0/-O1/-O2/-O3/-Os   optimization level
#   -s MODULARIZE=1       export as JS module
#   -s EXPORT_ES6=1       ES module output
#   -s ENVIRONMENT=web    target only the web

Emscripten の HTML 出力と Module

Emscripten の 'Module' オブジェクトは JS 側のランタイムです: _ プレフィックス付きの C 関数を公開し、メモリ(_malloc/_free)を管理し、フック(print、onRuntimeInitialized)を提供します。MODULARIZE を付けると、バンドラと非同期ロードに適した Promise を返すファクトリになります。

webassembly
// Generate a runnable HTML demo
//   emcc hello.c -o hello.html
// Then open hello.html in a browser.

// Modularized loader (use from JS):
//   emcc hello.c -o hello.js -s MODULARIZE=1 -s EXPORT_NAME='createModule'

import createModule from './hello.js';

const Module = await createModule({
  print: (text) => console.log('C said:', text),
  onRuntimeInitialized: () => {
    Module._main();          // call main
    const sum = Module._add(2, 3);
    console.log('sum:', sum);  // 5
  }
});

C から JS を呼ぶ(EM_JS / EM_ASM)

EM_JS は C から直接呼べる JS 関数をインラインで定義します — 効率的で同期的です。EM_ASM はインラインの JS スニペットを埋め込みます。引数には $0、$1、... を使います。これらのマクロは、別の JS バインディングを書かずに、C をブラウザ API(DOM、fetch、Web Audio)へつなぎます。

webassembly
#include <emscripten.h>

// EM_JS: define a JS function callable from C
EM_JS(void, callAlert, (int x), {
  alert("Value from C: " + x);
});

// EM_ASM: inline JS (use $n for arguments)
void logValue(int n) {
  EM_ASM({
    console.log("C passed:", $0);
  }, n);
}

int main() {
  callAlert(42);
  logValue(99);
  return 0;
}

ファイルシステムのサポート(MEMFS)

Emscripten はメモリ内の仮想ファイルシステム MEMFS を提供します。fopen/fread/fwrite は C と同じように働きます。--preload-file でアセットをコンパイル時に .data サイドカーへ埋め込みましょう。永続ストレージには IndexedDB へ同期する IDBFS、Node では実 FS を公開する NODERAWFS を使います。

webassembly
#include <stdio.h>
#include <emscripten.h>

int main() {
    // MEMFS: a virtual in-memory filesystem
    FILE *f = fopen("/tmp/data.txt", "w");
    fprintf(f, "Hello, MEMFS!\n");
    fclose(f);

    f = fopen("/tmp/data.txt", "r");
    char buf[64];
    fgets(buf, sizeof(buf), f);
    fclose(f);
    printf("%s", buf);
    return 0;
}

// Preload files at compile time:
//   emcc app.c -o app.html \
//     --preload-file assets/data.txt
12

Rust から Wasm へのコンパイル

wasm-pack のセットアップ

Rust は wasm32-unknown-unknown ターゲットで Wasm へコンパイルされます。推奨ツールは wasm-pack です — cargo を包み、wasm-bindgen を実行し、npm で使えるパッケージを作ります。WASI ターゲットには代わりに wasm32-wasi を使いましょう。

webassembly
# Install Rust (rustup)
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

# Add the wasm32 target
rustup target add wasm32-unknown-unknown

# Install wasm-pack (the canonical Wasm tool for Rust)
cargo install wasm-pack
# or: curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh

# Verify
wasm-pack --version

Rust のライブラリ構成

wasm-bindgen は Rust と JS の橋渡しです。#[wasm_bindgen] がエクスポート対象をマークします。文字列、Vec<u8>、JS オブジェクトは自動変換されます。コンストラクタ属性は new() を JS のコンストラクタとして公開します。Rust をネイティブのように感じさせる JS の接着コードを生成します。

webassembly
// src/lib.rs
use wasm_bindgen::prelude::*;

// Export a function callable from JS
#[wasm_bindgen]
pub fn add(a: i32, b: i32) -> i32 {
    a + b
}

// Export a struct with methods
#[wasm_bindgen]
pub struct Counter {
    count: i32,
}

#[wasm_bindgen]
impl Counter {
    #[wasm_bindgen(constructor)]
    pub fn new() -> Counter {
        Counter { count: 0 }
    }
    pub fn increment(&mut self) -> i32 {
        self.count += 1;
        self.count
    }
}

wasm-pack でのビルド

wasm-pack build は公開可能な npm パッケージを作ります: .wasm バイナリ、JS の接着コード、TypeScript の .d.ts ファイルです。--target web はブラウザで直接使える自己完結した ES モジュールを、--target bundler は webpack/vite との統合を提供します。生成された型により完全な TS の補完が得られます。

webassembly
# Build for the browser (npm package output)
wasm-pack build --target web

# Targets:
#   --target web       ES module, modern browsers
#   --target bundler   for webpack/rollup/vite
#   --target nodejs    CommonJS for Node.js
#   --target no-modules  global-based

# Output goes to ./pkg/
#   my_crate.js       JS glue
#   my_crate_bg.wasm  the binary
#   my_crate.d.ts     TypeScript types

# Use in JS:
import init, { add } from './pkg/my_crate.js';
await init();           // load the .wasm
console.log(add(2, 3)); // 5

wasm-bindgen による JS 相互運用

extern ブロックは JS の関数やクラスを Rust へインポートします。js_namespace = console は console.log を呼び、method はインポートした型に JS のメソッドを公開します。wasm-bindgen は文字列の変換(Rust の &str <-> JS の文字列)と所有権を処理します — 手動のメモリ操作は不要です。

webassembly
use wasm_bindgen::prelude::*;

// Call a JS function from Rust
#[wasm_bindgen]
extern "C" {
    #[wasm_bindgen(js_namespace = console)]
    fn log(s: &str);
}

#[wasm_bindgen]
pub fn run() {
    log("Hello from Rust!");
}

// Import a JS class
#[wasm_bindgen(module = "/js/util.js")]
extern "C" {
    pub type JsCounter;
    #[wasm_bindgen(constructor)]
    pub fn new() -> JsCounter;
    #[wasm_bindgen(method)]
    pub fn tick(this: &JsCounter) -> i32;
}

Rust から JS の呼び出しと panic

インポートした JS 関数は普通の Rust 関数として現れます。console_error_panic_hook を使うと、ブラウザコンソールで読める Rust の panic バックトレースが得られます(デフォルトの panic はメッセージなしで trap します)。#[wasm_bindgen(start)] 属性はインスタンス化時に main() を実行します — C の main のようなものです。

webassembly
use wasm_bindgen::prelude::*;

#[wasm_bindgen]
extern "C" {
    fn alert(s: &str);
}

#[wasm_bindgen]
pub fn greet(name: &str) {
    alert(&format!("Hello, {}!", name));
}

// Install a panic hook for readable errors:
#[wasm_bindgen(start)]
pub fn main() {
    console_error_panic_hook::set_once();
}
13

AssemblyScript

セットアップと Hello World

AssemblyScript は TypeScript 風の言語で、Wasm にコンパイルされます。C/Rust を学ばずに Wasm の性能が欲しい開発者向けです。構文は TS を映しますが、厳密な型を使います(number の代わりに i32 など)。ローダーを使うか、.wasm を直接インポートしましょう。

webassembly
# Install AssemblyScript compiler
npm install -g assemblyscript
# or use the boilerplate:
npm init assemblyscript my-app
cd my-app
npm install
npm run asbuild

// assembly/index.ts
export function add(a: i32, b: i32): i32 {
  return a + b;
}

// Load from JS:
import { instantiate } from "@assemblyscript/loader";
const module = await instantiate(fetch("build/release.wasm"));
console.log(module.exports.add(2, 3)); // 5

AssemblyScript の型

TypeScript と違い、AssemblyScript は具体的な数値型を強制します: i32、i64、f32、f64、u8、u16、u32 など。'number' はコンパイル時に拒否されます。StaticArray は GC を避け、ArrayBuffer/TypedArray は JS の API を反映します。厳密な型こそが、効率的な Wasm へのコンパイルを可能にしています。

webassembly
// Distinct numeric types (NOT just 'number')
let a: i32 = 42;
let b: i64 = 9007199254740993n;
let f: f64 = 3.14;
let u: u32 = 100;

// Bool, string, arrays
let flag: bool = true;
let s: string = "hi";
let arr: i32[] = [1, 2, 3];

// Static arrays (no GC overhead)
let sa: StaticArray<i32> = [1, 2, 3];

// TypedArray-like
let buf: ArrayBuffer = new ArrayBuffer(8);

メモリと文字列

AssemblyScript には管理対象のオブジェクト(Array、Map、String)のための小さな GC があります。JS へ渡るときの寿命の制御には __retain/__release を使いましょう。@assemblyscript/loader は、境界をまたぐための __getString、__newString、__getArray などを提供します。

webassembly
// Strings are UTF-16 in AssemblyScript memory
export function greet(name: string): string {
  return "Hello, " + name + "!";
}

// Manual memory management for buffers
export function process(len: i32): i32 {
  let buf = new ArrayBuffer(len);
  // ...fill buf...
  let result = __retain(buf);  // prevent GC
  return result;
}

// In JS, use the loader's __getString/__newString:
const ptr = module.exports.greet("World");
console.log(module.exports.__getString(ptr));

エクスポートとエントリポイント

export を付けた関数とクラスは Wasm のエクスポートになります。クラスはローダー経由で JS 互換のオブジェクトに対応します。_start が慣習的なエントリポイントです(C の main のような)。AssemblyScript の標準ライブラリは JS の Math、Array、Map を映しているので — 移行のカーブは緩やかです。

webassembly
// assembly/index.ts
export function fib(n: i32): i32 {
  if (n < 2) return n;
  return fib(n - 1) + fib(n - 2);
}

export class Vector {
  constructor(public x: f32, public y: f32) {}
  magnitude(): f32 {
    return Math.sqrt(this.x * this.x + this.y * this.y);
  }
}

// Module start function (runs at instantiation)
export function _start(): void {
  // initialization code
}

コンパイルと最適化

asc は AssemblyScript のコンパイラです。--optimize(-O)は Binaryen の wasm-opt を実行します。--runtime は GC を制御します: 'full'(デフォルト)、'half'(より小さい)、'none'(手動)。--importMemory はメモリをモジュール間で共有できます。ソースマップがあれば、元の .ts ソースでのデバッグが可能です。

webassembly
# Build debug vs release
npm run asbuild           # both debug and release
# or:
asc assembly/index.ts --outFile release.wasm --optimize

# Common flags
asc index.ts -o release.wasm \
  --optimize \
  --noAssert \
  --runtime half          # smaller GC runtime
  --importMemory          # use imported memory
  --sourceMap             # emit source map

# Optimize for size:
asc index.ts -o tiny.wasm --optimize --runtime none \
  --conformance --noDebug
14

WASI(WebAssembly System Interface)

WASI とは

WASI はブラウザの外の Wasm のための、移植可能でケイパビリティベースのシステムインターフェースです。Wasm が JS を呼ぶ Web と違い、WASI は Wasm にファイル、ネットワーク、環境への直接的な(サンドボックス化された)アクセスを与えます。ケイパビリティベースのセキュリティとは、プログラムが触れるのは明示的に preopen されたリソースだけという意味です。

webassembly
// WASI = WebAssembly System Interface
// A standardized API for Wasm to access OS capabilities:
//   - filesystem (files, directories)
//   - network sockets (preview2)
//   - environment variables, args
//   - clocks, random numbers
//   - process exit

// Capability-based security: a Wasm program can
// ONLY access resources it was explicitly granted.

// Targets:
//   wasm32-wasi           (preview1)
//   wasm32-wasip1         (preview1, new name)
//   wasm32-wasip2         (preview2, component model)

// Runtimes: wasmtime, wasmer, WasmEdge, browser_wasi_shim

wasmtime ランタイム

wasmtime は Bytecode Alliance のリファレンス WASI ランタイムです。--dir はホストのディレクトリを preopen し(ファイルアクセスを許可)、--env は環境変数を渡し、--net は preview2 でネットワーキングを有効にします。明示的な許可がなければ、Wasm プログラムは何も見えません — これがケイパビリティセキュリティの実例です。

webassembly
# Install wasmtime (the reference WASI runtime)
# macOS:  brew install wasmtime
# Linux:  curl https://wasmtime.dev/install.sh -sSf | bash
# Windows: scoop install wasmtime

# Run a WASI module
wasmtime hello.wasm

# Pass arguments
wasmtime hello.wasm arg1 arg2

# Preopen a directory (grant filesystem access)
wasmtime --dir=. app.wasm

# Set environment variables
wasmtime --env FOO=bar app.wasm

# Allow network (preview2)
wasmtime --net allow app.wasm

WASI での Wasm の実行(C の例)

WASI 向けに書かれたプログラムは、libc を使う普通の C プログラムに見えます。clang --target=wasm32-wasi と WASI の sysroot(wasi-sdk のリリースをダウンロード)でコンパイルします。同じ .wasm が再コンパイルなしで wasmtime、wasmer、WasmEdge、他の WASI ホストで動きます — これぞ移植性です。

webassembly
// wasi_hello.c
#include <stdio.h>
#include <unistd.h>

int main(int argc, char *argv[]) {
    printf("Hello from WASI!\n");
    printf("argc = %d\n", argc);
    for (int i = 0; i < argc; i++) printf("  argv[%d] = %s\n", i, argv[i]);
    return 0;
}

# Compile with the WASI SDK
clang --target=wasm32-wasi \
  --sysroot=/path/to/wasi-sysroot \
  -o hello.wasm wasi_hello.c

# Run
wasmtime hello.wasm foo bar
# Hello from WASI!
# argc = 3
#   argv[0] = hello.wasm
#   argv[1] = foo
#   argv[2] = bar

WASI のファイルシステムアクセス

WASI は POSIX 風のファイルシステム API(open、read、write、close)を公開します。preopen されたディレクトリの外のファイルは見えません。アクセスとリネームの許可には --dir=path:alias を使います。WASI preview2 は、より豊かな API のために component model のインターフェース(wasi filesystem、wasi sockets)を導入します。

webassembly
// wasi_fs.c — read a file passed via --dir
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>

int main() {
    int fd = open("input.txt", O_RDONLY);
    if (fd < 0) { perror("open"); return 1; }
    char buf[256];
    ssize_t n = read(fd, buf, sizeof(buf) - 1);
    if (n > 0) { buf[n] = '\0'; printf("%s", buf); }
    close(fd);
    return 0;
}

# Grant access, then run:
#   wasmtime --dir=. wasi_fs.wasm

WASI の環境と引数

WASI は標準の C インターフェース(argv、environ、getenv)で引数と環境変数を提供します。何が見えるかはホストが制御します — --env が特定の変数を許可します。これにより、Wasm プログラムはコード変更なしで設定可能になり、ホストの秘密の漏えいも制限されます。

webassembly
// wasi_env.c
#include <stdio.h>
#include <stdlib.h>

extern char **environ;

int main(int argc, char *argv[]) {
    printf("Args:\n");
    for (int i = 0; i < argc; i++) printf("  %s\n", argv[i]);

    printf("Env:\n");
    for (char **e = environ; *e; e++) printf("  %s\n", *e);

    const char *home = getenv("HOME");
    printf("HOME=%s\n", home ? home : "(unset)");
    return 0;
}

# Run with env vars:
#   wasmtime --env HOME=/tmp --env FOO=bar wasi_env.wasm a b c

WASI のソケット(preview)

WASI のソケットは preview2(component model)の一部です。wasi:sockets/tcp と wasi:sockets/udp がネットワーキングを提供し、wasi:http はより高レベルの HTTP クライアントを提供します。API は安定化が進んでいます — 今日の移植性には wasi:http を推奨します。wasmtime や WasmEdge のようなランタイムが実装しています。

webassembly
// WASI preview2 adds TCP/UDP sockets.
// In Rust (using wasi crate):
use wasi::sockets::network::{IpAddress, IpSocketAddress};

// Component-model based sockets:
//   - wasi:sockets/tcp
//   - wasi:sockets/udp
//   - wasi:sockets/ip-name-lookup

# Compile a Rust program for preview2:
cargo build --target wasm32-wasip2 --release

# Run with network access:
wasmtime --net allow target/wasm32-wasip2/release/myapp.wasm

// Note: socket APIs are still stabilizing.
// Use HTTP via wasi:http/types for stability.
15

デバッグ

wasm-objdump

wasm-objdump(WABT 提供)はモジュールの構造を表示します: 型、インポート、エクスポート、関数のシグネチャ、コードの逆アセンブリ、セクションサイズ。-x で高レベルの要約、-d で関数本体を WAT 風の命令に逆アセンブルします。モジュールの中身を実際に知るために不可欠です。

webassembly
# Inspect a .wasm file's structure
wasm-objdump -x module.wasm       # everything
wasm-objdump -d module.wasm       # disassemble functions
wasm-objdump -s module.wasm       # raw section contents
wasm-objdump -j Import -x m.wasm  # only the Import section

# Sample -x output:
# Section Type (1) at 0x0008:
#   type[0] (i32, i32) -> i32
# Section Function (3) at 0x0015:
#   func[0] type=0

検査のための wasm2wat

wasm2wat はバイナリの .wasm を人間が読める WAT に変換します。サードパーティのモジュールの理解、予想外の挙動のデバッグ、リバースエンジニアリングに非常に有用です。往復(wasm2wat → 編集 → wat2wasm)は挙動を保つため、WAT は真のソース形式と言えます。

webassembly
# Disassemble binary to readable text
wasm2wat module.wasm -o module.wat

# View in your editor
cat module.wat

# Round-trip: edit .wat, recompile
wat2wasm module.wat -o module.wasm

# Common inspection: find exports
grep "(export" module.wat

# Find imports
grep "(import" module.wat

ブラウザの DevTools

主要なブラウザはすべて DevTools で Wasm をデバッグできます: 逆アセンブルした WAT の表示、ブレークポイント、ローカル変数とコールスタックの検査。ソースマップ(Rust、AssemblyScript、Emscripten の -g)があれば、DevTools は元のソースへマップし戻します。DWARF デバッグ情報により、C/C++/Rust はさらに豊かなデバッグが可能です。

webassembly
// Chrome/Edge/Firefox DevTools support Wasm debugging:
//   1. Sources tab -> file tree shows .wasm entries
//   2. Click a .wasm to view disassembled WAT
//   3. Set breakpoints on function entries
//   4. Inspect the call stack and locals

// With source maps (Rust/AS), DevTools shows the
// ORIGINAL source (.rs / .ts) instead of WAT.

// Enable in chrome://flags:
//   "WebAssembly debugging: Support DWARF"

// Console logging from Wasm:
//   Import a JS log function and call it from WAT.
//   Rust: wasm_logger / console_log crate.
//   AS:   console.log via env import.

ソースマップ

ソースマップは Wasm の命令を元のソース言語へ結び付けます。Rust は wasm-pack 経由で、AssemblyScript は --sourceMap 経由で、Emscripten は -g4 経由で出力します。.wasm 内の sourceMappingURL コメント(カスタムセクション)が DevTools に .map の場所を教えます。なければ、生の WAT でデバッグすることになります。

webassembly
# Rust: source maps come automatically with wasm-pack
wasm-pack build --target web --dev

# AssemblyScript: emit source maps
asc index.ts -o release.wasm --sourceMap \
  --sourceMap include 'src/**/*.ts'

# Emscripten: include debug info and source map
emcc app.c -g4 -O0 -o app.js \
  --source-map-base http://localhost:8000/

# The .map file points DevTools back to the
# original .rs / .ts / .c source files.

# Validate a source map exists:
wasm-objdump -x app.wasm | grep sourceMappingURL

よくあるエラーと trap

繰り返し現れる Wasm のエラー: インポートの欠落(名前/型の不一致)、trap(unreachable、範囲外メモリ、ゼロ除算での整数オーバーフロー)、切り離された ArrayBuffer(grow の後)、i64 の境界の問題。危険な呼び出しは try/catch で包み、インポート/ポインタは前もって検証して、問題を早く表面化させましょう。

webassembly
// 1. LinkError: "import not found"
//    Cause: import object missing a name.
const imports = { env: { log: console.log } };
// Must match (import "env" "log" ...) exactly.

// 2. RuntimeError: "unreachable"
//    Cause: Wasm executed unreachable / panic / assert.

// 3. RuntimeError: "out of bounds memory access"
//    Cause: load/store at an invalid address.
//    Fix: check ptr/len before access; grow memory.

// 4. CompileError: "section size mismatch"
//    Cause: corrupted or truncated .wasm file.

// 5. TypeError: "i64 not supported"
//    Cause: i64 returns without BigInt integration.
//    Fix: use BigInt, or return two i32 values.

// 6. "detached ArrayBuffer"
//    Cause: used a TypedArray view after memory.grow.
//    Fix: re-create views after grow.
16

パフォーマンス最適化

インライン化と -O フラグ

-O3 は積極的なインライン化とループ最適化を有効にします。wasm-opt(Binaryen)は Wasm レベルの追加パス(インライン化、デッドコード、定数畳み込み)を実行します — 本番では必ず実行しましょう。-Os/-Oz は速度の一部をより小さいダウンロードと引き換えにします。-flto はプログラム全体の最適化を有効にします。

webassembly
# Compilation optimization levels
emcc app.c -O0 -o app.wasm   # no optimization (debug)
emcc app.c -O1 -o app.wasm   # basic
emcc app.c -O2 -o app.wasm   # standard
emcc app.c -O3 -o app.wasm   # aggressive (inlining)
emcc app.c -Os -o app.wasm   # optimize for size
emcc app.c -Oz -o app.wasm   # max size reduction

# Post-optimize with Binaryen
wasm-opt -O3 app.wasm -o app.opt.wasm
wasm-opt -Os app.wasm -o app.small.wasm

# LTO across translation units (C/C++)
emcc app.c -flto -O3 -o app.wasm

メモリレイアウトとアクセスパターン

Wasm の線形メモリは単なる ArrayBuffer です — CPU キャッシュの挙動がそのまま適用されます。連続したアクセスパターン(行優先データには行優先アクセス)は、ストライドアクセスより劇的に速いです。自然なアライメントを保ち(i32 は 4 バイト)、load/store が 1 命令で済むようにしましょう。

webassembly
// Cache-friendly access: linear, contiguous iteration
// GOOD: row-major traversal of a 2D array
for (i32 row = 0; row < rows; row++) {
  for (i32 col = 0; col < cols; col++) {
    sum += data[row * cols + col];
  }
}

// BAD: column-major traversal (cache misses)
for (i32 col = 0; col < cols; col++) {
  for (i32 row = 0; row < rows; row++) {
    sum += data[row * cols + col];
  }
}

// Prefer aligned access (4-byte for i32, 8 for i64).
// Allocators should respect natural alignment.

JS の境界跨ぎの最小化

JS→Wasm の呼び出しには毎回オーバーヘッドがあります(引数のマーシャリング、スタックの準備)。タイトなループは、ループを Wasm の内側へ移し、バッファを渡して 1 回だけ呼びましょう。これが Wasm のパフォーマンスの最も大きな秘訣です — まとまった操作は、要素ごとの呼び出しより桁違いに勝ります。

webassembly
// BAD: call Wasm per element (boundary overhead)
for (let i = 0; i < arr.length; i++) {
  result[i] = exports.process(arr[i]);
}

// GOOD: batch — one call for the whole array
const ptr = exports.alloc(arr.length * 4);
new Float32Array(memory.buffer, ptr, arr.length).set(arr);
exports.processBatch(ptr, arr.length);   // single call
const out = Array.from(new Float32Array(memory.buffer, ptr, arr.length));
exports.free(ptr, arr.length * 4);

// Each crossing costs ~tens of nanoseconds.
// Batch loops to amortize the overhead.

SIMD(Single Instruction, Multiple Data)

SIMD(v128)は 1 命令で 4 つの float か 4 つの int32 を処理します — 画像/音声/行列演算で 4 倍の高速化です。Emscripten は -msimd128 で有効化し、Rust は std::arch::wasm32 の intrinsic を使います。自動ベクトル化も助けになりますが、明示的な intrinsic が予測可能な利得を与えます。ブラウザで広くサポートされています。

webassembly
// C/C++ with Emscripten auto-vectorization
#include <emscripten/simd.h>
void addArrays(float *a, float *b, float *out, int n) {
    for (int i = 0; i < n; i += 4) {
        v128_t va = wasm_v128_load(a + i);
        v128_t vb = wasm_v128_load(b + i);
        wasm_v128_store(out + i, wasm_f32x4_add(va, vb));
    }
}

# Compile with SIMD enabled
emcc simd.c -O3 -msimd128 -o simd.wasm

// Rust: use std::arch::wasm32 intrinsics
use std::arch::wasm32::*;
unsafe { let v = f32x4_splat(1.0); }

スレッドと SharedArrayBuffer

Wasm のスレッドは Web Worker 間で Memory を共有し、同期にはアトミックを使います。COOP/COEP ヘッダー(クロスオリジン分離)が必要です。Emscripten の -pthread は pthread をエミュレートし、Rust の std::thread は wasm32-wasi-threads で動きます。CPU 依存の並列処理 — 画像処理、コーデック、ML 推論に最適です。

webassembly
// Enable threads in Emscripten
# emcc app.c -O3 -pthread -s PTHREAD_POOL_SIZE=4 -o app.js

// Browser requires cross-origin isolation:
//   /_headers (Cloudflare/Netlify)
//   Cross-Origin-Opener-Policy: same-origin
//   Cross-Origin-Embedder-Policy: require-corp

// Spawn workers sharing Wasm memory:
const memory = new WebAssembly.Memory({
  initial: 10, maximum: 100, shared: true
});
// Each Worker instantiates the module with this memory
// and uses Atomics for synchronization.

プロファイリングとベンチマーク

計測には performance.now() と DevTools の Performance タブを使いましょう — Wasm は JS と同じようにフレームチャートに現れます。測定の前にウォームアップしましょう(コンパイルのオーバーヘッドは 1 回だけ)。最適化された JS との比較も重要です — モダンな V8 は速く、Wasm が勝るのは予測可能な性能、数値カーネル、大きなワークロードであって、細かなタスクではありません。

webassembly
// Use performance.now() for high-res timing
const t0 = performance.now();
exports.heavyWork(ptr, len);
const t1 = performance.now();
console.log(`Wasm: ${(t1 - t0).toFixed(2)}ms`);

// Compare against JS equivalent
const t2 = performance.now();
jsEquivalent(data);
console.log(`JS:   ${(performance.now() - t2).toFixed(2)}ms`);

// Chrome DevTools Performance tab: profile Wasm
// like JS — flame charts show function time.

// Avoid microbenchmarks pitfalls:
//   - warm up first (JIT compilation)
//   - run many iterations
//   - compare against OPTIMIZED JS, not naive JS
17

Wasm vs JavaScript

性能の比較

Wasm が輝くのは計算量の多い数値処理です(画像処理、コーデック、暗号、ML)— 典型的には JS より 2〜10 倍速いです。DOM、JSON、文字列中心の処理では、多くの場合 JS の方が速くなります(処理がすでにネイティブコードにあるため — V8 の JSON.parse、ブラウザの DOM)。計測して判断しましょう — Wasm が常に速いと決めつけないこと。

webassembly
// Wasm vs JS — typical scenarios:
//
// Image processing (8MB):
//   JS:          120 ms
//   Wasm (-O3):   35 ms    ~3.4x faster
//
// SHA-256 (1MB):
//   JS:           45 ms
//   Wasm:          8 ms    ~5.6x faster
//
// DOM manipulation:
//   JS:            5 ms
//   Wasm:         20 ms    SLOWER (DOM is JS-native)
//
// JSON parse:
//   JS:            3 ms
//   Wasm:         15 ms    SLOWER (JSON.parse is C++ in V8)
//
// Rule of thumb: Wasm wins on compute-heavy numeric
// workloads; JS wins on DOM/JSON/string-heavy tasks.

Wasm のユースケース

Wasm が優れるのは: 既存の C/C++/Rust コードベースの移植(Figma、Photoshop の Web 版)、計算依存の数値カーネル(画像/ML/暗号)、サンドボックス化されたプラグインです。実例: Figma(レンダラ)、Photoshop(アプリ全体の移植)、Google Meet(背景ぼかし)。純粋な DOM アプリには、JS がたいてい正しい選択です。

webassembly
// Strong Wasm use cases:
//   - Image/video/audio processing (FFmpeg, OpenCV)
//   - Games & 3D engines (Unity, Unreal)
//   - Cryptography (hashing, encryption, ZK proofs)
//   - Machine learning inference (ONNX, TFLite)
//   - Codecs (AV1, VP9, MP3)
//   - Emulators (DOSBox, retro consoles)
//   - Heavy math (physics simulations, linear algebra)
//   - Reusing C/C++/Rust libraries (FFI alternative)
//   - Sandboxed plugins in editors (Figma, Photoshop)

// Figma: rendering engine in Wasm
// Photoshop: web port of full desktop app
// Google Meet: video background blur

JS を使うべきとき

UI、DOM、ブラウザ API、ほとんどの Web アプリのロジックには、JS が依然として正しい選択です — V8 は徹底的に最適化されています。Wasm を検討すべきは、プロファイリングで JS では最適化しきれないホットスポットが判明したときや、既存のネイティブコードベースを移植するときです。ハイブリッド(JS の UI + Wasm のホットスポット)がしばしば理想です。

webassembly
// JS is better when:
//   - DOM manipulation dominates
//   - Working with browser APIs (fetch, IndexedDB, WebRTC)
//   - Heavy string/JSON processing
//   - Small utilities and glue code
//   - Rapid prototyping (no compile step)
//   - Team lacks C/Rust expertise
//   - Module size matters more than runtime speed

// JS engines (V8, SpiderMonkey, JSC) are highly
// optimized. For most web apps, JS is fast enough
// AND simpler to ship and maintain.

// Hybrid: keep UI in JS, offload hotspots to Wasm.

ロードと起動コスト

Wasm には固定の起動コストがあります(ダウンロード+コンパイル+インスタンス化)— JS にはこれがありません。緩和策: ストリーミングコンパイル、Cache API によるコンパイル済みモジュールのキャッシュ、重要度の低い Wasm の遅延ロード。ウォームアップ後の Wasm の関数呼び出しは JS と同じくらい速いです — コストは前払いで、速い実行により回収されます。

webassembly
// Wasm has upfront costs JS doesn't:
//   1. Download the .wasm binary
//   2. Compile to machine code (~10-50 ms for small modules)
//   3. Instantiate (initialize memory, run start function)

// Mitigations:
//   - Cache compiled modules (WebAssembly.compileStreaming + Cache API)
//   - Stream compilation (instantiateStreaming)
//   - Lazy-load non-critical Wasm on demand
//   - Use Web Workers to compile off the main thread

// Streaming compile of a 1MB module:
//   ~30 ms download + ~10 ms compile (parallel)
// Cached: ~5 ms (re-instantiate from cached module)

相互運用コストと境界のオーバーヘッド

JS↔Wasm の呼び出しは安価ですが無料ではありません(1 回約 10〜100ns、文字列ではもっと)。高頻度のイベントでは、JS 側でまとめて、バッファを渡して Wasm を 1 回呼びましょう。JS オブジェクトを呼び出しごとに渡すのは避け、externref を使うかバイト列を memory へコピーします。境界は数値には速く、シリアライズされたデータには遅いです。

webassembly
// Each JS<->Wasm call costs ~10-100 ns:
//   - Marshal arguments (i32/f64 fast; strings/objects slow)
//   - Stack frame setup
//   - Inlined trampoline in the engine

// Implications:
//   - Don't call Wasm 1M times for tiny work — batch!
//   - Don't pass large objects per-call — copy once, share memory
//   - For DOM events, keep handlers in JS, call Wasm with batched data

// Pseudocode: batched event handling
let pendingEvents = [];
button.addEventListener('click', e => {
  pendingEvents.push(...);
  if (pendingEvents.length >= 100) {
    exports.processBatch(ptr, pendingEvents.length);
    pendingEvents = [];
  }
});
18

セキュリティモデル

サンドボックスモデル

Wasm のセキュリティの基盤はサンドボックスです: モジュールは、ホストが import で明示的に関数を提供しない限り、ホストのメモリ、ファイル、ネットワーク、デバイスにアクセスできません。これにより信頼できないコードを安全に実行できます — できるのは import が許すことだけです。型安全性と組み合わせて、バッファオーバーフローや RCE を防ぎます。

webassembly
// Wasm executes in a sandboxed virtual machine:
//   - No direct access to host memory (only its linear memory)
//   - No syscalls (must go through imported functions)
//   - No I/O unless the host provides it
//   - Control flow is structured (no arbitrary jumps)
//   - Type-checked at compile and run time

// All host access is EXPLICIT through imports.
// A module that didn't import "fs" cannot read files.

// Code:
//   (module
//     (import "env" "log" (func (param i32)))
//     ;; the ONLY host capability this module has is log()
//   )

同一オリジンポリシーと fetch

Wasm はブラウザのセキュリティモデルを脱出しません — 同一オリジンポリシーと CORS は、他のリソースと同様に .wasm の fetch に適用されます。クロスオリジンの Wasm には適切な CORS ヘッダーと application/wasm の MIME タイプが必要です。Wasm は CSP、クッキー、他のブラウザのセキュリティ機構を迂回することもできません。

webassembly
// Wasm modules obey the same-origin policy:
//   - fetch('https://other-origin/x.wasm') needs CORS headers
//   - The remote server must send:
//       Access-Control-Allow-Origin: *
//   - And the correct MIME: application/wasm

// Load cross-origin Wasm with streaming:
const { instance } = await WebAssembly.instantiateStreaming(
  fetch('https://cdn.example.com/lib.wasm', {
    mode: 'cors'
  }),
  imports
);

// Wasm cannot bypass CORS — it's subject to the
// browser's normal security model.

メモリの分離

Wasm のメモリは実行時に境界チェックされます — 範囲外のアクセスは memory を破壊する代わりに即座に trap します。モジュールは互いの memory、JS ヒープ、任意のホストアドレスを読めません。関数ポインタ(call_indirect)は型チェックされ、呼び出し先の偽造を防ぎます。これにより C/C++ の脆弱性のクラス丸ごとが消えます。

webassembly
// Each Wasm instance has its OWN linear memory.
//   - Out-of-bounds access traps (RuntimeError)
//   - One module's memory cannot read another's
//   - JS writes via TypedArray views are bounds-checked

// Even shared memory (threads) requires explicit
// opt-in and is still bounded:
const mem = new WebAssembly.Memory({ initial: 1, maximum: 10 });

// Wasm code CANNOT:
//   - Read JS heap
//   - Read other instances' memory
//   - Forge function pointers (call_indirect type-checks)
//   - Read arbitrary host memory addresses

// All memory access is bounds-checked at runtime.

ケイパビリティベースのセキュリティ

Wasm はケイパビリティベースのセキュリティに従います: import オブジェクトこそがモジュールのケイパビリティです。何をインポートするかを慎重に選べば、モジュールに最小限の特権を与えられます。log() だけをインポートするプラグインは、他には何もできません。これが安全なプラグインシステム(Figma、Shopify functions など)の基盤です。

webassembly
// Capability security: a module can ONLY do what
// the host explicitly grants via imports.

// Strict imports = minimal privilege
const imports = {
  env: {
    log: msg => console.log('[wasm]', msg)
    // NO file IO, NO network, NO timers
  }
};
WebAssembly.instantiateStreaming(fetch('plugin.wasm'), imports);

// The plugin can ONLY call log(). It cannot:
//   - Access the DOM
//   - Make network requests
//   - Read files
//   - Spawn workers
// unless you import those capabilities.

CSP と Trusted Types

Content Security Policy は Wasm を eval と同様に扱います — デフォルトでは CSP がブロックします。eval() をブロックしたまま Wasm を許可するには、script-src に 'wasm-unsafe-eval' を追加しましょう。unsafe-eval より寛容さが抑えられており、本番で推奨です。Trusted Types への対応では、動的な JS の接着コードをポリシーで包む必要があります。

webassembly
// Content Security Policy applies to Wasm:
//   - 'wasm-unsafe-eval' is required for instantiation
//   - Without it, CSP blocks WebAssembly.compile

// HTTP header:
//   Content-Security-Policy:
//     default-src 'self';
//     script-src 'self' 'wasm-unsafe-eval';

// Wasm output (e.g., Emscripten) often uses eval-like
// patterns for instantiation — CSP 'wasm-unsafe-eval'
// specifically allows Wasm while still blocking eval().

// Trusted Types: Wasm glue code must produce
// trusted scripts; use policy.createScript() for
// any dynamically generated JS that loads Wasm.
19

ツールチェーン

WABT(wat2wasm、wasm2wat)

WABT は Wasm のテキスト形式とバイナリ形式を扱う定番のツールキットです。wat2wasm/wasm2wat で往復し、wasm-objdump で構造を検査し、wasm-interp はリファレンスインタプリタでモジュールを実行します。wasm-decompile は C 風の読める形式を作ります。手書き、デバッグ、教育に不可欠です。

webassembly
# WABT = WebAssembly Binary Toolkit
# Install:
#   macOS:  brew install wabt
#   Ubuntu: apt install wabt
#   Windows: scoop install wabt

# Tools included:
wat2wasm hello.wat -o hello.wasm       # text -> binary
wasm2wat hello.wasm -o hello.wat       # binary -> text
wasm-validate hello.wasm               # validate
wasm-objdump -x hello.wasm             # inspect structure
wasm-interp hello.wasm                 # interpret (run)
wasm-decompile hello.wasm -o hello.dly # decompile to C-like

# Online: https://webassembly.github.io/wabt/demo/

Emscripten SDK

Emscripten は最も成熟した Wasm ツールチェーンです — C/C++、Fortran、他の LLVM 系言語をコンパイルします。emcc/em++ は Clang を包み、emcmake/emconfigure により既存の CMake/Autotools プロジェクトを無修正でビルドできます。互換性のため、libc、SDL、OpenGL(WebGL 経由)、pthreads の移植も提供します。

webassembly
# Emscripten: compile C/C++/LLVM languages to Wasm
git clone https://github.com/emscripten-core/emsdk.git
cd emsdk && ./emsdk install latest && ./emsdk activate latest
source ./emsdk_env.sh

# Key tools:
emcc        # C/C++ compiler (gcc/clang-like)
em++        # C++ compiler
emcmake     # wrapper for cmake
emconfigure # wrapper for ./configure
emranlib    # archive tool
emar        # archiver

# Common output:
emcc app.c -O3 -o app.js   # JS glue + .wasm
emcc app.c -o app.html     # runnable HTML demo

wasm-pack(Rust)

wasm-pack は公式の Rust→Wasm ツールです: ビルドし、wasm-bindgen を実行し、TypeScript の型を生成し、npm 用にパッケージ化します。--target で JS のモジュール形式を選びます。wasm-pack test は webdriver 経由で実ブラウザで Rust のテストを実行します。すぐ使えるプロジェクトの雛形には wasm-pack-template を使いましょう。

webassembly
# wasm-pack: build, test, publish Rust Wasm packages
cargo install wasm-pack

# Build for various targets
wasm-pack build --target web       # modern browsers
wasm-pack build --target bundler   # webpack/vite
wasm-pack build --target nodejs    # Node.js

# Test in a headless browser
wasm-pack test --headless --chrome

# Publish to npm
wasm-pack publish

# Generate a template project
cargo generate --git https://github.com/rustwasm/wasm-pack-template

Binaryen(wasm-opt)

Binaryen は Emscripten と wasm-pack が内部で使う最適化ツールキットです。wasm-opt は Wasm レベルのパス(インライン化、デッドコード除去、定数畳み込み)を実行します — 本番のビルドでは必ず実行しましょう。速度には -O3、最小サイズには -Oz です。wasm-metadce はモジュールをまたいで未使用のエクスポートを除去します。

webassembly
# Binaryen: Wasm optimization toolkit
# Often installed via Emscripten or standalone:
npm install -g binaryen

# wasm-opt: optimize .wasm files
wasm-opt -O3 input.wasm -o output.wasm       # speed
wasm-opt -Os input.wasm -o output.wasm       # size
wasm-opt -Oz input.wasm -o output.wasm       # min size

# Other tools:
wasm-as input.wat -o output.wasm             # assemble
wasm-dis input.wasm -o output.wat            # disassemble
wasm-merge a.wasm b.wasm -o merged.wasm      # link
wasm-shell input.wat                         # interpreter
wasm-metadce input.wasm -o output.wasm       # aggressive dead-code

wasm-tools(Bytecode Alliance)

wasm-tools は Bytecode Alliance のモダンな Rust ベースのツールキットです。パース/表示/検証ができ、目玉の機能は component model のサポート(component new/embed/describe)です。多くの操作で WABT より厳格で高速であり、component model の作業には推奨のツールです。

webassembly
# wasm-tools: modern Rust-based Wasm toolkit
cargo install wasm-tools

# Subcommands:
wasm-tools parse input.wat -o output.wasm      # text -> binary
wasm-tools print input.wasm -o output.wat      # binary -> text
wasm-tools validate input.wasm                 # validate
wasm-tools component new input.wasm -o c.wasm  # wrap as component
wasm-tools strip input.wasm -o stripped.wasm   # remove debug info
wasm-tools objdump input.wasm                  # inspect
wasm-tools smith                                # generate random modules (fuzzing)

# Component model support is a key feature.
# Stronger WAT parsing than WABT in edge cases.

ランタイム(wasmtime、wasmer、WasmEdge)

3 つの主要なスタンドアロンランタイム: wasmtime(Bytecode Alliance のリファレンス、component model 対応が最良)、wasmer(ピーク性能のための LLVM を含む複数バックエンド、JS バインディング)、WasmEdge(CNCF、クラウドネイティブと AI 推論に最適化)。すべて WASI を実装するため、同じ .wasm が横断して動きます。エコシステムとの相性で選びましょう。

webassembly
# wasmtime — Bytecode Alliance reference runtime
curl https://wasmtime.dev/install.sh -sSf | bash
wasmtime app.wasm

# wasmer — cross-platform, multiple backends
curl https://get.wasmer.io -sSf | sh
wasmer run app.wasm

# WasmEdge — CNCF, optimized for cloud/edge
curl -sSf https://raw.githubusercontent.com/WasmEdge/WasmEdge/master/utils/install.sh | bash
wasmedge app.wasm

# Comparison:
#   wasmtime:  reference, WASI preview1+2, components
#   wasmer:   multiple backends (Cranelift, LLVM), JS API
#   WasmEdge:  AI/ML extensions, Kubernetes-friendly

// All three run WASI modules portably.
20

Components とベストプラクティス

Wasm Components の概観

Component Model は Wasm の進化形です: コンポーネントが、線形メモリを手動でマーシャリングすることなく、豊かな型(文字列、レコード、リスト)で通信できるモジュール形式です。コンポーネントは言語を跨ぐライブラリのように組み合わされます(Rust のコンポーネント + JS のコンポーネント)。wasmtime、WasmEdge、Bytecode Alliance の広いエコシステムがサポートします。

webassembly
// Component Model: a higher-level module format
// that lets Wasm modules talk to each other and hosts
// using rich types (strings, records, variants),
// not just (i32, f64).

// Core Wasm module:  exports raw functions over memory.
// Component:         wraps a core module, exposes typed
//   interfaces described in WIT (Wasm Interface Type).

// Build flow:
//   1. Write WIT interface
//   2. Generate bindings for your language (Rust, C, JS)
//   3. Implement, compile to core .wasm
//   4. Wrap into a component with wasm-tools

// Tooling:
wasm-tools component new app.wasm -o app.wasm

// Run with wasmtime:
wasmtime app.wasm  # uses component interfaces

WIT(Wasm Interface Type)

WIT(Wasm Interface Type)はコンポーネントのための IDL です — レコード、バリアント、enum、リソース、関数を宣言します。wit-bindgen が言語固有のバインディングを生成します(Rust、C、JS、Python)。'world' キーワードは、コンポーネントが提供/消費する import と export を束ねます。これが移植可能で言語非依存の Wasm ライブラリの基盤です。

webassembly
// example.wit — describe a component's interface
package example:greeter;

interface api {
    // A record type
    record person {
        name: string,
        age: u32,
    }

    // A function taking/returning rich types
    greet: func(p: person) -> string;
}

world greeter-world {
    export api;
}

# Generate bindings:
#   Rust:     cargo component bindings
#   JS:       jco transpile
#   C/C++:    wit-bindgen c component.wit

# wit-bindgen is the binding generator
cargo install wit-bindgen-cli

ベストプラクティス: 小さく焦点を絞ったモジュール

1 つの巨大なモジュールより、小さく焦点を絞った複数の Wasm モジュールを推奨しましょう。小さいモジュールはダウンロードが速く、キャッシュに乗りやすく、遅延ロードも可能です(音声モジュールは必要なときだけロード)。memory は import でモジュール間で共有するか、型安全なモジュール間呼び出しには component model を使いましょう。それぞれに wasm-opt -Oz を実行します。

webassembly
// GOOD: One focused .wasm per concern
//   - renderer.wasm (drawing)
//   - audio.wasm (mixing)
//   - physics.wasm (simulation)
// Loaded lazily as needed.

// BAD: One giant monolithic .wasm
//   - app.wasm (1MB+, includes everything)

// Benefits of small modules:
//   - Faster initial load (only what's needed)
//   - Better caching (changed modules re-download)
//   - Easier parallel development
//   - Smaller attack surface per module

// Use wasm-opt -Oz to minimize each module.
// Share memory across modules via imports.

ベストプラクティス: エラー処理

Wasm の trap(ゼロ除算、範囲外メモリ、unreachable)は Wasm の内側からは捕捉できません — 関数が中断します。エクスポート関数は、trap の代わりにエラーコードや Result 型を返すように設計しましょう。最後の手段として、JS 側で WebAssembly.RuntimeError を捕捉します。component model は型付きのエラーバリアントをネイティブにサポートします。

webassembly
// Wasm traps are unrecoverable — handle errors gracefully.

// BAD: let divide crash
(func (export "div") (param i32 i32) (result i32)
  local.get 0  local.get 1  i32.div_s  ;; traps on 0
)

// GOOD: return a sentinel or error code
(func (export "div") (param i32 i32) (result i32)
  local.get 1
  i32.eqz
  if (result i32)
    i32.const -1   ;; error sentinel
  else
    local.get 0
    local.get 1
    i32.div_s
  end
)

// In Rust/AS: use Result<T, E> and export
// error variants via the component model.

ベストプラクティス: メモリ管理

Wasm のメモリは C と同様に扱います: すべての alloc には対応する free が必要です。alloc/free のヘルパーをエクスポートし、JS 側のバッファ利用は try/finally で包みましょう。memory.grow の後は TypedArray のビューを必ず作り直すこと(ArrayBuffer は切り離されます)。所有権を文書化しましょう: 解放の責任は呼び出し元か呼び出し先か? リークは性能を徐々に悪化させます。

webassembly
// Export alloc/free and use them consistently.
// C/C++ (Emscripten): _malloc / _free
// Rust:               wasm_bindgen's __alloc / __free
// AssemblyScript:     __new / __retain / __release

// JS wrapper for safe buffer passing:
function withBuffer(size, fn) {
  const ptr = exports.alloc(size);
  try {
    return fn(new Uint8Array(memory.buffer, ptr, size));
  } finally {
    exports.free(ptr, size);
  }
}

// NEVER leak:
//   - Re-create TypedArray views after memory.grow
//   - Free buffers passed in from JS
//   - For long-lived allocations, document ownership

ベストプラクティス: テストと CI

Wasm は本物の環境でテストしましょう: wasm-pack test はヘッドレスブラウザで Rust のテストを実行し、AssemblyScript と Emscripten にはそれぞれのランナーがあります。CI には wasm-validate とサイズのチェックを加えましょう。問題を早く見つけるには、-s ASSERTIONS=1(Emscripten)とデバッグビルドを使います。wat2wasm でリントし、リリース物には常に wasm-opt を実行しましょう。

webassembly
# Test Wasm just like any other code.

# Rust: wasm-pack test runs in a real browser
wasm-pack test --headless --chrome --firefox

# AssemblyScript: use the built-in test framework
npm run test

# C/C++ (Emscripten): use emcc with -s ASSERTIONS=1
#   and write tests in C, run with node:
node tests.js

# Validate .wasm in CI:
wasm-validate module.wasm

# Check size budgets:
ls -la module.wasm  # e.g., must be < 200KB

# Lint WAT with wat2wasm (catches syntax errors)
# Run wasm-opt -O3 to ensure optimization is applied

# GitHub Actions example:
# - uses: actions-rs/toolchain@v1
# - run: cargo install wasm-pack
# - run: wasm-pack test --headless

Was this helpful?