// 迭代方法 intfibonacci_iterative(int n) { if (n <= 1) return n; int a = 0, b = 1, c; for(int i = 2; i <= n; ++i){ c = a + b; a = b; b = c; } return b; }
intmain() { int number = 10; printf("Recursive Fibonacci of %d is %d\n", number, fibonacci_recursive(number)); printf("Iterative Fibonacci of %d is %d\n", number, fibonacci_iterative(number)); return0; }
{ // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version":"0.2.0", "configurations":[ { "type":"node", "request":"launch", "name":"WASM Debug", "skipFiles":[ "<node_internals>/**" ], "program":"${workspaceFolder}/fib.js" } ] }
vscode 下的 C 代码断点调试需要依赖 DWARF 调试信息 (注: 如果没有调试信息, 我们只能调试生成的 js 代码, 而不能直接在 C 中打断点), 我们使用 emcc 的 -g 编译参数, 让生成的 wasm 带上调试信息. 我们先通过如下命令编译 C 文件:
{ // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version":"0.2.0", "configurations":[ { "name":"Launch Chrome (fib.html)", "type":"chrome", "request":"launch", "url":"http://127.0.0.1:3000/fib.html", "preLaunchTask":"StartHTTPServer", }, ] }
❯ node --enable-source-maps unalign.js Hello, World! Aborted(alignment fault) /home/yeshan333/workspace/playground/emcc_playground/debug-blogpost/unalign.js:613 /** @suppress {checkTypes} */ var e = new WebAssembly.RuntimeError(what); ^
RuntimeError: Aborted(alignment fault) at abort (/home/yeshan333/workspace/playground/emcc_playground/debug-blogpost/unalign.js:613:41) at alignfault (/home/yeshan333/workspace/playground/emcc_playground/debug-blogpost/unalign.js:335:3) at unalign.wasm (wasm://wasm/unalign.wasm-00091ee6:wasm-function[107]:0x56e4) at unalign.wasm.throw_unalign_err() (wasm://wasm/unalign.wasm-00091ee6:wasm-function[6]:0x42f) at unalign.wasm.__original_main (wasm://wasm/unalign.wasm-00091ee6:wasm-function[7]:0x4f2) at unalign.wasm.main (wasm://wasm/unalign.wasm-00091ee6:wasm-function[8]:0x50f) at /home/yeshan333/workspace/playground/emcc_playground/debug-blogpost/unalign.js:682:12 at callMain (/home/yeshan333/workspace/playground/emcc_playground/debug-blogpost/unalign.js:1383:15) at doRun (/home/yeshan333/workspace/playground/emcc_playground/debug-blogpost/unalign.js:1421:23) at run (/home/yeshan333/workspace/playground/emcc_playground/debug-blogpost/unalign.js:1431:5)
但是如果是在 Web 浏览器环境(chrome)中, 我们能看到符号所在的 C 源文件, 打开 unalign.html, 我们能看到如下堆栈: