From 074785cea106179cb3305637055ab0a009ca74f2 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:42:52 -0500 Subject: initial commit --- files/pt-pt/webassembly/index.html | 115 +++++++++ .../utilizar_api_javascript_webassembly/index.html | 257 +++++++++++++++++++++ 2 files changed, 372 insertions(+) create mode 100644 files/pt-pt/webassembly/index.html create mode 100644 files/pt-pt/webassembly/utilizar_api_javascript_webassembly/index.html (limited to 'files/pt-pt/webassembly') diff --git a/files/pt-pt/webassembly/index.html b/files/pt-pt/webassembly/index.html new file mode 100644 index 0000000000..0f6ead1b6b --- /dev/null +++ b/files/pt-pt/webassembly/index.html @@ -0,0 +1,115 @@ +--- +title: WebAssembly +slug: WebAssembly +tags: + - Landing + - WebAssembly + - wasm +translation_of: WebAssembly +--- +
{{WebAssemblySidebar}}
+ +

WebAssembly é um novo tipo de código que pode ser executado nos navegadores da Web modernos — é uma linguagem de montagem de baixo nível com um formato binário compacto que é executado com desempenho quase nativo e fornece linguagens como C/C++ com um destino de compilação para que possam ser executadas na Web. Este também é projetado para funcionar com JavaScript, permitindo que ambos trabalhem juntos.

+ +

In a Nutshell

+ +

WebAssembly 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.

+ +

WebAssembly is designed to complement and run alongside JavaScript — using the WebAssembly JavaScript APIs, you can load WebAssembly modules into a JavaScript app and share functionality between the two. This allows you to take advantage of WebAssembly's performance and power and JavaScript's expressiveness and flexibility in the same apps, even if you don't know how to write WebAssembly code.

+ +

And what's even better is that it is being developed as a web standard via the W3C WebAssembly Working Group and Community Group with active participation from all major browser vendors.

+ +
+
+

Guias

+ +
+
WebAssembly concepts
+
Get started by reading the high-level concepts behind WebAssembly — what it is, why it is so useful, how it fits into the web platform (and beyond), and how to use it.
+
Compiling a New C/C++ Module to WebAssembly
+
When you’ve written code in C/C++, you can then compile it into .wasm using a tool like Emscripten. Let’s look at how it works.
+
Compiling an Existing C Module to WebAssembly
+
A core use-case for WebAssembly is to take the existing ecosystem of C libraries and allow developers to use them on the web.
+
Loading and running WebAssembly code
+
After you have a .wasm, this article covers how to fetch, compile and instantiate it, combining the WebAssembly JavaScript API with the Fetch or XHR APIs.
+
Using the WebAssembly JavaScript API
+
Once you've loaded a .wasm module, you'll want to use it. In this article we show you how to use WebAssembly via the WebAssembly JavaScript API.
+
Exported WebAssembly functions
+
Exported WebAssembly functions are the JavaScript reflections of WebAssembly functions which allow calling WebAssembly code from JavaScript. This article describes what they are.
+
Understanding WebAssembly text format
+
This article explains the wasm text format. This is the low-level textual representation of a .wasm module shown in browser developer tools when debugging.
+
Converting WebAssembly text format to wasm
+
This article provides a guide on how to convert a WebAssembly module written in the text format into a .wasm binary.
+
+
+ +
+

Referência de API

+ +
+
{{jsxref("Global_objects/WebAssembly", "WebAssembly")}}
+
This object acts as the namespace for all WebAssembly related functionality.
+
{{jsxref("Global_objects/WebAssembly/Module", "WebAssembly.Module()")}}
+
A WebAssembly.Module object contains stateless WebAssembly code that has already been compiled by the browser and can be efficiently shared with Workers, and instantiated multiple times.
+
{{jsxref("Global_objects/WebAssembly/Instance", "WebAssembly.Instance()")}}
+
A WebAssembly.Instance object is a stateful, executable instance of a ModuleInstance objects contain all the Exported WebAssembly functions that allow calling into WebAssembly code from JavaScript.
+
{{jsxref("Global_objects/WebAssembly/instantiateStreaming", "WebAssembly.instantiateStreaming()")}}
+
The WebAssembly.instantiateStreaming() function is the primary API for compiling and instantiating WebAssembly code, returning both a Module and its first Instance.
+
{{jsxref("Global_objects/WebAssembly/Memory", "WebAssembly.Memory()")}}
+
A WebAssembly.Memory object is a resizable {{jsxref("Global_objects/ArrayBuffer", "ArrayBuffer")}} that holds the raw bytes of memory accessed by an Instance.
+
{{jsxref("Global_objects/WebAssembly/Table", "WebAssembly.Table()")}}
+
A WebAssembly.Table object is a resizable typed array of opaque values, like function references, that are accessed by an Instance.
+
{{jsxref("WebAssembly.CompileError()")}}
+
Creates a new WebAssembly CompileError object.
+
{{jsxref("WebAssembly.LinkError()")}}
+
Creates a new WebAssembly LinkError object.
+
{{jsxref("WebAssembly.RuntimeError()")}}
+
Creates a new WebAssembly RuntimeError object.
+
+
+
+ +

Exemplos

+ + + +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('WebAssembly JS')}}{{Spec2('WebAssembly JS')}}Initial draft definition of the JavaScript API.
+ +

Compatibilidade de navegador

+ +
+ + +

{{Compat("javascript.builtins.WebAssembly")}}

+
+ +

Consultar também

+ + diff --git a/files/pt-pt/webassembly/utilizar_api_javascript_webassembly/index.html b/files/pt-pt/webassembly/utilizar_api_javascript_webassembly/index.html new file mode 100644 index 0000000000..d3fee6bffb --- /dev/null +++ b/files/pt-pt/webassembly/utilizar_api_javascript_webassembly/index.html @@ -0,0 +1,257 @@ +--- +title: Utilizar a WebAssembly JavaScript API +slug: WebAssembly/Utilizar_API_JavaScript_WebAssembly +tags: + - API + - Ferramentas de Desenvolvimento + - JavaScript + - WebAssembley + - compilar + - instantiate + - memoria + - tabela +translation_of: WebAssembly/Using_the_JavaScript_API +--- +
{{WebAssemblySidebar}}
+ +

Se já compilou um módulo a partir de outra linguagem utilziando as ferramentas, tal como Emscripten, ou carregou e executou o código por si mesmo, o passo seguinte é saber mais sobre como utilizar as outras funcionaldiades da WebAssembly JavaScript API. Este artigo ensina-lhe o que precisa de saber.

+ +
+

Nota: If you are unfamiliar with the basic concepts mentioned in this article and need more explanation, read WebAssembly concepts first, then come back.

+
+ +

Alguns exemplos simples

+ +

Let’s run through some examples that explain how to use the WebAssembly JavaScript API, and how to use it to load a wasm module in a web page.

+ +
+

Nota: You can find the sample code in our webassembly-examples GitHub repo.

+
+ +

Preparar o exemplo

+ +
    +
  1. First we need a wasm module! Grab our simple.wasm file and save a copy in a new directory on your local machine.
  2. +
  3. Next, let’s create a simple HTML file called index.html in the same directory as your wasm file (can use our simple template if you haven’t got one easily available).
  4. +
  5. Now, to help us understand what is going on here, let’s look at the text representation of our wasm module (which we also meet in Converting WebAssembly format to wasm): +
    (module
    +  (func $i (import "imports" "imported_func") (param i32))
    +  (func (export "exported_func")
    +    i32.const 42
    +    call $i))
    +
  6. +
  7. In the second line, you will see that the import has a two-level namespace — the internal function $i is imported from imports.imported_func. We need to reflect this two-level namespace in JavaScript when writing the object to be imported into the wasm module. Create a <script></script> element in your HTML file, and add the following code to it: +
    var importObject = {
    +  imports: { imported_func: arg => console.log(arg) }
    +};
    +
  8. +
+ +

Transmitir o módulo WebAssembly

+ +

New in Firefox 58 is the ability to compile and instantiate WebAssembly modules directly from underlying sources. This is achieved using the {{jsxref("WebAssembly.compileStreaming()")}} and {{jsxref("WebAssembly.instantiateStreaming()")}} methods. These methods are easier than their non-streaming counterparts, because they can turn the byte code directly into Module/Instance instances, cutting out the need to separately put the {{domxref("Response")}} into an {{domxref("ArrayBuffer")}}.

+ +

This example (see our instantiate-streaming.html demo on GitHub, and view it live also) shows how to use instantiateStreaming() to fetch a wasm module, import a JavaScript function into it, compile and instantiate it, and access its exported function — all in one step.

+ +

Add the following to your script, below the first block:

+ +
WebAssembly.instantiateStreaming(fetch('simple.wasm'), importObject)
+.then(obj => obj.instance.exports.exported_func());
+ +

The net result of this is that we call our exported WebAssembly function exported_func, which in turn calls our imported JavaScript function imported_func, which logs the value provided inside the WebAssembly instance (42) to the console. If you save your example code now and load it a browser that supports WebAssembly, you’ll see this in action!

+ +
+

Nota: This is a convoluted, longwinded example that achieves very little, but it does serve to illustrate what is possible — using WebAssembly code alongside JavaScript in your web applications. As we’ve said elsewhere, WebAssembly doesn’t aim to replace JavaScript; the two instead can work together, drawing on each other’s strengths.

+
+ +

Carregar o nosso módulo wasm sem transmitir

+ +

If you can't or don't want to use the streaming methods as described above, you can use the non-streaming methods {{jsxref("WebAssembly.compile")}} / {{jsxref("WebAssembly.instantiate")}} instead.

+ +

These methods don't directly access the byte code, so require an extra step to turn the response into an {{domxref("ArrayBuffer")}} before compiling/instantiating the wasm module.

+ +

The equivalent code would look like this:

+ +
fetch('simple.wasm').then(response =>
+  response.arrayBuffer()
+).then(bytes =>
+  WebAssembly.instantiate(bytes, importObject)
+).then(results => {
+  results.instance.exports.exported_func();
+});
+ +

Visualização de wasm nas ferramentas do programador

+ +

In Firefox 54+, the Developer Tool Debugger Panel has functionality to expose the text representation of any wasm code included in a web page. To view it, you can go to the Debugger Panel and click on the “wasm://” entry.

+ +

+ +

Starting soon in Firefox, in addition to viewing WebAssembly as text, developers will be able to debug (place breakpoints, inspect the callstack, single-step, etc.) WebAssembly using the text format. See WebAssembly debugging with Firefox DevTools for a video preview.

+ +

Memória

+ +

In the low-level memory model of WebAssembly, memory is represented as a contiguous range of untyped bytes called Linear Memory that are read and written by load and store instructions inside the module.  In this memory model, any load or store can access any byte in the entire linear memory, which is necessary to faithfully represent C/C++ concepts like pointers.

+ +

Unlike a native C/C++ program, however, where the available memory range spans the entire process, the memory accessible by a particular WebAssembly Instance is confined to one specific — potentially very small — range contained by a WebAssembly Memory object.  This allows a single web app to use multiple independent libraries — each of which are using WebAssembly internally — to have separate memories that are fully isolated from each other.

+ +

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.

+ +

Let’s start exploring this by looking at a quick example.

+ +
    +
  1. +

    Create another new simple HTML page (copy our simple template) and call it memory.html. Add a <script></script> element to the page.

    +
  2. +
  3. +

    Now add the following line to the top of your script, to create a memory instance:

    + +
    var memory = new WebAssembly.Memory({initial:10, maximum:100});
    + +

    The unit of initial and maximum 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.

    + +

    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:

    + +
    new Uint32Array(memory.buffer)[0] = 42;
    + +

    You can then return the same value using:

    + +
    new Uint32Array(memory.buffer)[0]
    +
  4. +
  5. +

    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.

    +
  6. +
+ +

Aumento de memória

+ +

A memory instance can be grown by calls to {{jsxref("Memory.prototype.grow()")}}, where again the argument is specified in units of WebAssembly pages:

+ +
memory.grow(1);
+ +

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.

+ +

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.

+ +

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 WebAssembly.Memory and passing it in as an import or by receiving a Memory export (via Instance.prototype.exports).

+ +

Exemplo de memória mais envolvida

+ +

Let’s make the above assertions clearer by looking at a more involved memory example — a WebAssembly module that imports the memory instance we defined earlier, populates it with an array of integers, then sums them. You can find this at memory.wasm.

+ +
    +
  1. +

    make a local copy of memory.wasm in the same directory as before.

    + +
    +

    Nota: You can see the module’s text representation at memory.wat.

    +
    +
  2. +
  3. +

    Go back to your memory.html sample file, and fetch, compile, and instantiate your wasm module as before — add the following to the bottom of your script:

    + +
    WebAssembly.instantiateStreaming(fetch('memory.wasm'), { js: { mem: memory } })
    +.then(obj => {
    +  // add code here
    +});
    +
  4. +
  5. +

    Since this module exports its memory, given an Instance of this module called instance we can use an exported function accumulate() to create and populate an input array directly in the module instance’s linear memory (mem). Add the following into your code, where indicated:

    + +
    var i32 = new Uint32Array(memory.buffer);
    +
    +for (var i = 0; i < 10; i++) {
    +  i32[i] = i;
    +}
    +
    +var sum = results.instance.exports.accumulate(0, 10);
    +console.log(sum);
    +
  6. +
+ +

Note how we create the {{domxref("Uint32Array")}} view on the Memory object’s buffer (Memory.prototype.buffer), not on the Memory itself.

+ +

Memory imports work just like function imports, only Memory objects are passed as values instead of JavaScript functions. Memory imports are useful for two reasons:

+ + + +
+

Nota: You can find our complete demo at memory.html (see it live also) — this version uses the fetchAndInstantiate() function.

+
+ +

Tabelas

+ +

A WebAssembly Table is a resizable typed array of references 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.

+ +

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.

+ +

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.

+ +

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.

+ +

Tables can be mutated via Table.prototype.set(), which updates one of the values in a table, and Table.prototype.grow(), 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 dynamic linking techniques.  The mutations are immediately accessible via Table.prototype.get() in JavaScript, and to wasm modules.

+ +

Um exemplo de tabela

+ +

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 table.wasm.

+ +
    +
  1. +

    Make a local copy of table.wasm in a new directory.

    + +
    +

    Nota: You can see the module’s text representation at table.wat.

    +
    +
  2. +
  3. +

    Create a new copy of our HTML template in the same directory and call it table.html.

    +
  4. +
  5. +

    As before, fetch, compile, and instantiate your wasm module — add the following into a {{htmlelement("script")}} element at the bottom of your HTML body:

    + +
    WebAssembly.instantiateStreaming(fetch('table.wasm'))
    +.then(function(obj) {
    +  // add code here
    +});
    +
  6. +
  7. +

    Now let’s access the data in the tables — add the following lines to your code in the indicated place:

    + +
    var tbl = results.instance.exports.tbl;
    +console.log(tbl.get(0)());  // 13
    +console.log(tbl.get(1)());  // 42
    +
  8. +
+ +

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 Table.prototype.get() call, then we add an extra set of parentheses on the end to actually invoke the function.

+ +
+

Nota: You can find our complete demo at table.html (see it live also) — this version uses the fetchAndInstantiate() function.

+
+ +

Multiplicidade

+ +

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:

+ + + +

You can see multiplicity in action in our Understanding text format article — see the Mutating tables and dynamic linking section.

+ +

Resumo

+ +

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.

+ +

Consultar também

+ + -- cgit v1.2.3-54-g00ecf