]> git.lizzy.rs Git - rust.git/blob - src/debuginfo.rs
Make codegen_call_inner a bit more readable
[rust.git] / src / debuginfo.rs
1 extern crate gimli;
2
3 use crate::prelude::*;
4
5 use std::marker::PhantomData;
6
7 use syntax::source_map::FileName;
8
9 use gimli::write::{
10     Address, AttributeValue, CompilationUnit, DebugAbbrev, DebugInfo, DebugLine, DebugRanges,
11     DebugRngLists, DebugStr, EndianVec, LineProgram, LineProgramId, LineProgramTable, Range,
12     RangeList, Result, SectionId, StringTable, UnitEntryId, UnitId, UnitTable,
13     Writer, FileId, LineStringTable, DebugLineStr, LineString,
14 };
15 use gimli::{Encoding, Format, RunTimeEndian};
16
17 use faerie::*;
18
19 fn target_endian(tcx: TyCtxt) -> RunTimeEndian {
20     use rustc::ty::layout::Endian;
21
22     match tcx.data_layout.endian {
23         Endian::Big => RunTimeEndian::Big,
24         Endian::Little => RunTimeEndian::Little,
25     }
26 }
27
28 fn line_program_add_file(line_program: &mut LineProgram, line_strings: &mut LineStringTable, file: &FileName) -> FileId {
29     match file {
30         FileName::Real(path) => {
31             let dir_name = LineString::new(path.parent().unwrap().to_str().unwrap().as_bytes(), line_program.encoding(), line_strings);
32             let dir_id =
33                 line_program.add_directory(dir_name);
34             let file_name = LineString::new(path.file_name().unwrap().to_str().unwrap().as_bytes(), line_program.encoding(), line_strings);
35             line_program.add_file(
36                 file_name,
37                 dir_id,
38                 None,
39             )
40         }
41         // FIXME give more appropriate file names
42         _ => {
43             let dir_id = line_program.default_directory();
44             let dummy_file_name = LineString::new(file.to_string().into_bytes(), line_program.encoding(), line_strings);
45             line_program.add_file(
46                 dummy_file_name,
47                 dir_id,
48                 None,
49             )
50         }
51     }
52 }
53
54 struct DebugReloc {
55     offset: u32,
56     size: u8,
57     name: String,
58     addend: i64,
59 }
60
61 pub struct DebugContext<'tcx> {
62     // Encoding info
63     endian: RunTimeEndian,
64     symbols: indexmap::IndexSet<String>,
65
66     // Main data
67     units: UnitTable,
68     line_programs: LineProgramTable,
69
70     // Side tables
71     strings: StringTable,
72     line_strings: LineStringTable,
73
74     // Global ids
75     unit_id: UnitId,
76     global_line_program: LineProgramId,
77     unit_range_list: RangeList,
78
79     _dummy: PhantomData<&'tcx ()>,
80 }
81
82 impl<'a, 'tcx: 'a> DebugContext<'tcx> {
83     pub fn new(tcx: TyCtxt, address_size: u8) -> Self {
84         let encoding = Encoding {
85             format: Format::Dwarf32,
86             // TODO: this should be configurable
87             // macOS doesn't seem to support DWARF > 3
88             version: 3,
89             address_size,
90         };
91
92         // FIXME: how to get version when building out of tree?
93         // Normally this would use option_env!("CFG_VERSION").
94         let producer = format!("cranelift fn (rustc version {})", "unknown version");
95         let comp_dir = tcx.sess.working_dir.0.to_string_lossy().into_owned();
96         let name = match tcx.sess.local_crate_source_file {
97             Some(ref path) => path.to_string_lossy().into_owned(),
98             None => tcx.crate_name(LOCAL_CRATE).to_string(),
99         };
100
101         let mut strings = StringTable::default();
102         let mut line_strings = LineStringTable::default();
103
104         let mut units = UnitTable::default();
105         let mut line_programs = LineProgramTable::default();
106
107         let global_line_program = line_programs.add(LineProgram::new(
108             encoding,
109             1,
110             1,
111             -5,
112             14,
113             LineString::new(comp_dir.as_bytes(), encoding, &mut line_strings),
114             LineString::new(name.as_bytes(), encoding, &mut line_strings),
115             None,
116         ));
117
118         let unit_id = units.add(CompilationUnit::new(encoding));
119         {
120             let name = strings.add(&*name);
121             let comp_dir = strings.add(&*comp_dir);
122
123             let unit = units.get_mut(unit_id);
124             let root = unit.root();
125             let root = unit.get_mut(root);
126             root.set(
127                 gimli::DW_AT_producer,
128                 AttributeValue::StringRef(strings.add(producer)),
129             );
130             root.set(
131                 gimli::DW_AT_language,
132                 AttributeValue::Language(gimli::DW_LANG_Rust),
133             );
134             root.set(gimli::DW_AT_name, AttributeValue::StringRef(name));
135             root.set(gimli::DW_AT_comp_dir, AttributeValue::StringRef(comp_dir));
136             root.set(
137                 gimli::DW_AT_stmt_list,
138                 AttributeValue::LineProgramRef(global_line_program),
139             );
140             root.set(
141                 gimli::DW_AT_low_pc,
142                 AttributeValue::Address(Address::Absolute(0)),
143             );
144         }
145
146          DebugContext {
147             endian: target_endian(tcx),
148             symbols: indexmap::IndexSet::new(),
149
150             strings,
151             line_strings,
152
153             units,
154             line_programs,
155
156             unit_id,
157             global_line_program,
158             unit_range_list: RangeList(Vec::new()),
159
160             _dummy: PhantomData,
161         }
162     }
163
164     fn emit_location(&mut self, tcx: TyCtxt<'a, 'tcx, 'tcx>, entry_id: UnitEntryId, span: Span) {
165         let loc = tcx.sess.source_map().lookup_char_pos(span.lo());
166
167         let line_program = self.line_programs.get_mut(self.global_line_program);
168         let file_id = line_program_add_file(line_program, &mut self.line_strings, &loc.file.name);
169
170         let unit = self.units.get_mut(self.unit_id);
171         let entry = unit.get_mut(entry_id);
172
173         entry.set(gimli::DW_AT_decl_file, AttributeValue::FileIndex(file_id));
174         entry.set(
175             gimli::DW_AT_decl_line,
176             AttributeValue::Udata(loc.line as u64),
177         );
178         // FIXME: probably omit this
179         entry.set(
180             gimli::DW_AT_decl_column,
181             AttributeValue::Udata(loc.col.to_usize() as u64),
182         );
183     }
184
185     pub fn emit(&mut self, artifact: &mut Artifact) {
186         let unit = self.units.get_mut(self.unit_id);
187         let unit_range_list_id = unit.ranges.add(self.unit_range_list.clone());
188         let root = unit.root();
189         let root = unit.get_mut(root);
190         root.set(
191             gimli::DW_AT_ranges,
192             AttributeValue::RangeListRef(unit_range_list_id),
193         );
194
195         let mut debug_abbrev = DebugAbbrev::from(WriterRelocate::new(self));
196         let mut debug_info = DebugInfo::from(WriterRelocate::new(self));
197         let mut debug_str = DebugStr::from(WriterRelocate::new(self));
198         let mut debug_line_str = DebugLineStr::from(WriterRelocate::new(self));
199         let mut debug_line = DebugLine::from(WriterRelocate::new(self));
200         let mut debug_ranges = DebugRanges::from(WriterRelocate::new(self));
201         let mut debug_rnglists = DebugRngLists::from(WriterRelocate::new(self));
202
203         let debug_str_offsets = self.strings.write(&mut debug_str).unwrap();
204         let debug_line_str_offsets = self.line_strings.write(&mut debug_line_str).unwrap();
205
206         let debug_line_offsets = self.line_programs.write(&mut debug_line, &debug_line_str_offsets, &debug_str_offsets).unwrap();
207
208         self.units
209             .write(
210                 &mut debug_abbrev,
211                 &mut debug_info,
212                 &mut debug_ranges,
213                 &mut debug_rnglists,
214                 &debug_line_offsets,
215                 &debug_line_str_offsets,
216                 &debug_str_offsets,
217             )
218             .unwrap();
219
220         macro decl_section($section:ident = $name:ident) {
221             artifact
222                 .declare_with(
223                     SectionId::$section.name(),
224                     Decl::DebugSection,
225                     $name.0.writer.into_vec(),
226                 )
227                 .unwrap();
228         }
229
230         decl_section!(DebugAbbrev = debug_abbrev);
231         decl_section!(DebugInfo = debug_info);
232         decl_section!(DebugStr = debug_str);
233         decl_section!(DebugLine = debug_line);
234         decl_section!(DebugLineStr = debug_line_str);
235
236         let debug_ranges_not_empty = !debug_ranges.0.writer.slice().is_empty();
237         if debug_ranges_not_empty {
238             decl_section!(DebugRanges = debug_ranges);
239         }
240
241         let debug_rnglists_not_empty = !debug_rnglists.0.writer.slice().is_empty();
242         if debug_rnglists_not_empty {
243             decl_section!(DebugRngLists = debug_rnglists);
244         }
245
246         macro sect_relocs($section:ident = $name:ident) {
247             for reloc in $name.0.relocs {
248                 artifact
249                     .link_with(
250                         faerie::Link {
251                             from: SectionId::$section.name(),
252                             to: &reloc.name,
253                             at: u64::from(reloc.offset),
254                         },
255                         faerie::Reloc::Debug {
256                             size: reloc.size,
257                             addend: reloc.addend as i32,
258                         },
259                     )
260                     .expect("faerie relocation error");
261             }
262         }
263
264         sect_relocs!(DebugAbbrev = debug_abbrev);
265         sect_relocs!(DebugInfo = debug_info);
266         sect_relocs!(DebugStr = debug_str);
267         sect_relocs!(DebugLine = debug_line);
268         sect_relocs!(DebugLineStr = debug_line_str);
269
270         if debug_ranges_not_empty {
271             sect_relocs!(DebugRanges = debug_ranges);
272         }
273
274         if debug_rnglists_not_empty {
275             sect_relocs!(DebugRngLists = debug_rnglists);
276         }
277     }
278
279     fn section_name(&self, id: SectionId) -> String {
280         id.name().to_string()
281     }
282 }
283
284 pub struct FunctionDebugContext<'a, 'tcx> {
285     debug_context: &'a mut DebugContext<'tcx>,
286     entry_id: UnitEntryId,
287     symbol: usize,
288     mir_span: Span,
289 }
290
291 impl<'a, 'b, 'tcx: 'b> FunctionDebugContext<'a, 'tcx> {
292     pub fn new(
293         tcx: TyCtxt<'b, 'tcx, 'tcx>,
294         debug_context: &'a mut DebugContext<'tcx>,
295         mir: &Mir,
296         name: &str,
297         _sig: &Signature,
298     ) -> Self {
299         let (symbol, _) = debug_context.symbols.insert_full(name.to_string());
300
301         let unit = debug_context.units.get_mut(debug_context.unit_id);
302         // FIXME: add to appropriate scope intead of root
303         let scope = unit.root();
304
305         let entry_id = unit.add(scope, gimli::DW_TAG_subprogram);
306         let entry = unit.get_mut(entry_id);
307         let name_id = debug_context.strings.add(name);
308         entry.set(
309             gimli::DW_AT_linkage_name,
310             AttributeValue::StringRef(name_id),
311         );
312
313         entry.set(
314             gimli::DW_AT_low_pc,
315             AttributeValue::Address(Address::Relative { symbol, addend: 0 }),
316         );
317
318         debug_context.emit_location(tcx, entry_id, mir.span);
319
320         FunctionDebugContext {
321             debug_context,
322             entry_id,
323             symbol,
324             mir_span: mir.span,
325         }
326     }
327
328     pub fn define(
329         &mut self,
330         tcx: TyCtxt,
331         //module: &mut Module<impl Backend>,
332         code_size: u32,
333         context: &Context,
334         isa: &cranelift::codegen::isa::TargetIsa,
335         source_info_set: &indexmap::IndexSet<SourceInfo>,
336     ) {
337         let unit = self.debug_context.units.get_mut(self.debug_context.unit_id);
338         let entry = unit.get_mut(self.entry_id);
339         entry.set(gimli::DW_AT_high_pc, AttributeValue::Udata(code_size as u64));
340
341         self.debug_context.unit_range_list.0.push(Range::StartLength {
342             begin: Address::Relative {
343                 symbol: self.symbol,
344                 addend: 0,
345             },
346             length: code_size as u64,
347         });
348
349         let line_program = self
350             .debug_context
351             .line_programs
352             .get_mut(self.debug_context.global_line_program);
353
354         line_program.begin_sequence(Some(Address::Relative {
355             symbol: self.symbol,
356             addend: 0,
357         }));
358
359         let encinfo = isa.encoding_info();
360         let func = &context.func;
361         let mut ebbs = func.layout.ebbs().collect::<Vec<_>>();
362         ebbs.sort_by_key(|ebb| func.offsets[*ebb]); // Ensure inst offsets always increase
363
364         let line_strings = &mut self.debug_context.line_strings;
365         let mut create_row_for_span = |line_program: &mut LineProgram, span: Span| {
366             let loc = tcx.sess.source_map().lookup_char_pos(span.lo());
367             let file_id = line_program_add_file(line_program, line_strings, &loc.file.name);
368
369             /*println!(
370                 "srcloc {:>04X} {}:{}:{}",
371                 line_program.row().address_offset,
372                 file.display(),
373                 loc.line,
374                 loc.col.to_u32()
375             );*/
376
377             line_program.row().file = file_id;
378             line_program.row().line = loc.line as u64;
379             line_program.row().column = loc.col.to_u32() as u64 + 1;
380             line_program.generate_row();
381         };
382
383         let mut end = 0;
384         for ebb in ebbs {
385             for (offset, inst, size) in func.inst_offsets(ebb, &encinfo) {
386                 let srcloc = func.srclocs[inst];
387                 line_program.row().address_offset = offset as u64;
388                 if !srcloc.is_default() {
389                     let source_info = *source_info_set.get_index(srcloc.bits() as usize).unwrap();
390                     create_row_for_span(line_program, source_info.span);
391                 } else {
392                     create_row_for_span(line_program, self.mir_span);
393                 }
394                 end = offset + size;
395             }
396         }
397
398         if code_size != end {
399             line_program.row().address_offset = end as u64;
400             create_row_for_span(line_program, self.mir_span);
401         }
402
403         line_program.end_sequence(code_size as u64);
404     }
405 }
406
407 struct WriterRelocate<'a, 'tcx> {
408     ctx: &'a DebugContext<'tcx>,
409     relocs: Vec<DebugReloc>,
410     writer: EndianVec<RunTimeEndian>,
411 }
412
413 impl<'a, 'tcx> WriterRelocate<'a, 'tcx> {
414     fn new(ctx: &'a DebugContext<'tcx>) -> Self {
415         WriterRelocate {
416             ctx,
417             relocs: Vec::new(),
418             writer: EndianVec::new(ctx.endian),
419         }
420     }
421 }
422
423 impl<'a, 'tcx> Writer for WriterRelocate<'a, 'tcx> {
424     type Endian = RunTimeEndian;
425
426     fn endian(&self) -> Self::Endian {
427         self.writer.endian()
428     }
429
430     fn len(&self) -> usize {
431         self.writer.len()
432     }
433
434     fn write(&mut self, bytes: &[u8]) -> Result<()> {
435         self.writer.write(bytes)
436     }
437
438     fn write_at(&mut self, offset: usize, bytes: &[u8]) -> Result<()> {
439         self.writer.write_at(offset, bytes)
440     }
441
442     fn write_address(&mut self, address: Address, size: u8) -> Result<()> {
443         match address {
444             Address::Absolute(val) => self.write_word(val, size),
445             Address::Relative { symbol, addend } => {
446                 let offset = self.len() as u64;
447                 self.relocs.push(DebugReloc {
448                     offset: offset as u32,
449                     size,
450                     name: self.ctx.symbols.get_index(symbol).unwrap().clone(),
451                     addend: addend as i64,
452                 });
453                 self.write_word(0, size)
454             }
455         }
456     }
457
458     fn write_offset(&mut self, val: usize, section: SectionId, size: u8) -> Result<()> {
459         let offset = self.len() as u32;
460         let name = self.ctx.section_name(section);
461         self.relocs.push(DebugReloc {
462             offset,
463             size,
464             name,
465             addend: val as i64,
466         });
467         self.write_word(0, size)
468     }
469
470     fn write_offset_at(
471         &mut self,
472         offset: usize,
473         val: usize,
474         section: SectionId,
475         size: u8,
476     ) -> Result<()> {
477         let name = self.ctx.section_name(section);
478         self.relocs.push(DebugReloc {
479             offset: offset as u32,
480             size,
481             name,
482             addend: val as i64,
483         });
484         self.write_word_at(offset, 0, size)
485     }
486 }