Skip to content

WebAssembly 치트시트

웹에서 빠르게 실행되는 바이너리 명령 형식.

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 모듈과 인스턴스

WebAssembly.Module은 컴파일된 무상태 표현으로 여러 인스턴스에서 안전하게 재사용할 수 있습니다. WebAssembly.Instance는 런타임 상태(메모리, 전역)를 보유합니다. 한 번 컴파일하고 여러 번 인스턴스화하면 병렬 워커 생성에 효율적입니다.

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, 예외, 스레드, 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 텍스트 형식

모듈과 S-표현식

WAT(WebAssembly Text format)는 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는 두 가지 주석 스타일을 지원합니다. ';;'는 한 줄, '(; ... ;)'는 블록 주석입니다. 블록 주석은 중첩되고 여러 줄에 걸칠 수 있어 개발 중 코드 덩어리를 비활성화할 때 유용합니다.

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는 함수, 메모리, 테이블, 전역에 인라인 (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))

데이터 세그먼트

데이터 세그먼트는 인스턴스화 시(활성) 또는 memory.init로 지연 초기화(수동)해 선형 메모리를 초기화합니다. 문자열에는 널 종료자용 \00, 줄바꿈용 \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에는 네 가지 기본 값 타입만 있습니다: 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바이트를 하나의 SIMD 레지스터에 패킹합니다. 레인은 i32x4(int32 4개), f32x4(float32 4개), i16x8, i8x16, f64x2로 주소 지정합니다. SIMD는 명령당 여러 값을 처리해 이미지/오디오/암호화 워크로드를 빠르게 합니다.

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)는 0으로 초기화되고 가변입니다. local.get, local.set, local.tee(설정 + 스택에 남김)를 사용하세요. 지역 변수는 메모리/전역 밖에서 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년부터 모든 주요 엔진이 지원합니다. 메모리를 통한 출력 매개변수가 필요 없어지고 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 $func) 함수를 하나 선언할 수 있어 초기화에 유용합니다. 인자도 반환 값도 없습니다. 모듈당 시작 함수는 하나만 허용됩니다.

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

메모리

선형 메모리 선언

선형 메모리는 64KiB 페이지 단위로 커지는 연속 ArrayBuffer 유사 영역입니다. (memory 1 10)은 초기=1, 최대=10을 선언합니다. 메모리는 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);
)

메모리 grow

memory.grow는 페이지를 추가하고 이전 크기(페이지)를 반환하며 실패 시 -1을 반환합니다. 중요: grow는 기반 ArrayBuffer를 분리(detach)해 기존의 모든 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!

로드와 저장 연산

로드/저장에는 크기(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가 하나의 메모리를 공유해 병렬성을 얻습니다. 원자 연산(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에는 네이티브 문자열 타입이 없습니다. 문자열은 선형 메모리의 바이트 시퀀스이며 보통 (포인터, 길이) 쌍으로 전달됩니다. TextEncoder/TextDecoder가 UTF-8 변환을 처리합니다. 쓰기 전에 메모리 영역이 충분히 큰지 항상 확인하세요.

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

테이블

테이블 선언

테이블은 간접 호출과 동적 디스패치에 쓰이는 참조(보통 funcref) 배열입니다. 바이트를 담는 메모리와 달리 테이블은 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이 런타임에 함수 시그니처 일치를 검사합니다(불일치 시 트랩). Wasm의 vtable과 객체 지향 디스패치의 기반입니다.

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 열거형, 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

전역

전역 선언

전역은 모듈 수준 단일 값이며 불변(기본) 또는 가변(mut)입니다. 함수 호출 간 유지되고 카운터, 설정 플래그, 상수에 유용합니다. 가변 전역은 메모리/테이블 밖에서 유일한 공유 가변 상태입니다.

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 객체를 여러 모듈 인스턴스에 공유하면 메모리를 건드리지 않고 상태를 조율하는 깔끔한 방법입니다.

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

전역 사용 사례

전역은 세 패턴에 적합합니다: (1) 가져온 설정 상수, (2) 인스턴스 간 공유되는 지속 카운터/상태, (3) 캐시된 계산 결과. 단일 값에는 메모리보다 단순하고 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) 함수를 호출하게 합니다. 각 가져오기는 두 수준 이름(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() }
});

메모리 가져오기

메모리를 가져오면 여러 Wasm 모듈(과 JS)이 하나의 메모리 영역을 공유할 수 있으며 Wasm '라이브러리'의 기반입니다. 한 모듈이 할당하고 쓰면 다른 모듈이 읽습니다. 데이터 복사 없이 모듈을 합성하며 컴포넌트 모델의 전조입니다.

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

전역과 테이블 가져오기

전역과 테이블도 가져올 수 있어 모듈 간 공유 상태와 함수 포인터 테이블을 가능하게 합니다. WebAssembly.Table은 JS 생성자입니다. 가져온 가변 전역은 호스트가 모듈을 다시 빌드하지 않고 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
    })
  }
};

함수, 메모리, 테이블 익스포트

모듈에 선언된 모든 것(함수, 메모리, 테이블, 전역)을 익스포트할 수 있습니다. 익스포트는 instance.exports의 속성이 됩니다. 메모리 익스포트는 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와 export

인라인 (import "m" "f")와 (export "name") 주석은 문법적 편의로 독립 (import ...)/(export ...) 형식과 같은 바이너리로 컴파일됩니다. 하나의 정의에 인라인 export를 붙일 수 있지만 가져온 항목은 import와 export를 따로 선언합니다.

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로 감싸세요. import 내부의 잡히지 않은 throw는 Wasm 호출자를 트랩시킵니다.

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를 소비합니다(0이 아니면 참). (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에서 일찍 반환하는 관용적 방법입니다.

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 인덱스를 소비해 나열된 라벨 중 하나로 점프하고 범위를 벗어나면 마지막(기본) 라벨로 갑니다. 각 케이스가 값을 반환할 수 있도록 block을 가장 바깥부터 중첩하세요. 태그로 디스패치하는 가장 효율적인 방법입니다.

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은 항상 트랩(런타임 예외 발생)하며 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 숫자에 직접 매핑됩니다. 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 도우미를 익스포트하거나 둘을 하나의 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 래퍼입니다. 하나를 만들어 여러 모듈 인스턴스에 넘기면 메모리를 건드리지 않고 가변 상태를 깔끔하게 공유합니다. .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 트랩(0 나눗셈, 범위 밖 메모리, 스택 오버플로)은 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 사이드카에 임베드하세요. 지속 저장에는 IDBFS가 IndexedDB에 동기화되고 NODERAWFS는 Node에서 실제 FS를 노출합니다.

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 객체는 자동 변환됩니다. constructor 속성은 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 string)과 소유권을 처리해 수동 메모리 관리가 필요 없습니다.

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 호출과 패닉

가져온 JS 함수는 일반 Rust 함수로 나타납니다. console_error_panic_hook을 쓰면 브라우저 콘솔에서 읽을 수 있는 Rust 패닉 백트레이스를 얻습니다(기본 패닉은 메시지 없이 트랩). #[wasm_bindgen(start)] 속성은 C의 main처럼 인스턴스화 시 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는 Wasm으로 컴파일되는 TypeScript 유사 언어입니다. 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를 호출하는 웹과 달리 WASI는 파일, 네트워크, 환경에 대한 직접(샌드박스) 접근을 줍니다. 능력 기반 보안은 프로그램이 명시적으로 미리 열어 준 리소스만 건드리게 합니다.

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은 호스트 디렉터리를 미리 열어(파일 접근 부여) 줍니다. --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)를 노출합니다. 미리 열지 않은 디렉터리 밖 파일은 보이지 않습니다. 접근을 부여하고 이름을 바꾸려면 --dir=path:alias를 사용하세요. WASI preview2는 더 풍부한 API를 위해 컴포넌트 모델 인터페이스(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 소켓(프리뷰)

WASI 소켓은 preview2(컴포넌트 모델)의 일부입니다. 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

흔한 오류와 트랩

반복되는 Wasm 오류: 가져오기 누락(이름/타입 불일치), 트랩(unreachable, 범위 밖 메모리, 0 나눗셈의 정수 오버플로), 분리된 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바이트)을 유지해 로드/저장이 단일 명령으로 처리되게 하세요.

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 안으로 옮기고 버퍼와 함께 한 번만 호출하세요. 가장 큰 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(단일 명령 다중 데이터)

SIMD(v128)는 명령당 float 4개 또는 int32 4개를 처리해 이미지/오디오/행렬 수학에서 4배 속도를 냅니다. Emscripten은 -msimd128로 켜고 Rust는 std::arch::wasm32 인트린직을 씁니다. 자동 벡터화도 도움이 되지만 명시적 인트린직이 예측 가능한 이점을 줍니다. 브라우저에서 널리 지원됩니다.

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처럼 플레임 차트에 나타납니다. 측정 전에 워밍업하세요(컴파일 오버헤드는 일회성). 최적화된 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, 문자열 위주 작업에서는 작업이 이미 네이티브 코드(V8의 JSON.parse, 브라우저 DOM)에 있어 JS가 더 빠른 경우가 많습니다. 프로파일링으로 결정하고 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 웹), 계산 바운드 숫자 커널(이미지/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, 대부분의 웹 앱 로직에는 JS가 여전히 올바른 선택입니다. V8은 매우 최적화되어 있습니다. 프로파일링에서 JS가 제거할 수 없는 핫스팟이 드러나거나 기존 네이티브 코드베이스를 이식할 때 Wasm을 선택하세요. 하이브리드 접근(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 호출은 저렴하지만 공짜는 아닙니다(각 약 10-100ns, 문자열은 더). 빈번한 이벤트에는 JS에서 배치 처리하고 버퍼와 함께 Wasm을 한 번 호출하세요. 호출마다 JS 객체를 넘기지 말고 externref를 쓰거나 바이트를 메모리에 복사하세요. 경계는 숫자에는 빠르고 직렬화 데이터에는 느립니다.

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은 브라우저 보안 모델을 벗어나지 않습니다. .wasm fetch에도 다른 리소스처럼 동일 출처 정책과 CORS가 적용됩니다. 교차 출처 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 메모리는 런타임에 범위 검사되므로 범위 밖 접근은 메모리를 손상시키는 대신 즉시 트랩합니다. 모듈은 서로의 메모리, 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가 차단합니다. script-src에 'wasm-unsafe-eval'을 추가하면 eval()은 막으면서 Wasm을 허용합니다. 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 경유), pthread 포팅도 제공합니다.

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 new/embed/describe)입니다. 많은 작업에서 WABT보다 엄격하고 빠르며 컴포넌트 모델 작업에 권장되는 도구입니다.

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)

세 가지 주요 독립 런타임: wasmtime(Bytecode Alliance 참조, 최고의 컴포넌트 모델 지원), 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

컴포넌트와 모범 사례

Wasm 컴포넌트 개요

컴포넌트 모델은 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입니다. 레코드, 변형, 열거형, 리소스, 함수를 선언합니다. wit-bindgen이 언어별 바인딩(Rust, C, JS, Python)을 생성합니다. 'world' 키워드는 컴포넌트가 제공/소비하는 가져오기와 내보내기를 묶습니다. 이식 가능한 언어 중립 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

모범 사례: 작고 집중된 모듈

하나의 거대 모놀리식 모듈보다 작고 집중된 여러 Wasm 모듈을 선호하세요. 작은 모듈은 다운로드가 빠르고 캐시가 잘 되며 지연 로드(필요할 때만 오디오 모듈 로드)할 수 있습니다. import로 모듈 간 메모리를 공유하거나 타입 안전 모듈 간 호출에 컴포넌트 모델을 사용하세요. 각각에 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 트랩(0 나눗셈, 범위 밖 메모리, unreachable)은 Wasm 내부에서 잡을 수 없고 함수를 중단합니다. 익스포트 함수는 트랩 대신 오류 코드나 Result 타입을 반환하도록 설계하세요. 최후 수단으로 JS 측에서 WebAssembly.RuntimeError를 잡으세요. 컴포넌트 모델은 타입 있는 오류 변형을 기본 지원합니다.

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 후에는 ArrayBuffer가 분리되므로 TypedArray 뷰를 다시 만드세요. 소유권(해제 책임이 호출자에게 있는지 피호출자에게 있는지)을 문서화하세요. 누수는 시간이 지나며 성능을 떨어뜨립니다.

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?