WebAssembly basic example: Adding

stisa, Mar 19, 2017

I’ve seen some examples but none that worked out of the box, so I made one. Based on the binary encoding spec.

Let’s begin with seeing it work.
Write two numbers in the boxes below and then click on = to show the result.

+ integer

Note: if it doesn’t do anything, pleas check your browser for compatibility with WebAssembly, eg open the console and type WebAssembly, if it outputs undefined your browser doesn’t support/dosen’t have enabled WebAssembly

Pretty basic huh?
Well, here’s the kicker: the result was calculated with WebAssembly.

Specifically, the wast representation of the module ( besides the comments after # ) used is:

(module 
 # Define a function that takes 2 i32 and return a i32
 (type $0 (func (param i32 i32) (result i32)))
 (memory $0 0)
 # Export the first function defined in the type section with name "add"
 (export "add" (func $0))
 # The body of the function defined above
 (func $0 (type $0) (param $var$0 i32) (param $var$1 i32) (result i32) 
  # The opcode that stands for addition of i32
  (i32.add
   (get_local $var$0) # load first param
   (get_local $var$1) # load second param
  )
 )
) 

And here’s the binary representation:

  Offset: 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 
--------:------------------------------------------------
00000000: 00 61 73 6D 01 00 00 00 01 07 01 60 02 7F 7F 01 
00000010: 7F 03 02 01 00 07 07 01 03 61 64 64 00 00 0A 09 
00000020: 01 07 00 20 00 20 01 6A 0B                      

Let’s have a closer look at the binary representation:

00 61 73 6D
Spells out \0wasm

01 00 00 00
Tells us that this module uses wasm version 1 ( 01 )

01 07 01 60 02 7F 7F 01 7F

03 02 01 00

07 07 01 03 61 64 64 00 00

0A 09 01 07 00 20 00 20 01 6A 0B

Lastly, to load the module we need a bit of javascript:

var wasmexports;
fetch('/js/add.wasm').then(response =>
  response.arrayBuffer()
  ).then(bytes =>
  WebAssembly.instantiate(bytes)
  ).then(results => {
    wasmexports = results.instance.exports
});

And in my case, to pass the value of the inputs to WebAssembly:

function showRes(){
  var a = document.getElementById("arg1").value
  var b = document.getElementById("arg2").value
  document.getElementById("result").innerText = wasmexports.add(a,b)
}

This blog is hosted on github, so you can find the wasm file here and the markdown file here.

Tags:

  • webassembly
  • example