Skip to content

WebAssembly Spickzettel

Binäres Instruktionsformat für schnelle Ausführung im Web.

01

Erste Schritte

Wasm in JS laden

WebAssembly (Wasm) ist ein Binärformat, das mit fast nativer Geschwindigkeit in Browsern läuft. instantiateStreaming lädt und kompiliert eine .wasm-Datei. Exports sind Funktionen, die sich aus JavaScript aufrufen lassen.

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-Modul & -Instanz

WebAssembly.Module ist die kompilierte, zustandslose Repräsentation — gefahrlos über mehrere Instanzen hinweg wiederverwendbar. WebAssembly.Instance hält Laufzeitzustand (Speicher, Globals). Einmal zu kompilieren und oft zu instanziieren ist effizient, um parallele Worker zu erzeugen.

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

Browser-Unterstützung & Feature-Erkennung

WebAssembly 1.0 wird von allen modernen Browsern unterstützt. Neuere Vorschläge (SIMD, Exceptions, Threads, GC) brauchen Feature-Erkennung. WebAssembly.validate prüft, ob Bytes ein gültiges Modul bilden, ohne zu kompilieren.

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;

Streaming vs. Nicht-Streaming

instantiateStreaming kompiliert das Modul, während es übers Netzwerk streamt — schnellerer Start. Der server MUSS 'Content-Type: application/wasm' senden. Nutzt du ein CDN oder einen statischen Host ohne diesen Header, auf den ArrayBuffer-Weg zurückfallen.

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-Magische Zahl & Header

Die magische Zahl des Wasm-Binärformats ist der ASCII-String '\0asm', gefolgt von einer 4-Byte-little-endian-Version. Dieser Header erlaubt es zu prüfen, ob eine Datei Wasm ist, bevor kompiliert wird. Das Format ist in Sektionen organisiert (Type, Import, Function, Memory usw.).

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 (minimales Beispiel)

Eine minimale Wasm-App: Das Modul importiert eine 'log'-Funktion aus JS und exportiert 'greet', das sie aufruft. Das WAT-(WebAssembly Text-)Format ist die menschenlesbare Darstellung, kompiliert zu Binär mit wat2wasm. Browser führen nur die Binärform aus.

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-Textformat

Modul & S-Ausdrücke

WAT (WebAssembly Text-Format) ist die textuelle Darstellung von Wasm. Alles ist in einen (module ...)-S-Ausdruck gewickelt. Instruktionen werden in stapelbasierter Reihenfolge geschrieben: Operanden zuerst geschoben, dann konsumiert die Operation sie.

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))
)

Kommentare in WAT

WAT unterstützt zwei Kommentarstile: ';;' für einzeilig und '(; ... ;)' für Blockkommentare. Blockkommentare dürfen verschachteln und sich über mehrere Zeilen erstrecken — nützlich, um in der Entwicklung Codeabschnitte zu deaktivieren.

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
)

Funktionsdefinitions-Syntax

Funktionen werden mit (func ...) deklariert. Parameter nutzen (param $name type) und Ergebnisse (result type). '$name' ist optional — ohne wird auf Funktionen/Locals per numerischem Index referenziert. Mehrwertige Rückgaben verlangen den multi-value-Vorschlag (weit unterstützt).

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
)

Inline-Export & -Import

WAT unterstützt Inline-(export "name")- und (import "module" "field")-Annotationen an Funktionen, Speichern, Tabellen und Globals — eine Kurzform der ausgefaltten (export ...)/(import ...)-Formen. Beide kompilieren zu identischer Binär-Ausgabe.

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))

Daten-Segmente

Daten-Segmente initialisieren linearen Speicher bei der Instanziierung (aktiv) oder lazy via memory.init (passiv). Strings schließen Escape-Sequenzen ein wie \00 für den Nullterminator und \n für den Zeilenumbruch. data.drop gibt den Speicher des Segments nach dem Kopieren frei.

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-Konvertierung

WABT (WebAssembly Binary Toolkit) liefert wat2wasm (Text→Binär), wasm2wat (Binär→Text), wasm-validate und wasm-objdump. Essenziell zum Inspizieren, Debuggen und handverfassten Schreiben von Wasm-Modulen. Die .wat-Form ist für Menschen; die .wasm-Form ist, was Browser ausführen.

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

Werttypen

Basiswerttypen (i32/i64/f32/f64)

Wasm hat nur vier Basiswerttypen: i32, i64, f32, f64. Die Vorzeichenhaftigkeit von Ganzzahlen wird durch die Operation bestimmt (z. B. i32.div_s vs. i32.div_u), nicht durch den Typ. Das hält das Typsystem minimal und vorhersagbar.

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.

Numerische Literale in WAT

Numerische Literale in WAT unterstützen dezimale, hexadezimale (0x) und binäre (0b) Formen. Floats unterstützen wissenschaftliche Notation, Unendlichkeit (inf) und NaN. WAT-Literale sind standardmäßig vorzeichenlos — negative Ganzzahlen werden mit führendem '-' kodiert.

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

Typkonvertierungen

Konvertierungen nutzen ein konsistentes Benennungsschema: extend (kleiner→größer), wrap (größer→kleiner), convert (int↔float), reinterpret (Bit-Level-Cast), demote/promote (Float-Präzision). Vorzeichenbehaftete Varianten nutzen _s, vorzeichenlose _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-Typ

Der v128-Typ packt 16 Bytes in ein einziges SIMD-Register. Lanes werden adressiert als i32x4 (4×int32), f32x4 (4×float32), i16x8, i8x16, f64x2. SIMD beschleunigt Bild-/Audio-/Krypto-Workloads, indem es mehrere Werte pro Instruktion verarbeitet.

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

Referenztypen (funcref/externref)

Der reference-types-Vorschlag ergänzt funcref (Funktionszeiger) und externref (opake Host-Referenz). externref ist mächtig: Er lässt Wasm JS-Objekte halten, ohne Kopieren oder Serialisierung. Kombiniert mit Tabellen ermöglicht das flexible Callback-Muster.

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

Funktionen

Funktionen definieren & aufrufen

Funktionen sind die fundamentale Codeeinheit. call ruft eine Funktion per Name/Index auf. Argumente werden vor dem Aufruf auf den Stack geschoben; Ergebnisse bleiben beim Rückkehr auf dem Stack. Der Stack muss der (result ...)-Deklaration entsprechen.

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
  )
)

Parameter & lokale Variablen

Parameter sind unveränderliche Locals, ab 0 indiziert. Deklarierte Locals (local $name type) werden auf Null initialisiert und sind veränderlich. local.get, local.set und local.tee nutzen (setzen + auf dem Stack belassen). Locals sind Wasm's einziges veränderliches Inventar außerhalb von Speicher/Globals.

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

Mehrere Rückgabewerte

Der multi-value-Vorschlag erlaubt Funktionen, mehrere Werte zurückzugeben (und null zu akzeptieren). Alle großen Engines unterstützen ihn seit 2020. Das entfernt die Notwendigkeit von out-Parametern über den Speicher und macht Idiome wie swap/minmax natürlich.

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
)

Rekursion

Wasm unterstützt direkte Rekursion — eine Funktion darf sich selbst aufrufen. Es gibt keine Tail-Call-Optimierung im MVP-Wasm (der tail-call-Vorschlag ergänzt return_call). Tiefe Rekursion riskiert Stack-Overflow, iterative Schleifen sind also für Produktionscode bevorzugt.

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))
)

Inline-Export & benannte Aufrufe

Inline-(export "name") an einer Funktionsdefinition ist die Kurzform einer separaten (export ...)-Deklaration. call_ref (reference-types-Vorschlag) ruft eine Funktion direkt über eine funcref auf und ermöglicht First-Class-Funktionswerte ohne Tabellenlookup.

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-Funktion

Ein Modul darf eine (start $func)-Funktion deklarieren, die bei der Instanziierung automatisch läuft — nützlich zur Initialisierung. Sie nimmt keine Argumente und liefert nichts zurück. Nur eine Startfunktion pro Modul erlaubt.

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

Speicher

Linearen Speicher deklarieren

Linearer Speicher ist eine zusammenhängende ArrayBuffer-artige Region, gewachsen in 64-KiB-Seiten. (memory 1 10) deklariert initial=1, max=10. Speicher ist der einzige Weg, Massendaten (Strings, Arrays) zwischen Wasm und JS zu übergeben. Exportieren, um aus JS zuzugreifen.

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);
)

Speicher vergrößern

memory.grow ergänzt Seiten und liefert die vorherige Größe (in Seiten), oder -1 bei Fehlschlag. Entscheidend: Das Wachsen löst den zugrunde liegenden ArrayBuffer ab — alle bestehenden TypedArray-Views werden unbrauchbar. Views nach jedem grow-Aufruf immer neu erzeugen.

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-Operationen

Loads/Stores haben Varianten nach Größe (8/16/32/64-Bit) und Vorzeichenerweiterung (_s/_u). offset=N ergänzt eine Konstante zum Adressoperanden; align= ist ein Hinweis (muss ≤ Größe sein). Alle Adressen sind Byte-Offsets in den linearen Speicher.

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

Speichergrößen & Ausrichtung

Ausrichtung in Wasm ist ein Performance-Hinweis, keine Korrektheitsbedingung — unausgerichteter Zugriff funktioniert immer. Der 'align'-Wert darf die natürliche Größe der Operation nicht überschreiten. memory.size liefert die aktuelle Seitenzahl (je 64 KiB).

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
)

Geteilter Speicher & Atomics

Geteilter Speicher (der threads-Vorschlag) lässt mehrere Wasm-Instanzen/Worker einen Speicher teilen, für Parallelität. Atomare Operationen (i32.atomic.load/store/rmw.add/cmpxchg) liefern Synchronisation. Verlangt Cross-Origin-Isolation (COOP/COEP-Header) in Browsern.

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
  )
)

Strings aus dem Speicher lesen

Wasm hat keinen nativen String-Typ — Strings sind Byte-Folgen im linearen Speicher, typisch als (pointer, length)-Paare übergeben. TextEncoder/TextDecoder handhaben die UTF-8-Konvertierung. Immer sicherstellen, dass die Speicherregion groß genug ist, bevor geschrieben wird.

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

Tabellen

Tabellen deklarieren

Tabellen sind Arrays von Referenzen (typisch funcref), genutzt für indirekte Aufrufe und dynamische Auslösung. Anders als der Speicher (der Bytes hält) halten Tabellen opake Referenzen, die Wasm nicht fälschen kann. (elem ...)-Segmente initialisieren Tabellen-Slots bei der Instanziierung.

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-Tabellen & call_indirect

call_indirect löst einen Aufruf über einen Tabelleneintrag per Index aus. Die (type ...)-Deklaration ist Pflicht — Wasm prüft zur Laufzeit, ob die Signatur der Funktion passt (Signatur-Mismatch trapt). Das ist das Fundament von vtables und OO-Auslösung in Wasm.

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)
  )
)

Tabelle wachsen, holen & setzen

table.grow hängt Slots an und liefert die vorherige Größe (oder -1). table.get/table.set lesen/schreiben Einträge per Index. Eine Tabelle zu vergrößern ermöglicht Laufzeitregistrierung von Callbacks. Anfangsgröße + max-Grenzen fürs Wachstum, um entfesselte Allokation zu verhindern.

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-Tabellen für Host-Objekte

externref-Tabellen speichern opake Referenzen auf Host-(JS-)Objekte — Wasm kann sie halten und weiterreichen, aber ihre Inhalte nicht inspizieren. Ideal für Callback-Registrierung, JS-Handle-Tabellen und die Brücke objektorientierter JS-APIs nach 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 });

Dynamisches Auslösungsmuster

Das dynamische Auslösungsmuster: Operationen in einer Tabelle speichern, dann call_indirect per Index. Kombiniert mit der Pflicht-Typprüfung ergibt das sichere vtable-artige Polymorphie. So implementieren Rust-Enums, C++-virtuelle Funktionen und Interpreter ihre Auslösung.

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

Globals

Globals deklarieren

Globals sind Einzelwerte auf Modulebene, entweder unveränderlich (Standard) oder veränderlich (mut). Sie halten über Funktionsaufrufe hinweg und eignen sich für Zähler, Konfigurationsflags und Konstanten. Veränderliche Globals sind der einzige geteilte veränderliche Zustand außerhalb von Speicher/Tabellen.

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
  )
)

Veränderliche vs. unveränderliche Globals

Ohne 'mut' ist ein Global unveränderlich und global.set ist ein Compile-Fehler. Der Initialisierer muss ein konstanter Ausdruck sein (z. B. i32.const, ref.null, global.get eines importierten unveränderlichen Globals). Standardmäßig unveränderlich wählen, zur Sicherheit.

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
  )
)

Globals importieren

Importierte Globals erlauben dem Host, Konfigurationswerte (oder WebAssembly.Global-Objekte) bei der Instanziierung in ein Modul zu injizieren. Unveränderliche importierte Globals können andere Globals initialisieren. WebAssembly.Global ist der JS-sichtbare Wrapper für veränderliche geteilte Globals.

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

Globals exportieren & teilen

Exportierte Globals sind aus JS als WebAssembly.Global-Objekte zugänglich, mit einer .value-Eigenschaft (lesbar und, wenn veränderlich, schreibbar). Ein Global-Objekt über mehrere Modulinstanzen zu teilen ist ein sauberer Weg, Zustand zu koordinieren, ohne den Speicher anzufassen.

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

Anwendungsfälle für Globals

Globals passen zu drei Mustern: (1) importierte Konfigurationskonstanten, (2) persistente Zähler/Zustand, über Instanzen geteilt, (3) gecachte Berechnungsergebnisse. Für Einzelwerte sind sie einfacher als der Speicher und für mehrere Instanzen sichtbar, wenn via JS geteilt.

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

Imports & Exports

Funktionen importieren

Imports erlauben Wasm, Host-(JS-)Funktionen aufzurufen. Jeder Import ist durch einen zweistufigen Namen identifiziert (module, field). Das an instantiate übergebene import-Objekt muss diesen Namen entsprechen. Imports sind der Weg, wie Wasm die Außenwelt erreicht — I/O, Logging, Scheduling.

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() }
});

Speicher importieren

Speicher zu importieren lässt mehrere Wasm-Module (und JS) eine Speicherregion teilen — die Basis von Wasm-'Bibliotheken'. Ein Modul allokiert und schreibt; ein anderes liest. So komponieren sich Module ohne Datenkopie — der Vorläufer des Component-Modells.

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

Globals & Tabellen importieren

Auch Globals und Tabellen lassen sich importieren, was geteilten Zustand und Funktionszeiger-Tabellen über Module hinweg ermöglicht. WebAssembly.Table ist der JS-Konstruktor. Importierte veränderliche Globals lassen den Host das Wasm-Verhalten dynamisch beeinflussen, ohne das Modul neu zu bauen.

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

Funktionen, Speicher, Tabellen exportieren

Alles in einem Modul Deklarierte lässt sich exportieren: Funktionen, Speicher, Tabellen, Globals. Exports werden Eigenschaften auf instance.exports. Speicher-Exports geben JS eine Sicht auf den linearen Heap; Global-Exports legen WebAssembly.Global-Objekte offen; Tabellen-Exports legen Funktionsrefs offen.

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

Inline-Imports & -Exports

Inline-(import "m" "f")- und (export "name")-Annotationen sind syntaktischer Zucker — sie kompilieren zu derselben Binär wie die eigenständigen (import ...)/(export ...)-Formen. Eine einzelne Definition darf einen Inline-Export haben, aber Imports und Exports werden für importierte Items getrennt deklariert.

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-Objekt-Best-Practices

Das import-Objekt so strukturieren, dass es den (module, field)-Namen des Moduls entspricht. Erforderliche Imports vor der Instanziierung validieren, um klare Fehler zu liefern. Host-Funktionen wo passend mit try/catch umhüllen — ein ungefangener throw innerhalb eines Imports trapt den Wasm-Aufrufer.

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

Kontrollfluss

block

block erzeugt einen gelabelten Scope, aus dem Verzweigungen austreten (via br). Verzweigungen in Wasm sind strukturiert — sie dürfen nur zum Ende eines umschließenden block/loop/if springen. Ein block mit (result ...) lässt seinen Wert auf dem Stack, wenn dorthin verzweigt oder durchgefallen wird.

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 ist wie block, aber br $loop springt an den ANFANG der Schleife (Iteration fortsetzen) statt ans Ende. Das Gegenteil von block. Wasm hat keine for/while-Schlüsselwörter — Iteration wird aus loop + einem bedingten br_if gebaut.

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 konsumiert ein i32 vom Stack (ungleich Null = wahr). Die (result ...)-Klausel lässt das if einen Wert liefern, wenn beide Zweige sich auf den Typ einigen. if ohne else ist erlaubt; der Zweig darf leer sein. if ist Zucker für 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 springt an das ENDE des benannten block/if (oder den ANFANG einer loop). br_if macht dasselbe bedingt. Labels dürfen auch numerisch sein (br 0 = innerstes). Verzweigen mit einem Wert lässt ihn auf dem Stack — Wasm's idiomatischer Weg, früh zurückzukehren.

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 implementiert ein switch: Er konsumiert einen i32-Index und springt zu einem der gelisteten Labels, oder zum letzten (Default-)Label, wenn außerhalb des Bereichs. Die Blöcke äußerste-zuerst verschachteln, damit jeder Fall seinen Wert zurückgeben kann. Der effizienteste Weg, auf ein Tag auszulösen.

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 verlässt die Funktion sofort mit dem Wert auf dem Stack. unreachable trapt immer (wirft eine Laufzeitausnahme) — genutzt, um Codepfade zu markieren, die nie ausgeführt werden sollten, ähnlich assert(false). Beide sind Kontrollfluss-Auswege jenseits des strukturierten Blockmodells.

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-Interoperabilität

Zahlen übergeben

i32/f32/f64 mappen direkt auf JS-Zahlen. i64 mappt auf JS BigInt (große Ganzzahlen übersteigen Number's sicheren Bereich). Für i64-Parameter/-Rückgaben immer BigInt nutzen. Die Konvertierung ist an der Grenze Zero-Copy, aber häufiges Überschreiten hat Overhead — Operationen in Wasm bündeln.

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);

Strings übergeben

Strings überqueren die Grenze als UTF-8-Byte-Folgen: JS kodiert sie in den Wasm-Speicher und übergibt dann (pointer, length). Oft exportiert Wasm alloc/free-Helfer, oder du packst beide in ein einzelnes i64 (untere 32 = ptr, obere 32 = len). Den Buffer immer freigeben oder wiederverwenden, um Lecks zu vermeiden.

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

Arrays & Massendaten übergeben

Für massenhafte numerische Daten den Wasm-Speicher als TypedArray des richtigen Typs ansehen (Float32Array, Int32Array usw.) und .set() zum Kopieren nutzen. Das ist der schnellste Weg — memcpy-artig. An der Zeigerausrichtung denken (4-Byte für i32/f32, 8-Byte für i64/f64) und Speicher immer freigeben.

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;
}

Speicherverwaltung über die Grenze

Wasm-Speicher wird manuell verwaltet — es gibt keinen Garbage Collector. Exportiert Wasm alloc/free (oder du nutzt einen malloc-artigen Helfer), JS-Zugriffe in try/finally wickeln, um Freigabe zu garantieren. Auf memory.grow achten, das ArrayBuffer-Views abtrennt — Views nach dem Wachsen neu erzeugen.

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 ist ein JS-Wrapper um einen Wasm-Global-Wert. Einen zu erzeugen und an mehrere Modulinstanzen zu übergeben teilt veränderlichen Zustand sauber, ohne den Speicher anzufassen. Die .value-Eigenschaft liest/schreibt das zugrunde liegende i32/i64/f32/f64 (oder 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 & Fehler

WebAssembly.Table speichert Funktionsreferenzen, zugänglich aus JS und Wasm — nützlich für Callback-Register und Auslösungstabellen. Wasm-Traps (Division durch Null, OOB-Speicher, Stack-Overflow) erscheinen in JS als WebAssembly.RuntimeError — riskante Aufrufe in try/catch wickeln.

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++ nach Wasm kompilieren

Emscripten-Setup

Emscripten ist die kanonische Toolchain, um C/C++ (und LLVM-Sprachen) nach Wasm zu kompilieren. Sie bündelt Clang, Binaryen und ein in den Browser portiertes libc/libstdc++. Die Umgebung in jeder Shell-Session mit emsdk_env aktivieren. Updates sind häufig — periodisch neu installieren.

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)

Hello World in C

Standard-C funktioniert unverändert — printf schreibt auf ein virtuelles Terminal, das Emscripten liefert. main() wird automatisch aufgerufen, wenn das Modul lädt. Aus JS aufgerufene Funktionen mit EMSCRIPTEN_KEEPALIVE oder dem Flag -s EXPORTED_FUNCTIONS exportieren.

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;
}

Mit emcc kompilieren

emcc treibt die Kompilierung an. -O3 aktiviert aggressive Optimierungen (Inlining, toter Code-Entfernung). EXPORTED_FUNCTIONS listet C-Symbole (mit führendem _) zur Exposition. MODULARIZE umhüllt den Loader als Factory zur Nutzung in Bundlern. Ausgabeformate: nur .wasm, .js-Glue + .wasm oder .html-Demo.

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-Ausgabe & Modul

Das Emscripten-'Module'-Objekt ist die JS-seitige Laufzeit: Es legt _-präfixierte C-Funktionen offen, verwaltet Speicher (_malloc/_free) und liefert Hooks (print, onRuntimeInitialized). MODULARIZE macht es zu einer Promise-liefernden Factory, geeignet für Bundler und async Laden.

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

JS aus C aufrufen (EM_JS / EM_ASM)

EM_JS definiert eine Inline-JS-Funktion, die C direkt aufrufen kann — effizient und synchron. EM_ASM bettet einen Inline-JS-Schnipsel ein. $0, $1, ... für Argumente nutzen. Diese Makros kleben C an Browser-APIs (DOM, fetch, Web Audio), ohne separate JS-Bindings zu schreiben.

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;
}

Dateisystem-Unterstützung (MEMFS)

Emscripten liefert MEMFS, ein virtuelles In-Memory-Dateisystem. fopen/fread/fwrite funktionieren wie in C. --preload-file nutzen, um Assets zur Compile-Zeit in die .data-Nebendatei einzubetten. Für persistente Speicherung synchronisiert IDBFS zu IndexedDB; NODERAWFS legt das echte Dateisystem in Node offen.

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 nach Wasm kompilieren

wasm-pack-Setup

Rust kompiliert via das wasm32-unknown-unknown-Ziel nach Wasm. wasm-pack ist das empfohlene Werkzeug — er umhüllt cargo, führt wasm-bindgen aus und erzeugt ein npm-fertiges Paket. Für WASI-Ziele stattdessen wasm32-wasi nutzen.

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-Lib-Struktur

wasm-bindgen ist die Brücke zwischen Rust und JS. #[wasm_bindgen] markiert Items für den Export. Strings, Vec<u8> und JS-Objekte werden automatisch konvertiert. Das constructor-Attribut legt new() als JS-Konstruktor offen. So entsteht der JS-Glue, der sich Rust nativ anfühlen lässt.

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
    }
}

Mit wasm-pack bauen

wasm-pack build erzeugt ein veröffentlichbares npm-Paket: die .wasm-Binär, JS-Glue und TypeScript-.d.ts-Dateien. --target web liefert ein in sich geschlossenes ES-Modul für direkte Browsernutzung; --target bundler integriert sich mit webpack/vite. Die generierten Typen geben volle TS-Autocomplete.

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-Interop

extern-Blöcke importieren JS-Funktionen und -Klassen nach Rust. js_namespace = console ruft console.log auf. method legt JS-Methoden auf importierten Typen offen. wasm-bindgen handhabt String-Konvertierungen (Rust &str <-> JS-String) und Besitzverhältnisse — kein manuelles Speicherjonglieren.

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;
}

JS aus Rust aufrufen & Panics

Importierte JS-Funktionen erscheinen als gewöhnliche Rust-Funktionen. console_error_panic_hook nutzen, um lesbare Rust-Panic-Backtraces in der Browser-Konsole zu bekommen (Standard-Panics trappen ohne Meldung). Das #[wasm_bindgen(start)]-Attribut führt main() bei der Instanziierung aus — wie C's 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

Setup & Hello World

AssemblyScript ist eine TypeScript-artige Sprache, die nach Wasm kompiliert. Sie zielt auf Entwickler, die Wasm's Performance wollen, ohne C/Rust zu lernen. Die Syntax spiegelt TS wider, aber mit strengen Typen (i32 statt number). Den Loader nutzen oder das .wasm direkt importieren.

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

Typen in AssemblyScript

Anders als TypeScript erzwingt AssemblyScript konkrete numerische Typen: i32, i64, f32, f64, u8, u16, u32 usw. 'number' wird zur Compile-Zeit zurückgewiesen. StaticArray vermeidet GC; ArrayBuffer/TypedArray spiegeln die JS-APIs. Die strenge Typisierung ist, was die Kompilierung zu effizientem Wasm ermöglicht.

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);

Speicher & Strings

AssemblyScript hat einen kleinen GC für verwaltete Objekte (Array, Map, String). __retain/__release nutzen, um Lebenszeiten zu steuern, wenn zur JS-Seite überquert wird. Der @assemblyscript/loader liefert __getString, __newString, __getArray usw., um über die Grenze zu brücken.

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));

Exports & Einstiegspunkte

Mit export markierte Funktionen und Klassen werden zu Wasm-Exports. Klassen mappen über den Loader auf JS-kompatible Objekte. _start ist der konventionelle Einstiegspunkt (wie C's main). AssemblyScripts Stdlib spiegelt JS Math, Array, Map — die Migrationskurve bleibt also sanft.

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
}

Kompilierung & Optimierungen

asc ist der AssemblyScript-Compiler. --optimize (-O) führt Binaryen's wasm-opt aus. --runtime steuert die GC: 'full' (Standard), 'half' (kleiner), 'none' (manuell). --importMemory erlaubt es, Speicher über Module hinweg zu teilen. Source-Maps ermöglichen das Debuggen im originalen .ts-Quelltext.

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)

Was ist WASI

WASI ist eine portable, fähigkeitsbasierte Systemschnittstelle für Wasm außerhalb des Browsers. Anders als im Web, wo Wasm in JS ruft, gibt WASI Wasm direkten (gesandboxten) Zugang zu Dateien, Netzwerk und Umgebung. Fähigkeitsbasierte Sicherheit heißt: Ein Programm darf nur Ressourcen anfassen, die explizit für es vorgeöffnet wurden.

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-Laufzeit

wasmtime ist die Referenz-WASI-Laufzeit der Bytecode Alliance. --dir öffnet ein Host-Verzeichnis vor (gewährt Dateizugriff). --env übergibt Env-Variablen. --net aktiviert Netzwerk in preview2. Ohne explizite Vergaben sieht das Wasm-Programm nichts — das ist fähigkeitsbasierte Sicherheit in Aktion.

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

Wasm mit WASI ausführen (C-Beispiel)

Für WASI geschriebene Programme sehen aus wie gewöhnliche C-Programme mit libc. Kompilieren mit clang --target=wasm32-wasi und einem WASI-Sysroot (das wasi-sdk-Release herunterladen). Dasselbe .wasm läuft auf wasmtime, wasmer, WasmEdge und anderen WASI-Hosts ohne Neukompilierung — echte Portabilität.

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-Dateisystemzugriff

WASI legt eine POSIX-artige Dateisystem-API offen (open, read, write, close). Dateien außerhalb vorgeöffner Verzeichnisse sind unsichtbar. --dir=path:alias nutzen, um Zugang zu gewähren und umzubenennen. WASI preview2 führt Component-Model-Schnittstellen ein (wasi filesystem, wasi sockets) für reichhaltigere APIs.

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-Umgebung & Argumente

WASI liefert Argumente und Umgebungsvariablen über Standard-C-Schnittstellen (argv, environ, getenv). Der Host steuert, was sichtbar ist — --env gewährt bestimmte Variablen. So lassen sich Wasm-Programme ohne Codeänderungen konfigurieren, und das Entweichen von Host-Geheimnissen wird begrenzt.

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-Sockets (Vorschau)

WASI-Sockets sind Teil von preview2 (Component-Modell). wasi:sockets/tcp und wasi:sockets/udp liefern Netzwerk; wasi:http bietet einen höherstufigen HTTP-Client. Die APIs stabilisieren sich — heute für Portabilität wasi:http bevorzugen. Laufzeiten wie wasmtime und WasmEdge implementieren diese.

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

Debugging

wasm-objdump

wasm-objdump (aus WABT) druckt die Struktur eines Moduls: Typen, Imports, Exports, Funktionssignaturen, Code-Disassemblierung und Sektionsgrößen. -x liefert eine hochstufige Zusammenfassung; -d disassembliert Funktionskörper in WAT-artige Instruktionen. Essenziell, um zu verstehen, was ein Modul tatsächlich enthält.

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 zur Inspektion

wasm2wat konvertiert eine binäre .wasm zurück in menschenlesbares WAT. Unbezahlbar, um Module Dritter zu verstehen, unerwartetes Verhalten zu debuggen und Reverse-Engineering zu betreiben. Der Rundtrip (wasm2wat → bearbeiten → wat2wasm) erhält das Verhalten, WAT ist also ein echtes Quellformat.

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

Browser-DevTools

Alle großen Browser können Wasm in den DevTools debuggen: disassembliertes WAT ansehen, Breakpoints setzen, Locals und den Aufrufstapel inspizieren. Mit Source-Maps (Rust, AssemblyScript, Emscripten -g) mappen DevTools zurück zum Originalquelltext. DWARF-Debug-Info ermöglicht reicheres Debuggen für 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.

Source-Maps

Source-Maps verlinken Wasm-Instruktionen zurück zur originalen Quellsprache. Rust emittiert sie via wasm-pack; AssemblyScript via --sourceMap; Emscripten via -g4. Der sourceMappingURL-Kommentar im .wasm (eigene Sektion) sagt den DevTools, wo das .map zu finden ist. Ohne debuggst du rohes 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

Häufige Fehler & Traps

Wiederkehrende Wasm-Fehler: fehlende Imports (Namen/Typen nicht passend), Traps (unreachable, OOB-Speicher, Ganzzahl-Overflow bei Division durch Null), abgetrennte ArrayBuffers (nach grow) und i64-Grenzprobleme. Riskante Aufrufe in try/catch wickeln und Imports/Zeiger vorab validieren, um Probleme früh offenzulegen.

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

Performance-Optimierung

Inlining & -O-Flags

-O3 aktiviert aggressives Inlining und Schleifenoptimierungen. wasm-opt (Binaryen) führt zusätzliche Wasm-Level-Durchläufe aus (Inlining, toter Code, konstantes Falten) — in Produktion immer ausführen. -Os/-Oz tauschen etwas Tempo gegen kleinere Downloads. -flto aktiviert Programmübergreifende Optimierung.

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

Speicherlayout & Zugriffsmuster

Wasm-linearer Speicher ist nur ein ArrayBuffer — CPU-Cache-Verhalten greift. Zusammenhängende Zugriffsmuster (row-major für row-major-Daten) sind dramatisch schneller als gestridete Zugriffe. Natürliche Ausrichtung halten (4-Byte für i32), damit Loads/Stores einzelne Instruktionen treffen.

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-Grenzübergänge minimieren

Jeder JS→Wasm-Aufruf hat Overhead (Argument-Marshaling, Stack-Setup). Bei engen Schleifen die Schleife IN Wasm verschieben und sie einmal mit einem Buffer aufrufen. Der größte einzelne Wasm-Performance-Tipp — Massenoperationen schlagen Element-für-Element-Aufrufe um Größenordnungen.

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) verarbeitet 4 Floats oder 4 int32s pro Instruktion — 4x Beschleunigung für Bild-/Audio-/Matrixmathematik. Emscripten aktiviert es mit -msimd128; Rust nutzt std::arch::wasm32-Intrinsics. Auto-Vektorisierung kann helfen, aber explizite Intrinsics liefern vorhersagbare Gewinne. Weit in Browsern unterstützt.

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

Threads & SharedArrayBuffer

Wasm-Threads teilen einen Memory über Web-Worker hinweg und nutzen Atomics zur Synchronisation. Verlangt COOP/COEP-Header (Cross-Origin-Isolation). Emscriptens -pthread emuliert pthreads; Rusts std::thread funktioniert auf wasm32-wasi-threads. Super für CPU-gebundene parallele Arbeit — Bildverarbeitung, Codecs, ML-Inferenz.

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.

Profiling & Benchmarks

Mit performance.now() und dem DevTools-Performance-Tab profilieren — Wasm erscheint in Flame-Charts wie JS. Vor dem Messen aufwärmen (Kompilierungs-Overhead fällt einmalig an). Gegen optimiertes JS vergleichen — modernes V8 ist schnell; Wasm gewinnt bei vorhersagbarer Performance, numerischen Kerneln und großen Workloads, nicht bei Mikrotasks.

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

Performance-Vergleich

Wasm glänzt bei rechenlastiger numerischer Arbeit (Bildverarbeitung, Codecs, Krypto, ML) — typisch 2-10x schneller als JS. Bei DOM-, JSON- oder stringlastiger Arbeit ist JS oft schneller, weil die Arbeit bereits in nativem Code steckt (V8's JSON.parse, das DOM des Browsers). Profilieren, um zu entscheiden — nie annehmen, Wasm sei immer schneller.

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.

Anwendungsfälle für Wasm

Wasm glänzt bei: bestehende C/C++/Rust-Codebasen zu portieren (Figma, Photoshop Web), rechengebundene numerische Kernel (Bild/ML/Krypto) und gesandboxte Plugins. Reale Gewinne sind Figma (Renderer), Photoshop (voller App-Port) und Google Meet (Hintergrund-Unschärfe). Für reine DOM-Apps ist JS meist die richtige Wahl.

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

Wann JS

JS bleibt die richtige Wahl für UI, DOM, Browser-APIs und die meisten Web-App-Logiken — V8 ist stark optimiert. Zu Wasm greifen, wenn Profiling einen Hotspot offenlegt, den JS nicht wegoptimieren kann, oder beim Portieren einer bestehenden nativen Codebasis. Ein Hybridansatz (JS-UI + Wasm-Hotspots) ist oft ideal.

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.

Lade- & Startkosten

Wasm hat fixe Startkosten (Download + Kompilierung + Instanziierung), die JS vermeidet. Abmildern durch Streaming-Kompilierung, gecachte kompilierte Module via die Cache-API und lazy Laden unkritischen Wasm. Nach dem Aufwärmen sind Wasm-Funktionsaufrufe so schnell wie JS — die Kosten fallen vorab an und werden durch schnellere Ausführung wieder hereingespielt.

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)

Interop-Kosten & Grenz-Overhead

JS↔Wasm-Aufrufe sind billig, aber nicht kostenlos (~10-100ns je, mehr bei Strings). Bei hochfrequenten Events in JS bündeln und Wasm einmal mit einem Buffer aufrufen. JS-Objekte pro Aufruf vermeiden — externref nutzen oder Bytes in den Speicher kopieren. Die Grenze ist schnell für Zahlen, langsam für serialisierte Daten.

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

Sicherheitsmodell

Sandbox-Modell

Wasm's Sicherheitsfundament ist die Sandbox: Ein Modul kann nicht auf Host-Speicher, Dateien, Netzwerk oder Geräte zugreifen, außer der Host liefert explizit Funktionen dafür via Imports. Das macht Wasm sicher für unvertrauten Code — er kann nur tun, was seine Imports erlauben. Kombiniert mit Typsicherheit verhindert das Buffer-Overflows und 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()
//   )

Same-Origin-Policy & Fetch

Wasm entkommt dem Sicherheitsmodell des Browsers nicht — Same-Origin-Policy und CORS gelten für .wasm-Fetches wie für jede Ressource. Cross-Origin-Wasm verlangt ordentliche CORS-Header und den MIME-Typ application/wasm. Wasm kann auch CSP, Cookies oder jedes andere Browser-Sicherheitsmechanismen nicht umgehen.

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.

Speicherisolation

Wasm-Speicher wird zur Laufzeit grenzgeprüft — jeder OOB-Zugriff trapt sofort, statt Speicher zu korrumpieren. Module können weder den Speicher des anderen noch den JS-Heap oder beliebige Host-Adressen lesen. Funktionszeiger (call_indirect) werden typgeprüft, Fälschung von Aufrufzielen wird verhindert. Das eliminiert ganze Klassen von C/C++-Schwachstellen.

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.

Fähigkeitsbasierte Sicherheit

Wasm folgt fähigkeitsbasierter Sicherheit: Das import-Objekt IST die Fähigkeit des Moduls. Sorgfältig zu wählen, was importiert wird, gibt einem Modul minimale Rechte. Ein Plugin, das nur log() importiert, kann nichts anderes tun. Das ist das Fundament sicherer Plugin-Systeme (Figma, Shopify Functions usw.).

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

Die Content-Security-Policy behandelt Wasm wie eval — standardmäßig blockiert CSP es. 'wasm-unsafe-eval' zu script-src ergänzen, um Wasm zu erlauben, während eval() blockiert bleibt. Das ist permissiver als unsafe-eval und für Produktion empfohlen. Trusted-Types-Kompatibilität verlangt, jeden dynamischen JS-Glue in eine Policy zu wickeln.

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

Werkzeugkette

WABT (wat2wasm, wasm2wat)

WABT ist das kanonische Toolkit für die Arbeit mit Wasm-Text- und Binärformaten. wat2wasm/wasm2wat als Rundtrip; wasm-objdump inspiziert die Struktur; wasm-interp führt Module in einer Referenzinterpreter aus. wasm-decompile erzeugt eine C-artige lesbare Form. Essenziell zum handverfassten Schreiben, Debuggen und Lehren.

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 ist die ausgereifteste Wasm-Toolchain — kompiliert C/C++, Fortran und andere LLVM-Sprachen. emcc/em++ umhüllen Clang; emcmake/emconfigure erlauben es, bestehende CMake-/Autotools-Projekte unverändert zu bauen. Er liefert auch libc-, SDL-, OpenGL-(via WebGL)- und pthreads-Ports für Kompatibilität.

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 ist das offizielle Rust→Wasm-Werkzeug: baut, führt wasm-bindgen aus, generiert TypeScript-Typen und paketiert für npm. --target wählt das JS-Modulformat. wasm-pack test führt Rust-Tests in echten Browsern via webdriver aus. Das wasm-pack-template für ein fertiges Projektgerüst nutzen.

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 ist das Optimierungs-Toolkit, das Emscripten und wasm-pack intern nutzen. wasm-opt führt Wasm-Level-Durchläufe aus (Inlining, toter Code-Entfernung, konstantes Falten) — auf Produktions-Builds immer ausführen. -O3 für Tempo, -Oz für minimale Größe. wasm-metadce entfernt ungenutzte Exports über Module hinweg.

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 ist ein modernes Rust-basiertes Toolkit der Bytecode Alliance. Er parst/druckt/validiert, aber sein herausragendes Feature ist die Component-Modell-Unterstützung (component new/embed/describe). Strenger und schneller als WABT bei vielen Operationen und das empfohlene Werkzeug für Component-Modell-Arbeit.

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.

Laufzeiten (wasmtime, wasmer, WasmEdge)

Drei große eigenständige Laufzeiten: wasmtime (Referenz der Bytecode Alliance, beste Component-Modell-Unterstützung), wasmer (mehrere Backends inkl. LLVM für Spitzen-Performance, JS-Bindings), WasmEdge (CNCF, optimiert für Cloud-native und AI-Inferenz). Alle implementieren WASI, dasselbe .wasm läuft also über sie hinweg. Nach Ökosystem-Passung wählen.

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

Komponenten & Best Practices

Wasm-Komponenten im Überblick

Das Component-Modell ist Wasm's Evolution: ein Modulformat, das Komponenten mit reichen Typen (Strings, Records, Listen) kommunizieren lässt, ohne manuell durch linearen Speicher zu marshalen. Komponenten komponieren wie Bibliotheken über Sprachen hinweg (Rust-Komponente + JS-Komponente). Unterstützt von wasmtime, WasmEdge und dem weiteren Bytecode-Alliance-Ökosystem.

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) ist die IDL für Komponenten — Records, Variants, Enums, Ressourcen und Funktionen deklarieren. wit-bindgen erzeugt sprachspezifische Bindings (Rust, C, JS, Python). Das 'world'-Schlüsselwort bündelt, welche Imports und Exports eine Komponente liefert/konsumiert. Das ist das Fundament portabler, sprachagnostischer Wasm-Bibliotheken.

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

Best Practice: kleine, fokussierte Module

Mehrere kleine, fokussierte Wasm-Module statt eines Monolithen bevorzugen. Kleinere Module laden schneller, cache-n besser und lassen sich lazy laden (das Audio-Modul nur laden, wenn nötig). Speicher über Imports über Module teilen oder das Component-Modell für typsichere Modulübergreifende Aufrufe nutzen. Auf jedem wasm-opt -Oz ausführen.

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.

Best Practice: Fehlerbehandlung

Wasm-Traps (Division durch Null, OOB-Speicher, unreachable) lassen sich von innen nicht fangen — sie brechen die Funktion ab. Exportierte Funktionen so entwerfen, dass sie Fehlercodes oder Result-Typen zurückgeben statt zu trappen. WebAssembly.RuntimeError auf der JS-Seite als letzten Ausweg fangen. Das Component-Modell unterstützt typisierte Fehler-Variants nativ.

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.

Best Practice: Speicherverwaltung

Wasm-Speicher wie in C behandeln: Jede Allokation braucht eine passende Freigabe. alloc/free-Helfer exportieren und die JS-seitige Buffer-Nutzung in try/finally wickeln. TypedArray-Views nach jedem memory.grow neu erzeugen (der ArrayBuffer trennt sich ab). Besitzverhältnisse dokumentieren: Wer ist fürs Freigeben verantwortlich — Aufrufer oder Aufgerufener? Lecks verschlechtern die Performance über die Zeit.

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

Best Practice: Testen & CI

Wasm in echten Umgebungen testen: wasm-pack test führt Rust-Tests in Headless-Browsern aus; AssemblyScript und Emscripten haben eigene Runner. wasm-validate und Größenchecks in CI ergänzen. -s ASSERTIONS=1 (Emscripten) und Debug-Builds nutzen, um Probleme früh zu erwischen. Mit wat2wasm lint-en und auf Release-Artefakten immer wasm-opt ausführen.

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?