]> git.lizzy.rs Git - rust.git/blob - src/debuginfo/mod.rs
Dedup file hashing logic with type
[rust.git] / src / debuginfo / mod.rs
1 mod emit;
2 mod line_info;
3
4 use std::convert::TryFrom;
5
6 use crate::prelude::*;
7
8 use rustc_span::FileName;
9
10 use cranelift_codegen::ir::{StackSlots, ValueLabel, ValueLoc};
11 use cranelift_codegen::isa::TargetIsa;
12 use cranelift_codegen::ValueLocRange;
13
14 use gimli::write::{
15     self, Address, AttributeValue, DwarfUnit, Expression, LineProgram, LineString, Location,
16     LocationList, Range, RangeList, UnitEntryId, Writer, FileInfo,
17 };
18 use gimli::{Encoding, Format, LineEncoding, RunTimeEndian, X86_64};
19
20 pub(crate) use emit::{DebugReloc, DebugRelocName};
21
22 fn target_endian(tcx: TyCtxt<'_>) -> RunTimeEndian {
23     use rustc_target::abi::Endian;
24
25     match tcx.data_layout.endian {
26         Endian::Big => RunTimeEndian::Big,
27         Endian::Little => RunTimeEndian::Little,
28     }
29 }
30
31 pub(crate) struct DebugContext<'tcx> {
32     tcx: TyCtxt<'tcx>,
33
34     endian: RunTimeEndian,
35     symbols: indexmap::IndexMap<FuncId, String>,
36
37     dwarf: DwarfUnit,
38     unit_range_list: RangeList,
39
40     types: FxHashMap<Ty<'tcx>, UnitEntryId>,
41 }
42
43 impl<'tcx> DebugContext<'tcx> {
44     pub(crate) fn new(tcx: TyCtxt<'tcx>, address_size: u8) -> Self {
45         let encoding = Encoding {
46             format: Format::Dwarf32,
47             // TODO: this should be configurable
48             // macOS doesn't seem to support DWARF > 3
49             // 5 version is required for md5 file hash
50             version: if tcx.sess.target.target.options.is_like_osx {
51                 3
52             } else {
53                 5
54             },
55             address_size,
56         };
57
58         let mut dwarf = DwarfUnit::new(encoding);
59
60         // FIXME: how to get version when building out of tree?
61         // Normally this would use option_env!("CFG_VERSION").
62         let producer = format!("cg_clif (rustc {})", "unknown version");
63         let comp_dir = tcx.sess.working_dir.0.to_string_lossy().into_owned();
64         let (name, file_hash) = match tcx.sess.local_crate_source_file.clone() {
65             Some(path) => {
66                 let name = path.to_string_lossy().into_owned();
67                 let hash = tcx.sess
68                     .source_map()
69                     .get_source_file(&FileName::Real(path))
70                     .and_then(|f| line_info::FileHash::try_from(f.src_hash).ok());
71                 (name, hash)
72             },
73             None => (tcx.crate_name(LOCAL_CRATE).to_string(), None),
74         };
75
76         let mut line_program = LineProgram::new(
77             encoding,
78             LineEncoding::default(),
79             LineString::new(comp_dir.as_bytes(), encoding, &mut dwarf.line_strings),
80             LineString::new(name.as_bytes(), encoding, &mut dwarf.line_strings),
81             Some(FileInfo {
82                 timestamp: 0,
83                 size: 0,
84                 md5: file_hash.unwrap_or_default().inner(),
85             }),
86         );
87         line_program.file_has_md5 = file_hash.is_some();
88
89         dwarf.unit.line_program = line_program;
90
91         {
92             let name = dwarf.strings.add(name);
93             let comp_dir = dwarf.strings.add(comp_dir);
94
95             let root = dwarf.unit.root();
96             let root = dwarf.unit.get_mut(root);
97             root.set(
98                 gimli::DW_AT_producer,
99                 AttributeValue::StringRef(dwarf.strings.add(producer)),
100             );
101             root.set(
102                 gimli::DW_AT_language,
103                 AttributeValue::Language(gimli::DW_LANG_Rust),
104             );
105             root.set(gimli::DW_AT_name, AttributeValue::StringRef(name));
106             root.set(gimli::DW_AT_comp_dir, AttributeValue::StringRef(comp_dir));
107             root.set(
108                 gimli::DW_AT_low_pc,
109                 AttributeValue::Address(Address::Constant(0)),
110             );
111         }
112
113         DebugContext {
114             tcx,
115
116             endian: target_endian(tcx),
117             symbols: indexmap::IndexMap::new(),
118
119             dwarf,
120             unit_range_list: RangeList(Vec::new()),
121
122             types: FxHashMap::default(),
123         }
124     }
125
126     fn dwarf_ty(&mut self, ty: Ty<'tcx>) -> UnitEntryId {
127         if let Some(type_id) = self.types.get(ty) {
128             return *type_id;
129         }
130
131         let new_entry = |dwarf: &mut DwarfUnit, tag| dwarf.unit.add(dwarf.unit.root(), tag);
132
133         let primitive = |dwarf: &mut DwarfUnit, ate| {
134             let type_id = new_entry(dwarf, gimli::DW_TAG_base_type);
135             let type_entry = dwarf.unit.get_mut(type_id);
136             type_entry.set(gimli::DW_AT_encoding, AttributeValue::Encoding(ate));
137             type_id
138         };
139
140         let name = format!("{}", ty);
141         let layout = self.tcx.layout_of(ParamEnv::reveal_all().and(ty)).unwrap();
142
143         let type_id = match ty.kind {
144             ty::Bool => primitive(&mut self.dwarf, gimli::DW_ATE_boolean),
145             ty::Char => primitive(&mut self.dwarf, gimli::DW_ATE_UTF),
146             ty::Uint(_) => primitive(&mut self.dwarf, gimli::DW_ATE_unsigned),
147             ty::Int(_) => primitive(&mut self.dwarf, gimli::DW_ATE_signed),
148             ty::Float(_) => primitive(&mut self.dwarf, gimli::DW_ATE_float),
149             ty::Ref(_, pointee_ty, _mutbl)
150             | ty::RawPtr(ty::TypeAndMut {
151                 ty: pointee_ty,
152                 mutbl: _mutbl,
153             }) => {
154                 let type_id = new_entry(&mut self.dwarf, gimli::DW_TAG_pointer_type);
155
156                 // Ensure that type is inserted before recursing to avoid duplicates
157                 self.types.insert(ty, type_id);
158
159                 let pointee = self.dwarf_ty(pointee_ty);
160
161                 let type_entry = self.dwarf.unit.get_mut(type_id);
162
163                 //type_entry.set(gimli::DW_AT_mutable, AttributeValue::Flag(mutbl == rustc_hir::Mutability::Mut));
164                 type_entry.set(gimli::DW_AT_type, AttributeValue::ThisUnitEntryRef(pointee));
165
166                 type_id
167             }
168             ty::Adt(adt_def, _substs) if adt_def.is_struct() && !layout.is_unsized() => {
169                 let type_id = new_entry(&mut self.dwarf, gimli::DW_TAG_structure_type);
170
171                 // Ensure that type is inserted before recursing to avoid duplicates
172                 self.types.insert(ty, type_id);
173
174                 let variant = adt_def.non_enum_variant();
175
176                 for (field_idx, field_def) in variant.fields.iter().enumerate() {
177                     let field_offset = layout.fields.offset(field_idx);
178                     let field_layout = layout.field(&layout::LayoutCx {
179                         tcx: self.tcx,
180                         param_env: ParamEnv::reveal_all(),
181                     }, field_idx).unwrap();
182
183                     let field_type = self.dwarf_ty(field_layout.ty);
184
185                     let field_id = self.dwarf.unit.add(type_id, gimli::DW_TAG_member);
186                     let field_entry = self.dwarf.unit.get_mut(field_id);
187
188                     field_entry.set(gimli::DW_AT_name, AttributeValue::String(field_def.ident.as_str().to_string().into_bytes()));
189                     field_entry.set(gimli::DW_AT_data_member_location, AttributeValue::Udata(field_offset.bytes()));
190                     field_entry.set(gimli::DW_AT_type, AttributeValue::ThisUnitEntryRef(field_type));
191                 }
192
193                 type_id
194             }
195             _ => new_entry(&mut self.dwarf, gimli::DW_TAG_structure_type),
196         };
197
198         let type_entry = self.dwarf.unit.get_mut(type_id);
199
200         type_entry.set(gimli::DW_AT_name, AttributeValue::String(name.into_bytes()));
201         type_entry.set(
202             gimli::DW_AT_byte_size,
203             AttributeValue::Udata(layout.size.bytes()),
204         );
205
206         self.types.insert(ty, type_id);
207
208         type_id
209     }
210 }
211
212 pub(crate) struct FunctionDebugContext<'a, 'tcx> {
213     debug_context: &'a mut DebugContext<'tcx>,
214     entry_id: UnitEntryId,
215     symbol: usize,
216     instance: Instance<'tcx>,
217     mir: &'tcx mir::Body<'tcx>,
218 }
219
220 impl<'a, 'tcx> FunctionDebugContext<'a, 'tcx> {
221     pub(crate) fn new(
222         debug_context: &'a mut DebugContext<'tcx>,
223         instance: Instance<'tcx>,
224         func_id: FuncId,
225         name: &str,
226     ) -> Self {
227         let mir = *debug_context.tcx.instance_mir(instance.def);
228
229         let (symbol, _) = debug_context.symbols.insert_full(func_id, name.to_string());
230
231         // FIXME: add to appropriate scope intead of root
232         let scope = debug_context.dwarf.unit.root();
233
234         let entry_id = debug_context
235             .dwarf
236             .unit
237             .add(scope, gimli::DW_TAG_subprogram);
238         let entry = debug_context.dwarf.unit.get_mut(entry_id);
239         let name_id = debug_context.dwarf.strings.add(name);
240         entry.set(
241             gimli::DW_AT_linkage_name,
242             AttributeValue::StringRef(name_id),
243         );
244
245         FunctionDebugContext {
246             debug_context,
247             entry_id,
248             symbol,
249             instance,
250             mir,
251         }
252     }
253
254     fn define_local(&mut self, name: String, ty: Ty<'tcx>) -> UnitEntryId {
255         let ty = self.debug_context.tcx.subst_and_normalize_erasing_regions(
256             self.instance.substs,
257             ty::ParamEnv::reveal_all(),
258             &ty,
259         );
260         let dw_ty = self.debug_context.dwarf_ty(ty);
261
262         let var_id = self
263             .debug_context
264             .dwarf
265             .unit
266             .add(self.entry_id, gimli::DW_TAG_variable);
267         let var_entry = self.debug_context.dwarf.unit.get_mut(var_id);
268
269         var_entry.set(gimli::DW_AT_name, AttributeValue::String(name.into_bytes()));
270         var_entry.set(gimli::DW_AT_type, AttributeValue::ThisUnitEntryRef(dw_ty));
271
272         var_id
273     }
274
275     pub(crate) fn define(
276         &mut self,
277         context: &Context,
278         isa: &dyn TargetIsa,
279         source_info_set: &indexmap::IndexSet<SourceInfo>,
280         local_map: FxHashMap<mir::Local, CPlace<'tcx>>,
281     ) {
282         let end = self.create_debug_lines(context, isa, source_info_set);
283
284         self.debug_context
285             .unit_range_list
286             .0
287             .push(Range::StartLength {
288                 begin: Address::Symbol {
289                     symbol: self.symbol,
290                     addend: 0,
291                 },
292                 length: end as u64,
293             });
294
295         // FIXME make it more reliable and implement scopes before re-enabling this.
296         if false {
297             let value_labels_ranges = context.build_value_labels_ranges(isa).unwrap();
298
299             for (local, _local_decl) in self.mir.local_decls.iter_enumerated() {
300                 let var_id = self.define_local(format!("{:?}", local), &self.mir.local_decls[local].ty);
301
302                 let location = place_location(
303                     self,
304                     isa,
305                     context,
306                     &local_map,
307                     &value_labels_ranges,
308                     Place {
309                         local,
310                         projection: ty::List::empty(),
311                     },
312                 );
313
314                 let var_entry = self.debug_context.dwarf.unit.get_mut(var_id);
315                 var_entry.set(gimli::DW_AT_location, location);
316             }
317         }
318
319         // FIXME create locals for all entries in mir.var_debug_info
320     }
321 }
322
323 fn place_location<'a, 'tcx>(
324     func_debug_ctx: &mut FunctionDebugContext<'a, 'tcx>,
325     isa: &dyn TargetIsa,
326     context: &Context,
327     local_map: &FxHashMap<mir::Local, CPlace<'tcx>>,
328     #[allow(rustc::default_hash_types)]
329     value_labels_ranges: &std::collections::HashMap<ValueLabel, Vec<ValueLocRange>>,
330     place: Place<'tcx>,
331 ) -> AttributeValue {
332     assert!(place.projection.is_empty()); // FIXME implement them
333
334     match local_map[&place.local].inner() {
335         CPlaceInner::Var(local) => {
336             let value_label = cranelift_codegen::ir::ValueLabel::from_u32(local.as_u32());
337             if let Some(value_loc_ranges) = value_labels_ranges.get(&value_label) {
338                 let loc_list = LocationList(
339                     value_loc_ranges
340                         .iter()
341                         .map(|value_loc_range| Location::StartEnd {
342                             begin: Address::Symbol {
343                                 symbol: func_debug_ctx.symbol,
344                                 addend: i64::from(value_loc_range.start),
345                             },
346                             end: Address::Symbol {
347                                 symbol: func_debug_ctx.symbol,
348                                 addend: i64::from(value_loc_range.end),
349                             },
350                             data: Expression(
351                                 translate_loc(isa, value_loc_range.loc, &context.func.stack_slots).unwrap(),
352                             ),
353                         })
354                         .collect(),
355                 );
356                 let loc_list_id = func_debug_ctx.debug_context.dwarf.unit.locations.add(loc_list);
357
358                 AttributeValue::LocationListRef(loc_list_id)
359             } else {
360                 // FIXME set value labels for unused locals
361
362                 AttributeValue::Exprloc(Expression(vec![]))
363             }
364         }
365         CPlaceInner::Addr(_, _) => {
366             // FIXME implement this (used by arguments and returns)
367
368             AttributeValue::Exprloc(Expression(vec![]))
369
370             // For PointerBase::Stack:
371             //AttributeValue::Exprloc(Expression(translate_loc(ValueLoc::Stack(*stack_slot), &context.func.stack_slots).unwrap()))
372         }
373     }
374 }
375
376 // Adapted from https://github.com/CraneStation/wasmtime/blob/5a1845b4caf7a5dba8eda1fef05213a532ed4259/crates/debug/src/transform/expression.rs#L59-L137
377 fn translate_loc(isa: &dyn TargetIsa, loc: ValueLoc, stack_slots: &StackSlots) -> Option<Vec<u8>> {
378     match loc {
379         ValueLoc::Reg(reg) => {
380             let machine_reg = isa.map_dwarf_register(reg).unwrap();
381             assert!(machine_reg <= 32); // FIXME
382             Some(vec![gimli::constants::DW_OP_reg0.0 + machine_reg as u8])
383         }
384         ValueLoc::Stack(ss) => {
385             if let Some(ss_offset) = stack_slots[ss].offset {
386                 let endian = gimli::RunTimeEndian::Little;
387                 let mut writer = write::EndianVec::new(endian);
388                 writer
389                     .write_u8(gimli::constants::DW_OP_breg0.0 + X86_64::RBP.0 as u8)
390                     .expect("bp wr");
391                 writer.write_sleb128(ss_offset as i64 + 16).expect("ss wr");
392                 let buf = writer.into_vec();
393                 return Some(buf);
394             }
395             None
396         }
397         _ => None,
398     }
399 }