WebAssembly – Javascript API

WebAssembly – JavaScript API ”; Previous Next In this chapter, we will understand how to load the wasm code and execute them in the browser using the help of javascript webassembly API. Here are some important API”s, we are going to make use throughout the tutorial to execute wasm code. fetch() Browser API WebAssembly.compile WebAssembly.instance WebAssembly.instantiate WebAssembly.instantiateStreaming Before we discuss the WebAssembly javascript API”s, to test the API and the output we are going to use the following C program and the .wasm code generated from the c program using wasm explorer. An example for C Program is as follows − #include<stdio.h> int square(int n) { return n*n; } We will make use of WASM explorer, to get the wasm code − Download WASM code and use it to test the API”s. fetch() Browser API fetch() API is meant to load .wasm network resource. <script> var result = fetch(“findsquare.wasm”); console.log(result); </script> It returns a promise as shown below − You can also make use of XMLHttpRequest method to fetch the wasm network resource. WebAssembly.compile() The api responsibility is to compile the module details that are fetched from .wasm. Syntax The syntax is as given below − WebAssembly.compile(buffer); Parameters Buffer − This code from .wasm has to be converted to a typed array or arraybuffer, before giving as input to compile. Return value It will return a promise that will have the compiled module. Example Let us see one example, that gives the output as a compiled module using webAssembly.compile(). <script> fetch(“findsquare.wasm”) .then(bytes => bytes.arrayBuffer()) .then(mod => { var compiledmod = WebAssembly.compile(mod); compiledmod.then(test=> { console.log(test); }) }) &lt/script> Output The console.log, when checked in the browser, will give you the compiled module details − The module has a constructor object with imports, exports, and customSections. Let us see the next API, to get more details of the compiled module. WebAssembly.instance Using the WebAssembly.instance, API will give you the executable instance of the compiled module that can be further executed to get the output. Syntax The syntax is as given below − new WebAssembly.Instance(compiled module) Return value The return value will be an object with the array of exports function that can be executed. Example <script> fetch(“findsquare.wasm”) .then(bytes => bytes.arrayBuffer()) .then(mod => WebAssembly.compile(mod)).then(module => { let instance = new WebAssembly.Instance(module); console.log(instance); }) </script> Output The output will give us an array of exports function as shown below − You can see the square function, that we got from the C code that is compiled. To execute the square function, you can do the following − <script> fetch(“findsquare.wasm”) .then(bytes => bytes.arrayBuffer()) .then(mod => WebAssembly.compile(mod)) .then(module => { let instance = new WebAssembly.Instance(module); console.log(instance.exports.square(15)); }) </script> The output will be − 225 WebAssembly.instantiate This API takes care of compiling and instantiating the module together. Syntax The syntax is as follows − WebAssembly.instantiate(arraybuffer, importObject) Parameters arraybuffer − The code from .wasm has to be converted to typed array or arraybuffer before giving as input to instantiate. importObject − The import object has to have details of the memory, imported functions to be used inside the module. It can be an empty module object, in case, there is nothing to be shared. Return value It will return a promise, that will have module and instance details. Example <script type=”text/javascript”> const importObj = { module: {} }; fetch(“findsquare.wasm”) .then(bytes => bytes.arrayBuffer()) .then(module => WebAssembly.instantiate(module, importObj)) .then(finalcode => { console.log(finalcode); console.log(finalcode.instance.exports.square(25)); }); </script> Output When you execute the code, you will get the below mentioned output. WebAssembly.instantiateStreaming This API takes care of compiling as well as instantiating the WebAssembly module from the .wasm code given. Syntax The syntax is as given below − WebAssembly.instantiateStreaming(wasmcode, importObject); Parameters wasmcode − Response from fetch or any other API that gives the wasm code and returns a promise. importObject − The import object has to have details of the memory, imported functions to be used inside the module. It can be an empty module object in case there is nothing to be shared. Return Value It will return a promise, that will have module and instance details. Example An example is discussed below − <script type=”text/javascript”> const importObj = { module: {} }; WebAssembly.instantiateStreaming(fetch(“findsquare.wasm”), importObj).then(obj => { console.log(obj); }); </script> When you test it in the browser, you will see an error − To make it work at your server end, you will have to add the mime type application/wasm or else make use of WebAssembly.instantiate(arraybuffer, importObject). Print Page Previous Next Advertisements ”;

WebAssembly – Program Structure

WebAssembly – Program Structure ”; Previous Next WebAssembly, also called WASM, is binary format low level code developed to be executed inside browsers in the most efficient way. WebAssembly code is structured with following concepts − Values Types Instructions Let us learn them in detail now. Values Values in WebAssembly are meant to store complex data such as text, strings and vectors. WebAssembly supports the following − Bytes Integers Floating point Names Bytes Bytes is the simplest form of values supported in WebAssembly. The value is in hexadecimal format. For example Bytes represented as b, can also take natural numbers n, where n <256. byte ::= 0x00| …. |0xFF Integers In WebAssembly, integers supported are as given below − i32: 32-bit integer i64: 64-bit integer Floating Point In WebAssembly floating point numbers supported are as follows − f32: 32-bit floating point f64: 64-bit floating point Names Names are sequence of character, with scalar values defined by Unicode, which is available at the link http://www.unicode.org/versions/Unicode12.1.0/ given herewith. Types The entities in WebAssembly are classified as types. The types supported are as stated below − Value Types Result Types Function Types Limits Memory Types Table Types Global Types External Types Let us study them one by one. Value Types The values type supported by WebAssembly are as mentioned below − i32: 32-bit integer i64: 64-bit integer f32: 32-bit floating point f64: 64-bit floating point valtype ::= i32|i64|f32|f64 Result Types The values written inside brackets are executed and stored inside result types. The result type is the output of the execution of a block of code made up of values. resulttype::=[valtype?] Function Types A function type will take in vector of parameters returns a vector of results. functype::=[vec(valtype)]–> [vec(valtype)] Limits Limits are the storage range linked with memory and table types. limits ::= {min u32, max u32} Memory Types Memory types deal with linear memories and the size range. memtype ::= limits Table Types Table Types are classified by the element type assigned to it. tabletype ::= limits elemtype elemtype ::= funcref Table type is dependent on the limit for the minimum and maximum size assigned to it. Global Types Global Type holds the global variables that have the value, that can change or remain the same. globaltype ::= mut valtype mut ::= const|var External Types External Types deals with imports and external values. externtype ::= func functype | table tabletype | mem memtype | global globaltype Instructions WebAssembly code is a sequence of instructions that follows a stack machine model. As WebAssembly follows a stack machine model, the instructions are pushed on the stack. The argument values for a function, for example, are popped from stack and the result is pushed back on the stack. In the end, there will be only one value in the stack and that is the result. Some of the commonly used Instructions are as follows − Numeric Instructions Variable Instructions Numeric Instructions Numeric Instructions are operations, which are performed on numeric value. For example nn, mm ::= 32|64 ibinop ::= add|sub|mul|div_sx|rem_sx|and|or|xor irelop ::= eq | ne | lt_sx | gt_sx | le_sx | ge_sx frelop ::= eq | ne | lt | gt | le | ge Variable Instructions Variable instructions are about accessing the local and global variables. For example To access local variables − get_local $a get_local $b To set local variables − set_local $a set_local $b To access global variables − get_global $a get_global $b To set global variables − set_global $a set_global $b Print Page Previous Next Advertisements ”;

WebAssembly – Home

WebAssembly Tutorial PDF Version Quick Guide Resources Job Search Discussion WebAssembly is a new programming language for the web. WebAssembly code is low level binary format, that is compatible with the web and can easily run in modern web browsers. The file size generated is small and it loads and executes faster. You can now compile languages like C, C++, Rust, etc. to binary format and it can run on the web just like javascript. Audience This tutorial is designed for software programmers who want to learn the basics of WebAssembly and its programming concepts in simple and easy ways. It will give you enough understanding on various functionalities of Requests library with suitable examples. Prerequisites Before proceeding with this tutorial, you should have a basic understanding of Javascript, and any one of the high level language like C, C++, Rust and Go. Print Page Previous Next Advertisements ”;

WebAssembly – Debugging WASM in Firefox

WebAssembly – Debugging WASM in Firefox ”; Previous Next WebAssembly support is added to all the latest browsers available with you today like Chrome, Firefox. The Firefox version 54+ onwards gives you a special feature to debug your wasm code. To do that, execute your code inside Firefox browsers that call wasm. For example, consider following C code that finds the square of the number. An example for the C Program is as follows − #include<stdio.h> int square(int n) { return n*n; } We will make use of WASM explorer to get the wasm code − Download WASM code and use it to see the output in the browser. The html file that loads the wasm is as follows − !doctype html> <html> <head> <meta charset=”utf-8″> <title>WebAssembly Square function</title> <style> div { font-size : 30px; text-align : center; color:orange; } </style> </head> <body> <div id=”textcontent”></div> <script> let square; fetch(“findsquare.wasm”).then(bytes => bytes.arrayBuffer()) .then(mod => WebAssembly.compile(mod)) .then(module => {return new WebAssembly.Instance(module) }) .then(instance => { square = instance.exports.square(13); console.log(“The square of 13 = ” +square); document.getElementById(“textcontent”).innerHTML = “The square of 13 = ” +square; }); </script> </body> </html> Open your Firefox browser and load the above html file and open the debugger tool. You should see wasm:// entry in the debugger tool. Click on wasm:// and it shows the wasm code converted to .wat format as shown above. You can take a look at the code of the exported function and can debug the code, if any issue comes up. Firefox also intends to add breakpoints, so that you can debug the code and check the execution flow. Print Page Previous Next Advertisements ”;

WebAssembly – Overview

WebAssembly – Overview ”; Previous Next WebAssembly is a new computer programming language for the web. WebAssembly code is a low level binary format, that is compatible with the web and can easily run in modern web browsers. The file size generated is small and it loads and executes faster. You can now compile languages like C, C++, Rust, etc. to binary format and it can run on the web just like javascript. Definition of WebAssembly As per the official website of WebAssembly, which is available at https://webassembly.org/, it is defined as WebAssembly (abbreviated as Wasm) is a binary instruction format for a stack-based virtual machine. Wasm is designed as a portable target for compilation of high-level languages like C/C++/Rust, enabling deployment on the web for client and server applications. Web Assembly is not something that a developer will have to write, but the code is written in languages like C, C++, Rust and can be compiled to WebAssembly (wasm). The same code can be run inside the web browsers. Web Assembly is a new language, the code is low-level assembly language, but with its text format feature, the code is readable and debugging is possible, if necessary. Goals of WebAssembly The open standards for WebAssembly are developed in a W3C Community Group that includes representatives from all major browsers as well as a W3C Working Group. The main goals of WebAssembly are mentioned below − Faster, Efficient and Portable − WebAssembly code is meant to run faster on different platforms taking advantage of the hardware available. Easy to read and debug − WebAssembly, being a low level assembly language, has text format support, that allows you to debug the code for any issues and also to rewrite the code, if necessary. Security − WebAssembly is safe to run on the web browsers, as it takes care of permissions and same-origin policies. Advantages of WebAssembly The following are the advantages of WebAssembly − Run is Modern Browsers − WebAssembly is able to execute without any issues on the modern web browsers which are available. Multiple Language support − Languages like C, C++, Rust, Go can now compile the code to WebAssembly and run the same in web browsers. So, the languages which were not able to run in a browser will now be able to do so. Faster, Efficient and Portable − Due to the small size of the code, it loads and executes faster. Easy to understand − Developers don’t have to do much stress in understanding WebAssembly coding, as they don’t have to write the code in WebAssembly. Instead compile the code in WebAssembly and execute the same on the web. Easy to Debug − Though the final code is in low level assembly language, you can also get it in text format, that is easy to read and debug. Disadvantages of WebAssembly The following are the disadvantages of WebAssembly − WebAssembly is still being worked on and it is too early to decide the future of it. WebAssembly is dependent on javascript to interact with the Document Object Model (DOM). Print Page Previous Next Advertisements ”;