]> git.lizzy.rs Git - rust.git/blob - src/debuginfo.rs
Monomorphize locals
[rust.git] / src / debuginfo.rs
1 use crate::prelude::*;
2
3 use crate::backend::WriteDebugInfo;
4
5 use std::marker::PhantomData;
6
7 use syntax::source_map::FileName;
8
9 use gimli::write::{
10     Address, AttributeValue, DwarfUnit, EndianVec, FileId, LineProgram, LineString,
11     LineStringTable, Range, RangeList, Result, Sections, UnitEntryId, Writer,
12 };
13 use gimli::{Encoding, Format, LineEncoding, RunTimeEndian, SectionId};
14
15 fn target_endian(tcx: TyCtxt) -> RunTimeEndian {
16     use rustc::ty::layout::Endian;
17
18     match tcx.data_layout.endian {
19         Endian::Big => RunTimeEndian::Big,
20         Endian::Little => RunTimeEndian::Little,
21     }
22 }
23
24 fn line_program_add_file(
25     line_program: &mut LineProgram,
26     line_strings: &mut LineStringTable,
27     file: &FileName,
28 ) -> FileId {
29     match file {
30         FileName::Real(path) => {
31             let dir_name = path.parent().unwrap().to_str().unwrap().as_bytes();
32             let dir_id = if !dir_name.is_empty() {
33                 let dir_name = LineString::new(dir_name, line_program.encoding(), line_strings);
34                 line_program.add_directory(dir_name)
35             } else {
36                 line_program.default_directory()
37             };
38             let file_name = LineString::new(
39                 path.file_name().unwrap().to_str().unwrap().as_bytes(),
40                 line_program.encoding(),
41                 line_strings,
42             );
43             line_program.add_file(file_name, dir_id, None)
44         }
45         // FIXME give more appropriate file names
46         _ => {
47             let dir_id = line_program.default_directory();
48             let dummy_file_name = LineString::new(
49                 file.to_string().into_bytes(),
50                 line_program.encoding(),
51                 line_strings,
52             );
53             line_program.add_file(dummy_file_name, dir_id, None)
54         }
55     }
56 }
57
58 #[derive(Clone)]
59 pub struct DebugReloc {
60     pub offset: u32,
61     pub size: u8,
62     pub name: DebugRelocName,
63     pub addend: i64,
64 }
65
66 #[derive(Clone)]
67 pub enum DebugRelocName {
68     Section(SectionId),
69     Symbol(usize),
70 }
71
72 pub struct DebugContext<'tcx> {
73     tcx: TyCtxt<'tcx>,
74
75     endian: RunTimeEndian,
76     symbols: indexmap::IndexMap<FuncId, String>,
77
78     dwarf: DwarfUnit,
79     unit_range_list: RangeList,
80
81     types: HashMap<Ty<'tcx>, UnitEntryId>,
82 }
83
84 impl<'tcx> DebugContext<'tcx> {
85     pub fn new(tcx: TyCtxt<'tcx>, address_size: u8) -> Self {
86         let encoding = Encoding {
87             format: Format::Dwarf32,
88             // TODO: this should be configurable
89             // macOS doesn't seem to support DWARF > 3
90             version: 3,
91             address_size,
92         };
93
94         let mut dwarf = DwarfUnit::new(encoding);
95
96         // FIXME: how to get version when building out of tree?
97         // Normally this would use option_env!("CFG_VERSION").
98         let producer = format!("cranelift fn (rustc version {})", "unknown version");
99         let comp_dir = tcx.sess.working_dir.0.to_string_lossy().into_owned();
100         let name = match tcx.sess.local_crate_source_file {
101             Some(ref path) => path.to_string_lossy().into_owned(),
102             None => tcx.crate_name(LOCAL_CRATE).to_string(),
103         };
104
105         let line_program = LineProgram::new(
106             encoding,
107             LineEncoding::default(),
108             LineString::new(comp_dir.as_bytes(), encoding, &mut dwarf.line_strings),
109             LineString::new(name.as_bytes(), encoding, &mut dwarf.line_strings),
110             None,
111         );
112         dwarf.unit.line_program = line_program;
113
114         {
115             let name = dwarf.strings.add(&*name);
116             let comp_dir = dwarf.strings.add(&*comp_dir);
117
118             let root = dwarf.unit.root();
119             let root = dwarf.unit.get_mut(root);
120             root.set(
121                 gimli::DW_AT_producer,
122                 AttributeValue::StringRef(dwarf.strings.add(producer)),
123             );
124             root.set(
125                 gimli::DW_AT_language,
126                 AttributeValue::Language(gimli::DW_LANG_Rust),
127             );
128             root.set(gimli::DW_AT_name, AttributeValue::StringRef(name));
129             root.set(gimli::DW_AT_comp_dir, AttributeValue::StringRef(comp_dir));
130             root.set(
131                 gimli::DW_AT_low_pc,
132                 AttributeValue::Address(Address::Constant(0)),
133             );
134         }
135
136         DebugContext {
137             tcx,
138
139             endian: target_endian(tcx),
140             symbols: indexmap::IndexMap::new(),
141
142             dwarf,
143             unit_range_list: RangeList(Vec::new()),
144
145             types: HashMap::new(),
146         }
147     }
148
149     fn emit_location(&mut self, entry_id: UnitEntryId, span: Span) {
150         let loc = self.tcx.sess.source_map().lookup_char_pos(span.lo());
151
152         let file_id = line_program_add_file(
153             &mut self.dwarf.unit.line_program,
154             &mut self.dwarf.line_strings,
155             &loc.file.name,
156         );
157
158         let entry = self.dwarf.unit.get_mut(entry_id);
159
160         entry.set(
161             gimli::DW_AT_decl_file,
162             AttributeValue::FileIndex(Some(file_id)),
163         );
164         entry.set(
165             gimli::DW_AT_decl_line,
166             AttributeValue::Udata(loc.line as u64),
167         );
168         // FIXME: probably omit this
169         entry.set(
170             gimli::DW_AT_decl_column,
171             AttributeValue::Udata(loc.col.to_usize() as u64),
172         );
173     }
174
175     fn dwarf_ty(&mut self, ty: Ty<'tcx>) -> UnitEntryId {
176         if let Some(type_id) = self.types.get(ty) {
177             return *type_id;
178         }
179
180         let new_entry = |dwarf: &mut DwarfUnit, tag| {
181             dwarf.unit.add(dwarf.unit.root(), tag)
182         };
183
184         let primtive = |dwarf: &mut DwarfUnit, ate| {
185             let type_id = new_entry(dwarf, gimli::DW_TAG_base_type);
186             let type_entry = dwarf.unit.get_mut(type_id);
187             type_entry.set(gimli::DW_AT_encoding, AttributeValue::Encoding(ate));
188             type_id
189         };
190
191         let type_id = match ty.kind {
192             ty::Bool => primtive(&mut self.dwarf, gimli::DW_ATE_boolean),
193             ty::Char => primtive(&mut self.dwarf, gimli::DW_ATE_UTF),
194             ty::Uint(_) => primtive(&mut self.dwarf, gimli::DW_ATE_unsigned),
195             ty::Int(_) => primtive(&mut self.dwarf, gimli::DW_ATE_signed),
196             ty::Float(_) => primtive(&mut self.dwarf, gimli::DW_ATE_float),
197             ty::Ref(_, pointee_ty, mutbl) | ty::RawPtr(ty::TypeAndMut { ty: pointee_ty, mutbl }) => {
198                 let type_id = new_entry(&mut self.dwarf, gimli::DW_TAG_pointer_type);
199
200                 // Ensure that type is inserted before recursing to avoid duplicates
201                 self.types.insert(ty, type_id);
202
203                 let pointee = self.dwarf_ty(pointee_ty);
204
205                 let type_entry = self.dwarf.unit.get_mut(type_id);
206
207                 //type_entry.set(gimli::DW_AT_mutable, AttributeValue::Flag(mutbl == rustc::hir::Mutability::MutMutable));
208                 type_entry.set(gimli::DW_AT_type, AttributeValue::ThisUnitEntryRef(pointee));
209
210                 type_id
211             }
212             _ => new_entry(&mut self.dwarf, gimli::DW_TAG_structure_type),
213         };
214         let name = format!("{}", ty);
215         let layout = self.tcx.layout_of(ParamEnv::reveal_all().and(ty)).unwrap();
216
217         let type_entry = self.dwarf.unit.get_mut(type_id);
218
219         type_entry.set(gimli::DW_AT_name, AttributeValue::String(name.into_bytes()));
220         type_entry.set(gimli::DW_AT_byte_size, AttributeValue::Udata(layout.size.bytes()));
221
222         self.types.insert(ty, type_id);
223
224         type_id
225     }
226
227     pub fn emit<P: WriteDebugInfo>(&mut self, product: &mut P) {
228         let unit_range_list_id = self.dwarf.unit.ranges.add(self.unit_range_list.clone());
229         let root = self.dwarf.unit.root();
230         let root = self.dwarf.unit.get_mut(root);
231         root.set(
232             gimli::DW_AT_ranges,
233             AttributeValue::RangeListRef(unit_range_list_id),
234         );
235
236         let mut sections = Sections::new(WriterRelocate::new(self));
237         self.dwarf.write(&mut sections).unwrap();
238
239         let mut section_map = HashMap::new();
240         let _: Result<()> = sections.for_each_mut(|id, section| {
241             if !section.writer.slice().is_empty() {
242                 let section_id = product.add_debug_section(id, section.writer.take());
243                 section_map.insert(id, section_id);
244             }
245             Ok(())
246         });
247
248         let _: Result<()> = sections.for_each(|id, section| {
249             if let Some(section_id) = section_map.get(&id) {
250                 for reloc in &section.relocs {
251                     product.add_debug_reloc(&section_map, &self.symbols, section_id, reloc);
252                 }
253             }
254             Ok(())
255         });
256     }
257 }
258
259 pub struct FunctionDebugContext<'a, 'tcx> {
260     debug_context: &'a mut DebugContext<'tcx>,
261     entry_id: UnitEntryId,
262     symbol: usize,
263     instance: Instance<'tcx>,
264     mir: &'tcx mir::Body<'tcx>,
265 }
266
267 impl<'a, 'tcx> FunctionDebugContext<'a, 'tcx> {
268     pub fn new(
269         debug_context: &'a mut DebugContext<'tcx>,
270         instance: Instance<'tcx>,
271         func_id: FuncId,
272         name: &str,
273         _sig: &Signature,
274     ) -> Self {
275         let mir = debug_context.tcx.instance_mir(instance.def);
276
277         let (symbol, _) = debug_context.symbols.insert_full(func_id, name.to_string());
278
279         // FIXME: add to appropriate scope intead of root
280         let scope = debug_context.dwarf.unit.root();
281
282         let entry_id = debug_context
283             .dwarf
284             .unit
285             .add(scope, gimli::DW_TAG_subprogram);
286         let entry = debug_context.dwarf.unit.get_mut(entry_id);
287         let name_id = debug_context.dwarf.strings.add(name);
288         entry.set(
289             gimli::DW_AT_linkage_name,
290             AttributeValue::StringRef(name_id),
291         );
292
293         entry.set(
294             gimli::DW_AT_low_pc,
295             AttributeValue::Address(Address::Symbol { symbol, addend: 0 }),
296         );
297
298         debug_context.emit_location(entry_id, mir.span);
299
300         FunctionDebugContext {
301             debug_context,
302             entry_id,
303             symbol,
304             instance,
305             mir,
306         }
307     }
308
309     pub fn define(
310         &mut self,
311         context: &Context,
312         isa: &dyn cranelift::codegen::isa::TargetIsa,
313         source_info_set: &indexmap::IndexSet<(Span, mir::SourceScope)>,
314     ) {
315         let tcx = self.debug_context.tcx;
316
317         let line_program = &mut self.debug_context.dwarf.unit.line_program;
318
319         line_program.begin_sequence(Some(Address::Symbol {
320             symbol: self.symbol,
321             addend: 0,
322         }));
323
324         let encinfo = isa.encoding_info();
325         let func = &context.func;
326         let mut ebbs = func.layout.ebbs().collect::<Vec<_>>();
327         ebbs.sort_by_key(|ebb| func.offsets[*ebb]); // Ensure inst offsets always increase
328
329         let line_strings = &mut self.debug_context.dwarf.line_strings;
330         let mut create_row_for_span = |line_program: &mut LineProgram, span: Span| {
331             let loc = tcx.sess.source_map().lookup_char_pos(span.lo());
332             let file_id = line_program_add_file(line_program, line_strings, &loc.file.name);
333
334             /*println!(
335                 "srcloc {:>04X} {}:{}:{}",
336                 line_program.row().address_offset,
337                 file.display(),
338                 loc.line,
339                 loc.col.to_u32()
340             );*/
341
342             line_program.row().file = file_id;
343             line_program.row().line = loc.line as u64;
344             line_program.row().column = loc.col.to_u32() as u64 + 1;
345             line_program.generate_row();
346         };
347
348         let mut end = 0;
349         for ebb in ebbs {
350             for (offset, inst, size) in func.inst_offsets(ebb, &encinfo) {
351                 let srcloc = func.srclocs[inst];
352                 line_program.row().address_offset = offset as u64;
353                 if !srcloc.is_default() {
354                     let source_info = *source_info_set.get_index(srcloc.bits() as usize).unwrap();
355                     create_row_for_span(line_program, source_info.0);
356                 } else {
357                     create_row_for_span(line_program, self.mir.span);
358                 }
359                 end = offset + size;
360             }
361         }
362
363         line_program.end_sequence(end as u64);
364
365         let entry = self.debug_context.dwarf.unit.get_mut(self.entry_id);
366         entry.set(gimli::DW_AT_high_pc, AttributeValue::Udata(end as u64));
367
368         {
369             let value_labels_ranges = context.build_value_labels_ranges(isa).unwrap();
370
371             for (value_label, value_loc_ranges) in value_labels_ranges.iter() {
372                 let live_ranges = RangeList(
373                     Some(Range::BaseAddress {
374                         address: Address::Symbol {
375                             symbol: self.symbol,
376                             addend: 0,
377                         },
378                     })
379                     .into_iter()
380                     .chain(
381                         value_loc_ranges
382                             .iter()
383                             .map(|val_loc_range| Range::OffsetPair {
384                                 begin: u64::from(val_loc_range.start),
385                                 end: u64::from(val_loc_range.end),
386                             }),
387                     )
388                     .collect(),
389                 );
390                 let live_ranges_id = self.debug_context.dwarf.unit.ranges.add(live_ranges);
391
392                 let local_ty = tcx.subst_and_normalize_erasing_regions(
393                     self.instance.substs,
394                     ty::ParamEnv::reveal_all(),
395                     &self.mir.local_decls[mir::Local::from_u32(value_label.as_u32())].ty,
396                 );
397                 let local_type = self.debug_context.dwarf_ty(local_ty);
398
399                 let var_id = self
400                     .debug_context
401                     .dwarf
402                     .unit
403                     .add(self.entry_id, gimli::DW_TAG_variable);
404                 let var_entry = self.debug_context.dwarf.unit.get_mut(var_id);
405
406                 var_entry.set(
407                     gimli::DW_AT_ranges,
408                     AttributeValue::RangeListRef(live_ranges_id),
409                 );
410                 var_entry.set(
411                     gimli::DW_AT_name,
412                     AttributeValue::String(format!("{:?}", value_label).into_bytes()),
413                 );
414                 var_entry.set(
415                     gimli::DW_AT_type,
416                     AttributeValue::ThisUnitEntryRef(local_type),
417                 );
418             }
419         }
420
421         self.debug_context
422             .unit_range_list
423             .0
424             .push(Range::StartLength {
425                 begin: Address::Symbol {
426                     symbol: self.symbol,
427                     addend: 0,
428                 },
429                 length: end as u64,
430             });
431     }
432 }
433
434 #[derive(Clone)]
435 struct WriterRelocate {
436     relocs: Vec<DebugReloc>,
437     writer: EndianVec<RunTimeEndian>,
438 }
439
440 impl WriterRelocate {
441     fn new(ctx: &DebugContext) -> Self {
442         WriterRelocate {
443             relocs: Vec::new(),
444             writer: EndianVec::new(ctx.endian),
445         }
446     }
447 }
448
449 impl Writer for WriterRelocate {
450     type Endian = RunTimeEndian;
451
452     fn endian(&self) -> Self::Endian {
453         self.writer.endian()
454     }
455
456     fn len(&self) -> usize {
457         self.writer.len()
458     }
459
460     fn write(&mut self, bytes: &[u8]) -> Result<()> {
461         self.writer.write(bytes)
462     }
463
464     fn write_at(&mut self, offset: usize, bytes: &[u8]) -> Result<()> {
465         self.writer.write_at(offset, bytes)
466     }
467
468     fn write_address(&mut self, address: Address, size: u8) -> Result<()> {
469         match address {
470             Address::Constant(val) => self.write_udata(val, size),
471             Address::Symbol { symbol, addend } => {
472                 let offset = self.len() as u64;
473                 self.relocs.push(DebugReloc {
474                     offset: offset as u32,
475                     size,
476                     name: DebugRelocName::Symbol(symbol),
477                     addend: addend as i64,
478                 });
479                 self.write_udata(0, size)
480             }
481         }
482     }
483
484     // TODO: implement write_eh_pointer
485
486     fn write_offset(&mut self, val: usize, section: SectionId, size: u8) -> Result<()> {
487         let offset = self.len() as u32;
488         self.relocs.push(DebugReloc {
489             offset,
490             size,
491             name: DebugRelocName::Section(section),
492             addend: val as i64,
493         });
494         self.write_udata(0, size)
495     }
496
497     fn write_offset_at(
498         &mut self,
499         offset: usize,
500         val: usize,
501         section: SectionId,
502         size: u8,
503     ) -> Result<()> {
504         self.relocs.push(DebugReloc {
505             offset: offset as u32,
506             size,
507             name: DebugRelocName::Section(section),
508             addend: val as i64,
509         });
510         self.write_udata_at(offset, 0, size)
511     }
512 }