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