Esta tradução está incompleta. Por favor, ajude a traduzir este artigo do Inglês.
Este artigo explica os conceitos por trás de como o WebAssembly funciona, incluindo os seus objetivos, os problemas que este resolve, e como ele é executado dentro do mecanismo de renderização do navegador da Web.
O que é WebAssembly?
O WebAssembly é um novo tipo de código que pode ser executado nos navegadores da Web modernos e fornece novas funcionalidades e grandes ganhos no desempenho. Este não é destinado principalmente para ser escrito à mão, mas é projetado para ser um alvo de compilação eficaz para linguagens de origem de baixo nível como C, C++, Rust, etc.
This has huge implications for the web platform — it provides a way to run code written in multiple languages on the web at near-native speed, with client apps running on the web that previously couldn’t have done so.
Objetivos de WebAssembly
WebAssembly is being created as an open standard inside the W3C WebAssembly Community Group with the following goals:
- Be fast, efficient, and portable — WebAssembly code can be executed at near-native speed across different platforms by taking advantage of common hardware capabilities.
- Be readable and debuggable — WebAssembly is a low-level assembly language, but it does have a human-readable text format (the specification for which is still being finalized) that allows code to be written, viewed, and debugged by hand.
- Keep secure — WebAssembly is specified to be run in a safe, sandboxed execution environment. Like other web code, it will enforce the browser's same-origin and permissions policies.
- Don't break the web — WebAssembly is designed so that it plays nicely with other web technologies and maintains backwards compatibility.
Como é que WebAssembly se ajusta na platforma da Web?
The web platform can be thought of as having two parts:
- A set of Web APIs that the Web app can call to control web browser/device functionality and make things happen (DOM, CSSOM, WebGL, IndexedDB, Web Audio API, etc.).
- WebAssembly is a low-level assembly-like language with a compact binary format that runs with near-native performance and provides languages with low-level memory models such as C++ and Rust with a compilation target so that they can run on the web. (Note that WebAssembly has the high-level goal of supporting languages with garbage-collected memory models in the future.)
Conceitos chave de WebAssembly
- Module: Represents a WebAssembly binary that has been compiled by the browser into executable machine code. A Module is stateless and thus, like a Blob, can be explicitly shared between windows and workers (via
postMessage()). A Module declares imports and exports just like an ES2015 module.
- Memory: A resizable ArrayBuffer that contains the linear array of bytes read and written by WebAssembly’s low-level memory access instructions.
- Table: A resizable typed array of references (e.g. to functions) that could not otherwise be stored as raw bytes in Memory (for safety and portability reasons).
- Instance: A Module paired with all the state it uses at runtime including a Memory, Table, and set of imported values. An Instance is like an ES2015 module that has been loaded into a particular global with a particular set of imports.
In the future, WebAssembly modules will be loadable just like ES2015 modules (using
Como é que eu utilizo WebAssembly na minha aplicação?
Above we talked about the raw primitives that WebAssembly adds to the Web platform: a binary format for code and APIs for loading and running this binary code. Now let’s talk about how we can use these primitives in practice.
The WebAssembly ecosystem is at a nascent stage; more tools will undoubtedly emerge going forward. Right now, there are three main entry points:
- Porting a C/C++ application with Emscripten.
- Writing or generating WebAssembly directly at the assembly level.
- Writing a Rust application and targetting WebAssembly as its output.
Let’s talk about these options:
Portabilidade a partir de C/C++
Two of the many options for creating WASM code are an online wasm assembler or Emscripten. There are a number of online WASM assembler choices, such as:
These are great resources for people who are trying to figure out where to start, but they lack some of the tooling and optimizations of Emscripten.
In a nutshell, the process works as follows:
- Emscripten first feeds the C/C++ into clang+LLVM — a mature open-source C/C++ compiler toolchain, shipped as part of XCode on OSX for example.
- Emscripten transforms the compiled result of clang+LLVM into a .wasm binary.
Nota: existem planos futuros para permitir que WebAssembly efetue chamadas diretamente das APIs da Web.
<textarea>. If the application uses OpenGL, the HTML also contains a
<canvas> element that is used as the rendering target. It’s very easy to modify the Emscripten output and turn it into whatever web app you require.
Escrever WebAssembly diretamente
In the same fashion as physical assembly languages, the WebAssembly binary format has a text representation — the two have a 1:1 correspondence. You can write or generate this format by hand and then convert it into the binary format with any of several WebAssemby text-to-binary tools.
For a simple guide on how to do this, see our Converting WebAssembly text format to wasm article.
Escrever WebAssembly com objetivo em Rust
Desde o fim de novembro de 2017, Rust Nightly tem suportado WebAssembly como a sua saída (destino), sem precisar que Emscripten a carregue. Mais detalhes aqui.
Este artigo forneceu uma explicação sobre o que é WebAssembly, por que é tão útil, como ele se encaixa na Web e como o pode utilizar.
- WebAssembly articles on Mozilla Hacks blog
- WebAssembly on Mozilla Research
- Carregar e executar o código WebAssembly — saiba como carregar o seu próprio módulo de WebAssembly numa página da Web.