Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CompileError: WebAssembly.compile(): expected magic word

I'm new to WebAssembly and trying to get a basic example working, but loading the .wasm file in Google Chrome returns:

CompileError: WebAssembly.compile(): expected magic word 00 61 73 6d, found 30 30 36 31 @+0

This is the C++ code:

#include <iostream>
using namespace std;

int main() 
{
    cout << "Hello, World!";
    return 0;
}

And this is the WASM file: https://drive.google.com/open?id=1nvoxoeZ6TA9OVc4JFHSwGIVxuDHFnIU1

Code that I'm executing in Chrome, based on documentation:

function instantiate(bytes, imports) {
  return WebAssembly.compile(bytes).then(function(m) {
      return new WebAssembly.Instance(m, imports)
  });
}

fetch('simple.wasm').then(function(response) {
    return response.arrayBuffer()
})
.then(function(bytes) {
    var importObject = {
        imports: {
            i: function(arg) {
                console.log(arg)
            }
        }
    };
    return instantiate(bytes, importObject)
})
.then(function(instance) {
    return instance.exports.e()
})
like image 977
Valip Avatar asked Aug 08 '26 16:08

Valip


1 Answers

The problem is that your .wasm file is in hex format instead of binary.

You should probably check your compile flags, but you can also convert it back from hex with something like this:

 fetch('simple.wasm').then(function(response) {
     return response.arrayBuffer()
 })
-.then(function(bytes) {
+.then(function(buffer) {
+    const bytes = fromHex(buffer);
     var importObject = {
         imports: {
             i: function(arg) {
function fromHex(hexBuffer) {
    const hexBytes = new Uint8Array(hexBuffer);
    if (hexBytes.length % 2 !== 0)
        throw new Error("Hex buffer must have an even length.");
    const result = new Uint8Array(hexBytes.length / 2);

    function fromAscii(char) {
        if (char < 0x30 || (char > 0x39 && char < 0x41) || (char > 0x46 && char < 0x61) || char > 0x66)
            throw new Error("Invalid hex character: " + String.fromCharCode(char));

        /* '0'..'9'           -> 0..9
           'A'..'F', 'a'..'f' -> 1..6 */
        const result = char & 0xF;
        /* 'A'..'F', 'a'..'f' -> 10..15 */
        return char & 0x40 ? result + 9 : result;
    }

    for (let i = 0, j = 0; i < result.length; i++, j+=2) {
        result[i] = (fromAscii(hexBytes[j]) << 4) |
                     fromAscii(hexBytes[j + 1]);
    }
    return result;
}
like image 190
Peter Mudrievskij Avatar answered Aug 10 '26 13:08

Peter Mudrievskij



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!