WebAssembly LinkError: WebAssembly.instantiate(): mismatch in shared state of memory, declared = 0, imported = 1

917 views Asked by At

I have a simple c code:

// accumulate.c
int arr[];

int accumulate(int start, int end) { 
   int sum = 0;
   for(int i = start; i < end; i++) {
      sum += arr[i];
   }
   return sum;
}

compile it to wasm:

$  emcc accumulate.c  -O3  -s SIDE_MODULE  -o accumulate.wasm

the following HTML works fine:

<!-- accumulate.html -->
<script>
    const memory = new WebAssembly.Memory({
        initial: 1,
    });

    const importObj = {
        env: {
            memory: memory,
            __memory_base: 0,
            g$arr: () => {}
        }
    };

    (async () => {
        const res = await fetch("accumulate.wasm");
        const wasmFile = await res.arrayBuffer();
        const module = await WebAssembly.compile(wasmFile);
        const instance = await WebAssembly.instantiate(module, importObj);

        const arr = new Uint32Array(memory.buffer);
        for (let i = 0; i < 10; i++) {
            arr[i] = i;
        }

        const sum = instance.exports.accumulate(0, 10);
        console.log("accumulate from 0 to 10: " + sum);
    })();
</script>

However, if I set memory to shared: true:

    const memory = new WebAssembly.Memory({
        initial: 1,
        maximum: 1,
        shared: true
    });

Chrome turns out the error "LinkError: WebAssembly.instantiate(): mismatch in shared state of memory, declared = 0, imported = 1".

1

There are 1 answers

1
tigercosmos On BEST ANSWER

Now I know it is because the wasm's memory needs to be declared as shared. See the issue on Emscripten