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