WebAssembly in 2016

https://github.com/webassembly/

What is WebAssembly?

A new standard being developed in a W3C Community Group with Apple, Google, Microsoft and Mozilla which defines:

  1. a compact, portable binary format which is fast to load and runs safely at predictably near-native speed
  2. a 1:1 text format rendered by developer tools when viewing source
Luke Wagner – WebAssembly: a new compiler target for the web

Why WebAssembly?

  • Image/Video processing/editing
  • Compression, encryption
  • VR and low latency
  • WebUsb
  • Scientific simulation
  • Platform simulation (QEMU, DOSBox, ...)
  • Games
  • Remote desktop, VPN
  • Existing cpp codebase
  • ... any cpu-bound code
Ben Smith – WebAssembly: birth of a virtual ISA

FAQ

  • Will Wasm replace JS?
  • No.
  • No. No.

Wasm binary

Is just a postorder serialization of an AST. They claim its better than Java bytecode.

WebAssembly features

  • No builtin objects, allocator
  • No GC
  • Linear memory
  • Just like asm.js
  • Only 32bit for now :(

I want to try it!

Great! Firefox and Chrome has Wasm support under flags. For the compiler follow the step by step.

VM Safety

Callstack and machine code is not in address space.

The only dangerous opcodes are .load and .store operations, as they index into memory. They employ a cool trick in 64bit machines: mmap 4GBs of continouos virtual memory, you can't over-index that with an i32 address. Runtime bound-checks on 32bits.

Target Wasm

  • Use emscripten
  • emcc -s BINARYEN=1 -s 'EXPORTED_FUNCTIONS=["_fib"]' fib.c -o fib.js
  • an llvm backend
  • produces asm.js
  • binaryen converts asm.js to webassembly

asm.js example

function module(global, env, buffer) {
  "use asm";
  ...
  function fib(n) {
    n = n|0;
    var a = 0, b = 1, t = 0;
    while ((n|0) >= 0) {
      t = b;
      b = (a + b)|0;
      a = t;
      n = (n - 1)|0;
    }
    return b|0;
  }
  return {fib: fib};
}

References