Debian Codegraph @

third_party/rust/wast/src/core/binary/dwarf.rs

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