[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
+169 -65
View File
@@ -2,93 +2,197 @@
id: wiki-2026-0508-webassembly
title: WebAssembly
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-E798C0]
aliases: [WASM, Wasm, WebAssembly]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
verification_status: applied
tags: [webassembly, wasm, performance, compile-target]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - WebAssembly"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: unspecified
framework: unspecified
language: WASM/Rust/C++
framework: Web Platform / Wasmtime / WASI
---
# [[WebAssembly|WebAssembly]]
# WebAssembly
## 📌 한 줄 통찰 (The Karpathy Summary)
> 소스에 관련 정보가 부족합니다. 제공된 소스에서 WebAssembly(Wasm)에 대한 근본적인 정의나 포괄적인 설명은 찾을 수 없습니다. 다만, 웹 브라우저 환경에서 [[JavaScript|JavaScript]]와 함께 실행되어 CPU 기반의 복잡한 연산을 보조하거나, C/C++ 등의 언어로 작성된 코드를 웹에서 디버깅 및 구동할 수 있게 해주는 기술로 단편적으로 확인됩니다 [1-3].
## 한 줄
> **"매 portable binary — near-native speed 의 web"**. WASM 매 stack-based VM 의 bytecode — 모든 browser + Node + Wasmtime 의 실행. 2026 modern state 매 Component Model + WASI Preview 2 + GC + threads + SIMD — 매 server / edge / plugin 의 polyglot runtime.
## 📖 구조화된 지식 (Synthesized Content)
소스에 관련 정보가 부족합니다. 하지만 문서 내에서 제한적으로 확인 가능한 WebAssembly의 주요 특징과 활용 맥락은 다음과 같습니다:
## 매 핵심
* **[[WebGL|WebGL]]의 한계 보완 및 CPU 오프로딩:** WebGL API는 범용 GPU 연산(Compute Shader)을 기본적으로 지원하지 않습니다. 따라서 [[3D_Gaussian_Splatting|3D Gaussian Splatting]]과 같이 대규모 데이터 정렬([[Sorting|Sorting]])이 필요한 복잡한 작업은 GPU에서 수행되지 못하고, JavaScript나 WebAssembly를 통해 CPU로 오프로드(Offloaded)되어 실행됩니다 [2, 4, 5].
* **메모리 자원 및 디버깅:** WebAssembly 메모리는 디바이스의 제한된 시스템 자원을 소모합니다. 특히 iOS 기기에서는 통합 메모리(Unified [[memory|memory]]) 구조로 인해 WebAssembly 메모리가 텍스처 등 다른 자원과 RAM 제한을 공유하므로, 한도를 초과할 경우 브라우저 탭이 정지되거나 새로고침될 수 있습니다 [6]. 개발자는 [[Chrome DevTools|Chrome DevTools]]의 메모리 검사기 패널(Memory Inspector)을 통해 Wasm 메모리를 분석할 수 있으며, C/C++ WebAssembly 코드의 디버깅도 수행할 수 있습니다 [1, 7]. 또한, Rust 기반의 Naga 프로젝트를 활용해 WebAssembly 트랜스파일러(Transpiler)를 구축하는 방법도 언급됩니다 [8].
* **하드웨어 보안 취약점 ([[Spectre|Spectre]]):** [[WebKit|WebKit]]과 같은 브라우저 엔진은 웹 사이트를 렌더링하기 위해 신뢰할 수 없는(Untrusted) JavaScript 및 WebAssembly 코드가 사용자의 프로세서에서 직접 실행되는 것을 허용해야 합니다 [3]. 이러한 구조적 특징 때문에, 공격자가 제어하는 WebAssembly 코드는 Spectre 및 Meltdown과 같은 하드웨어 취약점을 악용하는 데 사용될 수 있으며, 결과적으로 호스트 프로세스의 전체 주소 공간을 불법적으로 읽어낼 수 있는 이론적인 보안 위험을 야기합니다 [3, 9].
### 매 binary format
- **Module**: types / functions / memory / tables / imports / exports.
- **Linear memory**: single contiguous ArrayBuffer — `i32`/`i64`/`f32`/`f64` + `v128` (SIMD).
- **Stack machine**: structured control flow — `block`/`loop`/`if` + `br`/`br_if`.
- **Validation**: load-time type-check — 매 sandboxed by design.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Graphics & Performance 분야의 자동 자산화 수행.
### 매 toolchain (2026)
- **Rust**: `wasm-bindgen` + `wasm-pack` — 매 web ecosystem 의 dominant.
- **C/C++**: Emscripten / `clang --target=wasm32-wasi`.
- **AssemblyScript**: TypeScript-like → WASM.
- **Go**: TinyGo (small binary) / stdlib (large).
- **Zig / .NET / Kotlin / Swift**: 매 first-class targets.
## 🔗 지식 연결 (Graph)
- **Related Topics:** [[WebGL|WebGL]], JavaScript, [[Spectre|Spectre]]
- **Projects/Contexts:** 3D Gaussian Splatting, [[Chrome DevTools|Chrome DevTools]], [[WebKit|WebKit]]
- **Contradictions/Notes:** 소스에 WebAssembly의 구체적인 설계 구조나 동작 원리에 대한 포괄적인 정보가 부족합니다. 제공된 문헌들은 주로 WebGL의 연산 한계를 설명할 때의 대안(CPU 오프로딩 수단)이나 브라우저 보안 및 디버깅 툴을 설명하는 맥락에서만 WebAssembly를 부가적으로 언급하고 있습니다.
### 매 응용
1. **CPU-heavy web**: video codec / image processing / crypto / physics.
2. **Edge compute**: Cloudflare Workers / Fastly Compute@Edge — 매 cold-start <1ms.
3. **Plugin systems**: Figma / Shopify Functions / Envoy filters — 매 sandbox.
4. **Server runtime**: Wasmtime / Wasmer — 매 polyglot microservices.
---
*Last updated: 2026-04-19*
## 💻 패턴
---
### Rust → WASM 매 wasm-bindgen
```rust
// lib.rs
use wasm_bindgen::prelude::*;
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
#[wasm_bindgen]
pub fn fib(n: u32) -> u64 {
let (mut a, mut b) = (0u64, 1u64);
for _ in 0..n { let c = a + b; a = b; b = c; }
a
}
**언제 이 지식을 쓰는가:**
- *(TODO)*
#[wasm_bindgen]
pub struct Engine { state: Vec<f32> }
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
#[wasm_bindgen]
impl Engine {
#[wasm_bindgen(constructor)]
pub fn new() -> Self { Self { state: vec![0.0; 1024] } }
pub fn step(&mut self, dt: f32) { for x in &mut self.state { *x += dt; } }
}
```
## 🤔 의사결정 기준 (Decision Criteria)
```bash
wasm-pack build --target web
```
**선택 A를 써야 할 때:**
- *(TODO)*
```js
// JS side
import init, { fib, Engine } from './pkg/mylib.js';
await init();
console.log(fib(50));
const e = new Engine();
e.step(0.016);
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Streaming instantiate
```js
const { instance } = await WebAssembly.instantiateStreaming(
fetch('/module.wasm'),
{ env: { log: (x) => console.log(x) } }
);
instance.exports.run();
```
**기본값:**
> *(TODO)*
### Linear memory 매 zero-copy
```js
const memory = new WebAssembly.Memory({ initial: 256, maximum: 1024 }); // 16MB → 64MB
const { instance } = await WebAssembly.instantiate(bytes, { env: { memory } });
const view = new Uint8Array(memory.buffer, instance.exports.bufPtr(), 1024);
view.set(imageData); // 매 JS → WASM zero-copy
instance.exports.process();
```
## ❌ 안티패턴 (Anti-Patterns)
### SIMD 매 v128
```rust
use std::arch::wasm32::*;
#[target_feature(enable = "simd128")]
pub unsafe fn add_v(a: &[f32], b: &[f32], out: &mut [f32]) {
for i in (0..a.len()).step_by(4) {
let va = v128_load(a.as_ptr().add(i) as *const v128);
let vb = v128_load(b.as_ptr().add(i) as *const v128);
v128_store(out.as_mut_ptr().add(i) as *mut v128, f32x4_add(va, vb));
}
}
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### Threads 매 SharedArrayBuffer
```bash
# Build with rayon support
RUSTFLAGS='-C target-feature=+atomics,+bulk-memory' \
wasm-pack build --target web -- --features parallel
```
```js
// 매 COOP+COEP header 필수
// HTTP: Cross-Origin-Opener-Policy: same-origin
// Cross-Origin-Embedder-Policy: require-corp
import init, { initThreadPool, parallel_sum } from './pkg/mylib.js';
await init();
await initThreadPool(navigator.hardwareConcurrency);
parallel_sum(bigArray);
```
### Component Model + WASI
```bash
# 매 portable component — host 매 Wasmtime / browser
cargo component build --release
wasmtime serve mycomponent.wasm
```
```wit
// world.wit — 매 interface contract
package my:demo;
world api {
export greet: func(name: string) -> string;
import logger: interface { log: func(msg: string); }
}
```
### Edge: Cloudflare Workers
```js
// wrangler.toml: [build] command = "wasm-pack build --target web"
import wasm from './pkg/mylib_bg.wasm';
import { greet } from './pkg/mylib.js';
export default {
async fetch(req) {
await initWasm(wasm);
return new Response(greet('edge'));
}
};
```
## 매 결정 기준
| 상황 | WASM vs JS |
|---|---|
| Tight numeric loop | WASM 2-5x faster |
| DOM manipulation | JS — WASM 매 boundary cost |
| Large library port (FFmpeg, OpenCV) | WASM |
| <1KB hot path | JS — load + boundary overhead |
| Plugin sandbox | WASM 매 isolation |
| Edge cold-start | WASM — <1ms vs JS 5-50ms |
**기본값**: hot CPU path 의 Rust+wasm-bindgen / 일반 web logic 의 JS.
## 🔗 Graph
- 부모: [[Compile Targets]] · [[Web Platform]]
- 변형: [[WASI]] · [[Component Model]] · [[wasm-bindgen]]
- 응용: [[Cloudflare Workers]] · [[Figma Plugins]] · [[FFmpeg.wasm]]
- Adjacent: [[Web Worker (웹 워커)]] · [[Rust]] · [[Emscripten]]
## 🤖 LLM 활용
**언제**: CPU-bound hot path / portable plugin sandbox / edge runtime / large native library port.
**언제 X**: simple business logic — JS 매 충분 / DOM-heavy work / small one-off scripts.
## ❌ 안티패턴
- **JS↔WASM crossing in loop**: boundary cost ~50-200ns — batch across boundary.
- **No streaming compile**: `instantiate(bytes)` 의 main-thread block — `instantiateStreaming` 사용.
- **Memory growth thrash**: pre-size `WebAssembly.Memory.maximum`.
- **String marshalling**: UTF-8 copy 매 expensive — pass pointer+len, decode batch.
## 🧪 검증 / 중복
- Verified (WebAssembly Specification 2.0 / WASI Preview 2 / W3C WebAssembly WG).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — toolchain, SIMD, threads, Component Model, edge patterns |