WebAssembly Setup Issue (LinkError)



  • I compiled the code from https://docs.screeps.com/modules.html#Build-wasm-file and tried to run it in the simulation.

    Here is my "main" (Copy and pasted from the tutorial):

    module.exports.loop = function () {
    
        // This will return an ArrayBuffer with `addTwo.wasm` binary contents
        const bytecode = require('addTwo');
    
        const wasmModule = new WebAssembly.Module(bytecode);
    
        const imports = {};
    
        // Some predefined environment for Emscripten. See here:
        // https://github.com/WebAssembly/tool-conventions/blob/master/DynamicLinking.md
        imports.env = {
            memoryBase: 0,
            tableBase: 0,
            memory: new WebAssembly.Memory({ initial: 256 }),
            table: new WebAssembly.Table({ initial: 0, element: 'anyfunc' })    
        };
    
        const wasmInstance = new WebAssembly.Instance(wasmModule, imports);
    
        console.log(wasmInstance.exports._addTwo(2,3));
    }
    

    My wasm file is uploaded as the module "addTwo", here is the addTwo.c file i compiled:

    int addTwo(int a, int b) {
        return a + b;
    }
    

    The compile command was:

    emcc -s WASM=1 -s SIDE_MODULE=1 -O3 addTwo.c -o addTwo.wasm
    

    When I run the code the console outputs:

    LinkError: WebAssembly Instantiation: table import 0 is smaller than initial 2, got 0
        at Object.module.exports.loop:20:26
        at __mainLoop:1:15733
        at eval:2:4
        at Object.r.run:2:144134
    

    Does anyone know how to fix this issue?



  • I also get this issue when I run the same example code. I have emcc v1.38.12

    I was able to look at the required imports of the wasm module to see what was missing:

    const wasmModule = new WebAssembly.Module(bytecode);
    console.log("imports", WebAssembly.Module.imports(wasmModule));
    

    This output:

    imports [ { module: 'env', name: 'table', kind: 'table' },
      { module: 'env', name: 'memoryBase', kind: 'global' },
      { module: 'env', name: 'tableBase', kind: 'global' },
      { module: 'env', name: 'abort', kind: 'function' } ]
    

    So perhaps it needs an abort function to be defined.

    I added a new member to imports.env:

    abort: _ => { throw new Error('abort');},
    

    I think that needed to be done, but it wasn't the problem, it turns out that WebAssemblyTable needs to have initial set to 2 instead of 0.

    table: new WebAssembly.Table({ initial: 2, element: 'anyfunc' })