How to Debug WebAssembly with Source Maps
WebAssembly (WASM) enables high-performance applications on the web, but debugging raw binary or text-format WebAssembly (WAT) is incredibly challenging. This guide outlines how to use source maps and DWARF debug symbols to map compiled WASM bytecode back to its original source code—such as C++, Rust, or Go—directly inside browser developer tools for a seamless debugging experience.
Step 1: Generate Debug Information During Compilation
To map WASM back to its original language, you must instruct your compiler to include debug information (either source maps or DWARF symbols) during the build process.
- For C/C++ (Emscripten): Compile your code using the
-gflag. Usingemcc -g4 main.cpp -o main.jsgenerates source maps, preserves variable names, and retains the original source structure. - For Rust: Ensure you build in development mode
(
wasm-pack build --dev). By default, development builds retain DWARF debug symbols. Avoid using optimization flags likewasm-optor stripping symbols during this phase. - For Go (TinyGo): Use the default build command
without the
-no-debugflag, as debug symbols are included automatically during compilation.
Step 2: Configure Your Web Server
The browser needs to resolve the paths to your original source files
(e.g., .rs, .cpp, or .go files).
Ensure your local development server is configured to serve these raw
source files alongside your compiled .wasm and
.js glue files. If the browser cannot fetch the source
files, it cannot display the original code in the debugger.
Step 3: Enable Developer Tools Support
Modern web browsers require specific settings and extensions to interpret native debug symbols in WebAssembly.
- Install the DWARF Extension: If you are debugging Rust or C++ in Google Chrome, install the C/C++ DevTools Support (DWARF) extension from the Chrome Web Store.
- Enable Source Maps in Browser Settings: Open your browser’s Developer Tools, navigate to Settings (the gear icon), and ensure that Enable JavaScript source maps and Enable WebAssembly debugging (or WASM source maps) are checked under the Preferences panel.
Step 4: Debug Your Original Code in the Browser
With your project running and Developer Tools open, you can now debug your source code directly.
- Locate Your Source Files: Open the
Sources tab (Chrome) or Debugger tab
(Firefox). In the file navigator pane, you will see a dedicated folder
containing your original source files (e.g.,
file://paths or mapped source directories). - Set Breakpoints: Open your original source file
(e.g.,
lib.rsormain.cpp) and click on a line number to set a breakpoint, just as you would with standard JavaScript. - Inspect Variables and the Call Stack: Trigger the action in your web application that executes the WASM code. The browser will pause execution at your breakpoint. You can now step through the code line-by-line, view the call stack in your original language, and inspect active variable values in the Scope panel.