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