<01-26-2023> 74 days ago

reading time 3 minutes

lets bang bytes in wasm

isn't this so fucking cool?

me + web assembly = 💖

oh how i love WASM. it's not even funny (maybe a little, considering my hate for java). granted the JVM is perhaps just a little different, but bytecode this bytecode that.

i want to make you agree with me through my powers of unadulterated rhetoric. and perhaps a little fun.

the world's simplest web assembly binary can be expressed as such:

# you can copy and paste this! #
0x00 0x61 0x73 0x6d # magic 0 A S M #
0x01 0x00 0x00 0x00 # version 1 0 0 0 #

how would you like to write some raw bytecode? "yes!" i hear you cry.

let's talk about how wasm works for a moment.

web assembly is a very thoughtfully crafted virtual stack machine. it takes structured sequences of bytes (opcodes) and performs mutations on the stack itself.

there are only four data types in wasm, i32, i64, f32, f64. the list of instructions available is actually very simple.

this table by Pengo Wray is utterly fantastic.

i'll write out a small portion here and see what we can get up to.

opcode (param) : (what it do)
0x41 X:i32 : adds the next byte (i32) to the top of the stack.
    stack = []
    0x41 0x0a : stack.append(0x0a) --> stack = [10]
    # caveat on this, if the number is over some size you have to use leb128
    # you do not have to worry about this as i will provide a wrapper for it
    # but should you write your own WASM things, it will be necessary to resolve this. 
0x6A : pops two i32s from the stack and appends the sum of them to the stack.
    stack = [5:i32, 6:i32]
    0x6A : stack.append(stack.pop() + stack.pop()) --> stack = [11:i32]
0x0F : jump to outermost block and return the values off the stack.

how about we (you) write some wasm to return the number 42.

an image for the socratic method

so technically we need to actually write out a function declaration, and an export name, along with the parameters required. for now i will just auto append that to the bytecode.

i will also append the magic numbers for you cutie.✨

oh one more thing 👉👈 you have to write 0x0b to let wasm know you are done with your function.