3. WebAssembly란?
● New Standard developed by Mozilla, Microsoft, Google and Apple
● Compact, portable ‘Binary Format’ for Web
● Fast to load, runs safely
● Near-native performance
● Works on any device
6. WebAssembly 무엇이 좋은가?
● 속도가 빠르다 (높은 성능)
- 대용량 연산 작업이 필요한 경우에 대한 해법
● 보안을 향상 할 수 있다
● ActiveX, Portable Native Client (PNaCl)의 대체 가능
● 다양한 언어로 browser용 client(app)을 개발 가능
● 예를 들어보면?
○ P2P application, Image / Video / Music editing
○ Live video, CAD application
○ Game
7. WebAssembly 히스토리 & 등장배경
● 히스토리
● WebAssembly was first announced on 17 June 2015
● 15 March 2016 was demonstrated executing Unity's Angry Bots in Firefox, Chromium, Google Chrome, and Microsoft Edge.
● w3c에 그룹(https://www.w3.org/community/webassembly/)을 만들고, 메이저 4개 회사에서 진행중
● 현재 개발 진행중
● 등장배경
● web browser에서 native수준의 program구동에 대한 요구 사항 증대
● ActiveX, Native Clinet(NaCl), Portable Native Cilent(PNaCl)와 같은 native연동 필요성 증대 및 파편화 해결책이 필요해짐
● 구글 웹 툴킷(GWT) > 엠스크립튼과 맨드릴 코드패턴 > asm.js > WebAssembly
8. asm.js에 대해서 잠깐 살펴보기
● Intermediate language
● Subset of Javascript
● Compiling C/C++ to asm.js(Javascript)
● Very fast. Best result 1.5x native
● Natively runs in firefox, edge, chrome
www.slideshare.net/ValeriiaMaliarenko/web-assembly-overview-by-mikhail-sorokovsky
27. WebAssembly 정리
● WebAssembly는 현재 개발중인 프로젝트 이다.
○ 아직 정식 release (v1.0)이 되지 않았고, 기본(default)옵션으로 use할 수 있는 feature는 아니다.
● WebAssembly는 차세대 web tech중 꼭 알아야 하는 feature가 될 것이다.
○ 활용도가 매우 넓다.
○ 가능성이 매우 높은 기술이다.
○ 실제 major browser bender가 참여하고 있다.
● WebAssembly가 어렵게 공부해야하는 기술은 아니다.
○ 최종적으로, 정식 버전이 나오면, 우리는 compile, build만 잘해서 사용하면된다.
○ 물론 기본적인 개념과 빌드방법등은 조금 공부해야 하지만…
● 그래서…
○ 개발자라면, 실제 구현을 한번정도 따라해보기
○ 이후 관심을 놓지 말고, 가끔(2주정도?)마다 버전상황, relase상황 등을 확인해보기
35. emscripten 설치 (ubuntu)
1. install required module
#Update the package lists
sudo apt-get update
# Install *gcc* (and related dependencies)
sudo apt-get install build-essential
# Install cmake
sudo apt-get install cmake
# Install Python
sudo apt-get install python2.7
# Install node.js
sudo apt-get install nodejs
# Install Java (optional, only needed for Closure Compiler minification)
sudo apt-get install default-jre
2. install emcc
# download emscripten file
Portable Emscripten SDK for Linux and OS X (emsdk-portable.tar.gz)
# unzip
gunzip emsdk-portable.tar.gz
tar -xvf emsdk-portable.tar
# Fetch the latest registry of available tools.
./emsdk update
# Download and install the latest SDK tools.
./emsdk install latest
# Make the "latest" SDK "active"
./emsdk activate latest
# Set the current Emscripten path on Linux/Mac OS X
source ./emsdk_env.sh
36. binaryen 설치 (ubuntu)
1. pre-required
cmake, make
2. clone source code
clone https://github.com/WebAssembly/binaryen.git
3. build
cmake . && make
4. using tools
code that builds the following tools in bin/:
tools
wasm-shell
A shell that can load and interpret WebAssembly code. It can also run the spec test suite.
wasm-as
Assembles WebAssembly in text format (currently S-Expression format) into binary format (going through
Binaryen IR).
wasm-dis
Un-assembles WebAssembly in binary format into text format (going through Binaryen IR).
wasm-opt
Loads WebAssembly and runs Binaryen IR passes on it.
asm2wasm
An asm.js-to-WebAssembly compiler, using Emscripten's asm optimizer infrastructure. This is used by
Emscripten in Binaryen mode when it uses Emscripten's fastcomp asm.js backend.
s2wasm
A compiler from the .s format emitted by the new WebAssembly backend being developed in LLVM. This
is used by Emscripten in Binaryen mode when it integrates with the new LLVM backend.
wasm.js
wasm.js contains Binaryen components compiled to JavaScript, including the interpreter, asm2wasm, the
S-Expression parser, etc., which allow you to use Binaryen with Emscripten and execute code compiled to
WASM even if the browser doesn't have native support yet. This can be useful as a (slow) polyfill.
binaryen.js
A stand alone library that exposes Binaryen methods for parsing s-expressions and instantiating WASM
modules in JavaScript.
37. WebAssembly 트러블슈팅
● C코드 작성시 주의점
C 코드 작성시 API형태의 코드 작성을 하는경우
#include <emscripten.h> 헤더 추가와
EMSCRIPTEN_KEEPALIVE 키워드 추가 가 필요하다.
없는경우, 빌드시 미사용 api의 경우 asm.js파일에 추가되지 않는다.
즉 add 함수를 정의하고, 사용하는 곳이 없으면, asm.js파일로 빌드시 add라는 함수가 asm.js에 추가되지
않는다.
38. WebAssembly 트러블슈팅
● EMCC 빌드 주의점
emcc에 별다른 옵션을 주지 않고 빌드(기본빌드)하면, simple한 형태의 asm.js코드가 아닌. 즉각적으로 사
용할 수 있는 5000 ~ 10000라인의 asm.js코드가 생성된다.
해당 기본 빌드의 경우 node등에서 AMD(require)로 모듈을 바로 로딩해서 사용 가능하지만, api을 별도로
만들어서, 사용하려는 경우 불필요한 코드가 너무 많이 들어오게 된다.
따라서, simple한 형태의 api을 얻고 싶은 경우. ONLY_MY_CODE, --separate-asm 옵션을 사용한, emcc
빌드를 하여야 한다.
40. WebAssembly 트러블슈팅
● browser에서 구동시 wasm옵션을 먼저 설정해야함
WebAssembly isn't released yet, so it isn't enabled by default.
But you can test it in development builds:
In Firefox, use Nightly and set javascript.options.wasm in about:config.
In Chrome, use Canary and enable chrome://flags/#enable-webassembly.
41. WebAssembly 트러블슈팅
● browser에서 구동시 에러 발생 문제
현재 계속 개발중인 feature이기 때문에 compile한 wasm버전과, browser가 지원하는 wasm버
전이 다르면 구동이 되지 않고 위 그림과 같은 에러가 발생한다.
해결책
1. wasm이 지원되는 browser로 가장 최신 버전을 항상 유지한다.
a. In Firefox, use Nightly, In Chrome, use Canary
2. wasm컴파일러 역시 항상 최신 버전을 유지한다.
a. https://github.com/WebAssembly/binaryen 최신 소스로 빌드
b. http://kripken.github.io/emscripten-site/docs/getting_started/downloads.html#sdk-downloads emscripten도 항상 최신으로 유지
i. emsdk update
ii. emsdk install latest
iii. emsdk activate latest
42. WebAssembly binary code
● 처음 8 바이트는 파일 전문을 나타낸다.(예약)
● 이중 앞의 4바이트는 'magic number’이다. 해당값이 00 61 73 6d가 아니면, browser에서 wasm모듈화 function 사용시
곧바로 에러가 발생한다.
○ 00 61 73 6d
● 뒤의 4바이트는 버전 정보이다. 해당값과 browser에서 지원하는 wasm 버전값이 다르면, browser에서 에러를 발생시
킨다.
○ 0b 00 00 00
ref: http://blog.mikaellundin.name/2016/06/19/creating-a-webassembly-binary-and-running-it-in-a-browser.html
43. WebAssembly binary code
ref: http://blog.mikaellundin.name/2016/06/19/creating-a-webassembly-binary-and-running-it-in-a-browser.html
Type section
All sections are optional, so when they appear they need to be correctly labeled. We start with the type section.
그 외, function, memory, export, code, name section에 대한 자세한 설명은 참고 사이트에서 확인하면된
다.
44. Reference Sites
공식 사이트
web assembly 공식 사이트: http://webassembly.org/
emscripten 사이트: http://kripken.github.io/emscripten-site/index.html
binaryen 사이트: https://github.com/WebAssembly/binaryen
web assembly git: https://github.com/WebAssembly
개념설명 사이트
http://blog.mikaellundin.name/2016/06/19/creating-a-webassembly-binary-and-running-it-in-a-browser.html
https://auth0.com/blog/7-things-you-should-know-about-web-assembly/
http://www.scriptol.com/programming/wasm.php
http://usersnap.com/blog/what-is-webassembly-for-web-developer/
http://www.2ality.com/2015/06/web-assembly.html
https://medium.com/javascript-scene/why-we-need-webassembly-an-interview-with-brendan-eich-7fb2a60b0723#.pccdilipe
WebAssembly 맛보기
(WebAssembly preview and getting started)
WebAssembly 소개
뭐하는 놈인가? 이게 좋은건가? 등장배경은?
배경지식
asm.js
wast, wasm
중간요약
simple architecture
실제 구현해보기
정리 및 Q&A
참고 자료
트러블 슈팅
추가 심화 자료
WebAssembly란?
결론부터 >> binary encoding of the AST -> run on browser
홈페이지의 설명은 (WebAssembly or wasm is a new portable, size- and load-time-efficient format suitable for compilation to the web.)
당연 아무 Byte Code나 되는건 아니고, WebAssembly Spec에 맞는 Byte코드여야 함.
결국, Byte Code을 브라우저에서 바로 돌릴수 있게 하는 스펙 & 해당 스펙에 따라 실제 Byte Code을 돌리는 Browser(engine)이라고 볼 수 있음
개발자는 Add, Mov 등으로 구성된 Assembly처럼, WebAssembly용(WebAssembly에서 정의한) Assembly 코드를 작성하고, 이를 컴파일하여, WebAssembly용 Byte Code을 얻을 수 있음
WebAssembly가 되면 무엇이 좋을까?-> 공식데모 보여주기(게임)-> game, security, 대규모 연산, native 연동 등등-> 속도, 성능
chrome://flags/#enable-webassembly and enable
Firefox Nightly, open about:config and set javascript.options.wasm to true .
WebAssembly가 되면 무엇이 좋을까?
참고: https://medium.com/javascript-scene/why-we-need-webassembly-an-interview-with-brendan-eich-7fb2a60b0723#.t97ze0xv4
-> game, security, 대규모 연산, native 연동 등등-> 속도, 성능
참고: http://mozakai.blogspot.kr/2013/06/what-asmjs-is-and-what-asmjs-isnt.html
asm 이 새로운건 아님 - 최소한 2006년에 이미 구글 웹 툴킷(GWT)을 통해 자바를 자바스크립트로 컴파일하는 게 가능했다.
컴파일된 코드(즉 컴파일러가 산출해낸 자바스크립트)는 좀 괴상하게 생겼다. 대개는 개발자가 직접 작성했을 법한 모양새가 아니다. 그리고 컴파일러마다 산출물에 나타나는 특정한 패턴이나 코드 스타일이 있다. 예컨대 다른 언어의 클래스를 자바스크립트의 클래스로 옮기면서 프로토타입 상속을 사용할 수도 있고 (이렇게 하면 좀더 '전형적인' 자바스크립트처럼 보일 것이다) 상속을 사용하지 않고 함수 호출로만 클래스를 구현할 수도 있고 (this를 일일이 인자로 전달하면서 말이다. '전형적인' 모습하곤 좀 거리가 멀겠지) 등등. 각 컴파일러의 고유한 동작 방식 때문에 산출물에도 특정한 패턴이 생기는 것이다.
서로 다른 자바스크립트 패턴은 엔진별로 실행속도가 천차만별이었다.
C++를 자바스크립트로 변환해주는 컴파일러를 적어도 두 개는 댈 수 있는데, 엠스크립튼과 맨드릴 이 있다. 이 두개의 컴파일러는 여러 브라우저에서 최적의 성능을 내는 컴파일 결과물 패턴을 찾아냈다.
asm.js는 엠스크립튼/맨드릴 패턴을 타입 시스템으로서 공식적으로 정의할 목적으로 시작되었고 오픈소스로 개발되었다.
asm.js는 타입 시스템을 정의함으로써 보다 합리적으로 사전(ahead of time) 컴파일 할 수 있는 가능성이 열렸다.
ASM.js 단점
컴파일되어 나오는 사이즈가 큼
파싱 & AST에 hotspot이 생겨 바틀렉 발생
asm.js에 대한 이야기를 잠깐 하고 넘어가자. (background 지식)
-> js의 서브셋
-> asm.js엔진이 있음.
C언어를 GCC 도구(컴파일러)로 컴파일 하면 A.O 생성하는 것 처럼
C언어를 Emscript 도구(컴파일러)로 컴파일 하면 A.asm.js (asm.js 코드)를 생성해줌
asm.js의 구조
-> 인간이 만드는게 아니야~
a.c 파일 --> gcc --> a.o 파일
그럼
? 파일 --> ? --> asm.js 코드
a.c --> gcc 같은 툴 (emscripten) --> asm.js 코드
a.cpp --> gcc 같은 툴 (emscripten) --> asm.js 코드
asm.js > wasm
또는
c > wasm
하면 되겠네..
binaryen: binary + enscripten
WebAssembly byte code에 대해서 잠깐 살펴보면
--> WAST 포멧, WASM 포멧
--> Text, Binary
Binaryen is a compiler and toolchain infrastructure library for WebAssembly, written in C++. It aims to make compiling to WebAssembly easy, fast, and effective:
참고 https://github.com/WebAssembly/binaryen
asm2wasm: which compiles asm.js
s2wasm: which compiles the LLVM WebAssembly's backend .s output format
mir2wasm: which compiles Rust MIR
중간정리, simple architecture
참고 https://github.com/WebAssembly/binaryen
C/C++ Source ⇒ asm2wasm ⇒ WebAssembly
When using emcc with the BINARYEN option, it will use Binaryen to build to WebAssembly. This lets you compile C and C++ to WebAssembly, with emscripten using asm.js internally as a build step. Since emscripten's asm.js generation is very stable, and asm2wasm is a fairly simple process, this method of compiling C and C++ to WebAssembly is usable already. See the emscripten wiki for more details about how to use it.
C/C++ Source ⇒ WebAssembly LLVM backend ⇒ s2wasm ⇒ WebAssembly
Binaryen's s2wasm tool can translate the .s output from the LLVM WebAssembly backend into WebAssembly. You can receive .s output from llc, and then run s2wasm on that:
llc code.ll -march=wasm32 -filetype=asm -o code.s
s2wasm code.s > code.wast
You can also use Emscripten, which will do those steps for you (as well as link to system libraries, etc.). You can use either normal Emscripten, including it's "fastcomp" fork of LLVM, or you can use "vanilla" LLVM, that is, pure upstream LLVM without Emscripten's additions. With Vanilla LLVM, you can build with
./emcc input.cpp -s BINARYEN=1
With normal Emscripten, you will need to tell it to use the WebAssembly backend, since its default is asm.js, by setting an env var,
EMCC_WASM_BACKEND=1 ./emcc input.cpp -s BINARYEN=1
(without the env var, the BINARYEN option will make it use the asm.js backend, then asm2wasm).
For more details, see the emscripten wiki.
실전.. WebAssembly~ -- PreRequired, Tool 설치하기~(ubuntu)
a. make, cmake, clang, build-essential
b. emscripten
c. binaryen
과정 요약 정리
C코드 작성 -> asm.js -> wast -> wasm -> wasm로딩 하는 js코드 작성 -> browser테스트