Using source maps

Emscripten has the ability to generate source maps by passing some additional flags to the compiler. Source maps allow your browser to map the source of a file to the file being utilized in an application. For example, you can use a JavaScript build tool such Webpack to minify the code as part of your build process. However, it's incredibly difficult to navigate and troubleshoot the minified code if you're trying to find a bug. By generating a source map, you can view the code in its original form within the browser's development tools and set breakpoints for debugging. Let's generate a source map for our /chapter-06-interact-with-js/js-without-glue.cpp file. Within the /book-examples folder, run the following command in a terminal:

emcc chapter-06-interact-with-js/js-without-glue.cpp -O1 -g4 -s WASM=1 -s SIDE_MODULE=1 -s BINARYEN_ASYNC_COMPILATION=0 -o chapter-06-interact-with-js/js-without-glue.wasm --source-map-base http://localhost:8080/chapter-06-interact-with-js/

The -g4 argument enables source maps, while the --source-map-base argument tells the browser where to find the source map file. Once compiled, start your local server up from the /book-examples folder by running the following command:

serve -l 8080

Navigate to http://127.0.0.1:8080/chapter-06-interact-with-js/js-without-glue.html, open the Developer Tools, and select the Sources tab (in Chrome) or Debugger tab (in Firefox). If you're using Chrome, you should see the following:

Wasm source maps in Chrome Developer Tools

As you can see, the filenames aren't very helpful. Each file should include the function name at the top, although some of the names may have been mangled. You can set breakpoints if you encounter errors, and Chrome's debugging functionality allows you to navigate the call stack. Firefox handles their source maps differently. The following screenshot shows the Debugger view in Firefox's Developer Tools:

Wasm source map in Firefox Developer Tools

The source map is a single file that contains the Wat representation of the Wasm file. You can set breakpoints and debug code here as well. As WebAssembly evolves, more (and better) tooling will become available. In the meantime, logging to the console and utilizing source maps are the current debugging methods you can use.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset