Introduction To WebAssembly - Practical WebAssembly | PDF | Java Script | Compiler
0% found this document useful (0 votes)
6K views

Introduction To WebAssembly - Practical WebAssembly

Uploaded by

idontcare
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6K views

Introduction To WebAssembly - Practical WebAssembly

Uploaded by

idontcare
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Topics Start Learning Search 50,000+ courses, events, titles, and … Featured

Chapter 1. Introduction to WebAssembly

A NOTE FOR EARLY RELEASE READERS

With Early Release ebooks, you get books in their earliest form—the author’s raw and unedited content
as they write—so you can take advantage of these technologies long before the official release of these
titles.

This will be the 1st chapter of the final book.

If you have comments about how we might improve the content and/or examples in this book, or if you
notice missing material within this chapter, please reach out to the editor at shunter@oreilly.com.

Pinning down exactly where to start is one of the hardest things about explaining WebAssembly; there’s a
lot going on! However, I think a good place to start is a general knowledge of what the technology actual‐
ly is (and isn’t). I’ll start by covering just that, followed by a brief history of WebAssembly. After that
you’ll look at the use cases for WebAssembly, then you’ll take a brief look at how this all works.

What is WebAssembly?
I’ll start with the elephant in the room; WebAssembly is neither “Web” (strictly speaking) nor “Assembly”.
So if it’s neither of these things entirely, then what is it? There are multiple answers to this question, all
correct in their own rights. If you begin with the definition on the WebAssembly working group’s
website:

WebAssembly (abbreviated Wasm) is a binary instruction format for a stack-based virtual machine.
Wasm is designed as a portable compilation target for programming languages, enabling deployment
on the web for client and server applications.

—webassembly.org

WebAssembly is an Instruction Set

I’ll start with the first part of that definition-- “a binary instruction format for a stack-based virtual ma‐
chine”. Think of the instruction format as less of assembly code (written for a specific chipset) and more
of a middle-step between this stack-based virtual machine and the browser/the javascript runtime. This
instruction set has a binary format, usually suffixed with .wasm , and the text format, called WAT. The
text format is a more human-readable instruction format, and can be compiled into the binary format.

WebAssembly is a compile target

Now usually, you won’t find people writing wat by hand, then compiling it down to wasm. The aim of
WebAssembly is to allow you to use other languages to use your stack-based virtual machine; so you’ll
usually compile other languages to wat or wasm. So, in order for a language to support wasm, it will need
a compile target of wasm instructions.

WebAssembly is a technology stack

The topic of WebAssembly encompasses more than the language itself; there is the Virtual Machine (VM)
specifications to think about, the intermediate WAT language, and how to handle functionality that could
be added. The W3C charter for WebAssembly contains the following topics:
A binary format for WebAssembly A text format for WebAssembly Execution semantics of
WebAssembly Standardized debugging of WebAssembly programs Integration of WebAssembly with
ECMAScript Integration of WebAssembly with the Web Platform generally Use of WebAssembly outside
the Web Extensions to WebAssembly to encompass low-level machine features

—https://webassembly.github.io/cg-charter/

Througout this book, when I’m referring to the language, I’ll use wasm, and when I’m talking about the
over-arching technology, I’ll say WebAssembly.

WebAssembly is an evolution of the web

The idea of being able to easily adapt and run code from other programming languages at near-native
performance inside the browser is a huge leap forward for the web-- it puts the lessons of past attempts
(see Java Applets, DirectX, NaCl…​) to use to develop a performant, secure, portable way to run code in the
browser. Allowing JavaScript to offload some tasks to languages more suited for them, in a way that is
safe, performant, and built-in to the browser-- this is the friution of a long road of past milestones and
efforts.

What WebAssembly is not


Now that some of the things WebAssembly is have been addressed, I think it’s also fair to take a look at
what WebAssembly isn’t.

An “Assault on JavaScript”

WebAssembly was designed as a complement to JavaScript, not a rival or assailant. WebAssembly, as of


this writing, cannot access anything outside the VM it runs in, and can only communicote with the
JavaScript that runs it. You can go to great lengths to design a system that uses as little JS as possible, but
that defeats the purpose. WebAssembly works best generally when paired with JavaScript.

A Finished Standard

WebAssembly is in a constant state of flux currently as new features and standards are added. There are
key features still being fleshed out, and many are still in proposal form. It is a good idea to be cognizant
of both the things that have yet to be added and the fact that WebAsseembly can and will change.

History of WebAssembly
The history of WebAssembly is highly intertwined with the history of the web in general. However, I will
give a limited timeline here. What you should know is the impetus for WebAssembly; to quote webassem‐
bly.org, a solution would aim to be:

Efficient and Fast


Safe
Open and Debuggable
Part of the Open Web platform

—https://webassembly.github.io/cg-charter/

I’m going to skip to the closest predecessor of WebAssembly, asm.js.


asm.js

asm.js was introduced via a Working Draft in 2014, as an effort by Mozilla. While the origins of asm.js
point towards a goal of making better games in the browser, it soon grew into something more; some‐
thing that you could hypothesize affected the way WebAssembly developed. It grew into a desire to bring
code from outside the browser into it with minimal modification. It used Open Web platform technology;
it was at its core a highly-optimizable subset of JavaScript. This is in part because the work had already
been done to harden and test the VMs that run JavaScript in the browser. The reason it uses a subset of
the language is to further the amount of optimizations that can be done to increase performance.

One thing that asm.js shares in common with WebAssembly is that it established a compile target for
C/C++ using the LLVM toolset. Much like WebAssembly, you would compile your target code down into an
intermediary language (a subset of JavaScript) meant for a specific VM (the JavaScript VM).

The main tradeoff for asm.js was performance-- it was not nearly as performant as native code would be,
as you were still using JavaScript under the hood. It was however performant and accessible enough to
establish the issue of running other code bases in the JavaScript VM.

The advent of WebAssembly

WebAssembly was introduced in 2015 as a joint venture by many major browser vendors. It was an‐
nounced by Brendan Eich, then of Mozilla, and the creator of the JavaScript language1. They also simulta‐
neously launched a Working Group- where the work gets done in the WebAssembly standards world--
and a Community Group-- where people can submit feedback or ideas.

Implementation in Browsers and Other Runtimes

Momentum for WebAssembly gained pretty quickly. In 2017, Mozilla announced support for
WebAssembly in all major browsers2. Also in 2017, Node.JS added support for WebAssembly in version
83. So by 2017, you could run WebAssembly in every major browser and Node.js. In 2018, the first work‐
ing drafts for WebAssembly were submitted to the W3C4.

This also notes a shift in WebAssembly; what was primarily a browser technology was being made avail‐
able in other runtimes. This didn’t necessitate a broadening of focus either; because it’s a specification
that can be implemented against, the ability to create custom WebAssembly runtimes was an option that
remained open.

WebAssembly Standards Groups and Even More Standards

In 2019, there were a few major developments: the creation of the WebAssembly System Interface, or
WASI, and the establishment of the Bytecode Alliance are two of the larger ones.

WASI is a system interface for WebAssembly5-- WebAssembly has no real way to talk to the outside sys‐
tem it is running on. In the browser, it is given access to modern web APIs through communicating with
JavaScript. If you want to run WebAssembly outside of the browser, it’s a different story; there is no way
for WebAssembly to access system calls, like printing to stdout or using the filesystem, without a sys‐
tem interface like WASI.

The Bytecode Alliance was founded as an organization to create new software foundations based off the
wasm and WASI standards. It currently produces the wasmtime WebAssembly runtime, which as of this
writing just came into 1.0. The Bytecode Alliance is also overseeing the WASI specification6. The founding
members of the alliance were Mozilla, Fastly, Intel, and Red Hat7.
Development of the Standard

the Current state of WebAssembly

In 2022, quite a few proposals made their way forward towards standardization in the WebAssembly
sphere. Runtimes also made a lot of progress on many fronts, including performance. Another develop‐
ment is the release of a document specifying WebAssembly 2.0; this document solidifies years of work on
varying proposals8. WebAssembly 2.0 will most likely be fully backwards compatible9. Now I’ll dig into
the WebAssembly standard and the WebAssembly runtimes and the developments therein.

The Stardard

The arguably most anticipated proposal to make its way through the pipeline recently is garbage
collection.

The Runtimes

More types of runtimes


Perf getting better, with some rivaling LLVM perf

Use Cases for WebAssembly on (or off) the Web


There are many use cases for WebAssembly-- many are web-based, but some aren’t, showcasing interest‐
ing ways people have thought of to use WebAssembly. Let’s explaore the web-based applications first,
then take a spin into newer territory.

General Web Development

The use cases of WebAssembly are so vast in part because of the way WebAssembly was defined; it runs
at near-native speeds and allows you to harness the power of the languages that aren’t JavaScript. It’s se‐
cure thanks to the JavaScript vm and the containerized way the code runs. It’s portable to all modern
browsers, Node.JS, and even standalone runtimes.

Browser Use Cases

Many browser-based use cases stem from things JavaScript isn’t as good or performant at; for instance,
math that is either very computationally expensive or requires float precision. This paves the way for
games, as any game rendering or physics engine relies heavily on these kinds of operations.
Cryptography is another common use case, as it also needs a lot of precise math.

Another popular use case for WebAssembly is the porting of applications previously relegated to the
desktop to the web; code written in another laungage can be compiled into wasm and run in the browser.
Examples of this are Google Earth and AutoCAD.

Node.js

Native modules are an interesting subject for WebAssembly in Node.JS; these are modules, usually writ‐
ten in other languages like C/C++, that need to compile on the computing instance they are installed on.
This can cause a lot of problems with portability, as what compiles correctly on one machine may not
compile on another. This also makes them take a while to install, as they need to be re-compiled after
download. WebAssmebly suffers from neither of these concerns; it is compiled at development, and the
bytecode is shipped to Node.JS without the need for anything but to run it in the Node.JS instance. An ex‐
ample of replacing native modules with WebAssembly code is the source-map javascript library10.
Specialized Subjects

There are a couple of specialized subjects worth mentioning that use WebAssembly. One is serverless in‐
frastructure. Because of the secure way WebAssembly runs, and its performance, many serverless
providers are turning to WebAssembly as a way to run existing user code, such as serverless functions.
This also reflects into containerisation, wherein wasm is run in containers for running, among other
things, untrusted code. One reason WebAssembly makes a good choice for this is the security model; un‐
less you explicitly say so, the WebAssembly has no access to outside its container and untrusted code can
be run with little fear of unintended side effects. This side of WebAssembly has been growing over the
past few years11

The other is IoT-- because the WebAssembly runtime can be made rather small, people are doing re‐
search into running WebAssembly code on IoT devices; this seems like an interesting way to let you pro‐
gram hardware in any langugage that compiles to WebAssembly. The idea of portable IoT code that can
be moved from board to board, with a WASI instance dealing with the board specifics, is appealing (espe‐
cially to this IoT addict!).

A Brief Description of how WebAssembly Works


This section will cover the high-level basics of writing and running WebAssembly code. These are the
steps we’ll be taking throughout the book to build WebAssembly Applications.

Write in the language of your choice

There are many choices of langugage for writing WebAssembly; with more being added. This book will
focus on Rust with a little bit of AssemblyScript, but you have a litany of choices; as long as the language
compiles to wasm, you can’t go wrong. That being said, be sure to read up on the support of the language
you’d like to use — some are still in the experimental phase.

Compile to wasm

Once you have written your code, you’ll need to compile it to wasm. This is the step that turns your code
into the bytecode the WebAssembly runtime will run. I’ll talk about how to do this with Rust and
AssemblyScript in later chapters.

Pick a runtime

For many projects in WebAssembly, the browser will be the wasm runtime. However, that isn’t your only
choice. You can run WebAssembly code in Node.js, for example, and there are standalone runtimes, such
as wasmer and wasmtime. Whatever runtime you pick, make sure there’s WASI support if you need it. In
this book,you’ll work with the browser, Node.JS, Deno, and wasmtime.

Load your .wasm files in

This step highly depends on the runtime being used-- for the browser, it pulls the raw bytecode in, parses
it, and runs it. You’ll need to consult the runtime you’re using about how to get the wasm bytecode loaded
in, but many build tools offer pre-packaging of your wasm into javascript modules for ease of use in the
browser and Node.js/Deno.

Enjoy

Open your web browser or your Node.js/Deno program or your standalone runtime and watch as your
WebAssembly code executes. We’ll also talk about debugging and performance later in the book.
Now that we’ve covered the basics, you’ll get your hands dirty in the next chapter creating your first
WebAssembly module.

1 https://brendaneich.com/2015/06/from-asm-js-to-webassembly/

2 https://blog.mozilla.org/en/mozilla/webassembly-in-browsers/

3 https://github.com/nodejs/node/blob/main/doc/changelogs/CHANGELOG_V8.md#8.0.0

4 https://www.w3.org/TR/2022/WD-wasm-core-2-20220419/

5 https://hacks.mozilla.org/2019/03/standardizing-wasi-a-webassembly-system-interface/

6 https://hacks.mozilla.org/2019/03/standardizing-wasi-a-webassembly-system-interface/

7 https://hacks.mozilla.org/2019/11/announcing-the-bytecode-alliance/

8 https://webassembly.github.io/spec/core/

9 https://webassembly.github.io/spec/core/binary/modules.html

10 https://hacks.mozilla.org/2018/01/oxidizing-source-maps-with-rust-and-webassembly/

11 https://platform.uno/blog/the-state-of-webassembly-2022-and-2023/

You might also like