美文网首页
2019-07-31 WebAssembly调试

2019-07-31 WebAssembly调试

作者: oracle3 | 来源:发表于2019-07-31 18:58 被阅读0次

参考文章走近 WebAssembly 之调试大法调试wasm过程中有些错误,这里记录一下,可能是作者使用的emsdk版本太低导致

错误1:Uncaught (in promise) LinkError: WebAssembly Instantiation: Import #1 module="env" function="__memory_base" error: global import must be a number or WebAssembly.Global object

参考文章Cannot instantiate WebAssembly #11
So I found out the reason. With later version of emcc replace memoryBase with __memory_base and tableBase with __table_base
修改debug.html 如下:

<html>
<head>
  <script>
    // 下面这些配置是作为wasm初始化用的,去掉某一个会报错。
    const importObj = {
        env: {
            'memory': new WebAssembly.Memory({initial: 256, maximum: 256}),
            '__memory_base': 0,
            'tableBase': 0,
            'table': new WebAssembly.Table({initial: 10, element: 'anyfunc'}),
            abort:alert
        }
    };
 
  // 直接使用  WebAssembly.instantiateStream的方式会报错,说是 debug.wasm 资源不是 application/wasm 格式s.
  fetch('./debug.wasm').then(response =>
    response.arrayBuffer()
  ).then(bytes => WebAssembly.instantiate(bytes,importObj)).then(results => {
    instance = results.instance;
    var sumOfSquare= instance.exports._sumOfSquare;  //注意这里导出的方法名前有下划线!!
 
     var button = document.getElementById('run');
     button.addEventListener('click', function() {
          var input1 = 3;
          var input2 = 4;
          alert('sumOfSquare('+input1+','+input2+')='+sumOfSquare(input1,input2));
     }, false);
  });
 
  </script>
</head>
<body>
  <input type="button" id="run" value="click"/>
</body>
</html>

错误2:Uncaught TypeError: sumOfSquare is not a function

at HTMLInputElement.<anonymous> (debug.htm:26)

这里说找不到导出的函数sumOfSquare,反编译wasm看:

wasm2wat debug.wasm

显示:

(module
  (type (;0;) (func))
  (import "env" "__memory_base" (global (;0;) i32))
  (func (;0;) (type 0)
    global.get 0
    global.set 1
    global.get 1
    i32.const 5242880
    i32.add
    global.set 2)
  (global (;1;) (mut i32) (i32.const 0))
  (global (;2;) (mut i32) (i32.const 0))
  (export "__post_instantiate" (func 0)))

确实没有导出函数sumOfSquare,参考文章编译 C/C++ 为 WebAssembly
默认情况下,Emscripten 生成的代码只会调用 main() 函数,其它的函数将被视为无用代码。在一个函数名之前添加 EMSCRIPTEN_KEEPALIVE 能够防止这样的事情发生。你需要导入 emscripten.h 库来使用 EMSCRIPTEN_KEEPALIVE。
修改debug.c:

#include <emscripten/emscripten.h>

int EMSCRIPTEN_KEEPALIVE sumOfSquare(int a,int b){
    int t1=a*a;
    int t2=b*b;
    return t1+t2;
}

错误3:c语言无法调试

这个实在没办法,chrome和Firefox都不行

相关文章

网友评论

      本文标题:2019-07-31 WebAssembly调试

      本文链接:https://www.haomeiwen.com/subject/tlfxdctx.html