Repository navigation
feat: build a source map from DWARF at emit - #343
Conversation
Tools that show Wasm stack traces read source maps, not DWARF. walrus already rewrites DWARF to the emitted code's offsets, so the map's mappings can come from those line tables without a second parse. ModuleConfig::generate_source_map(true) turns it on, and Module::emit_wasm_with_source_map(url) returns the module and its map, with a sourceMappingURL section that points at url in place of any the module had.
There was a problem hiding this comment.
This PR builds a JSON source map at emit time from the DWARF that walrus has already rewritten (ModuleConfig::generate_source_map plus Module::emit_wasm_with_source_map), and adds a sourceMappingURL section. My guess is that it's for tooling such as wasm-bindgen, so browser stack traces can show source locations without anyone shipping or parsing DWARF. Building the map from the converted line tables means it always matches the emitted offsets, gc'd functions included. The alternative would be a separate pass over the input DWARF plus the code transform, and this approach rules that out. The design is clean and well tested, and Emit is crate-private, so turning ModuleDebugData::emit into an inherent method breaks no public API. One concrete bug remains in how source paths are built: files in directory 0 get the compilation directory joined twice when that directory is relative.
Not merge-ready:
- Source paths for files in DWARF directory 0 repeat the compilation directory when it is relative, for example after
--remap-path-prefix.
Directory 0 of a line program is the unit's compilation directory, and the path already starts from it, so a relative one (as left by `--remap-path-prefix`) came out twice: `myproj/myproj/src/lib.rs`. Skip directory 0, as addr2line does.
guybedford
left a comment
There was a problem hiding this comment.
Thanks for this. The mapping logic looks right to me, and rebased on main it passes its tests with the snapshot unchanged. The only conflict with #340 is the impl Emit for ModuleDebugData header in debug/mod.rs.
My main suggestion is structural: build the map from the line walk itself instead of from the re-read sections.
A source map row is output offset → input row. Since #340, convert_line_program computes exactly that through CodeMap and then serializes it, and this PR parses the serialized form to get the relation back. With generate_source_map alone, that converts and writes all of .debug_info only to discard it.
I tried the alternative on top of this branch rebased on main:
convert_line_programsplits intoread_sequences, awalk_linesthat yieldsRows { address, rows }/End { address }events per output function, and the DWARF encoder as one consumer of those events.- The source map is a second consumer. File paths come from the write
LineProgram's file table (get_file,get_directory,LineString::get), andpush_path,normalize,mappingsandvlqstay as they are. - Without
generate_dwarf,write::Dwarf::read_line_programon each unit's line program gives the sameConvertLineProgramreader withoutDwarf::convert, so no entries are read or converted and nothing is serialized.
Both modes share the reader and the walk, so the map still can't disagree with the emitted line tables.
With that change the tests in this PR and the existing DWARF tests pass unchanged, and the maps are byte-identical to this PR's on two real Rust debug modules (10 MB and 75 MB), with and without generate_dwarf. Emit time on the 75 MB module, where a plain emit takes 0.22s:
| this PR (rebased) | shared walk | |
|---|---|---|
generate_source_map |
3.1–3.3s | 1.35s |
generate_source_map + generate_dwarf |
3.2–3.3s | 3.2–3.5s |
The patch I tested is below. It is a rough sketch against this branch rebased on main, so treat it as a starting point rather than something to apply as is.
Patch
diff --git a/src/module/debug/dwarf.rs b/src/module/debug/dwarf.rs
index 6e7dece..380be86 100644
--- a/src/module/debug/dwarf.rs
+++ b/src/module/debug/dwarf.rs
@@ -393,12 +393,22 @@ pub(crate) fn convert(
from: &read::Dwarf<R>,
code: &CodeMap,
indices: Option<&Indices>,
+ mut lines: Option<&mut LineSink>,
) -> ConvertResult<write::Dwarf> {
let mut dwarf = write::Dwarf::default();
let mut units = dwarf.convert(from)?;
while let Some((mut unit, root)) = units.read_unit()? {
if let Some(program) = unit.read_line_program(None, None)? {
- let (program, files) = convert_line_program(program, code)?;
+ let mut rows = lines.is_some().then(Vec::new);
+ let (program, files) = convert_line_program(program, code, rows.as_mut())?;
+ if let (Some(visit), Some(rows)) = (&mut lines, rows) {
+ let files = Files {
+ program: &program,
+ strings: unit.strings,
+ line_strings: unit.line_strings,
+ };
+ visit(&files, rows);
+ }
unit.set_line_program(program, files);
}
let mut cx = Context {
@@ -456,16 +466,90 @@ struct Sequence {
rows: Vec<(u64, write::LineRow)>,
}
-/// Each output function gets sequences from every unit whose line program
-/// covers some of its code (usually just the unit its own input code
-/// belonged to, but a pass can copy code between functions), with a row
-/// wherever the input row covering its instructions changes. Instructions
-/// with no input location continue the row before them, and a sequence
-/// ends where the unit's coverage does.
-fn convert_line_program(
- mut program: write::ConvertLineProgram<'_, R>,
+/// A change in the input rows that cover emitted code.
+enum LineEvent<'a> {
+ /// These rows cover the code from `address` on.
+ Rows {
+ address: u64,
+ rows: &'a [(u64, write::LineRow)],
+ },
+ /// None of the unit's rows cover the code from `address` on.
+ End { address: u64 },
+}
+
+/// The emitted address from which a file, line and column hold, or from
+/// which none does.
+pub(crate) type Line = (u64, Option<(write::FileId, u64, u64)>);
+
+/// Takes the lines of each unit.
+pub(crate) type LineSink<'a> = dyn FnMut(&Files, Vec<Line>) + 'a;
+
+/// The files that a unit's `Line`s refer to.
+pub(crate) struct Files<'a> {
+ program: &'a write::LineProgram,
+ strings: &'a write::StringTable,
+ line_strings: &'a write::LineStringTable,
+}
+
+impl Files<'_> {
+ /// The compilation directory, the file's directory unless it is the
+ /// compilation directory, and the file's name.
+ pub(crate) fn path(&self, file: write::FileId) -> (&[u8], Option<&[u8]>, &[u8]) {
+ let comp_dir = self.program.default_directory();
+ let (name, dir) = self.program.get_file(file);
+ let dir = (dir != comp_dir).then(|| self.string(self.program.get_directory(dir)));
+ let comp_dir = self.string(self.program.get_directory(comp_dir));
+ (comp_dir, dir, self.string(name))
+ }
+
+ fn string<'a>(&'a self, string: &'a write::LineString) -> &'a [u8] {
+ string.get(self.strings, self.line_strings)
+ }
+}
+
+/// The lines of each unit, for a module whose DWARF isn't written.
+pub(crate) fn lines(
+ from: &read::Dwarf<R>,
code: &CodeMap,
-) -> ConvertResult<(write::LineProgram, Vec<write::FileId>)> {
+ visit: &mut LineSink,
+) -> ConvertResult<()> {
+ // Only its string tables are used, for the paths of DWARF 5 files.
+ let mut dwarf = write::Dwarf::default();
+ let mut units = from.units();
+ while let Some(header) = units.next()? {
+ let Some(program) = from.unit(header)?.line_program else {
+ continue;
+ };
+ let mut program = dwarf.read_line_program(from, program, None, None)?;
+ let sequences = read_sequences(&mut program)?;
+ let (program, _) = program.program();
+ let mut rows = Vec::new();
+ walk_lines(&sequences, code, &mut |event| push_lines(&mut rows, &event));
+ let files = Files {
+ program: &program,
+ strings: &dwarf.strings,
+ line_strings: &dwarf.line_strings,
+ };
+ visit(&files, rows);
+ }
+ Ok(())
+}
+
+fn push_lines(lines: &mut Vec<Line>, event: &LineEvent) {
+ let line = match *event {
+ // Of the rows at one address, readers take the last.
+ LineEvent::Rows { address, rows } => {
+ let row = rows[rows.len() - 1].1;
+ (address, Some((row.file, row.line, row.column)))
+ }
+ LineEvent::End { address } => (address, None),
+ };
+ if lines.last().map(|last| last.1) != Some(line.1) {
+ lines.push(line);
+ }
+}
+
+fn read_sequences(program: &mut write::ConvertLineProgram<'_, R>) -> ConvertResult<Vec<Sequence>> {
let mut sequences = Vec::new();
while let Some(sequence) = program.read_sequence()? {
let Some(start) = sequence.start else {
@@ -486,7 +570,16 @@ fn convert_line_program(
sequences.push(Sequence { start, end, rows });
}
sequences.sort_by_key(|s| s.start);
+ Ok(sequences)
+}
+/// Each output function gets events from every unit whose line program
+/// covers some of its code (usually just the unit its own input code
+/// belonged to, but a pass can copy code between functions), with rows
+/// wherever the input row covering its instructions changes. Instructions
+/// with no input location continue the row before them, and the rows end
+/// where the unit's coverage does.
+fn walk_lines(sequences: &[Sequence], code: &CodeMap, sink: &mut dyn FnMut(LineEvent)) {
// The rows covering an input address: those at it, or else the last one
// before it, in the same function. (A sequence can run on from one
// function into the next, whose start then seems to have the last row
@@ -515,7 +608,7 @@ fn convert_line_program(
// The output functions with code from the input functions the unit's
// sequences cover, in address order.
let mut targets = Vec::new();
- for sequence in &sequences {
+ for sequence in sequences {
let first = code.inputs.partition_point(|f| f.end <= sequence.start);
for (i, f) in code.inputs.iter().enumerate().skip(first) {
if f.start >= sequence.end {
@@ -529,41 +622,67 @@ fn convert_line_program(
for o in targets {
let f = &code.outputs[o];
- // The rows in effect, and the start of the open sequence. Output
- // instructions with no input location keep the rows in effect; an
- // input address no row covers ends the sequence, as in the input.
+ // The rows in effect, and whether any are. Output instructions with
+ // no input location keep the rows in effect; an input address no row
+ // covers ends them, as in the input.
let mut current = None;
- let mut open = None;
for position in 0..=f.instrs.len() {
let Some(input) = code.input_address(o, position) else {
continue;
};
let address = f.address(position);
let Some(rows) = covering(input) else {
- if let Some(start) = open.take() {
- program.end_sequence(address - start);
- current = None;
+ if current.take().is_some() {
+ sink(LineEvent::End { address });
}
continue;
};
if current.as_ref() == Some(&rows) {
continue;
}
- let start = *open.get_or_insert_with(|| {
- program.begin_sequence(Some(Address::Constant(address)));
- address
+ sink(LineEvent::Rows {
+ address,
+ rows: &sequences[rows.0].rows[rows.1.clone()],
});
- for (_, row) in &sequences[rows.0].rows[rows.1.clone()] {
- let mut row = *row;
- row.address_offset = address - start;
- program.generate_row(row);
- }
current = Some(rows);
}
- if let Some(start) = open {
- program.end_sequence(f.end - start);
+ if current.is_some() {
+ sink(LineEvent::End { address: f.end });
}
}
+}
+
+/// Writes a sequence for each run of rows, and collects them as `lines`.
+fn convert_line_program(
+ mut program: write::ConvertLineProgram<'_, R>,
+ code: &CodeMap,
+ mut lines: Option<&mut Vec<Line>>,
+) -> ConvertResult<(write::LineProgram, Vec<write::FileId>)> {
+ let sequences = read_sequences(&mut program)?;
+ let mut open = None;
+ walk_lines(&sequences, code, &mut |event| {
+ if let Some(lines) = &mut lines {
+ push_lines(lines, &event);
+ }
+ match event {
+ LineEvent::Rows { address, rows } => {
+ let start = *open.get_or_insert_with(|| {
+ program.begin_sequence(Some(Address::Constant(address)));
+ address
+ });
+ for (_, row) in rows {
+ let mut row = *row;
+ row.address_offset = address - start;
+ program.generate_row(row);
+ }
+ }
+ LineEvent::End { address } => {
+ if let Some(start) = open.take() {
+ program.end_sequence(address - start);
+ }
+ }
+ }
+ });
Ok(program.program())
}
diff --git a/src/module/debug/mod.rs b/src/module/debug/mod.rs
index d719516..da14f25 100644
--- a/src/module/debug/mod.rs
+++ b/src/module/debug/mod.rs
@@ -12,7 +12,8 @@ use gimli::*;
use std::cell::RefCell;
use std::collections::HashMap;
-use self::dwarf::{CodeMap, Indices, InputFunction, OutputFunction};
+use self::dwarf::{CodeMap, Files, Indices, InputFunction, Line, LineSink, OutputFunction};
+use self::source_map::SourceMap;
/// The DWARF debug section in input WebAssembly binary.
#[derive(Debug, Default)]
@@ -78,7 +79,7 @@ impl Module {
impl ModuleDebugData {
/// Rewrites the DWARF for the emitted code, and writes it to the module
/// when `generate_dwarf` is set. With `source_map`, returns the source map
- /// built from the rewritten DWARF.
+ /// of the same line rows.
pub(crate) fn emit(&self, cx: &mut EmitContext, source_map: bool) -> Option<String> {
let code_section_start = cx.code_transform.code_section_start;
let inputs = cx
@@ -149,12 +150,19 @@ impl ModuleDebugData {
global: &global,
});
- let mut dwarf =
- dwarf::convert(&from_dwarf, &code, indices.as_ref()).expect("cannot convert DWARF");
-
- let mut sections = write::Sections::new(write::EndianVec::new(gimli::LittleEndian));
- dwarf.write(&mut sections).expect("write failed");
+ let mut map = source_map.then(|| SourceMap::new(code_section_start as u64));
if cx.module.config.generate_dwarf {
+ let mut visit = |files: &Files, lines: Vec<Line>| {
+ if let Some(map) = &mut map {
+ map.unit(files, lines);
+ }
+ };
+ let lines = source_map.then_some(&mut visit as &mut LineSink);
+ let mut dwarf = dwarf::convert(&from_dwarf, &code, indices.as_ref(), lines)
+ .expect("cannot convert DWARF");
+
+ let mut sections = write::Sections::new(write::EndianVec::new(gimli::LittleEndian));
+ dwarf.write(&mut sections).expect("write failed");
sections
.for_each(
|id: SectionId, data: &write::EndianVec<LittleEndian>| -> Result<()> {
@@ -168,8 +176,13 @@ impl ModuleDebugData {
},
)
.expect("never");
+ } else if let Some(map) = &mut map {
+ dwarf::lines(&from_dwarf, &code, &mut |files, lines| {
+ map.unit(files, lines)
+ })
+ .expect("cannot read the DWARF line tables");
}
- source_map.then(|| source_map::build(§ions, &cx.code_transform))
+ map.map(SourceMap::finish)
}
}
diff --git a/src/module/debug/source_map.rs b/src/module/debug/source_map.rs
index 57e48e6..d3658d1 100644
--- a/src/module/debug/source_map.rs
+++ b/src/module/debug/source_map.rs
@@ -1,167 +1,89 @@
//! Builds a source map of the emitted module, with the `mappings` from the
-//! line tables of its rewritten DWARF.
+//! line rows of its DWARF at the addresses they were emitted to.
//!
//! In a source map of a Wasm module, the whole module is generated line 0 and
//! a generated column is a byte offset in the module.
-use crate::CodeTransform;
-use gimli::write::{EndianVec, Sections};
-use gimli::{ColumnType, EndianSlice, LittleEndian};
+use super::dwarf::{Files, Line};
+use gimli::write::FileId;
use std::collections::HashMap;
-type Reader<'a> = EndianSlice<'a, LittleEndian>;
-
/// A source location as DWARF writes it: a source index, a 1-based line and
/// a 1-based column, where column 0 is the start of the line.
type Location = (usize, u64, u64);
-/// What the source map is built from.
-#[derive(Default)]
-struct DebugInfo {
+pub(crate) struct SourceMap {
+ /// The module offset of the code section's contents, which DWARF
+ /// addresses are relative to.
+ code_start: u64,
sources: Vec<String>,
source_indices: HashMap<String, usize>,
- /// Each line table row's module offset and location, if it has one.
+ /// Each line's module offset and location, if it has one.
rows: Vec<(u64, Option<Location>)>,
}
-/// Returns the JSON source map of the module whose code `transform`
-/// describes, from its rewritten DWARF `sections`.
-pub(crate) fn build(
- sections: &Sections<EndianVec<LittleEndian>>,
- transform: &CodeTransform,
-) -> String {
- let dwarf = gimli::Dwarf::load(|id| -> gimli::Result<Reader> {
- let data = sections.get(id).map_or(&[][..], |w| w.slice());
- Ok(EndianSlice::new(data, LittleEndian))
- })
- .expect("cannot load the rewritten DWARF");
- let code_end = transform.function_ranges.iter().map(|(_, r)| r.end).max();
- let code_len = code_end.map_or(0, |end| end - transform.code_section_start) as u64;
- let mut info = DebugInfo::default();
- info.read(&dwarf, transform.code_section_start as u64, code_len)
- .expect("cannot read the rewritten DWARF");
-
- // Readers take the last mapping at an offset, so where one sequence ends
- // and the next starts, the next one's location goes last.
- info.rows
- .sort_by_key(|&(offset, location)| (offset, location.is_some()));
-
- let mut json = String::from("{\"version\":3,\"sources\":[");
- push_list(&mut json, info.sources.iter());
- json.push_str("],\"names\":[],\"mappings\":\"");
- json.push_str(&mappings(&info.rows));
- json.push_str("\"}");
- json
-}
-
-impl DebugInfo {
- /// Reads the line tables.
- fn read(
- &mut self,
- dwarf: &gimli::Dwarf<Reader>,
- code_start: u64,
- code_len: u64,
- ) -> gimli::Result<()> {
- let mut units = dwarf.units();
- while let Some(header) = units.next()? {
- let unit = dwarf.unit(header)?;
- self.read_line_table(dwarf, &unit, code_start, code_len)?;
+impl SourceMap {
+ pub(crate) fn new(code_start: u64) -> Self {
+ SourceMap {
+ code_start,
+ sources: Vec::new(),
+ source_indices: HashMap::new(),
+ rows: Vec::new(),
}
- Ok(())
}
- fn read_line_table(
- &mut self,
- dwarf: &gimli::Dwarf<Reader>,
- unit: &gimli::Unit<Reader>,
- code_start: u64,
- code_len: u64,
- ) -> gimli::Result<()> {
- let Some(program) = unit.line_program.clone() else {
- return Ok(());
- };
- let mut files = HashMap::new();
- let mut rows = program.rows();
- let mut sequence = Vec::new();
- // Whether the current sequence is in code the module still has.
- let mut sequence_live = None;
- while let Some((_, row)) = rows.next_row()? {
- let address = row.address();
- let live = *sequence_live.get_or_insert(0 < address && address < code_len);
- let offset = code_start + address;
- if row.end_sequence() {
- if live {
- sequence.push((offset, None));
- self.rows.append(&mut sequence);
- }
- sequence.clear();
- sequence_live = None;
- continue;
- }
- if !live {
- continue;
- }
+ /// Adds the lines of one unit.
+ pub(crate) fn unit(&mut self, files: &Files, lines: Vec<Line>) {
+ let mut sources = HashMap::new();
+ for (address, row) in lines {
// Line 0 is code that no single source line produced, so it gets
// no location rather than the location of the row before it.
- let location = match row.line() {
- Some(line) => {
- let source = self.file(dwarf, unit, &mut files, row.file_index())?;
- let column = match row.column() {
- ColumnType::LeftEdge => 0,
- ColumnType::Column(column) => column.get(),
- };
- source.map(|source| (source, line.get(), column))
- }
- None => None,
- };
- sequence.push((offset, location));
+ let location = row.filter(|row| row.1 != 0).map(|(file, line, column)| {
+ let source = match sources.get(&file) {
+ Some(&source) => source,
+ None => {
+ let source = self.source(files, file);
+ sources.insert(file, source);
+ source
+ }
+ };
+ (source, line, column)
+ });
+ self.rows.push((self.code_start + address, location));
}
- Ok(())
}
- /// The source index of a unit's file, which `files` caches.
- fn file(
- &mut self,
- dwarf: &gimli::Dwarf<Reader>,
- unit: &gimli::Unit<Reader>,
- files: &mut HashMap<u64, usize>,
- index: u64,
- ) -> gimli::Result<Option<usize>> {
- if let Some(&source) = files.get(&index) {
- return Ok(Some(source));
- }
- let Some(program) = &unit.line_program else {
- return Ok(None);
- };
- let header = program.header();
- let Some(file) = header.file(index) else {
- return Ok(None);
- };
+ /// The source index of a unit's file.
+ fn source(&mut self, files: &Files, file: FileId) -> usize {
// The file's name, under its directory and then the unit's
- // compilation directory, unless one of them is absolute. Directory 0
- // is the compilation directory itself, so it isn't joined again.
- let mut path = match unit.comp_dir {
- Some(dir) => dir.to_string_lossy().into_owned(),
- None => String::new(),
- };
- if let Some(dir) = file
- .directory(header)
- .filter(|_| file.directory_index() != 0)
- {
- push_path(&mut path, &dwarf.attr_string(unit, dir)?.to_string_lossy());
+ // compilation directory, unless one of them is absolute.
+ let (comp_dir, dir, name) = files.path(file);
+ let mut path = String::from_utf8_lossy(comp_dir).into_owned();
+ if let Some(dir) = dir {
+ push_path(&mut path, &String::from_utf8_lossy(dir));
}
- push_path(
- &mut path,
- &dwarf.attr_string(unit, file.path_name())?.to_string_lossy(),
- );
+ push_path(&mut path, &String::from_utf8_lossy(name));
let path = normalize(&path);
let next = self.sources.len();
- let source = *self.source_indices.entry(path).or_insert_with_key(|path| {
+ *self.source_indices.entry(path).or_insert_with_key(|path| {
self.sources.push(path.clone());
next
- });
- files.insert(index, source);
- Ok(Some(source))
+ })
+ }
+
+ /// The JSON source map.
+ pub(crate) fn finish(mut self) -> String {
+ // Readers take the last mapping at an offset, so where one unit's
+ // rows end and another's start, the location goes last.
+ self.rows
+ .sort_by_key(|&(offset, location)| (offset, location.is_some()));
+
+ let mut json = String::from("{\"version\":3,\"sources\":[");
+ push_list(&mut json, self.sources.iter());
+ json.push_str("],\"names\":[],\"mappings\":\"");
+ json.push_str(&mappings(&self.rows));
+ json.push_str("\"}");
+ json
}
}
This bears on #344 too, since its scopes read the rewritten .debug_info in the same way. The only thing they take from the rewrite is the pc ranges, and CodeMap::ranges is what #340 uses for DW_AT_low_pc / DW_AT_high_pc and range lists, so the entry walk there could read the input DWARF and map each range through it. I haven't tried that part.
| ) | ||
| .expect("never"); | ||
| } | ||
| source_map.then(|| source_map::build(§ions, &cx.code_transform)) |
There was a problem hiding this comment.
This is the round trip: the rows that convert_line_program has just placed are serialized by dwarf.write above and parsed back here. See the review summary for building the map from the walk directly.
| // Whether the current sequence is in code the module still has. | ||
| let mut sequence_live = None; | ||
| while let Some((_, row)) = rows.next_row()? { | ||
| let address = row.address(); | ||
| let live = *sequence_live.get_or_insert(0 < address && address < code_len); | ||
| let offset = code_start + address; | ||
| if row.end_sequence() { | ||
| if live { | ||
| sequence.push((offset, None)); | ||
| self.rows.append(&mut sequence); | ||
| } | ||
| sequence.clear(); | ||
| sequence_live = None; | ||
| continue; | ||
| } | ||
| if !live { | ||
| continue; | ||
| } |
There was a problem hiding this comment.
As far as I can tell this filter never fires: convert_line_program skips tombstoned input sequences and only writes sequences inside emitted functions, so every sequence read back here starts in live code. It goes away with the restructure, along with code_len.
# Conflicts: # src/module/debug/mod.rs
The map took its rows by writing the rewritten DWARF and parsing the line programs back, so generate_source_map alone converted and wrote all of .debug_info only to discard it. Split convert_line_program into read_sequences, walk_lines (which reports each output function's rows as LineEvents) and the writer, and make the source map a second consumer of those events. With generate_dwarf the conversion hands each unit's lines to the map; without it, dwarf::lines reads and walks only the line programs, so no entries are converted and nothing is serialized. The written DWARF and the maps don't change.
# Conflicts: # CHANGELOG.md
guybedford
left a comment
There was a problem hiding this comment.
Thanks for restructuring this, it looks good to me.
I compared against the previous revision on three real Rust debug modules (5–9 MB) after gc: the wasm and the maps are byte-identical with generate_source_map, with generate_dwarf, and with both, and a map-only emit of the largest went from 0.77s to 0.30s.
One optional nit inline.
| let mut add_unit = |files: &Files, lines: Vec<Line>| { | ||
| if let Some(map) = &mut map { | ||
| map.add_unit(files, lines); | ||
| } | ||
| }; | ||
| if cx.module.config.generate_dwarf { | ||
| let lines = source_map.then_some(&mut add_unit as _); |
There was a problem hiding this comment.
Optional nit: add_unit checks if let Some(map) again although it is only called when source_map is set, and as _ hides that the cast is to &mut LineSink. Building the closure from map.as_mut() and naming the type in the cast would make both explicit.
The closure that hands each unit's lines to the source map checked for the map again, although it only runs when there is one. Make it from `map.as_mut()` instead, and pass the resulting `Option<&mut LineSink>` to both `dwarf::convert` and `dwarf::lines`, naming the type rather than casting with `as _`.
feat: a source map of the emitted module, from its DWARF
Tools that show Wasm stack traces read source maps, not DWARF. walrus already rewrites DWARF to the emitted code's offsets at emit, so the map can be built there without a second parse, and it always describes the module walrus writes.
API.
ModuleConfig::generate_source_map(true)andModule::emit_wasm_with_source_map(url: &str) -> (Vec<u8>, Option<String>). A module emitted with a map always gets asourceMappingURLsection withurl, in place of any it had. Without the flag it isemit_wasm()and adds no section. DWARF is still written only withgenerate_dwarf.The map.
version,sources,names(empty) andmappingsfrom the line tables, where line 0 and the end of a sequence map to no location.sourcesare the files the mappings use, as DWARF records them under the unit's compilation directory, so usually absolute paths for the caller to relocate, with\turned into/and.and..removed.