Writing Wasm: modules

Posted on Apr 16, 2023

The most simple Wasm module doesn’t need much code. This post describes the definition of it, and how the resulting binary code looks like. It shall give the basis for further WAT-styled code.

Pre-requisites

Before you start to write Wasm modules, you need some tooling.

So, install wabt first. This includes wat2wasm and allows you to compile .wat files to .wasm with the following command:

wat2wasm sample.wat

With that you’ll get the Wasm binary with the .wasm ending.

You can inspect the binary code with hexdump:

hexdump -C sample.wasm

You can also show the binary code during the compilation:

wat2wasm sample.wat -v

For the execution you’ll need wasmtime or any other runtime for Wasm.

Initializing the module

Create a file with the name sample.wat. WAT is the S-representation for WebAssembly and is a human-readable format of Wasm. You can talk about it as the intermediate code before compiling it to Wasm.

The most simplest Wasm module is the following one:

(module)

When you compile it, you’ll see the Wasm_BINARY_MAGIC:

0000000: 0061 736d                                 ; Wasm_BINARY_MAGIC
0000004: 0100 0000                                 ; Wasm_BINARY_VERSION

The execution does nothing as this is the most basic module you can have in Wasm. But it is the starting point for other more important and working sections.

The sections of Wasm modules

This is just the beginning. Even if the module is the most basic block of Wasm and can stand for itself, there’s much more!

As you can see in the specification it can contain the list of multiple building blocks like functions, exports, memory and more:

Diagram of a Wasm module’s building blocks like functions, exports and memory

A closer look at these blocks will be part of other posts!

Want to know more?

Keep on reading and choose one of the related articles. You can also check the home page for my latest thoughts, notes and articles.