Debian Codegraph @

crates/wast/src/core/binary/dwarf.rs

raw ◀ ▶
1 Debian patch touch this file
1 //! Implementation of emitting DWARF debugging information for `*.wat` files.
2 //!
3 //! This is intended to be relatively simple but the goal is to enable emission
4 //! of DWARF sections which point back to the original `*.wat` file itself. This
5 //! enables debuggers like LLDB to debug `*.wat` files without necessarily
6 //! built-in knowledge of WebAssembly itself.
7 //!
8 //! Overall I was curious on weekend and decided to implement this. It's an
9 //! off-by-default crate feature and an off-by-default runtime feature of this
10 //! crate. Hopefully doesn't carry too much complexity with it while still being
11 //! easy/fun to play around with.
12
13 use crate::core::binary::{EncodeOptions, Encoder, GenerateDwarf, Names, RecOrType};
14 use crate::core::{InnerTypeKind, Local, ValType};
15 use crate::token::Span;
16 use gimli::write::{
17 self, Address, AttributeValue, DwarfUnit, Expression, FileId, LineProgram, LineString,
18 Sections, UnitEntryId, Writer,
19 };
20 use gimli::{Encoding, Format, LineEncoding, LittleEndian};
21 use std::cmp::Ordering;
22 use std::collections::HashMap;
23 use std::path::Path;
24
25 pub struct Dwarf<'a> {
26 // Metadata configured at `Dwarf` creation time
27 func_names: HashMap<u32, &'a str>,
28 func_imports: u32,
29 contents: &'a str,
30 file_id: FileId,
31 style: GenerateDwarf,
32 types: &'a [RecOrType<'a>],
33
34 dwarf: DwarfUnit,
35
36 // Next function index when `start_func` is called
37 next_func: u32,
38
39 // Current `DW_TAG_subprogram` that's being built as part of `start_func`.
40 cur_subprogram: Option<UnitEntryId>,
41 cur_subprogram_instrs: usize,
42
43 // Code-section-relative offset of the start of every function. Filled in
44 // as part of `end_func`.
45 sym_offsets: Vec<usize>,
46
47 // Metadata tracking what the line/column information was at the specified
48 // last offset.
49 line: u64,
50 column: u64,
51 last_offset: usize,
52
53 i32_ty: Option<UnitEntryId>,
54 i64_ty: Option<UnitEntryId>,
55 f32_ty: Option<UnitEntryId>,
56 f64_ty: Option<UnitEntryId>,
57 }
58
59 impl<'a> Dwarf<'a> {
60 /// Creates a new `Dwarf` from the specified configuration.
61 ///
62 /// * `func_imports` - the number of imported functions in this module, or
63 /// the index of the first defined function.
64 /// * `opts` - encoding options, namely where whether DWARF is to be emitted
65 /// is configured.
66 /// * `names` - the `name` custom section for this module, used to name
67 /// functions in DWARF.
68 pub fn new(
69 func_imports: u32,
70 opts: &EncodeOptions<'a>,
71 names: &Names<'a>,
72 types: &'a [RecOrType<'a>],
73 ) -> Option<Dwarf<'a>> {
74 // This is a load-bearing `?` which notably short-circuits all DWARF
75 // machinery entirely if this was not enabled at runtime.
76 let (file, contents, style) = opts.dwarf_info?;
77 let file = file.to_str()?;
78
79 // Configure some initial `gimli::write` context.
80 let encoding = Encoding {
81 address_size: 4,
82 format: Format::Dwarf32,
83 version: 5,
84 };
85 let mut dwarf = DwarfUnit::new(encoding);
86 let (comp_dir, comp_file) = match (
87 Path::new(file).parent().and_then(|s| s.to_str()),
88 Path::new(file).file_name().and_then(|s| s.to_str()),
89 ) {
90 (Some(parent), Some(file_name)) if !parent.is_empty() => (parent, file_name),
91 _ => (".", file),
92 };
93 let comp_dir_ref = dwarf.strings.add(comp_dir);
94 let comp_file_ref = dwarf.strings.add(comp_file);
95 dwarf.unit.line_program = LineProgram::new(
96 encoding,
97 LineEncoding::default(),
98 LineString::StringRef(comp_dir_ref),
•99 None,
100 LineString::StringRef(comp_file_ref),
101 None,
102 );
103 let dir_id = dwarf.unit.line_program.default_directory();
104 let file_id =
105 dwarf
106 .unit
107 .line_program
108 .add_file(LineString::StringRef(comp_file_ref), dir_id, None);
109
110 // Configure a single compilation unit which encompasses the entire code
111 // section. The code section isn't fully known at this point so only a
112 // "low pc" is emitted here.
113 let root = dwarf.unit.root();
114 let cu = dwarf.unit.get_mut(root);
115 cu.set(
116 gimli::DW_AT_producer,
117 AttributeValue::String(format!("wast {}", env!("CARGO_PKG_VERSION")).into_bytes()),
118 );
119 cu.set(
120 gimli::DW_AT_language,
121 // Technically this should be something like wasm or wat but that
122 // doesn't exist so fill in something here.
123 AttributeValue::Language(gimli::DW_LANG_C),
124 );
125 cu.set(gimli::DW_AT_name, AttributeValue::StringRef(comp_file_ref));
126 cu.set(
127 gimli::DW_AT_comp_dir,
128 AttributeValue::StringRef(comp_dir_ref),
129 );
130 cu.set(gimli::DW_AT_low_pc, AttributeValue::Data4(0));
131
132 // Build a lookup table for defined function index to its name.
133 let mut func_names = HashMap::new();
134 for (idx, name) in names.funcs.iter() {
135 func_names.insert(*idx, *name);
136 }
137
138 // Offsets pointing to newlines are considered internally as the 0th
139 // column of the next line, so handle the case that the contents start
140 // with a newline.
141 let (line, column) = if contents.starts_with("\n") {
142 (2, 0)
143 } else {
144 (1, 1)
145 };
146 Some(Dwarf {
147 dwarf,
148 style,
149 next_func: func_imports,
150 func_imports,
151 sym_offsets: Vec::new(),
152 contents,
153 line,
154 column,
155 last_offset: 0,
156 file_id,
157 cur_subprogram: None,
158 cur_subprogram_instrs: 0,
159 func_names,
160 i32_ty: None,
161 i64_ty: None,
162 f32_ty: None,
163 f64_ty: None,
164 types,
165 })
166 }
167
168 /// Start emitting a new function defined at `span`.
169 ///
170 /// This will start a new line program for this function and additionally
171 /// configure a new `DW_TAG_subprogram` for this new function.
172 pub fn start_func(&mut self, span: Span, ty: u32, locals: &[Local<'_>]) {
173 self.change_linecol(span);
174 let addr = Address::Symbol {
175 symbol: (self.next_func - self.func_imports) as usize,
176 addend: 0,
177 };
178 self.dwarf.unit.line_program.begin_sequence(Some(addr));
179
180 let root = self.dwarf.unit.root();
181 let subprogram = self.dwarf.unit.add(root, gimli::DW_TAG_subprogram);
182 let entry = self.dwarf.unit.get_mut(subprogram);
183 let fallback = format!("wasm-function[{}]", self.next_func);
184 let func_name = self
185 .func_names
186 .get(&self.next_func)
187 .copied()
188 .unwrap_or(&fallback);
189 entry.set(gimli::DW_AT_name, AttributeValue::String(func_name.into()));
190 entry.set(
191 gimli::DW_AT_decl_file,
192 AttributeValue::FileIndex(Some(self.file_id)),
193 );
194 entry.set(gimli::DW_AT_decl_line, AttributeValue::Udata(self.line));
195 entry.set(gimli::DW_AT_decl_column, AttributeValue::Udata(self.column));
196 entry.set(gimli::DW_AT_external, AttributeValue::FlagPresent);
197 entry.set(gimli::DW_AT_low_pc, AttributeValue::Address(addr));
198
199 if let GenerateDwarf::Full = self.style {
200 self.add_func_params_and_locals(subprogram, ty, locals);
201 }
202
203 self.cur_subprogram = Some(subprogram);
204 self.cur_subprogram_instrs = 0;
205 self.next_func += 1;
206 }
207
208 /// Adds `DW_TAG_formal_parameter` and `DW_TAG_variable` for all locals
209 /// (which are both params and function-defined locals).
210 ///
211 /// This is pretty simple in that the expression for the location of
212 /// these variables is constant, it's just "it's the local", and it spans
213 /// the entire function.
214 fn add_func_params_and_locals(
215 &mut self,
216 subprogram: UnitEntryId,
217 ty: u32,
218 locals: &[Local<'_>],
219 ) {
220 // Iterate through `self.types` which is what was encoded into the
221 // module and find the function type which gives access to the
222 // parameters which gives access to their types.
223 let ty = self
224 .types
225 .iter()
226 .flat_map(|t| match t {
227 RecOrType::Type(t) => std::slice::from_ref(*t),
228 RecOrType::Rec(r) => &r.types,
229 })
230 .nth(ty as usize);
231 let ty = match ty.map(|t| &t.def.kind) {
232 Some(InnerTypeKind::Func(ty)) => ty,
233 _ => return,
234 };
235
236 let mut local_idx = 0;
237 for (_, _, ty) in ty.params.iter() {
238 self.local(local_idx, subprogram, gimli::DW_TAG_formal_parameter, ty);
239 local_idx += 1;
240 }
241
242 for local in locals {
243 self.local(local_idx, subprogram, gimli::DW_TAG_variable, &local.ty);
244 local_idx += 1;
245 }
246 }
247
248 /// Attempts to define a local variable within `subprogram` with the `ty`
249 /// given.
250 ///
251 /// This does nothing if `ty` can't be represented in DWARF.
252 fn local(&mut self, local: u32, subprogram: UnitEntryId, tag: gimli::DwTag, ty: &ValType<'_>) {
253 let ty = match self.val_type_to_dwarf_type(ty) {
254 Some(ty) => ty,
255 None => return,
256 };
257
258 let param = self.dwarf.unit.add(subprogram, tag);
259 let entry = self.dwarf.unit.get_mut(param);
260 entry.set(
261 gimli::DW_AT_name,
262 AttributeValue::String(format!("local{local}").into()),
263 );
264
265 let mut loc = Expression::new();
266 loc.op_wasm_local(local);
267 loc.op(gimli::DW_OP_stack_value);
268 entry.set(gimli::DW_AT_location, AttributeValue::Exprloc(loc));
269 entry.set(gimli::DW_AT_type, AttributeValue::UnitRef(ty));
270 }
271
272 fn val_type_to_dwarf_type(&mut self, ty: &ValType<'_>) -> Option<UnitEntryId> {
273 match ty {
274 ValType::I32 => Some(self.i32_ty()),
275 ValType::I64 => Some(self.i64_ty()),
276 ValType::F32 => Some(self.f32_ty()),
277 ValType::F64 => Some(self.f64_ty()),
278 // TODO: make a C union of sorts or something like that to
279 // represent v128 as an array-of-lanes or u128 or something like
280 // that.
281 ValType::V128 => None,
282 // Not much that can be done about reference types without actually
283 // knowing what the engine does, this probably needs an addition to
284 // DWARF itself to represent this.
285 ValType::Ref(_) => None,
286 }
287 }
288
289 /// Emit an instruction which starts at `offset` and is defined at `span`.
290 ///
291 /// Note that `offset` is code-section-relative.
292 pub fn instr(&mut self, offset: usize, span: Span) {
293 self.change_linecol(span);
294 let offset = u64::try_from(offset).unwrap();
295
296 let mut changed = false;
297 let row = self.dwarf.unit.line_program.row();
298 set(&mut row.address_offset, offset, &mut changed);
299 set(&mut row.line, self.line, &mut changed);
300 set(&mut row.column, self.column, &mut changed);
301 set(&mut row.file, self.file_id, &mut changed);
302 set(&mut row.is_statement, true, &mut changed);
303 set(
304 &mut row.prologue_end,
305 self.cur_subprogram_instrs == 0,
306 &mut changed,
307 );
308
309 if changed {
310 self.dwarf.unit.line_program.generate_row();
311 }
312 self.cur_subprogram_instrs += 1;
313
314 fn set<T: PartialEq>(slot: &mut T, val: T, changed: &mut bool) {
315 if *slot != val {
316 *slot = val;
317 *changed = true;
318 }
319 }
320 }
321
322 /// Change `self.line` and `self.column` to be appropriate for the offset
323 /// in `span`.
324 ///
325 /// This will incrementally move from `self.last_offset` to `span.offset()`
326 /// and update line/column information as we go. It's assumed that this is
327 /// more efficient than a precalculate-all-the-positions-for-each-byte
328 /// approach since that would require a great deal of memory to store a
329 /// line/col for all bytes in the input string. It's also assumed that most
330 /// `span` adjustments are minor as it's between instructions in a function
331 /// which are frequently close together. Whether or not this assumption
332 /// pans out is yet to be seen.
333 fn change_linecol(&mut self, span: Span) {
334 let offset = span.offset();
335
336 loop {
337 match self.last_offset.cmp(&offset) {
338 Ordering::Less => {
339 let haystack = self.contents[self.last_offset + 1..].as_bytes();
340 let next_newline = match memchr::memchr_iter(b'\n', haystack).next() {
341 Some(pos) => pos + self.last_offset + 1,
342 None => break,
343 };
344 if next_newline > offset {
345 break;
346 } else {
347 self.line += 1;
348 self.column = 0;
349 self.last_offset = next_newline;
350 }
351 }
352 Ordering::Greater => {
353 let haystack = self.contents[..self.last_offset].as_bytes();
354 match memchr::memchr_iter(b'\n', haystack).next_back() {
355 Some(prev_newline) => {
356 if self.column == 0 {
357 self.line -= 1;
358 }
359 self.column = 0;
360 self.last_offset = prev_newline;
361 }
362 None => {
363 self.line = 1;
364 self.column = 1;
365 self.last_offset = 0;
366 }
367 }
368 }
369 Ordering::Equal => break,
370 }
371 }
372
373 match self.last_offset.cmp(&offset) {
374 Ordering::Less => {
375 self.column += (offset - self.last_offset) as u64;
376 }
377 Ordering::Greater => {
378 self.column -= (self.last_offset - offset) as u64;
379 }
380 Ordering::Equal => {}
381 }
382 self.last_offset = offset;
383 }
384
385 /// Completes emission of the latest function.
386 ///
387 /// The latest function took `func_size` bytes to encode and the current end
388 /// of the code section, after the function was appended, is
389 /// `code_section_end`.
390 pub fn end_func(&mut self, func_size: usize, code_section_end: usize) {
391 // Add a final row corresponding to the final `end` instruction in the
392 // function to ensure there's something for all bytecodes.
393 let row = self.dwarf.unit.line_program.row();
394 row.address_offset = (func_size - 1) as u64;
395 self.dwarf.unit.line_program.generate_row();
396
397 // This function's symbol is relative to the start of the function
398 // itself. Functions are encoded as a leb-size-of-function then the
399 // function itself, so to account for the size of the
400 // leb-size-of-function we calculate the function start as the current
401 // end of the code section minus the size of the function's bytes.
402 self.sym_offsets.push(code_section_end - func_size);
403
404 // The line program is relative to the start address, so only the
405 // function's size is used here.
406 self.dwarf
407 .unit
408 .line_program
409 .end_sequence(u64::try_from(func_size).unwrap());
410
411 // The high PC value here is relative to `DW_AT_low_pc`, so it's the
412 // size of the function.
413 let entry = self.dwarf.unit.get_mut(self.cur_subprogram.take().unwrap());
414 entry.set(
415 gimli::DW_AT_high_pc,
416 AttributeValue::Data4(func_size as u32),
417 );
418 }
419
420 pub fn set_code_section_size(&mut self, size: usize) {
421 let root = self.dwarf.unit.root();
422 let entry = self.dwarf.unit.get_mut(root);
423 entry.set(gimli::DW_AT_high_pc, AttributeValue::Data4(size as u32));
424 }
425
426 pub fn emit(&mut self, dst: &mut Encoder<'_>) {
427 let mut sections = Sections::new(DwarfWriter {
428 sym_offsets: &self.sym_offsets,
429 bytes: Vec::new(),
430 });
431 self.dwarf.write(&mut sections).unwrap();
432
433 sections
434 .for_each(|id, writer| {
435 if !writer.bytes.is_empty() {
436 dst.wasm.section(&wasm_encoder::CustomSection {
437 name: id.name().into(),
438 data: (&writer.bytes).into(),
439 });
440 }
441 Ok::<_, std::convert::Infallible>(())
442 })
443 .unwrap();
444 }
445
446 fn i32_ty(&mut self) -> UnitEntryId {
447 if self.i32_ty.is_none() {
448 self.i32_ty = Some(self.mk_primitive("i32", 4, gimli::DW_ATE_signed));
449 }
450 self.i32_ty.unwrap()
451 }
452
453 fn i64_ty(&mut self) -> UnitEntryId {
454 if self.i64_ty.is_none() {
455 self.i64_ty = Some(self.mk_primitive("i64", 8, gimli::DW_ATE_signed));
456 }
457 self.i64_ty.unwrap()
458 }
459
460 fn f32_ty(&mut self) -> UnitEntryId {
461 if self.f32_ty.is_none() {
462 self.f32_ty = Some(self.mk_primitive("f32", 4, gimli::DW_ATE_float));
463 }
464 self.f32_ty.unwrap()
465 }
466
467 fn f64_ty(&mut self) -> UnitEntryId {
468 if self.f64_ty.is_none() {
469 self.f64_ty = Some(self.mk_primitive("f64", 8, gimli::DW_ATE_float));
470 }
471 self.f64_ty.unwrap()
472 }
473
474 fn mk_primitive(&mut self, name: &str, byte_size: u8, encoding: gimli::DwAte) -> UnitEntryId {
475 let name = self.dwarf.strings.add(name);
476 let root = self.dwarf.unit.root();
477 let ty = self.dwarf.unit.add(root, gimli::DW_TAG_base_type);
478 let entry = self.dwarf.unit.get_mut(ty);
479 entry.set(gimli::DW_AT_name, AttributeValue::StringRef(name));
480 entry.set(gimli::DW_AT_byte_size, AttributeValue::Data1(byte_size));
481 entry.set(gimli::DW_AT_encoding, AttributeValue::Encoding(encoding));
482 ty
483 }
484 }
485
486 #[derive(Clone)]
487 struct DwarfWriter<'a> {
488 sym_offsets: &'a [usize],
489 bytes: Vec<u8>,
490 }
491
492 impl Writer for DwarfWriter<'_> {
493 type Endian = LittleEndian;
494
495 fn endian(&self) -> Self::Endian {
496 LittleEndian
497 }
498 fn len(&self) -> usize {
499 self.bytes.len()
500 }
501 fn write(&mut self, bytes: &[u8]) -> write::Result<()> {
502 self.bytes.extend_from_slice(bytes);
503 Ok(())
504 }
505 fn write_at(&mut self, offset: usize, bytes: &[u8]) -> write::Result<()> {
506 self.bytes[offset..][..bytes.len()].copy_from_slice(bytes);
507 Ok(())
508 }
509 fn write_address(&mut self, address: Address, size: u8) -> write::Result<()> {
510 match address {
511 Address::Constant(val) => self.write_udata(val, size),
512 Address::Symbol { symbol, addend } => {
513 assert_eq!(addend, 0);
514 let offset = self.sym_offsets[symbol];
515 self.write_udata(offset as u64, size)
516 }
517 }
518 }
519 }
520
521 #[cfg(test)]
522 mod tests {
523 use super::{Dwarf, EncodeOptions, GenerateDwarf};
524 use crate::token::Span;
525 use rand::rngs::SmallRng;
526 use rand::{Rng, SeedableRng};
527
528 fn linecol_test(contents: &str) {
529 let mut dwarf = Dwarf::new(
530 0,
531 EncodeOptions::default().dwarf("foo.wat".as_ref(), contents, GenerateDwarf::Lines),
532 &Default::default(),
533 &[],
534 )
535 .unwrap();
536
537 // Print some debugging information in case someone's debugging this
538 // test
539 let mut offset = 0;
540 for (i, line) in contents.lines().enumerate() {
541 println!(
542 "line {:2} is at {:2} .. {:2}",
543 i + 1,
544 offset,
545 offset + line.len()
546 );
547 offset += line.len() + 1;
548 }
549 println!("");
550
551 // Precalculate (line, col) for all characters, assumed to all be one
552 // byte here.
553 let mut precalculated_linecols = Vec::new();
554 let mut line = 1;
555 let mut col = 1;
556 for c in contents.chars() {
557 if c == '\n' {
558 line += 1;
559 col = 0;
560 }
561 precalculated_linecols.push((line, col));
562 col += 1;
563 }
564
565 // Traverse randomly throughout this string and assert that the
566 // incremental update matches the precalculated position.
567 let mut rand = SmallRng::seed_from_u64(102);
568 for _ in 0..1000 {
569 let pos = rand.random_range(0..contents.len());
570 dwarf.change_linecol(Span::from_offset(pos));
571 let (line, col) = precalculated_linecols[pos];
572
573 assert_eq!(dwarf.line, line, "line mismatch");
574 assert_eq!(dwarf.column, col, "column mismatch");
575 }
576 }
577
578 #[test]
579 fn linecol_simple() {
580 linecol_test(
581 "a
582
583 b
584 c (; ... ;)
585 d
586 e
587
588
589 f
590
591 fg",
592 );
593 }
594
595 #[test]
596 fn linecol_empty() {
597 linecol_test("x");
598 }
599
600 #[test]
601 fn linecol_start_newline() {
602 linecol_test("\nx ab\nyyy \ncc");
603 }
604
605 #[test]
606 fn linecol_lots_of_newlines() {
607 linecol_test("\n\n\n\n");
608 }
609
610 #[test]
611 fn linecol_interspersed() {
612 linecol_test("\na\nb\nc\n");
613 }
614 }