]> git.lizzy.rs Git - rust.git/blob - src/debuginfo/mod.rs
Fix function arguments for gdb
[rust.git] / src / debuginfo / mod.rs
1 mod emit;
2 mod line_info;
3
4 use crate::prelude::*;
5
6 use rustc_span::FileName;
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,
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 pub(crate) struct DebugContext<'tcx> {
30     tcx: TyCtxt<'tcx>,
31
32     endian: RunTimeEndian,
33     symbols: indexmap::IndexMap<FuncId, String>,
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>, address_size: u8) -> 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,
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                 let info = tcx.sess
69                     .source_map()
70                     .get_source_file(&FileName::Real(path))
71                     .map(|f| f.src_hash)
72                     .and_then(line_info::make_file_info);
73                 (name, info)
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(
96                 gimli::DW_AT_producer,
97                 AttributeValue::StringRef(dwarf.strings.add(producer)),
98             );
99             root.set(
100                 gimli::DW_AT_language,
101                 AttributeValue::Language(gimli::DW_LANG_Rust),
102             );
103             root.set(gimli::DW_AT_name, AttributeValue::StringRef(name));
104             root.set(gimli::DW_AT_comp_dir, AttributeValue::StringRef(comp_dir));
105             root.set(
106                 gimli::DW_AT_low_pc,
107                 AttributeValue::Address(Address::Constant(0)),
108             );
109         }
110
111         DebugContext {
112             tcx,
113
114             endian: target_endian(tcx),
115             symbols: indexmap::IndexMap::new(),
116
117             dwarf,
118             unit_range_list: RangeList(Vec::new()),
119
120             clif_types: FxHashMap::default(),
121             types: FxHashMap::default(),
122         }
123     }
124
125     fn dwarf_ty_for_clif_ty(&mut self, ty: Type) -> UnitEntryId {
126         if let Some(type_id) = self.clif_types.get(&ty) {
127             return *type_id;
128         }
129
130         let new_entry = |dwarf: &mut DwarfUnit, tag| dwarf.unit.add(dwarf.unit.root(), tag);
131
132         let primitive = |dwarf: &mut DwarfUnit, ate| {
133             let type_id = new_entry(dwarf, gimli::DW_TAG_base_type);
134             let type_entry = dwarf.unit.get_mut(type_id);
135             type_entry.set(gimli::DW_AT_encoding, AttributeValue::Encoding(ate));
136             type_id
137         };
138
139         let type_id = if ty.is_bool() {
140             primitive(&mut self.dwarf, gimli::DW_ATE_boolean)
141         } else if ty.is_int() {
142             primitive(&mut self.dwarf, gimli::DW_ATE_address)
143         } else if ty.is_float() {
144             primitive(&mut self.dwarf, gimli::DW_ATE_float)
145         } else {
146             new_entry(&mut self.dwarf, gimli::DW_TAG_structure_type)
147         };
148
149         let type_entry = self.dwarf.unit.get_mut(type_id);
150         type_entry.set(gimli::DW_AT_name, AttributeValue::String(format!("{}", ty).replace('i', "u").into_bytes()));
151         type_entry.set(
152             gimli::DW_AT_byte_size,
153             AttributeValue::Udata(u64::from(ty.bytes())),
154         );
155
156         type_id
157     }
158
159     fn dwarf_ty(&mut self, ty: Ty<'tcx>) -> UnitEntryId {
160         if let Some(type_id) = self.types.get(ty) {
161             return *type_id;
162         }
163
164         let new_entry = |dwarf: &mut DwarfUnit, tag| dwarf.unit.add(dwarf.unit.root(), tag);
165
166         let primitive = |dwarf: &mut DwarfUnit, ate| {
167             let type_id = new_entry(dwarf, gimli::DW_TAG_base_type);
168             let type_entry = dwarf.unit.get_mut(type_id);
169             type_entry.set(gimli::DW_AT_encoding, AttributeValue::Encoding(ate));
170             type_id
171         };
172
173         let name = format!("{}", ty);
174         let layout = self.tcx.layout_of(ParamEnv::reveal_all().and(ty)).unwrap();
175
176         let type_id = match ty.kind {
177             ty::Bool => primitive(&mut self.dwarf, gimli::DW_ATE_boolean),
178             ty::Char => primitive(&mut self.dwarf, gimli::DW_ATE_UTF),
179             ty::Uint(_) => primitive(&mut self.dwarf, gimli::DW_ATE_unsigned),
180             ty::Int(_) => primitive(&mut self.dwarf, gimli::DW_ATE_signed),
181             ty::Float(_) => primitive(&mut self.dwarf, gimli::DW_ATE_float),
182             ty::Ref(_, pointee_ty, _mutbl)
183             | ty::RawPtr(ty::TypeAndMut {
184                 ty: pointee_ty,
185                 mutbl: _mutbl,
186             }) => {
187                 let type_id = new_entry(&mut self.dwarf, gimli::DW_TAG_pointer_type);
188
189                 // Ensure that type is inserted before recursing to avoid duplicates
190                 self.types.insert(ty, type_id);
191
192                 let pointee = self.dwarf_ty(pointee_ty);
193
194                 let type_entry = self.dwarf.unit.get_mut(type_id);
195
196                 //type_entry.set(gimli::DW_AT_mutable, AttributeValue::Flag(mutbl == rustc_hir::Mutability::Mut));
197                 type_entry.set(gimli::DW_AT_type, AttributeValue::ThisUnitEntryRef(pointee));
198
199                 type_id
200             }
201             ty::Adt(adt_def, _substs) if adt_def.is_struct() && !layout.is_unsized() => {
202                 let type_id = new_entry(&mut self.dwarf, gimli::DW_TAG_structure_type);
203
204                 // Ensure that type is inserted before recursing to avoid duplicates
205                 self.types.insert(ty, type_id);
206
207                 let variant = adt_def.non_enum_variant();
208
209                 for (field_idx, field_def) in variant.fields.iter().enumerate() {
210                     let field_offset = layout.fields.offset(field_idx);
211                     let field_layout = layout.field(&layout::LayoutCx {
212                         tcx: self.tcx,
213                         param_env: ParamEnv::reveal_all(),
214                     }, field_idx).unwrap();
215
216                     let field_type = self.dwarf_ty(field_layout.ty);
217
218                     let field_id = self.dwarf.unit.add(type_id, gimli::DW_TAG_member);
219                     let field_entry = self.dwarf.unit.get_mut(field_id);
220
221                     field_entry.set(gimli::DW_AT_name, AttributeValue::String(field_def.ident.as_str().to_string().into_bytes()));
222                     field_entry.set(gimli::DW_AT_data_member_location, AttributeValue::Udata(field_offset.bytes()));
223                     field_entry.set(gimli::DW_AT_type, AttributeValue::ThisUnitEntryRef(field_type));
224                 }
225
226                 type_id
227             }
228             _ => new_entry(&mut self.dwarf, gimli::DW_TAG_structure_type),
229         };
230
231         let type_entry = self.dwarf.unit.get_mut(type_id);
232
233         type_entry.set(gimli::DW_AT_name, AttributeValue::String(name.into_bytes()));
234         type_entry.set(
235             gimli::DW_AT_byte_size,
236             AttributeValue::Udata(layout.size.bytes()),
237         );
238
239         self.types.insert(ty, type_id);
240
241         type_id
242     }
243 }
244
245 pub(crate) struct FunctionDebugContext<'a, 'tcx> {
246     debug_context: &'a mut DebugContext<'tcx>,
247     entry_id: UnitEntryId,
248     symbol: usize,
249     instance: Instance<'tcx>,
250     mir: &'tcx mir::Body<'tcx>,
251 }
252
253 impl<'a, 'tcx> FunctionDebugContext<'a, 'tcx> {
254     pub(crate) fn new(
255         debug_context: &'a mut DebugContext<'tcx>,
256         instance: Instance<'tcx>,
257         func_id: FuncId,
258         name: &str,
259     ) -> Self {
260         let mir = *debug_context.tcx.instance_mir(instance.def);
261
262         let (symbol, _) = debug_context.symbols.insert_full(func_id, name.to_string());
263
264         // FIXME: add to appropriate scope intead of root
265         let scope = debug_context.dwarf.unit.root();
266
267         let entry_id = debug_context
268             .dwarf
269             .unit
270             .add(scope, gimli::DW_TAG_subprogram);
271         let entry = debug_context.dwarf.unit.get_mut(entry_id);
272         let name_id = debug_context.dwarf.strings.add(name);
273         // Gdb requires DW_AT_name. Otherwise the DW_TAG_subprogram is skipped.
274         entry.set(
275             gimli::DW_AT_name,
276             AttributeValue::StringRef(name_id),
277         );
278         entry.set(
279             gimli::DW_AT_linkage_name,
280             AttributeValue::StringRef(name_id),
281         );
282
283         FunctionDebugContext {
284             debug_context,
285             entry_id,
286             symbol,
287             instance,
288             mir,
289         }
290     }
291
292     fn define_local(&mut self, name: String, ty: Ty<'tcx>) -> UnitEntryId {
293         let dw_ty = self.debug_context.dwarf_ty(ty);
294
295         let var_id = self
296             .debug_context
297             .dwarf
298             .unit
299             .add(self.entry_id, gimli::DW_TAG_variable);
300         let var_entry = self.debug_context.dwarf.unit.get_mut(var_id);
301
302         var_entry.set(gimli::DW_AT_name, AttributeValue::String(name.into_bytes()));
303         var_entry.set(gimli::DW_AT_type, AttributeValue::ThisUnitEntryRef(dw_ty));
304
305         var_id
306     }
307
308     pub(crate) fn define(
309         &mut self,
310         context: &Context,
311         isa: &dyn TargetIsa,
312         source_info_set: &indexmap::IndexSet<SourceInfo>,
313         local_map: FxHashMap<mir::Local, CPlace<'tcx>>,
314     ) {
315         if isa.get_mach_backend().is_some() {
316             return; // The AArch64 backend doesn't support line debuginfo yet.
317         }
318
319         let end = self.create_debug_lines(context, isa, source_info_set);
320
321         self.debug_context
322             .unit_range_list
323             .0
324             .push(Range::StartLength {
325                 begin: Address::Symbol {
326                     symbol: self.symbol,
327                     addend: 0,
328                 },
329                 length: u64::from(end),
330             });
331
332         let func_entry = self.debug_context.dwarf.unit.get_mut(self.entry_id);
333         // Gdb requires both DW_AT_low_pc and DW_AT_high_pc. Otherwise the DW_TAG_subprogram is skipped.
334         func_entry.set(gimli::DW_AT_low_pc, AttributeValue::Address(Address::Symbol {
335             symbol: self.symbol,
336             addend: 0,
337         }));
338         // Using Udata for DW_AT_high_pc requires at least DWARF4
339         func_entry.set(gimli::DW_AT_high_pc, AttributeValue::Udata(u64::from(end)));
340
341         // FIXME Remove once actual debuginfo for locals works.
342         for (i, (param, &val)) in context.func.signature.params.iter().zip(context.func.dfg.block_params(context.func.layout.entry_block().unwrap())).enumerate() {
343             use cranelift_codegen::ir::ArgumentPurpose;
344             let base_name = match param.purpose {
345                 ArgumentPurpose::Normal => "arg",
346                 ArgumentPurpose::StructReturn => "sret",
347                 ArgumentPurpose::Link | ArgumentPurpose::FramePointer | ArgumentPurpose::CalleeSaved => continue,
348                 ArgumentPurpose::VMContext | ArgumentPurpose::SignatureId | ArgumentPurpose::StackLimit => unreachable!(),
349             };
350             let name = format!("{}{}", base_name, i);
351
352             let dw_ty = self.debug_context.dwarf_ty_for_clif_ty(param.value_type);
353             let loc = Expression(
354                 translate_loc(isa, context.func.locations[val], &context.func.stack_slots).unwrap(),
355             );
356
357             let arg_id = self.debug_context.dwarf.unit.add(self.entry_id, gimli::DW_TAG_formal_parameter);
358             let var_entry = self.debug_context.dwarf.unit.get_mut(arg_id);
359
360             var_entry.set(gimli::DW_AT_name, AttributeValue::String(name.into_bytes()));
361             var_entry.set(gimli::DW_AT_type, AttributeValue::ThisUnitEntryRef(dw_ty));
362             var_entry.set(gimli::DW_AT_location, AttributeValue::Exprloc(loc));
363         }
364
365         // FIXME make it more reliable and implement scopes before re-enabling this.
366         if false {
367             let value_labels_ranges = context.build_value_labels_ranges(isa).unwrap();
368
369             for (local, _local_decl) in self.mir.local_decls.iter_enumerated() {
370                 let ty = self.debug_context.tcx.subst_and_normalize_erasing_regions(
371                     self.instance.substs,
372                     ty::ParamEnv::reveal_all(),
373                     &self.mir.local_decls[local].ty,
374                 );
375                 let var_id = self.define_local(format!("{:?}", local), ty);
376
377                 let location = place_location(
378                     self,
379                     isa,
380                     context,
381                     &local_map,
382                     &value_labels_ranges,
383                     Place {
384                         local,
385                         projection: ty::List::empty(),
386                     },
387                 );
388
389                 let var_entry = self.debug_context.dwarf.unit.get_mut(var_id);
390                 var_entry.set(gimli::DW_AT_location, location);
391             }
392         }
393
394         // FIXME create locals for all entries in mir.var_debug_info
395     }
396 }
397
398 fn place_location<'a, 'tcx>(
399     func_debug_ctx: &mut FunctionDebugContext<'a, 'tcx>,
400     isa: &dyn TargetIsa,
401     context: &Context,
402     local_map: &FxHashMap<mir::Local, CPlace<'tcx>>,
403     #[allow(rustc::default_hash_types)]
404     value_labels_ranges: &std::collections::HashMap<ValueLabel, Vec<ValueLocRange>>,
405     place: Place<'tcx>,
406 ) -> AttributeValue {
407     assert!(place.projection.is_empty()); // FIXME implement them
408
409     match local_map[&place.local].inner() {
410         CPlaceInner::Var(local) => {
411             let value_label = cranelift_codegen::ir::ValueLabel::from_u32(local.as_u32());
412             if let Some(value_loc_ranges) = value_labels_ranges.get(&value_label) {
413                 let loc_list = LocationList(
414                     value_loc_ranges
415                         .iter()
416                         .map(|value_loc_range| Location::StartEnd {
417                             begin: Address::Symbol {
418                                 symbol: func_debug_ctx.symbol,
419                                 addend: i64::from(value_loc_range.start),
420                             },
421                             end: Address::Symbol {
422                                 symbol: func_debug_ctx.symbol,
423                                 addend: i64::from(value_loc_range.end),
424                             },
425                             data: Expression(
426                                 translate_loc(isa, value_loc_range.loc, &context.func.stack_slots).unwrap(),
427                             ),
428                         })
429                         .collect(),
430                 );
431                 let loc_list_id = func_debug_ctx.debug_context.dwarf.unit.locations.add(loc_list);
432
433                 AttributeValue::LocationListRef(loc_list_id)
434             } else {
435                 // FIXME set value labels for unused locals
436
437                 AttributeValue::Exprloc(Expression(vec![]))
438             }
439         }
440         CPlaceInner::Addr(_, _) => {
441             // FIXME implement this (used by arguments and returns)
442
443             AttributeValue::Exprloc(Expression(vec![]))
444
445             // For PointerBase::Stack:
446             //AttributeValue::Exprloc(Expression(translate_loc(ValueLoc::Stack(*stack_slot), &context.func.stack_slots).unwrap()))
447         }
448     }
449 }
450
451 // Adapted from https://github.com/CraneStation/wasmtime/blob/5a1845b4caf7a5dba8eda1fef05213a532ed4259/crates/debug/src/transform/expression.rs#L59-L137
452 fn translate_loc(isa: &dyn TargetIsa, loc: ValueLoc, stack_slots: &StackSlots) -> Option<Vec<u8>> {
453     match loc {
454         ValueLoc::Reg(reg) => {
455             let machine_reg = isa.map_dwarf_register(reg).unwrap();
456             assert!(machine_reg <= 32); // FIXME
457             Some(vec![gimli::constants::DW_OP_reg0.0 + machine_reg as u8])
458         }
459         ValueLoc::Stack(ss) => {
460             if let Some(ss_offset) = stack_slots[ss].offset {
461                 let endian = gimli::RunTimeEndian::Little;
462                 let mut writer = write::EndianVec::new(endian);
463                 writer
464                     .write_u8(gimli::constants::DW_OP_breg0.0 + X86_64::RBP.0 as u8)
465                     .expect("bp wr");
466                 writer.write_sleb128(ss_offset as i64 + 16).expect("ss wr");
467                 let buf = writer.into_vec();
468                 return Some(buf);
469             }
470             None
471         }
472         _ => None,
473     }
474 }