WebAssembly - Validation


Advertisements

In this chapter, we are going to discuss the webassembly.validate() function that will validate the .wasm output. The .wasm is available when we compile C, C++ or rust code.

You can make use of the following tools to get the wasm code.

Syntax

The syntax is as given below −

WebAssembly.validate(bufferSource);

Parameters

bufferSource − The bufferSource has the binary code that comes from either C, C++ or Rust program. It is in the form of typedarray or ArrayBuffer.

Return Value

The function will return true if the .wasm code is valid and false if not.

Let us try one example. Go to Wasm fiddler, which is available at https://wasdk.github.io/WasmFiddle/, enter C code of your choice and down the wasm code.

Buffer Source

The block marked in red is the C code. Click on the Build button at the center to execute the code.

Validating

Click on the Wasm , button to download the .wasm code. Save the .wasm at your end and let us use the same for validating.

Example

For Example: validate.html

<!doctype html>
<html>
   <head> 
      <meta charset="utf-8">
      <title>Testing WASM validate()</title>
   </head>
   <body>
      <script> 
         fetch('program.wasm').then(res => res.arrayBuffer() ).then(function(testbytes) {
         var valid = WebAssembly.validate(testbytes); 
            if (valid) {
               console.log("Valid Wasm Bytes!"); 
            } else {
               console.log("Invalid Wasm Code!"); 
            }
         }); 
      </script> 
   </body>
</html>

I have hosted the above .html file in wamp server along with the download .wasm file. Here, is the output when you test it in the browser.

Output

The output is the mentioned below −

Mentioned
Advertisements