In this lesson, you will learn how to bridge the gap between optimized WebAssembly binaries and your original Rust source code using DWARF debug information.
When you compile Rust to Wasm, the resulting binary is a series of low-level instructions that bear little resemblance to your high-level code. Without extra metadata, your browser's Developer Tools will only show you cryptic bytecode, making it impossible to set breakpoints or inspect variables.
To solve this, we leverage DWARF (Debugging With Attributed Record Formats). DWARF is a standardized debugging format that acts as a map between the machine-level binary and your Rust source files. When you compile with debug symbols enabled, the compiler embeds this "map" into the Wasm file (or a sidecar file), allowing tools like Chrome DevTools to correlate specific memory addresses back to your main.rs or lib.rs file.
Enabling Debug Symbols
By default, the Rust compiler strips debug information to minimize binary size. To include it, ensure your Cargo.toml is configured to preserve these symbols during compilation:
[profile.dev]
debug = true
When debug = true is set, wasm-pack or cargo build --target wasm32-unknown-unknown will bundle the DWARF data.
Inspecting in the Browser
Once the Wasm is loaded in the browser, open the Sources panel in your DevTools. If you have the wasm-bindgen and DWARF integration configured correctly, you will see a file:// tree containing your actual Rust source files alongside the generated Wasm. You can now:
- Set Breakpoints: Click on line numbers in your Rust source just as you would with JavaScript.
- Examine Variables: Use the Scope pane to inspect the values of Rust variables, provided the variables haven't been optimized away.
- Trace Backtraces: View the call stack in terms of Rust functions rather than mangled Wasm import names.
Keep in mind that these debug symbols significantly increase binary size. Always ensure you are using a separate dev profile for debugging and a release profile with debug = false for production deployments to keep your Wasm payload performant and compact.
Key Takeaway: By setting debug = true in your profile, you embed DWARF metadata that allows browsers to map low-level Wasm instructions back to your readable Rust source code, enabling familiar debugging workflows.