aboutsummaryrefslogtreecommitdiff
path: root/files/pt-br/webassembly
diff options
context:
space:
mode:
authorPeter Bengtsson <mail@peterbe.com>2020-12-08 14:42:52 -0500
committerPeter Bengtsson <mail@peterbe.com>2020-12-08 14:42:52 -0500
commit074785cea106179cb3305637055ab0a009ca74f2 (patch)
treee6ae371cccd642aa2b67f39752a2cdf1fd4eb040 /files/pt-br/webassembly
parentda78a9e329e272dedb2400b79a3bdeebff387d47 (diff)
downloadtranslated-content-074785cea106179cb3305637055ab0a009ca74f2.tar.gz
translated-content-074785cea106179cb3305637055ab0a009ca74f2.tar.bz2
translated-content-074785cea106179cb3305637055ab0a009ca74f2.zip
initial commit
Diffstat (limited to 'files/pt-br/webassembly')
-rw-r--r--files/pt-br/webassembly/concepts/index.html163
-rw-r--r--files/pt-br/webassembly/entendendo_o_formato_textual_do_webassembly/index.html512
-rw-r--r--files/pt-br/webassembly/index.html162
-rw-r--r--files/pt-br/webassembly/usando_a_api_javascript_do_webassembly/index.html269
4 files changed, 1106 insertions, 0 deletions
diff --git a/files/pt-br/webassembly/concepts/index.html b/files/pt-br/webassembly/concepts/index.html
new file mode 100644
index 0000000000..7dde5c9ef1
--- /dev/null
+++ b/files/pt-br/webassembly/concepts/index.html
@@ -0,0 +1,163 @@
+---
+title: Conceitos do WebAssembly
+slug: WebAssembly/Concepts
+tags:
+ - conceitos
+ - plataforma web
+translation_of: WebAssembly/Concepts
+---
+<div>{{WebAssemblySidebar}}</div>
+
+<p class="summary">Este artigo explica os conceitos por trás de como o WebAssembly funciona, incluindo seus objetivos, os problemas que ele resolve e como ele roda dentro do mecanismo de renderização de um browser.</p>
+
+<h2 id="O_que_é_WebAssembly">O que é WebAssembly?</h2>
+
+<p>WebAssembly é um novo tipo de código que pode ser executado nos browsers modernos e fornece novas carecterísticas e maiores ganhos em performance. Ele não foi pensado incialmente para ser escrito à mão, ao contrário, foi pensado para ser um compilador-alvo eficiente para linguagens de baixo nível como C, C++, Rust, etc.</p>
+
+<p>Ele possui implicações enormes para a plataforma web — ele fornece um caminho para executar códigos escritos em múltiplas linguagens na web, com velocidades próximas às das linguagens nativas com apps sendo executados na web, onde antes não era possível.</p>
+
+<p>Além disso, você não precisa saber como criar código WebAssembly para tirar vantagem dele. Os módulos WebAssembly podem ser importados num app web (ou Node.js), expondo funções do WebAssembly para uso via JavaScript. Os frameworks de JavaScript poderiam usar o WebAssembly para conseguir enormes vantagens de performance e novas características enquanto disponibiliza funcionalidades aos desenvolvedores web.</p>
+
+<h2 id="Objetivos_do_WebAssembly">Objetivos do WebAssembly</h2>
+
+<p>WebAssembly está sendo criado em código aberto dentro do <a href="https://www.w3.org/community/webassembly/">W3C WebAssembly Community Group</a> com os seguintes objetivos:</p>
+
+<ul>
+ <li>Ser rápido, eficiente e móvel — o código WebAssembly pode ser executado a velocidades próximas de nativas entre diferentes plataformas, tirando vantagem das <a href="http://webassembly.org/docs/portability/#assumptions-for-efficient-execution">capacidades comuns de hardware</a>.</li>
+ <li>Ser compreensível e debuggable — WebAssembly é uma linguagem assembly de baixo nível, mas ela tem um formato de texto compreensível para os humanos (especificação pela qual ainda está sendo finalizado) que permite que o código seja escrito, visto e debugado à mão.</li>
+ <li>Manter a segurança — WebAssembly é especificado para ser executado num ambiente seguro e controlado. Como outros códigos web, ele reforçará as mesmas políticas de origem e permissões dos browsers.</li>
+ <li>Não quebrar a web — WebAssembly foi pensado de maneira que ele seja executado em harmonia com outras tecnologias web, mantendo a compatibilidade retroativa.</li>
+</ul>
+
+<div class="note">
+<p><strong>Nota</strong>: WebAssembly também terá usos fora dos ambientes web e JavaScript (veja <a href="http://webassembly.org/docs/non-web/">Non-web embeddings</a>).</p>
+</div>
+
+<h2 id="Como_o_WebAssembly_se_encaixa_na_plataforma_web">Como o WebAssembly se encaixa na plataforma web?</h2>
+
+<p>A plataforma web pode ser dividida em duas partes:</p>
+
+<ul>
+ <li>Uma máquina virtual (VM) que executa o código de uma aplicação Web, por exemplo códigos JavaScript que enriquecem suas aplicações.</li>
+ <li>Um conjunto de <a href="/en-US/docs/Web/API">Web APIs</a> que um Web app pode invocar para controlar funcionalidades web browser/device (dispositivo) e fazer as coisas acontecerem (<a href="/en-US/docs/Web/API/Document_Object_Model">DOM</a>, <a href="/en-US/docs/Web/API/CSS_Object_Model">CSSOM</a>, <a href="/en-US/docs/Web/API/WebGL_API">WebGL</a>, <a href="/en-US/docs/Web/API/IndexedDB_API">IndexedDB</a>, <a href="/en-US/docs/Web/API/Web_Audio_API">Web Audio API</a>, etc.).</li>
+</ul>
+
+<p>Historicamente, a VM tem tido permissão para carregar apenas JavaScript. Isto tem funcionado bem para nós, já que o JavaScript é poderoso o suficiente para resolver a maioria dos problemas da Web atualmente. No entanto, temos enfrentado problemas de performance, quando tentamos usar o JavaScript para tarefas mais intensivas como games em 3D, realidades virtual e aumentada, visão de computador, edição de imagens ou videos e um sem número de outros domínios que demandam performance nativa (veja <a href="http://webassembly.org/docs/use-cases/">Casos de uso WebAssembly</a> para mais ideias).</p>
+
+<p>Adicionalmente, o custo de baixar, parsear e compilar aplicações JavaScript muito grandes, é proibitivo. Plataformas mobile e outras de recursos restritos, podem ampliar ainda mais estes gargalos de performance.</p>
+
+<p>WebAssembly é uma linguagem diferente do JavaScript, mas não foi pensada para ser sua substituta. Ao contrário, foi pensada para complementar e trabalhar lado a lado com o JavaScript, permitindo aos desenvolvedores web tirarem vantagem dos pontos fortes das duas linguagens:</p>
+
+<ul>
+ <li>JavaScript é uma linguagem de alto nível, flexível e expressiva o suficiente para escrever aplicações web. Ela tem muitas vantagens — é dinamicamente tipada, não ncessita ser compilada e tem um enorme ecossistema que disponibiliza poderosos frameworks, bibliotecas (libs) e outros recursos.</li>
+ <li>WebAssembly é uma linguagem de baixo nível do tipo assembly com um formato binário compacto, que é executado com performance próximo à nativa, que disponibiliza linguagens com modelos de memória de baixo nível como C++ e Rust, com uma compilação-alvo, assim podendo ser executados na web. (Note que o WebAssembly tem uma <a href="http://webassembly.org/docs/high-level-goals/">meta futura de suporte de alto nível</a> para linguagens com modelos de memória garbage-collected.)</li>
+</ul>
+
+<p>Com o advento do WebAssembly nos browsers, a máquina virtual a que nos referimos antes, vai carregar e executar dois tipos de código — JavaScript E WebAssembly.</p>
+
+<p>Os diferentes tipos de códigos podem invocar um ao outro conforme necessário — o <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly">WebAssembly JavaScript API</a> encapsula código WebAssembly exportado com funções JavaScript que podem ser invocados normalmente, e código WebAssembly pode importar de forma síncrona, funções normais de JavaScript. Na verdade, a unidade básica do código WebAssembly é chamado de módulo, e módulos WebAssembly são semelhantes em vários níveis aos módulos de ES2015.</p>
+
+<h3 id="Conceitos-chave_do_WebAssembly">Conceitos-chave do WebAssembly</h3>
+
+<p>Existem diversos conceitos-chave que precisam ser compreendidos, sobre como o WebAssembly é executado no browser. Todos estes conceitos são refletidos 1:1 na <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly">WebAssembly JavaScript API</a>.</p>
+
+<ul>
+ <li><strong>Módulo</strong>: Representa o binário do WebAssembly que foi compilado pelo browser, em código executável pela máquina. Um módulo não tem estado e, tal qual um <a href="/en-US/docs/Web/API/Blob">Blob</a>, pode ser explicitamente compartilhado entre janelas e workers (via <code><a href="/en-US/docs/Web/API/MessagePort/postMessage">postMessage()</a></code>). Um Módulo declara imports e exports, assim com um módulo ES2015.</li>
+ <li><strong>Memória</strong>: Um ArrayBuffer redimensionável que contém um array linear de bytes, lidos e escritos pelas intruções de memória de baixo nível do WebAssembly.</li>
+ <li><strong>Tabela</strong>: Um array tipado de referências redimensionável (por exemplo para funções) que, em outra situação, não poderia ser armazenado como bytes puros na Memória (por questões de segurança e portabilidade).</li>
+ <li><strong>Instância</strong>: Um Módulo pareado com todo o estado utilizado durante a execução, incluindo uma Memória, Tabela e um conjunto de valores importados. Uma Instância é como um módulo ES2015 que foi carregado em um global específico com um conjunto de importações específico.</li>
+</ul>
+
+<p>A API JavaScript disponibiliza aos desenvolvedores a habilidade de criar módulos, memórias, tabelas e instâncias. Dada uma instância WebAssembly, o código JavaScript pode, de forma síncrona, invocar seus exports, os quais são expostos como funções normais de JavaScript. Funções arbitrárias de JavaScript também podem ser invocadas de forma síncrona pelo código WebAssembly, sendo passados nestas funções JavaScript como imports para um instância WebAssembly.</p>
+
+<p>Uma vez que o JavaScript tem controle total sobre como o código WebAssembly é carregado, compilado e executado, desenvolvedores JavaScript poderiam até pensar no WebAssembly como apenas uma ferramenta do JavaScript, para geração de funções de alta performance de forma eficiente.</p>
+
+<p>No futuro, módulos WebAssembly serão carregáveis assim como <a href="https://github.com/WebAssembly/proposals/issues/12">módulos ES2015</a> (usando <code>&lt;script type='module'&gt;</code>), o que quer dizer que o JavaScript será capaz de buscar, compilar e importar um módulo WebAssembly tão facilmente quanto um módulo ES2015.</p>
+
+<h2 id="Como_eu_utilizo_o_WebAssembly_em_minha_aplicação">Como eu utilizo o WebAssembly em minha aplicação?</h2>
+
+<p>Acima nós falamos sobre primitivas puras que o WebAssembly adiciona à plataforma Web: um formato binário para código e APIs para carregar e executar esse código binário. Agora vamos falar sobre como nós podemos utilizar estas primitivas na prática.</p>
+
+<p>O ecossistema do WebAssembly está em seu estado inicial: sem dúvidas, mais ferramentas vão aparecer. Neste momento, existem quatro pontos de entrada principais: </p>
+
+<ul>
+ <li>Portando uma aplicação C/C++ com <a href="/en-US/docs/Mozilla/Projects/Emscripten">Emscripten</a>.</li>
+ <li>Escrevendo ou gerando WebAssembly diretamente no nível do assembly.</li>
+ <li>Escrevendo uma aplicação Rust e definindo WebAssembly como seu output.</li>
+ <li>Usando <a href="https://docs.assemblyscript.org/">AssemblyScript</a> que se parece com TypeScript e compila ao binário WebAssembly.</li>
+</ul>
+
+<p>Vamos falar sobre estas opções:</p>
+
+<h3 id="Portando_a_partir_de_CC">Portando a partir de C/C++</h3>
+
+<p>Duas das muitas opções para criar códigos WASM, são um assembler wasm online ou <a href="/en-US/docs/Mozilla/Projects/Emscripten">Emscripten</a>. Existem algumas opções de assembler wasm online, como:</p>
+
+<ul>
+ <li><a href="https://wasdk.github.io/WasmFiddle/">WasmFiddle</a></li>
+ <li><a href="https://anonyco.github.io/WasmFiddle/">WasmFiddle++</a></li>
+ <li><a href="https://mbebenita.github.io/WasmExplorer/">WasmExplorer</a></li>
+</ul>
+
+<p>Estes são excelentes recursos para pessoas que estão tentando descobrir por onde começar, mas não possuem as otimizações e ferramentas do Emscripten.</p>
+
+<p>A ferramenta Emscripten é capaz de pegar qualquer código fonte C/C++ e compilá-lo para um módulo .wasm, além da "cola" JavaScript necessária para carregar e executar o módulo, e um documento HTML para exibir os resultados do código.</p>
+
+<p><img alt="" src="https://mdn.mozillademos.org/files/14647/emscripten-diagram.png" style="display: block; height: 104px; margin: 0px auto; width: 764px;"></p>
+
+<p>De maneira resumida, o processo funciona da seguinte maneira:</p>
+
+<ol>
+ <li><span id="docs-internal-guid-40340921-7fff-385f-85d0-d4ec1fd0e64e" style="background-color: transparent; color: #000000; font-family: Arial; font-size: 12pt; font-style: normal; font-variant: normal; font-weight: 400; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;">Emscripten primeiro alimenta o C/C++ no clang+LLVM — um maduro compilador C/C++, enviado como parte do Xcode do OSX, por exemplo.</span></li>
+ <li dir="ltr" style="list-style-type: decimal; font-size: 12pt; font-family: Arial; color: #000000; background-color: transparent; font-weight: 400; font-style: normal; font-variant: normal; text-decoration: none; vertical-align: baseline; white-space: pre;">
+ <p dir="ltr" style="line-height: 1.5; margin-top: 10pt; margin-bottom: 10pt;"><span style="background-color: transparent; color: #000000; font-family: Arial; font-size: 12pt; font-style: normal; font-variant: normal; font-weight: 400; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;">Emscripten transforma o resultado compilado do clang+LLVM em um binário .wasm</span></p>
+ </li>
+ <li dir="ltr" style="list-style-type: decimal; font-size: 12pt; font-family: Arial; color: #000000; background-color: transparent; font-weight: 400; font-style: normal; font-variant: normal; text-decoration: none; vertical-align: baseline; white-space: pre;">
+ <p dir="ltr" style="line-height: 1.5; margin-top: 10pt; margin-bottom: 10pt;"><span style="background-color: transparent; color: #000000; font-family: Arial; font-size: 12pt; font-style: normal; font-variant: normal; font-weight: 400; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;">Por si só, o WebAssembly atualmente não pode acessar diretamente o DOM; ele só pode chamar o JavaScript, transmitindo tipos de dados primitivos de ponto flutuante e inteiro. Portanto, para acessar qualquer API da Web, o WebAssembly precisa chamar o JavaScript, que faz a chamada da API da Web. Portanto, o Emscripten cria o código de “cola” HTML e JavaScript necessário para alcançar isso.</span></p>
+ </li>
+</ol>
+
+<div class="note">
+<p><strong>Nota</strong>: Existem planos futuros para <a href="https://github.com/WebAssembly/gc/blob/master/README.md">permitir o WebAssembly chamar APIs Web diretamente</a>.</p>
+</div>
+
+<p><span style="background-color: transparent; color: #000000; font-family: Arial; font-size: 12pt; font-style: normal; font-variant: normal; font-weight: 400; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;">O código de "cola" JavaScript não é tão simples quanto você imagina. Para começar, o Emscripten implementa bibliotecas populares de C/C++ como SDL, OpenGL, OpenAL e partes do POSIX. Essas bibliotecas são implementadas em termos de APIs da Web e, portanto, cada uma exige algum código JavaScript para conectar o WebAssembly à API da Web subjacente.</span></p>
+
+<p dir="ltr" id="docs-internal-guid-052eef79-7fff-abe5-b985-780a26b0c1fe" style="line-height: 1.5; margin-top: 0pt; margin-bottom: 0pt;"><span style="background-color: transparent; color: #000000; font-family: Arial; font-size: 12pt; font-style: normal; font-variant: normal; font-weight: 400; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;">Portanto, parte do código está implementando a funcionalidade de cada biblioteca respectiva usada pelo código C/C ++. O código de “cola” também contém a lógica para chamar as APIs JavaScript do WebAssembly mencionadas acima para buscar, carregar e executar o arquivo .wasm.</span></p>
+
+<p dir="ltr" style="line-height: 1.5; margin-top: 0pt; margin-bottom: 0pt;"></p>
+
+<p dir="ltr" style="line-height: 1.5; margin-top: 0pt; margin-bottom: 0pt;"><span style="background-color: transparent; color: #000000; font-family: Arial; font-size: 12pt; font-style: normal; font-variant: normal; font-weight: 400; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;">O documento HTML gerado carrega o arquivo JavaScript e grava stdout em um </span>{{htmlelement("textarea")}}<span style="background-color: transparent; color: #000000; font-family: Arial; font-size: 12pt; font-style: normal; font-variant: normal; font-weight: 400; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;">. Se o aplicativo usar OpenGL, o HTML também conterá um elemento </span>{{htmlelement("canvas")}}<span style="background-color: transparent; color: #000000; font-family: Arial; font-size: 12pt; font-style: normal; font-variant: normal; font-weight: 400; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;"> usado como destino de renderização. É muito fácil modificar a saída do Emscripten e transformá-la em qualquer aplicativo da web que você precisar.</span></p>
+
+<p dir="ltr" style="line-height: 1.5; margin-top: 0pt; margin-bottom: 0pt;"></p>
+
+<p>Você pode encontrar a documentação completa em Emscripten em <a href="http://emscripten.org">emscripten.org</a>, e um guia para implementar a cadeia de ferramentas e compilar seu próprio aplicativo C/C ++ no wasm em <a href="https://developer.mozilla.org/en-US/docs/WebAssembly/C_to_wasm">Compiling from C/C++ to WebAssembly</a>.</p>
+
+<h3 id="Escrevendo_WebAssembly_diretamente">Escrevendo WebAssembly diretamente</h3>
+
+<p>Deseja criar seu próprio compilador, ou suas próprias ferramentas, ou criar uma biblioteca JavaScript que gere o WebAssembly em tempo de execução?</p>
+
+<p>Da mesma maneira que as linguagens assembly físicas, o formato binário do WebAssembly tem uma representação de texto — os dois têm uma correspondência 1:1. Você pode escrever ou gerar esse formato manualmente e depois convertê-lo no formato binário com qualquer uma das várias <a href="http://webassembly.org/getting-started/advanced-tools/">WebAssemby text-to-binary tools</a>.</p>
+
+<p>Para um guia simples de como fazer isso, consulte o artigo <a href="/en-US/docs/WebAssembly/Text_format_to_wasm">Converting WebAssembly text format to wasm</a>.</p>
+
+<h3 id="Escrevendo_em_Rust_mirando_WebAssembly">Escrevendo em Rust mirando WebAssembly</h3>
+
+<p>Também é possível escrever o código Rust e compilar para WebAssembly, graças ao trabalho incansável do Rust WebAssembly Working Group. Você pode começar a instalar a cadeia de ferramentas necessária, compilar um programa Rust de amostra em um pacote npm do WebAssembly e usá-lo em um aplicativo web de amostra, no artigo <a href="/en-US/docs/WebAssembly/Rust_to_wasm">Compiling from Rust to WebAssembly</a>.</p>
+
+<h3 id="Usando_AssemblyScript">Usando AssemblyScript</h3>
+
+<p>Para desenvolvedores web que quereem testar o WebAssembly sem a necessidade de abrende detalhes de C ou Rust, AssemblyScript irá sem a melhor opção. Ele gera um pequeno bundle e seu desempenho é um pouco mais lento comparado a C ou Rust. Você pode conferir sua documentação em <a href="https://docs.assemblyscript.org/">https://docs.assemblyscript.org/</a>.</p>
+
+<h2 id="Sumário">Sumário</h2>
+
+<p>Este artigo apresentou a você uma explicação sobre o que é o WebAssembly, porque ele é tão útil, como ele se encaixa na web e como você pode se utilizar dele.</p>
+
+<h2 id="Veja_também">Veja também</h2>
+
+<ul>
+ <li><a href="https://hacks.mozilla.org/category/webassembly/">WebAssembly articles on Mozilla Hacks blog</a></li>
+ <li><a href="https://research.mozilla.org/webassembly/">WebAssembly on Mozilla Research</a></li>
+ <li><a href="/en-US/docs/WebAssembly/Loading_and_running">Loading and running WebAssembly code</a> — descubra como carregar seu próprio módulo WebAssembly numa página web.</li>
+ <li><a href="/en-US/docs/WebAssembly/Using_the_JavaScript_API">Using the WebAssembly JavaScript API</a> — descubra como utilizar outras características importantes do WebAssembly JavaScript API.</li>
+</ul>
diff --git a/files/pt-br/webassembly/entendendo_o_formato_textual_do_webassembly/index.html b/files/pt-br/webassembly/entendendo_o_formato_textual_do_webassembly/index.html
new file mode 100644
index 0000000000..70568c9112
--- /dev/null
+++ b/files/pt-br/webassembly/entendendo_o_formato_textual_do_webassembly/index.html
@@ -0,0 +1,512 @@
+---
+title: Entendendo o formato textual do WebAssembly
+slug: WebAssembly/Entendendo_o_formato_textual_do_WebAssembly
+translation_of: WebAssembly/Understanding_the_text_format
+---
+<div>{{WebAssemblySidebar}}</div>
+
+<p class="summary">Para permitir que o WebAssembly seja lido e editado por humanos foi criado uma representação textual do código binário wasm. Essa é uma forma textual intermediária desenvolvida para ser usada em editores de textos, ferramentas de desenvolvimento dos navegatores, etc. Esse artigo expica como essa expressão textual funciona, mostrando a sintase de maneira bruta,  e como ela está relacionada com o código binário ao qual ela representa - e os objetos que encapsulam o wasm dentro do JavaScript.</p>
+
+<div class="note">
+<p><strong>Nota</strong>: Esse artigo trata de maneira aprofundada a descrição textual do WebAssembly, se você é um desenvolvedor web que quer apenas carregar algum módulo wasm em seu código JavaScript e usá-lo em sua página web recomendamos que dê uma olhada no seguinte artigo: <a href="/en-US/docs/WebAssembly/Using_the_JavaScript_API">Using the WebAssembly JavaScript API</a>. Esse artigo será de grande valia caso você queira otimizar a performance de módulos wasm em seu código JavaScript, ou ainda fazer seu próprio compilador de WebAssembly. </p>
+</div>
+
+<h2 id="S-expressions">S-expressions</h2>
+
+<p>Em seus dois formatos, binário e textual, a unidade fundamental do WebAssembly é um módulo. Na forma textual, um módulo é representado como uma grande S-expression.  S-expressions são um tipo bem antigo e simples de representar textualmente árvores de dados, então podemos descrever um módulo como uma árvore de nós que descreve a estrutura e código daquele módulo. Diferente da Árvore Sintática Abstrata de uma linguagem de programação qualquer, a árvore do WebAssembly é bem rasa, consistindo basicamente de uma grande lista de instruções.</p>
+
+<p>First, let’s see what an S-expression looks like.  Each node in the tree goes inside a pair of parentheses — <code>( ... )</code>.  The first label inside the parenthesis tells you what type of node it is, and after that there is a space-separated list of either attributes or child nodes.  So that means the WebAssembly S-expression:</p>
+
+<pre>(module (memory 1) (func))</pre>
+
+<p>represents a tree with the root node “module” and two child nodes, a "memory" node with the attribute "1" and a "func" node.  We’ll see shortly what these nodes actually mean.</p>
+
+<h3 id="The_simplest_module">The simplest module</h3>
+
+<p>Let's start with the simplest, shortest possible wasm module.</p>
+
+<pre>(module)</pre>
+
+<p>This module is totally empty, but is still a valid module.</p>
+
+<p>If we convert our module to binary now (see <a href="/en-US/docs/WebAssembly/Text_format_to_wasm">Converting WebAssembly text format to wasm</a>), we’ll see just the 8 byte module header described in the <a href="http://webassembly.org/docs/binary-encoding/#high-level-structure">binary format</a>:</p>
+
+<pre>0000000: 0061 736d ; WASM_BINARY_MAGIC
+0000004: 0d00 0000 ; WASM_BINARY_VERSION</pre>
+
+<h3 id="Adding_functionality_to_your_module">Adding functionality to your module</h3>
+
+<p>Ok, that’s not very interesting, let’s add some executable code to this module.</p>
+
+<p>All code in a webassembly module is grouped into functions, which have the following pseudo-code structure:</p>
+
+<pre>( func &lt;signature&gt; &lt;locals&gt; &lt;body&gt; )</pre>
+
+<ul>
+ <li>The <strong>signature</strong> declares what the function takes (parameters) and returns (return values).</li>
+ <li>The <strong>locals</strong> are like vars in JavaScript, but with explicit types declared.</li>
+ <li>The <strong>body</strong> is just a linear list of low-level instructions.</li>
+</ul>
+
+<p>So this is similar to functions in other languages, even if it looks different because it is an S-expression.</p>
+
+<h2 id="Signatures_and_parameters">Signatures and parameters</h2>
+
+<p>The signature is a sequence of parameter type declarations followed by a list of return type declarations. It is worth noting here that:</p>
+
+<ul>
+ <li>The absence of a (result) means the function doesn’t return anything.</li>
+ <li>In the current iteration, there can be at most 1 return type, but <a href="https://webassembly.org/docs/future-features#multiple-return">later this will be relaxed</a> to any number.</li>
+</ul>
+
+<p>Each parameter has a type explicitly declared; wasm currently has four available types:</p>
+
+<ul>
+ <li><code>i32</code>: 32-bit integer</li>
+ <li><code>i64</code>: 64-bit integer</li>
+ <li><code>f32</code>: 32-bit float</li>
+ <li><code>f64</code>: 64-bit float</li>
+</ul>
+
+<p>A single parameter is written <code>(param i32)</code> and the return type is written <code>(result i32)</code>, hence a binary function that takes two 32-bit integers and returns a 64-bit float would be written like this:</p>
+
+<pre>(func (param i32) (param i32) (result f64) ... )</pre>
+
+<p>After the signature, locals are listed with their type, for example <code>(local i32)</code>. Parameters are basically just locals that are initialized with the value of the corresponding argument passed by the caller.</p>
+
+<h2 id="Getting_and_setting_locals_and_parameters">Getting and setting locals and parameters</h2>
+
+<p>Locals/parameters can be read and written by the body of the function with the <code>get_local</code> and <code>set_local</code> instructions.</p>
+
+<p>The <code>get_local</code>/<code>set_local</code> commands refer to the item to be got/set by its numeric index: parameters are referred to first, in order of their declaration, followed by locals in order of their declaration.  So given the following function:</p>
+
+<pre>(func (param i32) (param f32) (local f64)
+ get_local 0
+ get_local 1
+ get_local 2)</pre>
+
+<p>The instruction <code>get_local 0</code> would get the i32 parameter, <code>get_local 1</code> would get the f32 parameter, and <code>get_local 2</code> would get the f64 local.</p>
+
+<p>There is another issue here — using numeric indices to refer to items can be confusing and annoying, so the text format allows you to name parameters, locals, and most other items simply by including a name prefixed by a dollar symbol (<code>$</code>) just before the type declaration.</p>
+
+<p>Thus you could rewrite our previous signature like so:</p>
+
+<pre>(func (param $p1 i32) (param $p2 f32) (local $loc i32) …)</pre>
+
+<p>And then could write <code>get_local $p1</code> instead of <code>get_local 0</code>, etc.  (Note that when this text gets converted to binary, though, the binary will contain only the integer.)</p>
+
+<h2 id="Stack_machines">Stack machines</h2>
+
+<p>Before we can write a function body, we have to talk about one more thing: stack machines. Although the browser compiles it to something more efficient, wasm execution is defined in terms of a stack machine where the basic idea is that every type of instruction pushes and/or pops a certain number of <code>i32</code>/<code>i64</code>/<code>f32</code>/<code>f64</code> values from a stack.</p>
+
+<p>For example, <code>get_local</code> is defined to push the value of the local it read onto the stack, and <code>i32.add</code> pops two <code>i32</code> values (it implicitly grabs the previous two values pushed onto the stack), computes their sum (modulo 2^32) and pushes the resulting i32 value.</p>
+
+<p>When a function is called, it starts with an empty stack which is gradually filled up and emptied as the body’s instructions are executed. So for example, after executing the following function:</p>
+
+<pre>(func (param $p i32)
+ get_local $p
+ get_local $p
+ i32.add)</pre>
+
+<p>The stack contains exactly one <code>i32</code> value — the result of the expression (<code>$p + $p</code>), which is handled by <code>i32.add</code>. The return value of a function is just the final value left on the stack.</p>
+
+<p>The WebAssembly validation rules ensure the stack matches exactly: if you declare a <code>(result f32)</code>, then the stack must contain exactly one <code>f32</code> at the end.  If there is no result type, the stack must be empty.</p>
+
+<h2 id="Our_first_function_body">Our first function body</h2>
+
+<p>As mentioned before, the function body is simply a list of instructions that are followed as the function is called. Putting this together with what we have already learned, we can finally define a module containing our own simple function:</p>
+
+<pre>(module
+ (func (param $lhs i32) (param $rhs i32) (result i32)
+ get_local $lhs
+ get_local $rhs
+ i32.add))</pre>
+
+<p>This function gets two parameters, adds them together, and returns the result.</p>
+
+<p>There are a lot more things that can be put inside function bodies, but we will start off simple for now, and you’ll see a lot more examples as you go along. For a full list of the available opcodes, consult the <a href="http://webassembly.org/docs/semantics/">webassembly.org Semantics reference</a>.</p>
+
+<h3 id="Calling_the_function">Calling the function</h3>
+
+<p>Our function won’t do very much on its own — now we need to call it. How do we do that? Like in an ES2015 module, wasm functions must be explicitly exported by an <code>export</code> statement inside the module.</p>
+
+<p>Like locals, functions are identified by an index by default, but for convenience, they can be named. Let's start by doing this — first, we'll add a name preceded by a dollar sign, just after the <code>func</code> keyword:</p>
+
+<pre>(func $add … )</pre>
+
+<p>Now we need to add an export declaration — this looks like so:</p>
+
+<pre>(export "add" (func $add))</pre>
+
+<p>Here, <code>add</code> is the name the function will be identified by in JavaScript whereas <code>$add</code> picks out which WebAssembly function inside the Module is being exported.</p>
+
+<p>So our final module (for now) looks like this:</p>
+
+<pre>(module
+ (func $add (param $lhs i32) (param $rhs i32) (result i32)
+ get_local $lhs
+ get_local $rhs
+ i32.add)
+ (export "add" (func $add))
+)</pre>
+
+<p>If you want to follow along with the example, save the above our module into a file called <code>add.wat</code>, then convert it into a binary file called <code>add.wasm</code> using wabt (see <a href="/en-US/docs/WebAssembly/Text_format_to_wasm">Converting WebAssembly text format to wasm</a> for details).</p>
+
+<p>Next, we’ll load our binary into a typed array called <code>addCode</code> (as described in <a href="/en-US/docs/WebAssembly/Fetching_WebAssembly_bytecode">Fetching WebAssembly Bytecode</a>), compile and instantiate it, and execute our <code>add</code> function in JavaScript (we can now find <code>add()</code> in the <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Instance/exports">exports</a></code> property of the instance):</p>
+
+<pre class="brush: js">fetchAndInstantiate('add.wasm').then(function(instance) {
+ console.log(instance.exports.add(1, 2)); // "3"
+});
+
+// fetchAndInstantiate() found in wasm-utils.js
+function fetchAndInstantiate(url, importObject) {
+ return fetch(url).then(response =&gt;
+ response.arrayBuffer()
+ ).then(bytes =&gt;
+ WebAssembly.instantiate(bytes, importObject)
+ ).then(results =&gt;
+ results.instance
+ );
+}</pre>
+
+<div class="note">
+<p><strong>Note</strong>: You can find this example in GitHub as <a href="https://github.com/mdn/webassembly-examples/blob/master/understanding-text-format/add.html">add.html</a> (<a href="https://mdn.github.io/webassembly-examples/understanding-text-format/add.html">see it live also</a>). Also see {{jsxref("WebAssembly.instantiate()")}} for more details about the instantiate function, and <code><a href="https://github.com/mdn/webassembly-examples/blob/master/wasm-utils.js">wasm-utils.js</a></code> for the <code>fetchAndInstantiate()</code> source code.</p>
+</div>
+
+<h2 id="Exploring_fundamentals">Exploring fundamentals</h2>
+
+<p>Now we’ve covered the real basics, let’s move on to look at some more advanced features.</p>
+
+<h3 id="Calling_functions_from_other_functions_in_the_same_module">Calling functions from other functions in the same module</h3>
+
+<p>The <code>call</code> instruction calls a single function, given its index or name. For example, the following module contains two functions — one just returns the value 42, the other returns the result of calling the first plus one:</p>
+
+<pre>(module
+ (func $getAnswer (result i32)
+ i32.const 42)
+ (func (export "getAnswerPlus1") (result i32)
+ call $getAnswer
+ i32.const 1
+ i32.add))</pre>
+
+<div class="note">
+<p><strong>Note</strong>: <code>i32.const</code> just defines a 32-bit integer and pushes it onto the stack. You could swap out the <code>i32</code> for any of the other available types, and change the value of the const to whatever you like (here we’ve set the value to <code>42</code>).</p>
+</div>
+
+<p>In this example you’ll notice an <code>(export "getAnswerPlus1")</code> section, declared just after the <code>func</code> statement in the second function — this is a shorthand way of declaring that we want to export this function, and defining the name we want to export it as.</p>
+
+<p>This is functionally equivalent to including a separate function statement outside the function, elsewhere in the module in the same manner as we did before, e.g.:</p>
+
+<pre>(export "getAnswerPlus1" (func $functionName))</pre>
+
+<p>The JavaScript code to call our above module looks like so:</p>
+
+<pre class="brush: js">fetchAndInstantiate('call.wasm').then(function(instance) {
+ console.log(instance.exports.getAnswerPlus1()); // "43"
+});</pre>
+
+<div class="note">
+<p><strong>Note</strong>: You can find this example on GitHub as <a href="https://github.com/mdn/webassembly-examples/blob/master/understanding-text-format/call.html">call.html</a> (<a href="https://mdn.github.io/webassembly-examples/understanding-text-format/call.html">see it live also</a>). Again, see <code><a href="https://github.com/mdn/webassembly-examples/blob/master/wasm-utils.js">wasm-utils.js</a></code> for the <code>fetchAndInstantiate()</code> source.</p>
+</div>
+
+<h3 id="Importing_functions_from_JavaScript">Importing functions from JavaScript</h3>
+
+<p>We have already seen JavaScript calling WebAssembly functions, but what about WebAssembly calling JavaScript functions? WebAssembly doesn’t actually have any built-in knowledge of JavaScript, but it does have a general way to import functions that can accept either JavaScript or wasm functions. Let’s look at an example:</p>
+
+<pre>(module
+ (import "console" "log" (func $log (param i32)))
+ (func (export "logIt")
+ i32.const 13
+ call $log))</pre>
+
+<p>WebAssembly has a two-level namespace so the import statement here is saying that we’re asking to import the <code>log</code> function from the <code>console</code> module. You can also see that the exported <code>logIt</code> function calls the imported function using the <code>call</code> instruction we introduced above.</p>
+
+<p>Imported functions are just like normal functions: they have a signature that WebAssembly validation checks statically, and they are given an index and can be named and called.</p>
+
+<p>JavaScript functions have no notion of signature, so any JavaScript function can be passed, regardless of the import’s declared signature. Once a module declares an import, the caller of {{jsxref("WebAssembly.instantiate()")}} must pass in an import object that has the corresponding properties.</p>
+
+<p>For the above, we need an object (let's call it <code>importObject</code>) such that <code>importObject.console.log</code> is a JavaScript function.</p>
+
+<p>This would look like the following:</p>
+
+<pre class="brush: js">var importObject = {
+ console: {
+ log: function(arg) {
+ console.log(arg);
+ }
+ }
+};
+
+fetchAndInstantiate('logger.wasm', importObject).then(function(instance) {
+ instance.exports.logIt();
+});</pre>
+
+<div class="note">
+<p><strong>Note</strong>: You can find this example on GitHub as <a href="https://github.com/mdn/webassembly-examples/blob/master/understanding-text-format/logger.html">logger.html</a> (<a href="https://mdn.github.io/webassembly-examples/understanding-text-format/logger.html">see it live also</a>).</p>
+</div>
+
+<h3 id="WebAssembly_Memory">WebAssembly Memory</h3>
+
+<p>The above example is a pretty terrible logging function: it only prints a single integer!  What if we wanted to log a text string? To deal with strings and other more complex data types, WebAssembly provides <strong>memory</strong>. According to WebAssembly, memory is just a large array of bytes that can grow over time. WebAssembly contains instructions like <code>i32.load</code> and <code>i32.store</code> for reading and writing from <a href="http://webassembly.org/docs/semantics/#linear-memory">linear memory</a>.</p>
+
+<p>From JavaScript’s point of view, it’s is as though memory is all inside one big (resizable) {{domxref("ArrayBuffer")}}. That’s literally all that asm.js has to play with (except that it isn't resizable; see the asm.js <a href="http://asmjs.org/spec/latest/#programming-model">Programming model</a>).</p>
+
+<p>So a string is just a sequence of bytes somewhere inside this linear memory. Let's assume that we’ve written a suitable string of bytes to memory; how do we pass that string out to JavaScript?</p>
+
+<p>The key is that JavaScript can create WebAssembly linear memory instances via the {{jsxref("WebAssembly.Memory()")}} interface, and access an existing memory instance (currently you can only have one per module instance) using the associated instance methods. Memory instances have a <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Memory/buffer">buffer</a></code> getter, which returns an <code>ArrayBuffer</code> that points at the whole linear memory.</p>
+
+<p>Memory instances can also grow, for example via the <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Memory/grow">Memory.grow()</a></code> method in JavaScript. When growth occurs, since <code>ArrayBuffer</code>s can’t change size, the current <code>ArrayBuffer</code> is detached and a new <code>ArrayBuffer</code> is created to point to the newer, bigger memory. This means all we need to do to pass a string to JavaScript is to pass out the offset of the string in linear memory along with some way to indicate the length.</p>
+
+<p>While there are many different ways to encode a string’s length in the string itself (for example, C strings); for simplicity here we just pass both offset and length as parameters:</p>
+
+<pre>(import "console" "log" (func $log (param i32) (param i32)))</pre>
+
+<p>On the JavaScript side, we can use the <a href="/en-US/docs/Web/API/TextDecoder">TextDecoder API</a> to easily decode our bytes into a JavaScript string.  (We specify <code>utf8</code> here, but many other encodings are supported.)</p>
+
+<pre class="brush: js">consoleLogString(offset, length) {
+ var bytes = new Uint8Array(memory.buffer, offset, length);
+ var string = new TextDecoder('utf8').decode(bytes);
+ console.log(string);
+}</pre>
+
+<p>The last missing piece of the puzzle is where <code>consoleLogString</code> gets access to the WebAssembly <code>memory</code>. WebAssembly gives us a lot of flexibility here: we can either create a <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Memory">Memory</a></code> object in JavaScript and have the WebAssembly module import the memory, or we can have the WebAssembly module create the memory and export it to JavaScript.</p>
+
+<p>For simplicity, let's create it in JavaScript then import it into WebAssembly.  Our <code>import</code> statement is written as follows:</p>
+
+<pre>(import "js" "mem" (memory 1))</pre>
+
+<p>The <code>1</code> indicates that the imported memory must have at least 1 page of memory (WebAssembly defines a page to be 64KB.)</p>
+
+<p>So let's see a complete module that prints the string “Hi”.  In a normal compiled C program, you’d call a function to allocate some memory for the string, but since we’re just writing our own assembly here and we own the entire linear memory, we can just write the string contents into global memory using a <code>data</code> section.  Data sections allow a string of bytes to be written at a given offset at instantiation time and are similar to the <code>.data</code> sections in native executable formats.</p>
+
+<p>Our final wasm module looks like this:</p>
+
+<pre>(module
+ (import "console" "log" (func $log (param i32 i32)))
+ (import "js" "mem" (memory 1))
+ (data (i32.const 0) "Hi")
+ (func (export "writeHi")
+ i32.const 0 ;; pass offset 0 to log
+ i32.const 2 ;; pass length 2 to log
+ call $log))</pre>
+
+<div class="note">
+<p><strong>Note</strong>: Above, note the double semi-colon syntax (<code>;;</code>) for allowing comments in WebAssembly files.</p>
+</div>
+
+<p>Now from JavaScript we can create a Memory with 1 page and pass it in. This results in "Hi" being printed to the console:</p>
+
+<pre class="brush: js">var memory = new WebAssembly.Memory({initial:1});
+
+var importObj = { console: { log: consoleLogString }, js: { mem: memory } };
+
+fetchAndInstantiate('logger2.wasm', importObj).then(function(instance) {
+ instance.exports.writeHi();
+});</pre>
+
+<div class="note">
+<p><strong>Note</strong>: You can find the full source on GitHub as <a href="https://github.com/mdn/webassembly-examples/blob/master/understanding-text-format/logger2.html">logger2.html</a> (<a href="https://mdn.github.io/webassembly-examples/understanding-text-format/logger2.html">also see it live</a>).</p>
+</div>
+
+<h3 id="WebAssembly_tables">WebAssembly tables</h3>
+
+<p>To finish this tour of the WebAssembly text format, let’s look at the most intricate, and often confusing, part of WebAssembly: <strong>tables</strong>. Tables are basically resizable arrays of references that can be accessed by index from WebAssembly code.</p>
+
+<p>To see why tables are needed, we need to first observe that the <code>call</code> instruction we saw earlier (see {{anch("Calling functions from other functions in the same module")}}) takes a static function index and thus can only ever call one function — but what if the callee is a runtime value?</p>
+
+<ul>
+ <li>In JavaScript we see this all the time: functions are first-class values.</li>
+ <li>In C/C++, we see this with function pointers.</li>
+ <li>In C++, we see this with virtual functions.</li>
+</ul>
+
+<p>WebAssembly needed a type of call instruction to achieve this, so we gave it <code>call_indirect</code>, which takes a dynamic function operand. The problem is that the only types we have to give operands in WebAssembly are (currently) <code>i32</code>/<code>i64</code>/<code>f32</code>/<code>f64</code>.</p>
+
+<p>WebAssembly could add an <code>anyfunc</code> type ("any" because the type could hold functions of any signature), but unfortunately this <code>anyfunc</code> type couldn’t be stored in linear memory for security reasons. Linear memory exposes the raw contents of stored values as bytes and this would allow wasm content to arbitrarily observe and corrupt raw function addresses, which is something that cannot be allowed on the web.</p>
+
+<p>The solution was to store function references in a table and pass around table indices instead, which are just i32 values. <code>call_indirect</code>’s operand can therefore simply be an i32 index value.</p>
+
+<h4 id="Defining_a_table_in_wasm">Defining a table in wasm</h4>
+
+<p>So how do we place wasm functions in our table? Just like <code>data</code> sections can be used to initialize regions of linear memory with bytes, <code>elem</code> sections can be used to initialize regions of tables with functions:</p>
+
+<pre>(module
+ (table 2 anyfunc)
+ (elem (i32.const 0) $f1 $f2)
+ (func $f1 (result i32)
+ i32.const 42)
+ (func $f2 (result i32)
+ i32.const 13)
+ ...
+)</pre>
+
+<ul>
+ <li>In <code>(table 2 anyfunc)</code>, the 2 is the initial size of the table (meaning it will store two references) and <code>anyfunc</code> declares that the element type of these references is "a function with any signature". In the current iteration of WebAssembly, this is the only allowed element type, but in the future, more element types will be added.</li>
+ <li>The functions (<code>func</code>) sections are just like any other declared wasm functions. These are the functions we are going to refer to in our table (for example’s sake, each one just returns a constant value). Note that the order the sections are declared in doesn’t matter here — you can declare your functions anywhere and still refer to them in your <code>elem</code> section.</li>
+ <li>The <code>elem</code> section can list any subset of the functions in a module, in any order, allowing duplicates. This is a list of the functions that are to be referenced by the table, in the order they are to be referenced.</li>
+ <li>The <code>(i32.const 0)</code> value inside the <code>elem</code> section is an offset — this needs to be declared at the start of the section, and specifies at what index in the table function references start to be populated. Here we’ve specified 0, and a size of 2 (see above), so we can fill in two references at indexes 0 and 1. If we wanted to start writing our references at offset 1, we’d have to write <code>(i32.const 1)</code>, and the table size would have to be 3.</li>
+</ul>
+
+<div class="note">
+<p><strong>Note</strong>: Uninitialized elements are given a default throw-on-call value.</p>
+</div>
+
+<p>In JavaScript, the equivalent calls to create such a table instance would look something like this:</p>
+
+<pre class="brush: js">function() {
+ // table section
+ var tbl = new WebAssembly.Table({initial:2, element:"anyfunc"});
+
+ // function sections:
+ var f1 = function() { … }
+ var f2 = function() { … }
+
+ // elem section
+ tbl.set(0, f1);
+ tbl.set(1, f2);
+};</pre>
+
+<h4 id="Using_the_table">Using the table</h4>
+
+<p>Moving on, now we’ve defined the table we need to use it somehow. Let's use this section of code to do so:</p>
+
+<pre>(type $return_i32 (func (result i32))) ;; if this was f32, type checking would fail
+(func (export "callByIndex") (param $i i32) (result i32)
+ get_local $i
+ call_indirect $return_i32)</pre>
+
+<ul>
+ <li>The <code>(type $return_i32 (func (param i32)))</code> block specifies a type, with a reference name. This type is used when performing type checking of the table function reference calls later on. Here we are saying that the references need to be functions that return an <code>i32</code> as a result.</li>
+ <li>Next, we define a function that will be exported with the name <code>callByIndex</code>. This will take one <code>i32</code> as a parameter, which is given the argument name <code>$i</code>.</li>
+ <li>Inside the function, we add one value to the stack — whatever value is passed in as the parameter <code>$i</code>.</li>
+ <li>Finally, we use <code>call_indirect</code> to call a function from the table — it implicitly pops the value of <code>$i</code> off the stack. The net result of this is that the <code>callByIndex</code> function invokes the <code>$i</code>’th function in the table.</li>
+</ul>
+
+<p>You could also declare the <code>call_indirect</code> parameter explicitly during the command call instead of before it, like this:</p>
+
+<pre>(call_indirect $return_i32 (get_local $i))</pre>
+
+<p>In a higher level, more expressive language like JavaScript, you could imagine doing the same thing with an array (or probably more likely, object) containing functions. The pseudo code would look something like <code>tbl[i]()</code>.</p>
+
+<p>So, back to the typechecking. Since WebAssembly is typechecked, and <code>anyfunc</code> means "any function signature", we have to supply the presumed signature of the callee at the callsite, hence we include the <code>$return_i32</code> type, to tell the program a function returning an <code>i32</code> is expected. If the callee doesn’t have a matching signature (say an <code>f32</code> is returned instead), a {{jsxref("WebAssembly.RuntimeError")}} is thrown.</p>
+
+<p>So what links the <code>call_indirect</code> to the table we are calling? The answer is that there is only one table allowed right now per module instance, and that is what <code>call_indirect</code> is implicitly calling. In the future, when multiple tables are allowed, we would also need to specify a table identifier of some kind, along the lines of</p>
+
+<pre>call_indirect $my_spicy_table $i32_to_void</pre>
+
+<p>The full module all together looks like this, and can be found in our <a href="https://github.com/mdn/webassembly-examples/blob/master/understanding-text-format/wasm-table.wat">wasm-table.wat</a> example file:</p>
+
+<pre>(module
+ (table 2 anyfunc)
+ (func $f1 (result i32)
+ i32.const 42)
+ (func $f2 (result i32)
+ i32.const 13)
+ (elem (i32.const 0) $f1 $f2)
+ (type $return_i32 (func (result i32)))
+ (func (export "callByIndex") (param $i i32) (result i32)
+ get_local $i
+ call_indirect $return_i32)
+)</pre>
+
+<p>We load it into a webpage using the following JavaScript:</p>
+
+<pre class="brush: js">fetchAndInstantiate('wasm-table.wasm').then(function(instance) {
+  console.log(instance.exports.callByIndex(0)); // returns 42
+  console.log(instance.exports.callByIndex(1)); // returns 13
+  console.log(instance.exports.callByIndex(2));
+ // returns an error, because there is no index position 2 in the table
+});</pre>
+
+<div class="note">
+<p><strong>Note</strong>: You can find this example on GitHub as <a href="https://github.com/mdn/webassembly-examples/blob/master/understanding-text-format/wasm-table.html">wasm-table.html</a> (<a href="https://mdn.github.io/webassembly-examples/understanding-text-format/wasm-table.html">see it live also</a>).</p>
+</div>
+
+<div class="note">
+<p><strong>Note</strong>: Just like Memory, Tables can also be created from JavaScript (see <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Table">WebAssembly.Table()</a></code>) as well as imported to/from another wasm module.</p>
+</div>
+
+<h3 id="Mutating_tables_and_dynamic_linking">Mutating tables and dynamic linking</h3>
+
+<p>Because JavaScript has full access to function references, the Table object can be mutated from JavaScript by the <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Table/grow">grow()</a></code>, <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Table/get">get()</a></code> and <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Table/set">set()</a></code> methods. When WebAssembly gets <a href="http://webassembly.org/docs/gc/">reference types</a>, WebAssembly code will be able to mutate tables itself with <code>get_elem</code>/<code>set_elem</code> instructions.</p>
+
+<p>Because tables are mutable, they can be used to implement sophisticated load-time and run-time <a href="http://webassembly.org/docs/dynamic-linking">dynamic linking schemes</a>. When a program is dynamically linked, multiple instances share the same memory and table. This is symmetric to a native application where multiple compiled <code>.dll</code>s share a single process’s address space.</p>
+
+<p>To see this in action, we’ll create a single import object containing a Memory object and a Table object, and pass this same import object to multiple <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiate">instantiate()</a></code> calls.</p>
+
+<p>Our <code>.wat</code> examples look like so:</p>
+
+<p><code>shared0.wat</code>:</p>
+
+<pre>(module
+ (import "js" "memory" (memory 1))
+ (import "js" "table" (table 1 anyfunc))
+ (elem (i32.const 0) $shared0func)
+ (func $shared0func (result i32)
+ i32.const 0
+ i32.load)
+)</pre>
+
+<p><code>shared1.wat</code>:</p>
+
+<pre>(module
+ (import "js" "memory" (memory 1))
+ (import "js" "table" (table 1 anyfunc))
+ (type $void_to_i32 (func (result i32)))
+ (func (export “doIt”) (result i32)
+ i32.const 0
+ i32.const 42
+ i32.store ;; store 42 at address 0
+ i32.const 0
+ call_indirect $void_to_i32)
+)</pre>
+
+<p>These work as follows:</p>
+
+<ol>
+ <li>The function <code>shared0func</code> is defined in <code>shared0.wat</code>, and stored in our imported table.</li>
+ <li>This function creates a constant containing the value <code>0</code>, and then uses the <code>i32.load</code> command to load the value contained in the provided memory index. The index provided is <code>0</code> — again, it implicitly pops the previous value off the stack. So <code>shared0func</code> loads and returns the value stored at memory index <code>0</code>.</li>
+ <li>In <code>shared1.wat</code>, we export a function called <code>doIt</code> — this fucntion creates two constants containing the values <code>0</code> and <code>42</code>, then calls <code>i32.store</code> to store a provided value at a provided index of the imported memory. Again, it implicitly pops these values off the stack, so the result is that it stores the value <code>42</code> in memory index <code>0</code>,</li>
+ <li>In the last part of the function, we create a constant with value <code>0</code>, then call the function at this index 0 of the table, which is <code>shared0func</code>, stored there earlier by the <code>elem</code> block in <code>shared0.wat</code>.</li>
+ <li>When called, <code>shared0func</code> loads the <code>42</code> we stored in memory using the <code>i32.store</code> command in <code>shared1.wat</code>.</li>
+</ol>
+
+<div class="note">
+<p><strong>Note</strong>: The above expressions again pop values from the stack implicitly, but you could declare these explicitly inside the command calls instead, for example:</p>
+
+<pre>(i32.store (i32.const 0) (i32.const 42))
+(call_indirect $void_to_i32 (i32.const 0))</pre>
+</div>
+
+<p>After converting to assembly, we then use <code>shared0.wasm</code> and <code>shared1.wasm</code> in JavaScript via the following code:</p>
+
+<pre class="brush: js">var importObj = {
+ js: {
+ memory : new WebAssembly.Memory({ initial: 1 }),
+ table : new WebAssembly.Table({ initial: 1, element: "anyfunc" })
+ }
+};
+
+Promise.all([
+ fetchAndInstantiate('shared0.wasm', importObj),
+ fetchAndInstantiate('shared1.wasm', importObj)
+]).then(function(results) {
+ console.log(results[1].exports.doIt()); // prints 42
+});</pre>
+
+<p>Each of the modules that is being compiled can import the same memory and table objects and thus share the same linear memory and table "address space".</p>
+
+<div class="note">
+<p><strong>Note</strong>: You can find this example on GitHub as <a href="https://github.com/mdn/webassembly-examples/blob/master/understanding-text-format/shared-address-space.html">shared-address-space.html</a> (<a href="https://mdn.github.io/webassembly-examples/understanding-text-format/shared-address-space.html">see it live also</a>).</p>
+</div>
+
+<h2 id="Summary">Summary</h2>
+
+<p>This finishes our high-level tour of the major components of the WebAssembly text format and how they get reflected in the WebAssembly JS API.</p>
+
+<h2 id="See_also">See also</h2>
+
+<ul>
+ <li>The main thing that wasn’t included is a comprehensive list of all the instructions that can occur in function bodies.  See the <a href="http://webassembly.org/docs/semantics">WebAssembly semantics</a> for a treatment of each instruction.</li>
+ <li>See also the <a href="https://github.com/WebAssembly/spec/blob/master/interpreter/README.md#s-expression-syntax">grammar of the text format</a> that is implemented by the spec interpreter.</li>
+</ul>
diff --git a/files/pt-br/webassembly/index.html b/files/pt-br/webassembly/index.html
new file mode 100644
index 0000000000..33f3716767
--- /dev/null
+++ b/files/pt-br/webassembly/index.html
@@ -0,0 +1,162 @@
+---
+title: WebAssembly
+slug: WebAssembly
+tags:
+ - WebAssembly
+ - wasm
+translation_of: WebAssembly
+---
+<div>{{WebAssemblySidebar}}{{SeeCompatTable}}</div>
+
+<p class="summary" dir="ltr" id="docs-internal-guid-22bb55aa-d69e-e8ef-cbc6-aafea272f684">O WebAssembly é um novo tipo de código que pode ser executado em browsers modernos — se trata de uma linguagem de baixo nível como assembly, com um formato binário compacto que executa com performance quase nativa e que fornece um novo alvo de compilação para linguagens como C/C++, para que possam ser executadas na web. Também foi projetado para executar em conjunto com o JavaScript, permitindo que ambos trabalhem juntos.</p>
+
+<h2 dir="ltr" id="Em_poucas_palavras">Em poucas palavras</h2>
+
+<p dir="ltr">O WebAssembly tem enormes implicações para a plataforma web — ele irá fornecer uma maneira de executar na web código escrito em diversas linguagens em velocidade quase nativa, com apps que não conseguiriam fazer isso antes.</p>
+
+<p dir="ltr">O WebAssembly foi projetado para complementar e executar lado a lado com JavaScript — usando as APIs JavaScript do WebAssembly, você pode carregar módulos WebAssembly em um aplicativo JavaScript e compartilhar funcionalidade entre ambos. Isso permite que você aproveite o desempenho e poder da WebAssembly e a expressividade e flexibilidade do JavaScript nos mesmos aplicativos, mesmo que você não saiba como escrever código de WebAssembly.</p>
+
+<p dir="ltr">E o que é ainda melhor é que ele está sendo desenvolvido como um padrão web através da <a href="https://www.w3.org/community/webassembly/">W3C WebAssembly Community Group</a> com participantes ativos de todos os principais fornecedores de browsers.</p>
+
+<div class="row topicpage-table">
+<div class="section">
+<h2 dir="ltr" id="Guias">Guias</h2>
+
+<dl>
+ <dt><a href="/en-US/docs/WebAssembly/Concepts">Conceitos WebAssembly</a></dt>
+ <dd>Comece lendo os conceitos de alto nível por trás do WebAssembly - o que é, por que é tão útil, como ele se encaixa na plataforma web e como usá-lo.</dd>
+ <dt><a href="/en-US/docs/WebAssembly/C_to_wasm">Compilando C/C++ para WebAssembly</a></dt>
+ <dd>Quando você escreve o código em C/C++, você pode então compilá-lo em .wasm usando uma ferramenta como <a href="/en-US/docs/Mozilla/Projects/Emscripten/"> Emscripten</a>. Veja como isso funciona.</dd>
+ <dt><a href="/en-US/docs/WebAssembly/Loading_and_running">Carregando e executando código WebAssembly</a></dt>
+ <dd>Depois de ter um .wasm, este artigo aborda como buscá-lo, compilá-lo e instanciá-lo, combinando a API <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly">JavaScript WebAssembly </a> como <a href="/en-US/docs/Web/API/Fetch_API"> Obter </a> ou APIs <a href="/en-US/docs/Web/API/XMLHttpRequest"> XHR.</a></dd>
+ <dt><a href="/en-US/docs/WebAssembly/Caching_modules">Compilando módulos de WebAssembly no cache</a></dt>
+ <dd>O cache de grandes módulos WebAssembly no cliente é útil para melhorar o desempenho da inicialização do aplicativo. Este artigo explica como usar isso usando <a href="/en-US/docs/Web/API/IndexedDB_API"> IndexedDB</a>.</dd>
+ <dt><a href="/en-US/docs/WebAssembly/Using_the_JavaScript_API">Usando a API JavaScript do WebAssembly</a></dt>
+ <dd>Depois de carregar um módulo .wasm, você vai querer usá-lo. Neste artigo, mostramos como usar a WebAssembly através da API JavaScript da WebAssembly.</dd>
+ <dt><a href="/en-US/docs/WebAssembly/Exported_functions">Exportando funções de WebAssembly </a></dt>
+ <dd>Funções WebAssembly exportadas são as reflexões de JavaScript das funções da WebAssembly e permitem chamar o código WebAssembly do JavaScript. Este artigo descreve o que são.</dd>
+ <dt><a href="/en-US/docs/WebAssembly/Understanding_the_text_format">Compreendendo o formato de texto do WebAssembly</a></dt>
+ <dd>Este artigo explica o formato de texto wasm. Esta é a representação textual de baixo nível de um módulo .wasm mostrado nas ferramentas de desenvolvedor do navegador ao depurar.</dd>
+ <dt><a href="/en-US/docs/WebAssembly/Text_format_to_wasm">Convertendo o formato de texto do WebAssembly para o wasm</a></dt>
+ <dd>Este artigo fornece um guia sobre como converter um módulo WebAssembly escrito no formato de texto em um binário .wasm.</dd>
+</dl>
+</div>
+
+<div class="section">
+<h2 dir="ltr" id="Referência_da_API">Referência da API</h2>
+
+<dl>
+ <dt>{{jsxref("Global_objects/WebAssembly", "WebAssembly")}}</dt>
+ <dd>Este objeto atua como o espaço para todas as funcionalidade relacionada à WebAssembly.</dd>
+ <dt>{{jsxref("Global_objects/WebAssembly/Module", "WebAssembly.Module")}}</dt>
+ <dd>A <code>WebAssembly.Module</code> o objeto contém o código da WebAssembly sem estado que já foi compilado pelo navegador e pode ser eficientemente <a href="/en-US/docs/Web/API/Worker/postMessage"> compartilhado com os trabalhos</a>, <a href="/En-US/docs /WebAssembly/Caching_modules"> armazenados em cache no IndexedDB</a>, e instanciados várias vezes.</dd>
+ <dt>{{jsxref("Global_objects/WebAssembly/Instance", "WebAssembly.Instance")}}</dt>
+ <dd>A <code>WebAssembly.Instance</code> o objeto é uma instância executável e estável de um <code> Módulo</code>. Os objetos <code> Instanciados </code> contêm todas as <a href="/en-US/docs/WebAssembly/Exported_functions"> funções de WebAssembly exportadas </a> que permitem chamar o código WebAssembly do JavaScript.</dd>
+ <dt>{{jsxref("Global_objects/WebAssembly/instantiate", "WebAssembly.instantiate()")}}</dt>
+ <dd>The <code>WebAssembly.instantiate()</code> a função é a API primária para compilar e instanciar o código WebAssembly, retornando um <code> Module </code> e sua primeira <code> instância </code>.</dd>
+ <dt>{{jsxref("Global_objects/WebAssembly/Memory", "WebAssembly.Memory()")}}</dt>
+ <dd>Em <code> WebAssembly. </code>O objeto <code> Memory </code> é redimensionável {{jsxref ("Global_objects / ArrayBuffer","ArrayBuffer")}} que detém os bytes de memória invocados por uma <code>instância</code> de código.</dd>
+ <dt>{{jsxref("Global_objects/WebAssembly/Table", "WebAssembly.Table()")}}</dt>
+ <dd>Em <code> WebAssembly. </code>O objeto <code> Table </code> é uma matriz redimensionável de valores opacos, como referências de funções, acessadas por uma <code>instância</code> de código.</dd>
+ <dt>{{jsxref("WebAssembly.CompileError()")}}</dt>
+ <dd>Cria um novo objeto WebAssembly<code> CompileError</code>.</dd>
+ <dt>{{jsxref("WebAssembly.LinkError()")}}</dt>
+ <dd>Cria um novo objeto WebAssembly <code> LinkError</code>.</dd>
+ <dt>{{jsxref("WebAssembly.RuntimeError()")}}</dt>
+ <dd>Cria um novo objeto WebAssembly <code> RuntimeError</code>.</dd>
+</dl>
+</div>
+</div>
+
+<h2 dir="ltr" id="Exemplos">Exemplos</h2>
+
+<ul dir="ltr">
+ <li><a href="https://github.com/JasonWeathersby/WASMSobel">WASMSobel</a></li>
+ <li>Consulte nosso <a href="https://github.com/mdn/webassembly-examples/"> webassembly-examples </a> para outros exemplos.</li>
+</ul>
+
+<h2 id="Especificações">Especificações</h2>
+
+<table class="standard-table">
+ <thead>
+ <tr>
+ <th scope="col">Especificações</th>
+ <th scope="col">Status</th>
+ <th scope="col">Comentários</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td>{{SpecName('WebAssembly JS')}}</td>
+ <td>{{Spec2('WebAssembly JS')}}</td>
+ <td>Definição inicial do projeto da API do JavaScript.</td>
+ </tr>
+ </tbody>
+</table>
+
+<h2 id="Browser_compatibility" name="Browser_compatibility">Compatibilidade do navegador</h2>
+
+<div>{{CompatibilityTable}}</div>
+
+<div id="compat-desktop">
+<table class="compat-table">
+ <tbody>
+ <tr>
+ <th>Características</th>
+ <th>Chrome</th>
+ <th>Edge</th>
+ <th>Firefox (Gecko)</th>
+ <th>Internet Explorer</th>
+ <th>Opera</th>
+ <th>Safari (WebKit)</th>
+ </tr>
+ <tr>
+ <td>Suporte básico</td>
+ <td>57</td>
+ <td>{{CompatNo}}</td>
+ <td>{{CompatGeckoDesktop(52)}}<sup>[1]</sup></td>
+ <td>{{CompatNo}}</td>
+ <td>{{CompatVersionUnknown}}</td>
+ <td>{{CompatNo}}</td>
+ </tr>
+ </tbody>
+</table>
+</div>
+
+<div id="compat-mobile">
+<table class="compat-table">
+ <tbody>
+ <tr>
+ <th>Características</th>
+ <th>Chrome for Android</th>
+ <th>Android Webview</th>
+ <th>Edge Mobile</th>
+ <th>Firefox Mobile (Gecko)</th>
+ <th>IE Mobile</th>
+ <th>Opera Mobile</th>
+ <th>Safari Mobile</th>
+ </tr>
+ <tr>
+ <td>Suporte básico</td>
+ <td>57</td>
+ <td>57</td>
+ <td>{{CompatNo}}</td>
+ <td>{{CompatGeckoMobile(52)}}<sup>[1]</sup></td>
+ <td>{{CompatNo}}</td>
+ <td>{{CompatNo}}</td>
+ <td>{{CompatNo}}</td>
+ </tr>
+ </tbody>
+</table>
+</div>
+
+<p>[1] O WebAssembly está habilitado no Firefox 52+, embora desativado no <a href="https://www.mozilla.org/en-US/firefox/organizations/"> Firefox 52 estendido versão para suporte</a> (ESR.)</p>
+
+<h2 id="Veja_também">Veja também</h2>
+
+<ul dir="ltr">
+ <li><a href="http://webassembly.org/">webassembly.org</a></li>
+ <li><a href="https://hacks.mozilla.org/category/webassembly/">WebAssembly articles on Mozilla Hacks blog</a></li>
+ <li><a href="https://www.w3.org/community/webassembly/">W3C WebAssembly Community Group</a></li>
+ <li><a href="/en-US/docs/Web/HTTP/Headers/Large-Allocation">Large-Allocation HTTP header</a></li>
+</ul>
diff --git a/files/pt-br/webassembly/usando_a_api_javascript_do_webassembly/index.html b/files/pt-br/webassembly/usando_a_api_javascript_do_webassembly/index.html
new file mode 100644
index 0000000000..e9146bef62
--- /dev/null
+++ b/files/pt-br/webassembly/usando_a_api_javascript_do_webassembly/index.html
@@ -0,0 +1,269 @@
+---
+title: Usando a API JavaScript do WebAssembly
+slug: WebAssembly/Usando_a_API_JavaScript_do_WebAssembly
+tags:
+ - API
+ - Compilador
+ - DevTools
+ - JavaScript
+ - WebAssembly
+ - compilar
+ - memoria
+ - tabela
+translation_of: WebAssembly/Using_the_JavaScript_API
+---
+<div>{{WebAssemblySidebar}}</div>
+
+<p class="summary">Se você já <a href="/en-US/docs/WebAssembly/C_to_wasm">compilou um módulo de outra linguagem utilizando ferramentas como o Emscripten</a>, ou <a href="/en-US/docs/WebAssembly/Loading_and_running">carregou e executou o código sozinho</a>, o próximo passo é aprender mais sobre o uso de outros recursos da API JavaScript do WebAssembly. Este artigo te ensina o que você precisará saber.</p>
+
+<div class="note">
+<p><strong>Nota</strong>: Se você não estiver familiarizado com os conceitos básicos mencionados neste artigo e precisar de mais explicação, leia <a href="/en-US/docs/WebAssembly/Concepts">WebAssembly concepts</a> primeiro, e depois volte aqui.</p>
+</div>
+
+<h2 id="Um_exemplo_simples">Um exemplo simples</h2>
+
+<p>Vamos percorrer o passo a passo de um exemplo que explica como usar a API JavaScript do WebAssembly, e como usá-la para carregar um módulo wasm em uma página web.</p>
+
+<div class="note">
+<p><strong>Nota</strong>: Você pode encontrar o código de exemplo no nosso repositório di GitHub <a href="https://github.com/mdn/webassembly-examples">webassembly-examples</a>.</p>
+</div>
+
+<h3 id="Preparando_o_exemplo">Preparando o exemplo</h3>
+
+<ol>
+ <li>Primeiro precisamos de um módulo wasm! Pegue o nosso arquivo <a href="https://github.com/mdn/webassembly-examples/raw/master/js-api-examples/simple.wasm">simple.wasm</a> e salve uma cópia em um novo diretório em sua máquina local.</li>
+ <li>Depois, tenha certeza de que você está usando um browser com suporte ao WebAssembly. O Firefox 52+ e o Chrome 57+ já vem com WebAssembly habilitado por padrão.</li>
+ <li>Depois, crie um arquivo html simples chamado <code>index.html</code> no mesmo diretório que seu arquivo wasm (você pode usar o nosso <a href="https://github.com/mdn/webassembly-examples/blob/master/template/template.html">template simples</a> caso você não tenha algum por aí).</li>
+ <li>Agora, para ajudar a entender o que está acontecendo aqui, vamos olhar a representação textual do nosso módulo wasm (do qual também encontramos em <a href="/en-US/docs/WebAssembly/Text_format_to_wasm#A_first_look_at_the_text_format">Converting WebAssembly format to wasm</a>):
+ <pre>(module
+ (func $i (import "imports" "imported_func") (param i32))
+ (func (export "exported_func")
+ i32.const 42
+ call $i))</pre>
+ </li>
+ <li>Na segunda linha, você perceberá que o import tem um namespace de dois níveis — a função interna <code>$i</code> que é importada do <code>imports.imported_func</code>. Precisamos refletir esse namespace de dois níveis no JavaScript ao escrever o objeto que será importado no módulo wasm. Crie um elemento <code>&lt;script&gt;&lt;/script&gt;</code> no seu arquivo HTML, e adicione o seguinte código:
+ <pre class="brush: js">var importObject = {
+ imports: {
+ imported_func: function(arg) {
+ console.log(arg);
+ }
+ }
+ };</pre>
+ </li>
+</ol>
+
+<p>Conforme explicado acima, temos nossa função que será importada em <code>imports.imported_func</code>.</p>
+
+<div class="note">
+<p><strong>Nota</strong>: Isto poderia ser mais conciso usando <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">a sintaxe de arrow function do ES6</a>:</p>
+
+<pre class="brush: js">var importObject = { imports: { imported_func: arg =&gt; console.log(arg) } };</pre>
+</div>
+
+<p>O estilo que você preferir fica a sua escolha.</p>
+
+<h3 id="Carregando_e_utilizando_o_nosso_módulo_wasm">Carregando e utilizando o nosso módulo wasm</h3>
+
+<p>Com o objeto que iremos importar preparado, vamos baixar o nosso arquivo wasm, torná-lo disponível em um array buffer, e em seguida fazer uso de sua função exportada.</p>
+
+<p>Adicione o código abaixo no seu script:</p>
+
+<pre class="brush: js">fetch('simple.wasm').then(response =&gt;
+ response.arrayBuffer()
+).then(bytes =&gt;
+ WebAssembly.instantiate(bytes, importObject)
+).then(results =&gt; {
+ results.instance.exports.exported_func();
+});</pre>
+
+<div class="note">
+<p><strong>Nota</strong>: Já explicamos com grandes detalhes como funciona essa síntaxe em <a href="/en-US/docs/WebAssembly/Loading_and_running#Using_Fetch">Loading and running WebAssembly code</a>. Volte lá e se atualize caso não se sinta confortável com o assunto.</p>
+</div>
+
+<p>O resultado liquido disto é que nós chamamos nossa função <code>exported_func</code> exportada pelo WebAssembly, que por sua vez chama a nossa função JavaScript importada <code>imported_func</code>, que mostra no console o valor fornecido (42) dentro da instância do WebAssembly. Se você salvar seu código de exemplo agora e carregá-lo em um browser que suporta WebAssembly, você verá isso em ação!</p>
+
+<div class="note">
+<p><strong>Nota</strong>: O WebAssembly está habilitado por padrão no Firefox 52+, no Chrome 57+ e no Opera mais recente (você também pode executar código wasm no Firefox 47+ habilitando a flag <code>javascript.options.wasm</code> em <em>about:config</em>, ou no Chrome (51+) e no Opera (38+) indo em <em>chrome://flags</em> e habilitando a flag <em>Experimental WebAssembly</em> .)</p>
+</div>
+
+<p>Este exemplo é longo e um pouco complicado que alcança muito pouco, mas serve para mostrar o que é possível — usando código WebAssembly junto com JavaScript em suas aplicações web. Como já dissemos em outro lugar, o WebAssembly não pretende substituir o JavaScript; ambos podem trabalhar juntos, juntando forças.</p>
+
+<h3 id="Visualizando_o_wasm_no_developer_tools">Visualizando o wasm no developer tools</h3>
+
+<p>No Firefox 54+, o painel Debugger do Developer Tool consegue exibir a representação textual do qualquer código wasm inserido em uma página web. Para visualizá-lo, abra o painel Debugger e clique em “xxx &gt; wasm”.</p>
+
+<p><img alt="" src="https://mdn.mozillademos.org/files/14655/wasm-debugger-output.png" style="display: block; height: 354px; margin: 0px auto; width: 1026px;"></p>
+
+<p>Muito em breve no Firefox, além de visualizar o WebAssembly em seu formato textual, os desenvolvedores serão capazes de depurar (colocar breakpoints, inspecionar o callstack, etc.) o WebAssembly utilizando o formato textual. Assista o vídeo  <span class="watch-title" dir="ltr" id="eow-title" title="WebAssembly debugging with Firefox DevTools"><a href="https://www.youtube.com/watch?v=R1WtBkMeGds">WebAssembly debugging with Firefox DevTools</a> </span>para ter uma prévia.</p>
+
+<h2 id="Memória">Memória</h2>
+
+<p>No modelo de memória de baixo nível do WebAssembly, a memória é representada como uma faixa contínua de bytes não tipados chamados de <a href="http://webassembly.org/docs/semantics/#linear-memory">Memória Linear</a> que são lidos e escritos por <a href="http://webassembly.org/docs/semantics/#linear-memory-accesses">instruções de carga e armazenamento</a> dentro do módulo. Neste modelo de memória, qualquer carga ou armazenamento pode acessar qualquer byte na memória linear inteira, o que é necessário para representar fielmente conceitos de C/C++ como ponteiros.</p>
+
+<p>Ao contrário de um programa C/C++ nativo, contudo, onde a coleção de memória disponível se estende por todo o processo, a memória que é acessível por uma instância de WebAssembly em particular se limita a uma única — e potencialmente muito pequena — coleção contida por um objeto do tipo WebAssembly Memory.  Isto possibilita que uma única aplicação web utilize diversas bibliotecas independentes — cada uma das quais estiverem utilizando o WebAssembly internamente — para ter memórias separadas que são totalmente isoladas umas das outras.</p>
+
+<p>In JavaScript, a Memory instance can be thought of as a resizable ArrayBuffer and, just as with ArrayBuffers, a single web app can create many independent Memory objects.  You can create one using the {{jsxref("WebAssembly.Memory()")}} constructor, which takes as arguments an initial size and (optionally) a maximum size.</p>
+
+<p>Let’s start exploring this by looking at a quick example.</p>
+
+<ol>
+ <li>
+ <p>Create another new simple HTML page (copy our <a href="https://github.com/mdn/webassembly-examples/blob/master/template/template.html">simple template</a>) and call it <code>memory.html</code>. Add a <code>&lt;script&gt;&lt;/script&gt;</code> element to the page.</p>
+ </li>
+ <li>
+ <p>Now add the following line to the top of your script, to create a memory instance:</p>
+
+ <pre class="brush: js">var memory = new WebAssembly.Memory({initial:10, maximum:100});</pre>
+
+ <p>The unit of <code>initial</code> and <code>maximum</code> is WebAssembly pages — these are fixed to 64KB in size. This means that the above memory instance has an initial size of 640KB, and a maximum size of 6.4MB.</p>
+
+ <p>WebAssembly memory exposes its bytes by simply providing a buffer getter/setter that returns an ArrayBuffer. For example, to write 42 directly into the first word of linear memory, you can do this:</p>
+
+ <pre class="brush: js">new Uint32Array(memory.buffer)[0] = 42;</pre>
+
+ <p>You can then return the same value using:</p>
+
+ <pre class="brush: js">new Uint32Array(memory.buffer)[0]</pre>
+ </li>
+ <li>
+ <p>Try this now in your demo — save what you’ve added so far, load it in your browser, then try entering the above two lines in your JavaScript console.</p>
+ </li>
+</ol>
+
+<h3 id="Growing_memory">Growing memory</h3>
+
+<p>A memory instance can be grown by calls to {{jsxref("Memory.prototype.grow()")}}, where again the argument is specified in units of WebAssembly pages:</p>
+
+<pre class="brush: js">memory.grow(1);</pre>
+
+<p>If a maximum value was supplied upon creation of the memory instance, attempts to grow past this maximum will throw a {{jsxref("WebAssembly.RangeError")}} exception. The engine takes advantage of this supplied upper-bounds to reserve memory ahead of time, which can make resizing more efficient.</p>
+
+<p>Note: Since an {{domxref("ArrayBuffer")}}’s byteLength is immutable, after a successful {{jsxref("Memory.prototype.grow()")}} operation the buffer getter will return a new ArrayBuffer object (with the new byteLength) and any previous ArrayBuffer objects become “detached”, or disconnected from the underlying memory they previously pointed to.</p>
+
+<p>Just like functions, linear memories can be defined inside a module or imported. Similarly, a module may also optionally export its memory. This means that JavaScript can get access to the memory of a WebAssembly instance either by creating a new <code>WebAssembly.Memory</code> and passing it in as an import or by receiving a Memory export (via <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Instance/exports">Instance.prototype.exports</a></code>).</p>
+
+<h3 id="More_involved_memory_example">More involved memory example</h3>
+
+<p>Let’s make the above assertions clearer by looking at a more involved memory example — a WebAssembly module that sums an array of integers. You can find this at <a href="https://github.com/mdn/webassembly-examples/raw/master/js-api-examples/memory.wasm">memory.wasm.</a></p>
+
+<ol>
+ <li>
+ <p>make a local copy of <code>memory.wasm</code> in the same directory as before.</p>
+
+ <div class="note">
+ <p><strong>Note</strong>: You can see the module’s text representation at <a href="https://github.com/mdn/webassembly-examples/blob/master/js-api-examples/memory.wat">memory.wat</a>.</p>
+ </div>
+ </li>
+ <li>
+ <p>Go back to your <code>memory.html</code> sample file, and fetch, compile, and instantiate your wasm module as before — add the following to the bottom of your script:</p>
+
+ <pre class="brush: js">fetch('memory.wasm').then(response =&gt;
+  response.arrayBuffer()
+).then(bytes =&gt;
+  WebAssembly.instantiate(bytes)
+).then(results =&gt; {
+ // add your code here
+});</pre>
+ </li>
+ <li>
+ <p>Since this module exports its memory, given an Instance of this module called instance we can use an exported function <code>accumulate()</code> to create and populate an input array directly in the module instance’s linear memory (<code>mem</code>). Add the following into your code, where indicated:</p>
+
+ <pre class="brush: js">var i32 = new Uint32Array(results.instance.exports.mem.buffer);
+for (var i = 0; i &lt; 10; i++) {
+  i32[i] = i;
+}
+
+var sum = results.instance.exports.accumulate(0, 10);
+console.log(sum);</pre>
+ </li>
+</ol>
+
+<p>Note how we create the {{domxref("Uint32Array")}} view on the Memory object’s buffer (<code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Memory/buffer">Memory.prototype.buffer</a></code>), not on the Memory itself.</p>
+
+<p>As importações de memória funcionam como importações de função, apenas objetos de memória são passados ​​como valores em vez de funções JavaScript. As importações de memória são úteis por dois motivos:</p>
+
+<ul>
+ <li>Eles permitem que o JavaScript busque e crie o conteúdo inicial da memória antes ou simultaneamente com a compilação do módulo.</li>
+ <li>Eles permitem que um único objeto Memory seja importado por várias instâncias do módulo, o que é um bloco de construção crítico para implementar a vinculação dinâmica no WebAssembly.</li>
+</ul>
+
+<div class="note">
+<p><strong>Note</strong>: You can find our complete demo at <a href="https://github.com/mdn/webassembly-examples/blob/master/js-api-examples/memory.html">memory.html</a> (<a href="https://mdn.github.io/webassembly-examples/js-api-examples/memory.html">see it live also</a>) — this version uses the <code><a href="https://github.com/mdn/webassembly-examples/blob/master/wasm-utils.js">fetchAndInstantiate()</a></code> function.</p>
+</div>
+
+<h2 id="Tables">Tables</h2>
+
+<p>A WebAssembly Table is a resizable typed array of <a href="https://en.wikipedia.org/wiki/Reference_(computer_science)">references</a> that can be accessed by both JavaScript and WebAssembly code.  While Memory provides a resizable typed array of raw bytes, it is unsafe for references to be stored in a Memory since a reference is an engine-trusted value whose bytes must not be read or written directly by content for safety, portability, and stability reasons.</p>
+
+<p>Tables have an element type, which limits the types of reference that can be stored in the table.  In the current iteration of WebAssembly, there is only one type of reference needed by WebAssembly code — functions — and thus only one valid element type.  In future iterations, more element types will be added.</p>
+
+<p>Function references are necessary to compile languages like C/C++ that have function pointers.  In a native implementation of C/C++, a function pointer is represented by the raw address of the function’s code in the process’s virtual address space and so, for the safety reasons mentioned above, cannot be stored directly in linear memory.  Instead, function references are stored in a table and their indexes, which are integers and can be stored in linear memory, are passed around instead.</p>
+
+<p>When the time comes to call a function pointer, the WebAssembly caller supplies the index, which can then be safety bounds checked against the table before indexing and calling the indexed function reference.  Thus, tables are currently a rather low-level primitive used to compile low-level programming language features safely and portably.</p>
+
+<p>Tables can be mutated via <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Table/set">Table.prototype.set()</a></code>, which updates one of the values in a table, and <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Table/grow">Table.prototype.grow()</a></code>, which increases the number of values that can be stored in a table.  This allows the indirectly-callable set of functions to change over time, which is necessary for <a href="http://webassembly.org/docs/dynamic-linking/">dynamic linking techniques</a>.  The mutations are immediately accessible via <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Table/get">Table.prototype.get()</a></code> in JavaScript, and to wasm modules.</p>
+
+<h3 id="A_table_example">A table example</h3>
+
+<p>Let’s looking at an simple table example — a WebAssembly module that creates and exports a table with two elements: element 0 returns 13 and element 1 returns 42. You can find this at <a href="https://github.com/mdn/webassembly-examples/raw/master/js-api-examples/table.wasm">table.wasm</a>.</p>
+
+<ol>
+ <li>
+ <p>Make a local copy of <code>table.wasm</code> in a new directory.</p>
+
+ <div class="note">
+ <p><strong>Note</strong>: You can see the module’s text representation at <a href="https://github.com/mdn/webassembly-examples/blob/master/js-api-examples/table.wat">table.wat</a>.</p>
+ </div>
+ </li>
+ <li>
+ <p>Create a new copy of our <a href="https://github.com/mdn/webassembly-examples/blob/master/template/template.html">HTML template</a> in the same directory and call it <code>table.html</code>.</p>
+ </li>
+ <li>
+ <p>As before, fetch, compile, and instantiate your wasm module — add the following into a {{htmlelement("script")}} element at the bottom of your HTML body:</p>
+
+ <pre class="brush: js">fetch('table.wasm').then(response =&gt;
+  response.arrayBuffer()
+).then(bytes =&gt;
+  WebAssembly.instantiate(bytes)
+).then(results =&gt; {
+ // add your code here
+});</pre>
+ </li>
+ <li>
+ <p>Now let’s access the data in the tables — add the following lines to your code in the indicated place:</p>
+
+ <pre class="brush: js">var tbl = results.instance.exports.tbl;
+console.log(tbl.get(0)());  // 13
+console.log(tbl.get(1)());  // 42</pre>
+ </li>
+</ol>
+
+<p>This code accesses each function reference stored in the table in turn, and instantiates them to print the values they hold to the console — note how each function reference is retrieved with a <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Table/get">Table.prototype.get()</a></code> call, then we add an extra set of parentheses on the end to actually invoke the function.</p>
+
+<div class="note">
+<p><strong>Note</strong>: You can find our complete demo at <a href="https://github.com/mdn/webassembly-examples/blob/master/js-api-examples/table.html">table.html</a> (<a href="https://mdn.github.io/webassembly-examples/js-api-examples/table.html">see it live also</a>) — this version uses the <code><a href="https://github.com/mdn/webassembly-examples/blob/master/wasm-utils.js">fetchAndInstantiate()</a></code> function.</p>
+</div>
+
+<h2 id="Multiplicity">Multiplicity</h2>
+
+<p>Now we’ve demonstrated usage of the main key WebAssembly building blocks, this is a good place to mention the concept of multiplicity. This provides WebAssembly with a multitude of advances in terms of architectural efficiency:</p>
+
+<ul>
+ <li>One module can have N Instances, in the same way that one function literal can produce N closure values.</li>
+ <li>One module instance can use 0–1 memory instances, which provide the "address space" of the instance. Future versions of WebAssembly may allow 0–N memory instances per module instance (see <a href="http://webassembly.org/docs/future-features/#multiple-tables-and-memories">Multiple Tables and Memories</a>).</li>
+ <li>One module instance can use 0–1 table instances — this is the "function address space" of the instance, used to implement C function pointers. Future versions of WebAssembly may allow 0–N table instances per module instance in the future.</li>
+ <li>One memory or table instance can be used by 0–N module instances — these instances all share the same address space, allowing <a href="http://webassembly.org/docs/dynamic-linking">dynamic linking</a>.</li>
+</ul>
+
+<p>You can see multiplicity in action in our Understanding text format article — see the Mutating tables and dynamic linking section (TBD).</p>
+
+<h2 id="Summary">Summary</h2>
+
+<p>This article has taken you through the basics of using the WebAssembly JavaScript API to include a WebAssembly module in a JavaScript context and make use of its functions, and how to use WebAssembly memory and tables in JavaScript. We also touched on the concept of multiplicity.</p>
+
+<h2 id="See_also">See also</h2>
+
+<ul>
+ <li><a href="http://webassembly.org/">webassembly.org</a></li>
+ <li><a href="/en-US/docs/WebAssembly/Concepts">WebAssembly concepts</a></li>
+</ul>