Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Learn WebAssembly
Learn WebAssembly

Learn WebAssembly: Build web applications with native performance using Wasm and C/C++

eBook
₱579.99 ₱2000.99
Paperback
₱2500.99
Subscription
Free Trial

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Learn WebAssembly

What is WebAssembly?

WebAssembly (Wasm) represents an important stepping stone for the web platform. Enabling a developer to run compiled code on the web without a plugin or browser lock-in presents many new opportunities. Some confusion exists about what WebAssembly is, as does some skepticism about its staying power.

In this chapter, we will discuss how WebAssembly came to be, what WebAssembly is with regard to the official definition, and the technologies it encompasses. The potential use cases, supported languages, and limitations will be covered, as well as where to find additional information.

Our goal for this chapter is to understand the following:

  • The technologies that led the way for WebAssembly
  • What WebAssembly is and some of its potential use cases
  • Which programming languages can be used with WebAssembly
  • The current limitations of WebAssembly
  • How WebAssembly relates to Emscripten and asm.js

The road to WebAssembly

Web development has had an interesting history, to say the least. Several (failed) attempts have been made to expand the platform to support different languages. Clunky solutions such as plugins failed to stand the test of time, and limiting a user to a single browser is a recipe for disaster.

WebAssembly was developed as an elegant solution to a problem that has existed since browsers were first able to execute code: If you want to develop for the web, you have to use JavaScript. Fortunately, using JavaScript doesn't have the same negative connotations it had back in the early 2000s, but it continues to have certain limitations as a programming language. In this section, we're going to discuss the technologies that led to WebAssembly to get a better grasp of why this new technology is needed.

The evolution of JavaScript

JavaScript was created by Brendan Eich in just 10 days back in 1995. Originally seen as a toy language by programmers, it was used primarily to make buttons flash or banners appear on a web page. The last decade has seen JavaScript evolve from a toy to a platform with profound capabilities and a massive following.

In 2008 heavy competition in the browser market resulted in the addition of just-in-time (JIT) compilers, which increased the execution speed of JavaScript by a factor of 10. Node.js debuted in 2009 and represented a paradigm shift in web development. Ryan Dahl combined Google's V8 JavaScript engine, an event loop, and a low-level I/O API to build a platform that allowed for the use of JavaScript across the server and client side. Node.js led to npm, a package manager that allowed for the development of libraries to be used within the Node.js ecosystem. As of the time of writing, there are over 600,000 packages available with hundreds being added every day:

Package count growth on npm since 2012, taken from Modulecounts

It's not just the Node.js ecosystem that is growing; JavaScript itself is being actively developed. The ECMA Technical Committee 39 (TC39), which dictates the standards for JavaScript and oversees the addition of new language features, releases yearly updates to JavaScript with a community-driven proposal process. Between its wealth of libraries and tooling, constant improvements to the language, and possessing one of the largest communities of programmers, JavaScript has become a force to be reckoned with.

But the language does have some shortcomings:

  • Up until recently, JavaScript only included 64-bit floating point numbers. This can cause issues with very large or very small numbers. BigInt, a new numeric primitive that can alleviate some of these issues, is in the the process of being added to the ECMAScript specification, but it may take some time until it's fully supported in browsers.
  • JavaScript is weakly typed, which adds to its flexibility, but can cause confusion and bugs. It essentially gives you enough rope to hang yourself.
  • JavaScript isn't as performant as compiled languages despite the best efforts of the browser vendors.
  • If a developer wants to create a web application, they need to learn JavaScript—whether they like it or not.

To avoid having to write more than a few lines of JavaScript, some developers built transpilers to convert other languages to JavaScript. Transpilers (or source-to-source compilers) are types of compilers that convert source code in one programming language to equivalent source code in another programming language. TypeScript, which is a popular tool for frontend JavaScript development, transpiles TypeScript to valid JavaScript targeted for browsers or Node.js. Pick any programming language and there's a good chance that someone created a JavaScript transpiler for it. For example, if you prefer to write Python, you have about 15 different tools that you can use to generate JavaScript. In the end, though, it's still JavaScript, so you're still subject to the idiosyncrasies of the language.

As the web evolved into a valid platform for building and distributing applications, more and more complex and resource-intensive applications were created. In order to meet the demands of these applications, browser vendors began working on new technologies to integrate into their software without disrupting the normal course of web development. Google and Mozilla, creators of Chrome and Firefox, respectively, took two different paths to achieve this goal, culminating in the creation of WebAssembly.

Google and Native Client

Google developed Native Client (NaCl) with the intent to safely run native code within a web browser. The executable code would run in a sandbox and offered the performance advantages of native code execution.

In the context of software development, a sandbox is an environment that prevents executable code from interacting with other parts of your system. It is intended to prevent the spread of malicious code and place restrictions on what software can do.

NaCl was tied to a specific architecture, while Portable Native Client (PNaCl) was an architecture-independent version of NaCl developed to run on any platform. The technology consisted of two elements:

  • Toolchains which could transform C/C++ code to NaCl modules
  • Runtime components which were components embedded in the browser that allowed execution of NaCl modules:
The Native Client toolchains and their outputs

NaCl's architecture-specific executable (nexe) was limited to applications and extensions that were installed from Google's Chrome Web Store, but PNaCl executables (pexe) can be freely distributed on the web and embedded in web applications. Portability was made possible with Pepper, an open source API for creating NaCl modules, and its corresponding plugin API (PPAPI). Pepper enabled communication between NaCl modules and the hosting browser, and allowed for access to system-level functions in a safe and portable way. Applications could be easily distributed by including a manifest file and a compiled module (pexe) with the corresponding HTML, CSS, and JavaScript:

Pepper's role in a Native Client application

NaCl offered promising opportunities to overcome the performance limitations of the web, but it had some drawbacks. Although Chrome had built-in support for PNaCl executables and Pepper, other major browser did not. Detractors of the technology took issue with the black-box nature of the applications as well as the potential security risks and complexity.

Mozilla focused its efforts on improving the performance of JavaScript with asm.js. They wouldn't add support for Pepper to Firefox due to the incompleteness of its API specification and limited documentation. In the end, NaCl was deprecated in May, 2017, in favor of WebAssembly.

Mozilla and asm.js

Mozilla debuted asm.js in 2013 and provided a way for developers to translate their C and C++ source code to JavaScript. The official specification for asm.js defines it as a strict subset of JavaScript that can be used as a low-level, efficient target language for compilers. It's still valid JavaScript, but the language features are limited to those that are amenable to ahead-of-time (AOT) optimization. AOT is a technique that the browser's JavaScript engine uses to execute code more efficiently by compiling it down to native machine code. asm.js achieves these performance gains by having 100% type consistency and manual memory management.

Using a tool such as Emscripten, C/C++ code can be transpiled down to asm.js and easily distributed using the same means as normal JavaScript. Accessing the functions in an asm.js module requires linking, which involves calling its function to obtain an object with the module's exports.

asm.js is incredibly flexible, however, certain interactions with the module can cause a loss of performance. For example, if an asm.js module is given access to a custom JavaScript function that fails dynamic or static validation, the code can't take advantage of AOT and falls back to the interpreter:

The asm.js AOT compilation workflow

asm.js isn't just a stepping stone. It forms the basis for WebAssembly's Minimum Viable Product (MVP). The official WebAssembly site explicitly mentions asm.js in the section entitled WebAssembly High-Level Goals.

So why create WebAssembly when you could use asm.js? Aside from the potential performance loss, an asm.js module is a text file that must be transferred over the network before any compilation can take place. A WebAssembly module is in a binary format, which makes it much more efficient to transfer due to its smaller size. 

WebAssembly modules use a promise-based approach to instantiation, which takes advantage of modern JavaScript and eliminates the need for any is this loaded yet? code.

WebAssembly is born

The World Wide Web Consortium (W3C), an international community built to develop web standards, formed the WebAssembly Working Group in April, 2015, to standardize WebAssembly and oversee the specification and proposal process. Since then, the Core Specification and corresponding JavaScript API and Web API have been released. The initial implementation of WebAssembly support in browsers was based on the feature set of asm.js. WebAssembly's binary format and corresponding .wasm file combined facets of asm.js output with PNaCl's concept of a distributed executable.

So how will WebAssembly succeed where NaCl failed? According to Dr. Axel Rauschmayer, there are three reasons detailed at http://2ality.com/2015/06/web-assembly.html#what-is-different-this-time:

"First, this is a collaborative effort, no single company goes it alone. At the moment, the following projects are involved: Firefox, Chromium, Edge and WebKit.

Second, the interoperability with the web platform and JavaScript is excellent. Using WebAssembly code from JavaScript will be as simple as importing a module.

Third, this is not about replacing JavaScript engines, it is more about adding a new feature to them. That greatly reduces the amount of work to implement WebAssembly and should help with getting the support of the web development community."

- Dr. Axel Rauschmayer

What exactly is WebAssembly and where can I use it?

WebAssembly has a succinct and descriptive definition on the official site, but it's only a piece of the puzzle. There are several other components that fall under the umbrella of WebAssembly. Understanding the role each component plays will give you a better understanding of the technology as a whole. In this section, we will provide a detailed breakdown of WebAssembly's definition and describe potential use cases.

Official definition

The official WebAssembly website (https://webassembly.org) offers this definition:

 Wasm is a binary instruction format for a stack-based virtual machine. Wasm is designed as a portable target for compilation of high-level languages like C/C++/Rust, enabling deployment on the web for client and server applications.

Let's break that definition down into parts to add some clarification.

Binary instruction format

WebAssembly actually encompasses several elements—a binary format and text format, which are documented in the Core Specification, the corresponding APIs (JavaScript and web), and a compilation target. The binary and text format both map to a common structure in the form of an abstract syntax. To better understand abstract syntax, it can be explained in the context of an abstract syntax tree (AST). An AST is a tree representation of the structure of source code for a programming language. Tools such as ESLint use JavaScript's AST to find linting errors. The following example contains a function and the corresponding AST for JavaScript (taken from https://astexplorer.net).

A simple JavaScript function follows:

function doStuff(thingToDo) {
console.log(thingToDo);
}

The corresponding AST is as follows:

{
"type": "Program",
"start": 0,
"end": 57,
"body": [
{
"type": "FunctionDeclaration",
"start": 9,
"end": 16,
"id": {
"type": "Identifier",
"start": 17,
"end": 26,
"name": "doStuff"
},
"generator": false,
"expression": false,
"params": [
{
"type": "Identifier",
"start": 28,
"end": 57,
"name": "thingToDo"
}
],
"body": {
"type": "BlockStatement",
"start": 32,
"end": 55,
"body": [
{
"type": "ExpressionStatement",
"start": 32,
"end": 55,
"expression": {
"type": "CallExpression",
"start": 32,
"end": 54,
"callee": {
"type": "MemberExpression",
"start": 32,
"end": 43,
"object": {
"type": "Identifier",
"start": 32,
"end": 39,
"name": "console"
},
"property": {
"type": "Identifier",
"start": 40,
"end": 43,
"name": "log"
},
"computed": false
},
"arguments": [
{
"type": "Identifier",
"start": 44,
"end": 53,
"name": "thingToDo"
}
]
}
}
]
}
}
],
"sourceType": "module"
}

An AST may be verbose, but it does an excellent job at describing the components of a program. Representing source code in an AST makes verification and compilation simple and efficient. WebAssembly code in text format is serialized into an AST and compiled to the binary format (as a .wasm file), which is fetched, loaded, and utilized by a web page. When the module is loaded, the browser's JavaScript engine utilizes a decoding stack to decode the .wasm file into an AST, perform type checking, and interpret it to execute functions. WebAssembly started as a binary instruction format for an AST. Due to the performance implications of verifying Wasm expressions that return void, the binary instruction format was updated to target a stack machine.

A stack machine consists of two elements: a stack and instructions. A stack is a data structure with two operations: push and pop. Items are pushed onto the stack and subsequently popped from the stack in last in, first out (LIFO) order. A stack also includes a pointer, which points to the item at the top of the stack. Instructions represent actions to perform on the items in the stack. For example, an ADD instruction might pop the top two items from the stack (the values 100 and 10), and push a single item with the sum back onto the stack (the value 110):

A simple stack machine

WebAssembly's stack machine operates in the same way. A program counter (pointer) maintains the execution position within the code and a virtual control stack keeps track of blocks and if constructs as they are entered (pushed) and exited (popped). The instructions are executed with no reference to an AST. Thus, the binary instruction format portion of the definition refers to a binary representation of instructions that are in a format readable by the decoding stack in the browser.

Portable target for compilation

WebAssembly was designed from the beginning with portability in mind. Portability in this context means that WebAssembly's binary format can be executed efficiently on a variety of operating systems and instruction set architectures, on and off the web. The specification for WebAssembly defines portability in the context of an execution environment. WebAssembly was designed to run efficiently in environments that meet certain characteristics, most of which are related to memory. WebAssembly's portability can also be attributed to the absence of a specific API around the core technologies. Instead, it defines an import mechanism where the set of available imports is defined by the host environment.

In a nutshell, this means that WebAssembly isn't tied to a specific environment, such as the web or desktop. The WebAssembly Working Group has defined a Web API, but that's separate from the Core Specification. The Web API caters to WebAssembly, not the other way around.

The compilation aspect of the definition indicates that WebAssembly will be simple to compile down to its binary format from source code written in high-level languages. The MVP focuses on two languages, C and C++, but Rust can also be used given its similarities to C++. Compilation will be achieved through the use of a Clang/LLVM backend, although we'll be using Emscripten in this book to generate our Wasm modules. The plan is to eventually add support for other languages and compilers (such as GCC), but the MVP is focused on LLVM.

The core specification

The official definition gives some high-level insight into the overall technology, but for the sake of completeness, it's worth digging a little deeper. WebAssembly's Core Specification is the official document to reference if you want to understand WebAssembly at a very granular level. If you're interested in learning about the characteristics of the runtime structure with regard to the execution environment, check out section 4: Execution. We won't cover that here, but understanding where the Core Specification fits in will help in establishing a complete definition of WebAssembly.

Language concepts

The Core Specification states WebAssembly encodes a low-level, assembly-like programming language. The specification defines the structure, execution, and validation of this language as well as the details of the binary and text formats. The language itself is structured around the following concepts:

  • Values, or rather value types that WebAssembly provides
  • Instructions that are executed within the stack machine
  • Traps produced under error conditions and abort execution
  • Functions into which code is organized, each of which takes a sequence of values as parameters and returns a sequence of values as a result
  • Tables, which are arrays of values of a particular element type (such as function references) that are selectable by the executing program
  • Linear Memory, which is an array of raw bytes that can be used to store and load values
  • Modules, WebAssembly binary (.wasm file) that contains function, tables, and linear memories
  • Embedder, the mechanism by which WebAssembly can be executed in a host environment, such as a web browser

Functions, tables, memory, and modules have direct correlations with the JavaScript API and are important to be aware of. These concepts describe the underlying structure of the language itself and how to write or encode WebAssembly. With regard to usage, understanding the corresponding semantic phases of WebAssembly provides a complete definition of the technology:

Language concepts and their relationship

Semantic phases

The Core Specification describes the different phases an encoded module (.wasm file) undergoes when it is being utilized in a host environment (such as a web browser). This aspect of the specification represents how the output is handled and executed:

  • Decoding: The binary format is converted into a module
  • Validation: The decoded module undergoes validation checks (such as type checking) to ensure the module is well formed and safe
  • Execution, Part 1: Instantiation: A module instance, which is the dynamic representation of the module, is instantiated by initializing the Globals, Memories, and Tables, and invokes the module's start() function
  • Execution, Part 2: Invocation: Exported functions are called from the module instance:

 The following diagram provides a visual representation of the semantic phases:

Semantic phases of module use

The JavaScript and Web APIs

The WebAssembly Working Group also released API specifications for interacting with JavaScript and the web, which qualifies them for inclusion in the WebAssembly technology space. The JavaScript API is scoped to the JavaScript language itself, without being specifically tied to an environment (for example, web browsers or Node.js). It defines classes, methods, and objects for interacting with WebAssembly and managing the compilation and instantiation processes. The Web API is an extension of the JavaScript API that defines functionality specific to web browsers. The Web API specification currently only defines two methods, compileStreaming and instantiateStreaming, which are convenience methods that simplify the use of Wasm modules in the browser. These will be covered in greater detail in Chapter 2, Elements of WebAssembly - Wat, Wasm, and the JavaScript API.

So will it replace JavaScript?

WebAssembly's ultimate goal is not to replace JavaScript, but rather to complement it. JavaScript's rich ecosystem and flexibility still makes it the ideal language for the web. WebAssembly's JavaScript API makes interoperability between the two technologies relatively simple. So will you be able to build a web application using just WebAssembly? One of the explicit goals of WebAssembly is portability, and replicating all of JavaScript's functionality could inhibit that goal. However, the official site includes a goal to execute and integrate well with the existing web platform, so only time will tell. It may not be practical to write the entire code base in a language that compiles down to WebAssembly, but moving some of the application logic to Wasm modules could be beneficial in terms of performance and load times.

Where can I use it?

WebAssembly's official site has an extensive list of potential use cases. I'm not going to cover them all here, but there are several that represent significant enhancements to the capabilities of the web platform:

  • Image/video editing
  • Games
  • Music applications (streaming, caching)
  • Image recognition
  • Live video augmentation
  • VR and augmented reality

Although some of these use cases are technically feasible with JavaScript, HTML, and CSS, using WebAssembly can offer significant performance gains. Serving up a binary file (instead of a single JavaScript file) can greatly reduce the bundle size, and instantiating the Wasm module on page load speeds up code execution.

WebAssembly isn't just limited to the browser. Outside the browser, you could use it to build hybrid native apps on mobile devices or perform server-side computations of untrusted code. Using Wasm modules for phone apps could be incredibly beneficial in terms of power usage and performance.

WebAssembly also offers flexibility with regard to how it can be used. You can write your entire code base in WebAssembly, although this may not be practical in its current form or in the context of a web application. Given WebAssembly's robust JavaScript API, you could write the UI in JavaScript/HTML and use Wasm modules for functionality that doesn't directly access the DOM. Once additional languages are supported, objects can be easily passed between the Wasm module and JavaScript code, which will greatly simplify integration and increase developer adoption.

What languages are supported?

WebAssembly's high-level goals for their MVP was to provide roughly the same functionality as asm.js. The two technologies are very closely related. C, C++, and Rust are very popular languages that support manual memory allocation, which made them ideal candidates for the initial implementation. In this section, we're going to provide a brief overview of each programming language.

C and C++

C and C++ are low-level programming languages that have been around for over 30 years. C is procedural and doesn't inherently support object-oriented programming concepts such as classes and inheritance, but it's fast, portable, and widely used. 

C++ was built to fill the gaps in C by adding features such as operator overloading and improved type checking. Both languages consistently rank in the top 10 most popular programming languages, which make them ideally suited for the MVP:

TIOBE Very Long Term History of the top 10 programming languages

C and C++ support is also baked into Emscripten, so in addition to simplifying the compilation process, it allows you to take advantage of WebAssembly's full capabilities. It is also possible to compile C/C++ code down to a .wasm file using LLVM. LLVM is a collection of modular and reusable compiler and toolchain technologies. In a nutshell, it's a framework that simplifies the configuration of a compilation process from source code to machine code. If you made your own programming language and would like to build a compiler, LLVM has tools to simplify the process. I'll cover how to compile C/C++ into .wasm files using LLVM in Chapter 10, Advanced Tools and Upcoming Features.

The following snippet demonstrates how to print Hello World! to the console using C++:

#include <iostream>

int main() {
std::cout << "Hello, World!\n";
return 0;
}

Rust

C and C++ were intended to be the primary languages used for WebAssembly, but Rust is a perfectly suitable substitute. Rust is a systems programming language that is syntactically similar to C++. It was designed with memory safety in mind, but still retains the performance advantages of C and C++. The current nightly build of Rust's compiler can generate .wasm files from Rust source code, so if you prefer Rust and are familiar with C++, you should be able to use Rust for most of the examples in this book.

The following snippet demonstrates how to print Hello World! to the console using Rust:

fn main() {
println!("Hello World!");
}

Other languages

Various tooling exists to enable the use of WebAssembly with some of the other popular programming languages, although they are mostly experimental:

  • C# via Blazor
  • Haxe via WebIDL
  • Java via TeaVM or Bytecoder
  • Kotlin via TeaVM
  • TypeScript via AssemblyScript

It is also technically possible to transpile a language to C and consequently compile that to a Wasm module, but the success of compilation is contingent on the output of the transpiler. More than likely, you'd have to make significant changes to the code to get it to work.

What are the limitations?

Admittedly, WebAssembly is not without its limitations. New features are being actively developed and the technology is constantly evolving, but the MVP functionality represents only a portion of WebAssembly's capabilities. In this section, we'll cover some of these limitations and how they impact the development process.

No garbage collection

WebAssembly supports a flat linear memory, which isn't a limitation per se, but requires some understanding of how to explicitly allocate memory to execute code. C and C++ were logical choices for the MVP because memory management is built into the language. The reason why some of the more popular high-level languages such as Java weren't included initially is due to something called garbage collection (GC).

GC is a form of automated memory management wherein memory occupied by objects that are no longer in use by the program is reclaimed automatically. GC is analogous to an automatic transmission on a car. It has been heavily optimized by skilled engineers to operate as efficiently as possible, but limits the amount of control the driver has. Manually allocating memory is like driving a car with a manual transmission. It affords greater control over speed and torque, but misuse or lack of experience can leave you stranded with a severely damaged car. Part of C and C++'s excellent performance and speed can be attributed to the manual allocation of memory.

GC languages allow you to program without having to worry about memory availability or allocation. JavaScript is an example of a GC language. The browser engine employs something called a mark-and-sweep algorithm to collect unreachable objects and free up the corresponding memory. Support for GC languages is currently being worked on in WebAssembly, but it's hard to say exactly when it will be completed.

No direct DOM access

WebAssembly is unable to access the DOM, so any DOM manipulation needs to be done indirectly through JavaScript or using a tool such as Emscripten. There are plans to add the ability to reference DOM and other Web API objects directly, but that's still in the proposal phase. DOM manipulation will likely go hand in hand with GC languages, since it will allow the seamless passing of objects between WebAssembly and JavaScript code.

No support in older browsers

Older browsers don't have the global WebAssembly object available to instantiate and load Wasm modules. There are experimental polyfills that utilize asm.js if the object isn't found, but the WebAssembly Working Group currently has no plans to create one. Since asm.js and WebAssembly are closely related, simply serving up an asm.js file if the WebAssembly object is unavailable will still offer performance gains while accommodating for backward compatibility. You can see which browsers currently support WebAssembly at https://caniuse.com/#feat=wasm.

How does it relate to Emscripten?

Emscripten is the source-to-source compiler that can generate asm.js from C and C++ source code. We'll use it as a build tool to generate the Wasm modules. In this section, we'll quickly review how Emscripten relates to WebAssembly.

Emscripten's role

Emscripten is an LLVM-to-JavaScript compiler, which means it takes LLVM bitcode output of a compiler such as Clang (for C and C++), and converts that to JavaScript. It isn't one specific technology, but rather a combination of technologies that work together to build, compile, and run asm.js. To generate Wasm modules, we'll use the Emscripten SDK (EMSDK)  Manager:

Wasm module generation with the EMSDK

The EMSDK and Binaryen

In Chapter 4, Installing the Required Dependencies, we'll install the EMSDK and use it to manage the dependencies required to compile C and C++ to Wasm modules. Emscripten uses Binaryen's asm2wasm tool to compile the asm.js output by Emscripten to a .wasm file. Binaryen is a compiler and toolchain infrastructure library that includes tools to compile various formats to WebAssembly modules and vice versa. Understanding the inner workings of Binaryen isn't required to use WebAssembly, but it is important to be aware of the underlying technologies and how they work together. By passing certain flags into the compile command for Emscripten (emcc), we can pipe the resultant asm.js code to Binaryen to output our .wasm file.

Summary

In this chapter, we discussed the history of WebAssembly with regard to the technologies that led to its creation. A detailed overview of the definition of WebAssembly was provided to allow for a greater understanding of the underlying technologies involved.

The Core Specification, JavaScript API, and Web API were presented as important elements of WebAssembly and demonstrate how the technology will evolve. We also reviewed potentials use cases, currently supported languages, and tools that enable the use of non-supported languages.

The limitations of WebAssembly are the absence of GC, the inability to communicate directly with the DOM, and the lack of support for older browsers. These were discussed to convey the newness of the technology and shed light on some of its shortcomings. Finally, we discussed Emscripten's role in the development process and where it fits into the WebAssembly development workflow.

In Chapter 2Elements of WebAssembly - Wat, Wasm, and the JavaScript API, we'll be diving deeper into the elements that make up WebAssembly: the WebAssembly text format (Wat), binary format (Wasm), JavaScript, and Web APIs.

Questions

  1. Which two technologies influenced the creation of WebAssembly?
  2. What is a stack machine and how does it relate to WebAssembly?
  3. In what ways does WebAssembly complement JavaScript?
  4. Which three programming languages can be compiled to Wasm modules?
  5. What role does LLVM play with regard to WebAssembly?
  6. What are three potential use cases for WebAssembly?
  7. How are DOM access and GC related?
  8. What tool does Emscripten use to generate Wasm modules?

Further reading

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Generate WebAssembly modules from C and C++ using Emscripten and interact with these modules in the browser
  • Learn how to use WebAssembly outside of the browser and load modules using Node.js
  • Build a high-performance application using C and WebAssembly and port an existing C++ game to WebAssembly using Emscripten

Description

WebAssembly is a brand-new technology that represents a paradigm shift in web development. This book teaches programmers to leverage this technology to write high-performance applications that run in the browser. This book introduces you to powerful WebAssembly concepts to help you write lean and powerful web applications with native performance. You start with the evolution of web programming, the state of things today, and what can be done with the advent and release of WebAssembly. We take a look at the journey from JavaScript to asm.js to WebAssembly. We then move on to analyze the anatomy of a WebAssembly module and the relationship between binary and text formats, along with the corresponding JavaScript API. Further on, you'll implement all the techniques you've learned to build a high-performance application using C and WebAssembly, and then port an existing game written in C++ to WebAssembly using Emscripten. By the end of this book, you will be well-equipped to create high-performance applications and games for the web using WebAssembly.

Who is this book for?

If you are a web developer or C/C++ programmer keen to leverage the powerful technology of WebAssembly to build high-performance web applications, then this book is for you.

What you will learn

  • Learn how WebAssembly came to be and its associated elements (text format, module, and JavaScript API)
  • Create, load, and debug a WebAssembly module (editor and compiler/toolchain)
  • Build a high-performance application using C and WebAssembly
  • Extend WebAssembly's feature set using Emscripten by porting a game written in C++
  • Explore upcoming features of WebAssembly, Node.js integration, and alternative compilation methods
Estimated delivery fee Deliver to Philippines

Standard delivery 10 - 13 business days

₱492.95

Premium delivery 5 - 8 business days

₱2548.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Sep 25, 2018
Length: 328 pages
Edition : 1st
Language : English
ISBN-13 : 9781788997379
Languages :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Philippines

Standard delivery 10 - 13 business days

₱492.95

Premium delivery 5 - 8 business days

₱2548.95
(Includes tracking information)

Product Details

Publication date : Sep 25, 2018
Length: 328 pages
Edition : 1st
Language : English
ISBN-13 : 9781788997379
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just ₱260 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just ₱260 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 7,859.97
Hands-On Game Development with WebAssembly
₱2245.99
Learn WebAssembly
₱2500.99
CMake Cookbook
₱3112.99
Total 7,859.97 Stars icon
Banner background image

Table of Contents

11 Chapters
What is WebAssembly? Chevron down icon Chevron up icon
Elements of WebAssembly - Wat, Wasm, and the JavaScript API Chevron down icon Chevron up icon
Setting Up a Development Environment Chevron down icon Chevron up icon
Installing the Required Dependencies Chevron down icon Chevron up icon
Creating and Loading a WebAssembly Module Chevron down icon Chevron up icon
Interacting with JavaScript and Debugging Chevron down icon Chevron up icon
Creating an Application from Scratch Chevron down icon Chevron up icon
Porting a Game with Emscripten Chevron down icon Chevron up icon
Integrating with Node.js Chevron down icon Chevron up icon
Advanced Tools and Upcoming Features Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Half star icon Empty star icon Empty star icon 2.3
(4 Ratings)
5 star 25%
4 star 0%
3 star 0%
2 star 25%
1 star 50%
Amazon Customer Dec 27, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
The information is very valuable and easier to follow than the website. It explains webassembly and how to use it.
Amazon Verified review Amazon
Amazon Customer Dec 26, 2018
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
An okay book to start with WebAssembly, however the quality of the book is horrible, especially at later chapters with code examples. While the idea/content could be salvaged, this book is in dire need of proof-reading and checking that their examples are valid.If you see it on sale for under 5$ - get it. Outside of that price range, you are better reading unofficial blog post with WebAssembly examples.
Amazon Verified review Amazon
MATHEUS JOSE SANTOS Jul 17, 2022
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
Awful quality control from Pack from the printing process through distribution. Is it was two or three missing pages it would be understandable, but 72 pages is just BS.
Amazon Verified review Amazon
Catherine Holloway Feb 13, 2020
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
I was hoping to gain an understanding of how to write and compile a minimal "hello world" example with C code compiled to a wasm file, and how to load this file in the browser. I've read several tutorials online and none worked, so I figured I could trust pakt to deliver something to explain what the browser expects for WebAssembly.instantiate(). Unfortunately, this book suffers from exactly the same problem as all the tutorials. Emscripten has already moved on, and the example code in this book is out of date. The author writes clearly and explains the basic concepts well, but it's not what I needed. This book was a waste of my time.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela