]> git.lizzy.rs Git - rust.git/blob - src/debuginfo/mod.rs
fmt: Run cargo fmt since it is available
[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, LineString, Location,
14     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(
145             gimli::DW_AT_name,
146             AttributeValue::String(format!("{}", ty).replace('i', "u").into_bytes()),
147         );
148         type_entry.set(
149             gimli::DW_AT_byte_size,
150             AttributeValue::Udata(u64::from(ty.bytes())),
151         );
152
153         type_id
154     }
155
156     fn dwarf_ty(&mut self, ty: Ty<'tcx>) -> UnitEntryId {
157         if let Some(type_id) = self.types.get(ty) {
158             return *type_id;
159         }
160
161         let new_entry = |dwarf: &mut DwarfUnit, tag| dwarf.unit.add(dwarf.unit.root(), tag);
162
163         let primitive = |dwarf: &mut DwarfUnit, ate| {
164             let type_id = new_entry(dwarf, gimli::DW_TAG_base_type);
165             let type_entry = dwarf.unit.get_mut(type_id);
166             type_entry.set(gimli::DW_AT_encoding, AttributeValue::Encoding(ate));
167             type_id
168         };
169
170         let name = format!("{}", ty);
171         let layout = self.tcx.layout_of(ParamEnv::reveal_all().and(ty)).unwrap();
172
173         let type_id = match ty.kind {
174             ty::Bool => primitive(&mut self.dwarf, gimli::DW_ATE_boolean),
175             ty::Char => primitive(&mut self.dwarf, gimli::DW_ATE_UTF),
176             ty::Uint(_) => primitive(&mut self.dwarf, gimli::DW_ATE_unsigned),
177             ty::Int(_) => primitive(&mut self.dwarf, gimli::DW_ATE_signed),
178             ty::Float(_) => primitive(&mut self.dwarf, gimli::DW_ATE_float),
179             ty::Ref(_, pointee_ty, _mutbl)
180             | ty::RawPtr(ty::TypeAndMut {
181                 ty: pointee_ty,
182                 mutbl: _mutbl,
183             }) => {
184                 let type_id = new_entry(&mut self.dwarf, gimli::DW_TAG_pointer_type);
185
186                 // Ensure that type is inserted before recursing to avoid duplicates
187                 self.types.insert(ty, type_id);
188
189                 let pointee = self.dwarf_ty(pointee_ty);
190
191                 let type_entry = self.dwarf.unit.get_mut(type_id);
192
193                 //type_entry.set(gimli::DW_AT_mutable, AttributeValue::Flag(mutbl == rustc_hir::Mutability::Mut));
194                 type_entry.set(gimli::DW_AT_type, AttributeValue::UnitRef(pointee));
195
196                 type_id
197             }
198             ty::Adt(adt_def, _substs) if adt_def.is_struct() && !layout.is_unsized() => {
199                 let type_id = new_entry(&mut self.dwarf, gimli::DW_TAG_structure_type);
200
201                 // Ensure that type is inserted before recursing to avoid duplicates
202                 self.types.insert(ty, type_id);
203
204                 let variant = adt_def.non_enum_variant();
205
206                 for (field_idx, field_def) in variant.fields.iter().enumerate() {
207                     let field_offset = layout.fields.offset(field_idx);
208                     let field_layout = layout
209                         .field(
210                             &layout::LayoutCx {
211                                 tcx: self.tcx,
212                                 param_env: ParamEnv::reveal_all(),
213                             },
214                             field_idx,
215                         )
216                         .unwrap();
217
218                     let field_type = self.dwarf_ty(field_layout.ty);
219
220                     let field_id = self.dwarf.unit.add(type_id, gimli::DW_TAG_member);
221                     let field_entry = self.dwarf.unit.get_mut(field_id);
222
223                     field_entry.set(
224                         gimli::DW_AT_name,
225                         AttributeValue::String(field_def.ident.as_str().to_string().into_bytes()),
226                     );
227                     field_entry.set(
228                         gimli::DW_AT_data_member_location,
229                         AttributeValue::Udata(field_offset.bytes()),
230                     );
231                     field_entry.set(gimli::DW_AT_type, AttributeValue::UnitRef(field_type));
232                 }
233
234                 type_id
235             }
236             _ => new_entry(&mut self.dwarf, gimli::DW_TAG_structure_type),
237         };
238
239         let type_entry = self.dwarf.unit.get_mut(type_id);
240
241         type_entry.set(gimli::DW_AT_name, AttributeValue::String(name.into_bytes()));
242         type_entry.set(
243             gimli::DW_AT_byte_size,
244             AttributeValue::Udata(layout.size.bytes()),
245         );
246
247         self.types.insert(ty, type_id);
248
249         type_id
250     }
251
252     fn define_local(&mut self, scope: UnitEntryId, name: String, ty: Ty<'tcx>) -> UnitEntryId {
253         let dw_ty = self.dwarf_ty(ty);
254
255         let var_id = self.dwarf.unit.add(scope, gimli::DW_TAG_variable);
256         let var_entry = self.dwarf.unit.get_mut(var_id);
257
258         var_entry.set(gimli::DW_AT_name, AttributeValue::String(name.into_bytes()));
259         var_entry.set(gimli::DW_AT_type, AttributeValue::UnitRef(dw_ty));
260
261         var_id
262     }
263
264     pub(crate) fn define_function(
265         &mut self,
266         instance: Instance<'tcx>,
267         func_id: FuncId,
268         name: &str,
269         isa: &dyn TargetIsa,
270         context: &Context,
271         source_info_set: &indexmap::IndexSet<SourceInfo>,
272         local_map: FxHashMap<mir::Local, CPlace<'tcx>>,
273     ) {
274         let symbol = func_id.as_u32() as usize;
275         let mir = self.tcx.instance_mir(instance.def);
276
277         // FIXME: add to appropriate scope instead of root
278         let scope = self.dwarf.unit.root();
279
280         let entry_id = self.dwarf.unit.add(scope, gimli::DW_TAG_subprogram);
281         let entry = self.dwarf.unit.get_mut(entry_id);
282         let name_id = self.dwarf.strings.add(name);
283         // Gdb requires DW_AT_name. Otherwise the DW_TAG_subprogram is skipped.
284         entry.set(gimli::DW_AT_name, AttributeValue::StringRef(name_id));
285         entry.set(
286             gimli::DW_AT_linkage_name,
287             AttributeValue::StringRef(name_id),
288         );
289
290         let end =
291             self.create_debug_lines(isa, symbol, entry_id, context, mir.span, source_info_set);
292
293         self.unit_range_list.0.push(Range::StartLength {
294             begin: Address::Symbol { symbol, addend: 0 },
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(
305             gimli::DW_AT_low_pc,
306             AttributeValue::Address(Address::Symbol { symbol, 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
313             .func
314             .signature
315             .params
316             .iter()
317             .zip(
318                 context
319                     .func
320                     .dfg
321                     .block_params(context.func.layout.entry_block().unwrap()),
322             )
323             .enumerate()
324         {
325             use cranelift_codegen::ir::ArgumentPurpose;
326             let base_name = match param.purpose {
327                 ArgumentPurpose::Normal => "arg",
328                 ArgumentPurpose::StructArgument(_) => "struct_arg",
329                 ArgumentPurpose::StructReturn => "sret",
330                 ArgumentPurpose::Link
331                 | ArgumentPurpose::FramePointer
332                 | ArgumentPurpose::CalleeSaved => continue,
333                 ArgumentPurpose::VMContext
334                 | ArgumentPurpose::SignatureId
335                 | ArgumentPurpose::StackLimit => unreachable!(),
336             };
337             let name = format!("{}{}", base_name, i);
338
339             let dw_ty = self.dwarf_ty_for_clif_ty(param.value_type);
340             let loc =
341                 translate_loc(isa, context.func.locations[val], &context.func.stack_slots).unwrap();
342
343             let arg_id = self
344                 .dwarf
345                 .unit
346                 .add(entry_id, gimli::DW_TAG_formal_parameter);
347             let var_entry = self.dwarf.unit.get_mut(arg_id);
348
349             var_entry.set(gimli::DW_AT_name, AttributeValue::String(name.into_bytes()));
350             var_entry.set(gimli::DW_AT_type, AttributeValue::UnitRef(dw_ty));
351             var_entry.set(gimli::DW_AT_location, AttributeValue::Exprloc(loc));
352         }
353
354         // FIXME make it more reliable and implement scopes before re-enabling this.
355         if false {
356             let value_labels_ranges = context.build_value_labels_ranges(isa).unwrap();
357
358             for (local, _local_decl) in mir.local_decls.iter_enumerated() {
359                 let ty = self.tcx.subst_and_normalize_erasing_regions(
360                     instance.substs,
361                     ty::ParamEnv::reveal_all(),
362                     &mir.local_decls[local].ty,
363                 );
364                 let var_id = self.define_local(entry_id, format!("{:?}", local), ty);
365
366                 let location = place_location(
367                     self,
368                     isa,
369                     symbol,
370                     context,
371                     &local_map,
372                     &value_labels_ranges,
373                     Place {
374                         local,
375                         projection: ty::List::empty(),
376                     },
377                 );
378
379                 let var_entry = self.dwarf.unit.get_mut(var_id);
380                 var_entry.set(gimli::DW_AT_location, location);
381             }
382         }
383
384         // FIXME create locals for all entries in mir.var_debug_info
385     }
386 }
387
388 fn place_location<'tcx>(
389     debug_context: &mut DebugContext<'tcx>,
390     isa: &dyn TargetIsa,
391     symbol: usize,
392     context: &Context,
393     local_map: &FxHashMap<mir::Local, CPlace<'tcx>>,
394     #[allow(rustc::default_hash_types)] value_labels_ranges: &std::collections::HashMap<
395         ValueLabel,
396         Vec<ValueLocRange>,
397     >,
398     place: Place<'tcx>,
399 ) -> AttributeValue {
400     assert!(place.projection.is_empty()); // FIXME implement them
401
402     match local_map[&place.local].inner() {
403         CPlaceInner::Var(_local, var) => {
404             let value_label = cranelift_codegen::ir::ValueLabel::new(var.index());
405             if let Some(value_loc_ranges) = value_labels_ranges.get(&value_label) {
406                 let loc_list = LocationList(
407                     value_loc_ranges
408                         .iter()
409                         .map(|value_loc_range| Location::StartEnd {
410                             begin: Address::Symbol {
411                                 symbol,
412                                 addend: i64::from(value_loc_range.start),
413                             },
414                             end: Address::Symbol {
415                                 symbol,
416                                 addend: i64::from(value_loc_range.end),
417                             },
418                             data: translate_loc(
419                                 isa,
420                                 value_loc_range.loc,
421                                 &context.func.stack_slots,
422                             )
423                             .unwrap(),
424                         })
425                         .collect(),
426                 );
427                 let loc_list_id = debug_context.dwarf.unit.locations.add(loc_list);
428
429                 AttributeValue::LocationListRef(loc_list_id)
430             } else {
431                 // FIXME set value labels for unused locals
432
433                 AttributeValue::Exprloc(Expression::new())
434             }
435         }
436         CPlaceInner::VarPair(_, _, _) => {
437             // FIXME implement this
438
439             AttributeValue::Exprloc(Expression::new())
440         }
441         CPlaceInner::VarLane(_, _, _) => {
442             // FIXME implement this
443
444             AttributeValue::Exprloc(Expression::new())
445         }
446         CPlaceInner::Addr(_, _) => {
447             // FIXME implement this (used by arguments and returns)
448
449             AttributeValue::Exprloc(Expression::new())
450
451             // For PointerBase::Stack:
452             //AttributeValue::Exprloc(translate_loc(ValueLoc::Stack(*stack_slot), &context.func.stack_slots).unwrap())
453         }
454     }
455 }
456
457 // Adapted from https://github.com/CraneStation/wasmtime/blob/5a1845b4caf7a5dba8eda1fef05213a532ed4259/crates/debug/src/transform/expression.rs#L59-L137
458 fn translate_loc(
459     isa: &dyn TargetIsa,
460     loc: ValueLoc,
461     stack_slots: &StackSlots,
462 ) -> Option<Expression> {
463     match loc {
464         ValueLoc::Reg(reg) => {
465             let machine_reg = isa.map_dwarf_register(reg).unwrap();
466             let mut expr = Expression::new();
467             expr.op_reg(gimli::Register(machine_reg));
468             Some(expr)
469         }
470         ValueLoc::Stack(ss) => {
471             if let Some(ss_offset) = stack_slots[ss].offset {
472                 let mut expr = Expression::new();
473                 expr.op_breg(X86_64::RBP, i64::from(ss_offset) + 16);
474                 Some(expr)
475             } else {
476                 None
477             }
478         }
479         _ => None,
480     }
481 }