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