WebAssembly Fundamentals
local graph
Chapter 1 — WebAssembly Fundamentals
Section titled “Chapter 1 — WebAssembly Fundamentals”CHAPTER 1
WebAssembly Fundamentals
With WebAssembly, there is a symbiotic relationship between the compiled WebAssembly binary (called a module) and the host responsible for interpreting it. This relationship is at the heart of everything that you can do with this new technology, and understanding where the boundaries are between module and host is key to being able to build effective WebAssembly applications.
WebAssembly can be viewed at two different levels—the raw, foundational level and at the higher level of other programming languages using WebAssembly as a target. Before you can understand and appreciate what languages like Rust are doing when they produce WebAssembly modules, you’ll need to know what WebAssembly can do, what it can’t, and how to use language-independent tools.
This chapter gets you started at the foundation level, giving you an overview of what WebAssembly is, how it works, and how other features can be built upon this foundation. By the end of this chapter, you’ll be able to create and build your own WebAssembly modules using cross-platform language tools and your favorite code editor. While what you learn in these first few chapters may not be things you do on a daily basis, the context they provide will be invaluable as you build real applications with WebAssembly.
Introducing WebAssembly
If the modern programmable web is merely a toy store, then WebAssembly is a toy warehouse filled with toys as far as the eye can see. Developers who spend most of their time working on the front end often long for some of the features, testability, and constraints prevalent in the world of servers and services. Likewise, folks who spend most of their time toiling behind the counter, away from the customer but carefully assembling all the parts of their order, often long for the fluid, expressive, blank canvas world the front end represents. People who work in both worlds are keenly aware of the paradigm differences between the two and why the grass isn’t always greener on the other side.
What if “sides” or “front” or “back” didn’t matter anymore? What if there was a new way of doing things, where you could write loosely coupled business logic that flows between servers, services, clients, and browsers without any shenanigans? What if you could have the best parts of the front- and back- end worlds and still choose the most appropriate language for your problems?
By the time you reach the end of this book, you’ll have learned enough about WebAssembly development that these propositions won’t sound like they came from a snake-oil salesman. They’ll ring true and hopefully inspire you to start building amazing new WebAssembly applications.
What Is WebAssembly?
The WebAssembly home page¹ says that it is a binary instruction format for a stack-based virtual machine. Wasm (a contraction, not an acronym, for WebAssembly) is designed to be portable (capable of running on different OSes, architectures, and environments without modification), and used as a compilation target for higher-level languages like C++, Rust, Go, and many others. The website also claims that Wasm enables deployment on the web for client and server applications alike.
Let’s pick this definition apart a bit, because it’s rather dense.
First, and most importantly, WebAssembly is a portable binary instruction format. This is very similar to the original intent behind Java’s bytecode and, if you’re familiar with the .NET Framework, you may recognize this concept as implemented in ILASM, the low-level instruction set supporting the Common Language Runtime. You’ll see this in depth in the next chapter, but for now it should suffice to know that the operations encoded in a WebAssembly module are not tightly coupled to any one hardware architecture or operating system, and these operations are just codes that a parser knows how to interpret.
Next, there’s the phrase stack-based virtual machine. We’ll go over this in detail soon, but the short explanation is that this stack machine simultane- ously contributes to WebAssembly’s tremendous speed, power, and several of its limitations.
[1] webassembly.org
Finally, there’s a spot in the definition on which I fundamentally disagree. The phrase “deployment on the web” might limit your thinking and your imagination. This is a portable format that can run anywhere you can build a host, which you’ll also be learning about later. Limiting WebAssembly’s scope to the web (despite its name) does it a disservice.
What WebAssembly Is Not
Section titled “What WebAssembly Is Not”The first question I get asked once I get on my WebAssembly soapbox is, “Isn’t Wasm just another transpile target for JS?” Transpiling is translating from one high-level source language to another high-level source language. This is in contrast to the usual compiling, which takes a high-level source language and translates it into a low-level machine code. For example, converting TypeScript or React JSX into browser-executable JavaScript is done through transpiling. WebAssembly is not a JavaScript transpile target (though you can actually compile TypeScript into a Wasm module if you’re into that sort of thing).
WebAssembly is also not meant to replace JavaScript. This is somewhat of a controversial opinion, as a large group of WebAssembly devotees online are convinced that it represents the death knell of JavaScript. While it might signal the beginning of a new era in which you write significantly less manual JavaScript, you still need JS to host WebAssembly 1.0 in the browser.
It’s also not intended as a mere replacement for (or successor to) Flash, Sil- verlight, Adobe AIR, or Java Applets. As you’ll discover, WebAssembly isn’t run as a process outside the browser. How seamlessly it integrates with the user experience is entirely up to the developer and the tools they use.
Another important thing to remember is that WebAssembly, on its own, isn’t a programming language. While there is both a binary and a text format, writing it by hand for anything beyond a few samples would take far too long and be too difficult to test and troubleshoot. Knowing how to write it by hand, however, will help you make the right decisions as you learn to build WebAssembly applications with Rust.
WebAssembly doesn’t stand on its own. Like a game cartridge without a console or a BluRay disc without a player, it’s incomplete in isolation. Much like a symbiote that needs to feed off of its host to survive, WebAssembly can’t interact with anything outside the bounds of its own sandbox unless the host allows it. All I/O and other interactions are done entirely at the behest of the host such as a browser or a console application. While this might sound like an unfair limitation, you’ll see a number of times throughout this book why this is actually a good thing.
Try It Out
The best way to start learning something is to jump right in. Imagine one of those ball pits kids get to play in but, sadly, us adults are usually forbidden. As learners, our first exposure to new material is like jumping into this pit, surrounded by a dizzying array of colors and buried up to our necks in con- fusion. As we struggle to make our way to the far end of the ball pit, we gradually get our footing, the colors become more familiar, the shape and landscape of the ball pit gets smaller, and we’re able to reason about it. After a while, we crawl out of the pit, having learned enough that we’re eager to jump back in and discover more.
For WebAssembly, you’re going to jump into the ball pit by using an online tool called WebAssembly Studio. In December 2017, Mozilla started working on this project as a way to provide a low-friction introduction to WebAssembly. It’s a combination of some of their other WebAssembly tools like WasmFiddle.² This tool is entirely online and lets you create new projects in C, Rust, or AssemblyScript, a tool for compiling TypeScript to WebAssembly. It has gone through bursts of community activity and contribution since its creation.
Open up your browser (any up-to-date version of Firefox, Edge, Chrome, or Safari should work) and point it at webassembly.studio. You’ll come to a screen that presents the following options for creating a new project:
- Empty C Project
- Empty Rust Project
- Empty AssemblyScript Project
- Hello World in C
- Hello World Rust Project
Choose “Empty Rust Project” and then click the Create button. This will create a new project within WebAssembly Studio, including a README.md file, a src directory, and the file you want to explore: main.rs. You’ll see the following code:
#[no_mangle]pub extern "C" fn add_one(x: i32) -> i32 { x + 1}[2] wasdk.github.io/WasmFiddle/
The WebAssembly Studio site, with its almost entirely black color scheme, doesn’t make for print-friendly screenshots so none have been included here.
If you’re familiar with Rust, then this should be self-explanatory. If you’re new to Rust, don’t worry—you’ll spend quite a bit of time working through Rust’s syntax throughout the book. This code listing defines a function that adds 1 to a 32-bit signed integer, returning that value in a signed 32-bit integer. Believe it or not, this code can produce a WebAssembly module.
Using Rust’s no_mangle macro tells the compiler not to change the signature of the function during compilation. As you’ll see in upcoming chapters, there are some aspects of executing WebAssembly that require some naming conventions.
Click the Build and Run button and you’ll see the blue bar on the bottom of the editor flash. Then, the white square canvas in the bottom right-hand corner will display the number 42.
Congratulations, you’ve just written, compiled, and executed your first WebAssembly module. Where did the number 42 come from? Take a look at the main.js file by clicking on it in your browser:
fetch(’../out/main.wasm’).then(response =>
response.arrayBuffer()).then(bytes => WebAssembly.instantiate(bytes)).then(results => {instance = results.instance;document.getElementById("container").innerText = instance.exports.add_one(41)}).catch(console.error);Don’t worry if some of this JavaScript looks unfamiliar to you—it’ll be second nature by the time we’re done. The indicated line of code invokes the add_one function in the WebAssembly module and places the result value inside the container DOM element. And now you’ve built a WebAssembly module that adds 1 to any number. It might not be all that impressive, but you’ve taken that first leap into WebAssembly.
The pattern of writing Rust code, compiling to WebAssembly, and then running the module in a browser is one that you’ll repeat many times throughout this book. For now, though, let’s take a step back from this code and take a look at what makes WebAssembly tick so you can have a better idea of what’s happening in the preceding example.
Understanding WebAssembly Architecture
Section titled “Understanding WebAssembly Architecture”In this section, you’ll get a good look inside the engine that makes WebAssembly work. Its unique architecture makes it incredibly powerful, portable, and efficient—though this power comes with some limitations.
Stack Machines
Section titled “Stack Machines”The type of computer that you’re using right now is likely a Register Machine. Laptops, desktops, mobile devices, virtual machines, even microcontrollers and embedded devices are register machines. A register machine is a machine (physical or virtual) where the processor instructions explicitly refer to certain registers, or data storage locations, on the processor. Accessing these registers is fast and efficient because the data is available directly within the CPU.
For example, if you want to add two numbers together, you’d use the ADD instruction and you’d pass it the names of two registers as parameters, as shown in this bit of x86 assembly:
ADD al, ah
In the preceding code, the values contained in ah and al will be added together, with the result stored in al.
WebAssembly is a stack machine. In a stack machine, most of the instructions assume that the operands are sitting on the stack, rather than stored in specified registers. The WebAssembly stack is a LIFO (Last In, First Out) stack. If you’re unfamiliar with the concept of a stack: it is as its name implies—values are piled (stacked) on top of each other, and unlike arrays where you can access any data regardless of location in the pile, stacks only allow you to pop data off or push data onto the top.
To add two numbers in a stack machine, you push those numbers onto the top of the stack. Then you push the ADD instruction onto the stack. The two operands and the instruction are then popped off the top and the result of the addition is pushed on in their place.
There are a number of advantages to a stack machine that made it an appealing choice for WebAssembly: their small binary size, efficient instruction coding, and ease of portability just to name a few.
There are some fairly well-known stack machines, including the Java Virtual Machine (JVM) and the bytecode executor for the _ .NET Common Language Runtime_. In the case of those virtual machines, developers are spared the effort of writing assembly or thinking in prefix or Polish³ (where the operator comes first) notation because of the intermediate steps and code generation happening behind the scenes.
Data Types
Section titled “Data Types”Admit it—you’ve been spoiled. Modern programming languages with hashes, lists, arrays, sets, extra-large numbers, and tuples have spoiled you. These languages also probably let you create your own types through structs or classes. Some of them even let you overload operators, and some of those overloads can even work on custom types. The world is your oyster and you have few limits. That is not the world of WebAssembly. As their name should imply, assembly languages are designed to be made up of primitives that can be used as building blocks by higher level languages.
WebAssembly 1.0 has exactly four data types:
| Type | Description |
|---|---|
| i32 | 32-Bit Integer |
| i64 | 64-Bit Integer |
| f32 | 32-Bit Floating-Point Number |
| f64 | 64-Bit Floating-Point Number |
One aspect of this relatively limited set of data types is that WebAssembly doesn’t assign any intrinsic signed-ness to numbers as they’re stored. The assumption of whether a number is signed or unsigned is only performed at the time of an operation. For example, while there’s only one i32 data type, there are signed and unsigned versions of that type’s arithmetic operators, e.g. i32.add and i32.add_u.
When you’re using a high-level language that compiles to WebAssembly on your behalf, you shouldn’t have to worry about this subtlety. But when you’re writing raw Wasm in the text format by hand, it could trip you up in unexpected ways.
Control Flow
Section titled “Control Flow”WebAssembly’s handling of control flow is a little different than other, less portable assembly languages. WebAssembly goes to great lengths to ensure that its control flow can’t invalidate type safety, and can’t be hijacked by attackers even with a “heap corruption”⁴-style attack in linear memory. For
[3] en.wikipedia.org/wiki/Polish_notation [4] https://pdfs.semanticscholar.org/14f1/4b032235c345dfb3b3ecc8a879bbe4072407.pdf example. many assembly languages allow easily exploited blind jump instruc- tions, whereas you’ll discover that WebAssembly does not. This additional layer of safety pairs well with the safety-first philosophy of Rust.
Wasm control flow is accomplished the same way everything else is within a stack machine—by pushing things onto, and popping things off of, the stack. For example, with an if instruction, if whatever is at the top of the stack evaluates as true (non-zero), then the if branch will be executed.
Take a look at an example of the if statement in action:
(if (i32.eq (call $getHealth) (i32.const 0)) (then (call $doDeath)) (else (call $stillAlive)) )In this code, if our hypothetical player’s health has reached 0, then we’ll call the doDeath function, otherwise we’ll call the stillAlive function. All those seem- ingly extra parentheses will make sense later in the chapter.
WebAssembly has the following control flow instructions available:
| Instruction | Description |
|---|---|
| if | Marks the beginning of an if branching instruction. |
| else | Marks the else block of an if instruction |
| loop | A labeled block used to create loops |
| block | A sequence of instructions, often used within expressions |
| br | Branch to the given label in a containing instruction or block |
| br_if | Identical to a branch, but with a prerequisite condition |
| br_table | Branches, but instead of to a label it jumps to a function index in a table |
| return | Returns a value from the instruction (1.0 only supports one return value) |
| end | Marks the end of a block, loop, if, or a function |
| nop | No self-respecting assembly language is without an operation that does nothing |
Linear Memory
As you work with linear memory, you’ll truly begin to appreciate the extent to which modern high-level languages have spoiled you. With most languages, you can quickly and easily create a new instance of something on the heap with an operator like new.
Internally, the compiler knows the size of this thing (or has some trick to compensate for not knowing). When you pass an instance of something to a function, the compiler knows whether you’re passing a pointer or a value and how to arrange that value on your stack or heap in order to make the data available to a function.
WebAssembly doesn’t have a heap in the traditional sense. There’s no concept of a new operator. In fact, you don’t allocate memory at the object level because there are no objects. There’s also no garbage collection (at least not in the 1.0 MVP).
Instead, WebAssembly has linear memory. This is a contiguous block of bytes that can be declared internally within the module, exported out of a module, or imported from the host. Think of it as though the code you’re writing is restricted to using a single variable that is a byte array. Your WebAssembly module can grow the linear memory block in increments called pages of 64KB if it needs more space. Sadly, determining if you need more space is entirely up to you and your code—there’s no runtime to do this for you.
This image with variables and byte offsets illustrates just one way to store data in a block of linear memory (how you choose to use and fill linear memory is entirely up to you and your code):
| var1 [0…39] | var2 [40…79] | var3 [80…119] | unused |
In addition to the efficiency of direct memory access, there’s another reason why it’s ideal for WebAssembly: security. While the host can read and write any linear memory given to a Wasm module at any time, the Wasm module can never access any of the host’s memory.
Direct DOM Access Is an Illusion
If you’ve seen WebAssembly demos that look like they’re directly accessing the browser DOM from inside the module—that’s an illusion. The host and module are sharing a block of linear memory, and the host is choosing to execute bespoke JavaScript to translate the contents of that shared memory area into updates to the DOM, just like you saw at the beginning of this chapter. This may change in future versions of WebAssembly, but for now, this remains little more than smoke and mirrors.
As you’ll see in the coming chapters, linear memory is crucial to being able to create powerful applications with WebAssembly. Before using high-level languages like Rust, you should learn how to manipulate linear memory manually so you can appreciate the extent of the work done on your behalf by tools and code generation and understand the impact of your designs.
Building a WebAssembly Application
Section titled “Building a WebAssembly Application”At the beginning of this chapter, you built and ran a simple Rust-based WebAssembly application using WebAssembly studio. In this section, you’ll install some tools on your machine that will allow you to compile and interpret WebAssembly modules.
Installing the WebAssembly Binary Toolkit
Section titled “Installing the WebAssembly Binary Toolkit”The WebAssembly Binary Toolkit (pronounced “wabbit”) is a general-purpose set of command-line tools you’ll use for building, examining, and troubleshooting WebAssembly modules. Whether you’re on Windows, Mac, or Linux, the first thing you’re going to need to install is CMake.1
Installing CMake varies widely across operating systems, so you’ll need to check the instructions specific to your platform. Come back and continue with the wabt installation once you’ve verified that CMake is up and running locally.
Next, follow the instructions on the wabt2 GitHub repository README to complete the installation. You should be able to get the binaries from a release, but if you want to build the toolkit yourself, go ahead and simply run make install and then, after a fairly lengthy compilation process, you’ll see a bunch of executables in the bin directory beneath wherever you checked out the repository, including some or all of the following:
- wasm2c
- wasm2wat
- wasm-interp
- wasm-objdump
- wasm-opcodecnt
- wasm-validate
- wast2json
- wat2wasm
- wat-desugar
The exact list of files may have changed since this book was published, but you’ll at the very least need wat2wasm and wasm-objdump for the next section where you will be writing real WebAssembly code. Make sure that you can
execute both of these commands in a terminal or a shell and get the help text before continuing on.
On my machine, make install installed all of the compiled binaries in /usr/local/bin:
— Install configuration: “Debug” — Installing: /usr/local/bin/wat2wasm — Installing: /usr/local/bin/wast2json — Installing: /usr/local/bin/wasm2wat — Installing: /usr/local/bin/wasm2c — Installing: /usr/local/bin/wasm-opcodecnt — Installing: /usr/local/bin/wasm-objdump — Installing: /usr/local/bin/wasm-interp — Installing: /usr/local/bin/spectest-interp — Installing: /usr/local/bin/wat-desugar — Installing: /usr/local/bin/wasm-validate — Installing: /usr/local/bin/wabt-unit-tests
Coding in the WebAssembly Text Format
Before I launch into an arguably dense and detailed section of fairly low-level coding, I want to answer the question of why. Why should you spend the effort learning how to write raw wast when you’ve got modern compilers that can do it for you?
I don’t like magic. I don’t like black boxes that do things I don’t understand. I am put off when I have to use a third-party system when I don’t understand its internal workings, or at least the motivations behind the decisions made in the building of the thing.
You could go forward and build powerful WebAssembly applications and live your life without knowing how it all works inside. However, I contend that this chapter and its contents provide the foundation on which a solid WebAssembly development practice should be built. You could, in theory, skip this chapter. But, as Morpheus told Neo in The Matrix, “You take the red pill—you stay in Wonderland and I show you how deep the rabbit-hole goes.”
When we get into the chapters on building alternative, non-browser hosts for WebAssembly modules, you will absolutely benefit from the knowledge and experience gained in this chapter.
The physical process of writing code in the WebAssembly Text Format (.wat files) is pretty easy—just open up your favorite text editor (VSCode, Atom, and others all have syntax highlighters for WebAssembly) and start typing.
As you now know, WebAssembly doesn’t have a string data type. This makes the canonical “Hello, World” sample a little difficult. In fact, the code required to actually produce that output in a browser is pretty complicated. If you try to go this route as your first exposure to writing wat, you’re likely to get dis- couraged.
For a simpler example that takes advantage of WebAssembly’s simple data types, let’s try creating a module with a single function that adds two numbers together and returns the result. Open up your text editor and create the add1.wat file with the following contents:
fundamentals/add1.wat
(module (func $add (param $lhs i32) (param $rhs i32) (result i32) get_local $lhs get_local $rhs i32.add) (export "add" (func $add)))The first expression at the top of every module is the module declaration. Note that there’s no module name, package name, or namespace. There are a number of other things that can go below this declaration, but in this case, you’re just creating a single function, marked by the func keyword. Each parameter to a function is indicated with an S-expression⁷ (a parenthesized syntax for representing data or code as nested trees, first created for Lisp) in the following form:
(param $parametername datatype)
In this case, there are two 32-bit integer parameters: rhs and the result will be a 32-bit integer.
The call to get_local retrieves a function-scoped value and places it on the Wasm execution stack. In this function, you’re calling get_local twice, putting the two parameters on the stack, and then calling i32.add. This adds the two values on the stack, pops them off, and puts the sum in their place. The value left on the stack at the end of the function is the default return value.
The order these instructions appear in the code can seem awkward. This is pure postfix (operator-last) notation and makes for some difficult reading. You don’t necessarily have to do it this way. There’s an alternative, pure S-expression prefix notation where you put the operation first and operands second, as you see in this code:
[7] en.wikipedia.org/wiki/S-expression fundamentals/add2.wat
(module (func $add (param $lhs i32) (param $rhs i32) (result i32) (i32.add (get_local $lhs) (get_local $rhs) ) ) (export "add" (func $add)))In the second form, there are more parentheses, but the code is easier to read, especially as you get into more complicated patterns like those in the next chapter. I’ll be using the second form from now on.
To invoke this function in WebAssembly, you use the call keyword, as shown in this code that adds 9 and 5:
(call $add (i32.const 5) (i32.const 9))Using the Binary Toolkit
Section titled “Using the Binary Toolkit”Now that you’ve got some source code, it’s time to compile it and do some exploration with the “wabbit” tools. Go to the directory where you created add1.wat and run the following commands (wat2wasm should be in your path):
wat2wasm add2.wat -o add_sexpr.wasm
If everything goes according to plan, you’ll receive the “no news is good news” response—nothing. Next, use wasm-objdump to get a look at what actually made it into your compiled add.wasm file. The -x option adds extra detail to the output:
$ wasm-objdump add.wasm -xadd.wasm: file format wasm 0x1Section Details:Type: - type[0] (i32, i32) -> i32Function: - func[0] sig=0 <add>Export: - func[0] <add> -> "add"There’s some pretty good information here. You can tell that there’s a function type declared that accepts two integers and returns an integer. There’s a function at index 0 called add. Finally, there’s an export called add.
It is important to keep in mind that you can create functions in a WebAssembly module and not export them. In fact, functions are all private to the module and remain unexported until you explicitly write an export statement. If you run the same object dump command on add_sexpr.wasm, you’ll see the exact same type and exports.
There’s one last thing worth exploring—take a look at what the code looks like after a round trip when you convert the binary add_sexpr.wasm file to its corresponding text format:
$ wasm2wat add_sexpr.wasm -o roundtrip.wat
fundamentals/roundtrip.wat
(module (type (;0;) (func (param i32 i32) (result i32))) (func (;0;) (type 0) (param i32 i32) (result i32) get_local 0 get_local 1 i32.add) (export "add" (func 0)))Here you can see that there’s a type created, a function of that data type, and then the instructions have reverted to the inverted stack notation rather than the instruction-first version. Finally, you can see that the export now just refers to the function at index 0 rather than a name. The separation of the symbol name and the function index is part of what ensures this kind of round-trip compilation is possible.
The reason this round trip is important is to show what WebAssembly might look like when produced by other languages, and, just in case you had any doubts, to prove that your code is truly portable and can be opened, disassembled, and re-generated at will. This also means anyone with access to these tools can see everything inside your WebAssembly module—a point to take note of when it comes to design and security in the future.
WebAssembly Source Maps
If a web browser has access to both the binary format and the original source code, then you can expose a source map through the developer tools. Even at this early stage in the technology’s life, you can already set breakpoints within WebAssembly modules written in Rust running in Firefox. When the respective line of code comes up, the browser renders the original (non-wat) code via the source map and not the minified code that you saw in the round-trip file. Wrapping Up
In this chapter, you got your first real exposure to writing WebAssembly code. You got the “wabbit” toolkit installed and you used it to compile, examine, and disassemble WebAssembly modules. You’ve received a preliminary exposure to the syntax and specifications for WebAssembly and you should be able to experiment with creating your own very basic modules.
In the next chapter, you’ll build on what you’ve learned so far to create a fully functioning game with just the basic WebAssembly tools.