]> git.lizzy.rs Git - rust.git/blob - src/debuginfo/mod.rs
Generate simple debuginfo for arguments
[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         entry.set(
274             gimli::DW_AT_linkage_name,
275             AttributeValue::StringRef(name_id),
276         );
277
278         FunctionDebugContext {
279             debug_context,
280             entry_id,
281             symbol,
282             instance,
283             mir,
284         }
285     }
286
287     fn define_local(&mut self, name: String, ty: Ty<'tcx>) -> UnitEntryId {
288         let dw_ty = self.debug_context.dwarf_ty(ty);
289
290         let var_id = self
291             .debug_context
292             .dwarf
293             .unit
294             .add(self.entry_id, gimli::DW_TAG_variable);
295         let var_entry = self.debug_context.dwarf.unit.get_mut(var_id);
296
297         var_entry.set(gimli::DW_AT_name, AttributeValue::String(name.into_bytes()));
298         var_entry.set(gimli::DW_AT_type, AttributeValue::ThisUnitEntryRef(dw_ty));
299
300         var_id
301     }
302
303     pub(crate) fn define(
304         &mut self,
305         context: &Context,
306         isa: &dyn TargetIsa,
307         source_info_set: &indexmap::IndexSet<SourceInfo>,
308         local_map: FxHashMap<mir::Local, CPlace<'tcx>>,
309     ) {
310         if isa.get_mach_backend().is_some() {
311             return; // The AArch64 backend doesn't support line debuginfo yet.
312         }
313
314         let end = self.create_debug_lines(context, isa, source_info_set);
315
316         self.debug_context
317             .unit_range_list
318             .0
319             .push(Range::StartLength {
320                 begin: Address::Symbol {
321                     symbol: self.symbol,
322                     addend: 0,
323                 },
324                 length: u64::from(end),
325             });
326
327         // FIXME Remove once actual debuginfo for locals works.
328         for (i, (param, &val)) in context.func.signature.params.iter().zip(context.func.dfg.block_params(context.func.layout.entry_block().unwrap())).enumerate() {
329             use cranelift_codegen::ir::ArgumentPurpose;
330             let base_name = match param.purpose {
331                 ArgumentPurpose::Normal => "arg",
332                 ArgumentPurpose::StructReturn => "sret",
333                 ArgumentPurpose::Link | ArgumentPurpose::FramePointer | ArgumentPurpose::CalleeSaved => continue,
334                 ArgumentPurpose::VMContext | ArgumentPurpose::SignatureId | ArgumentPurpose::StackLimit => unreachable!(),
335             };
336             let name = format!("{}{}", base_name, i);
337
338             let dw_ty = self.debug_context.dwarf_ty_for_clif_ty(param.value_type);
339             let loc = Expression(
340                 translate_loc(isa, context.func.locations[val], &context.func.stack_slots).unwrap(),
341             );
342
343             let arg_id = self.debug_context.dwarf.unit.add(self.entry_id, gimli::DW_TAG_formal_parameter);
344             let var_entry = self.debug_context.dwarf.unit.get_mut(arg_id);
345
346             var_entry.set(gimli::DW_AT_name, AttributeValue::String(name.into_bytes()));
347             var_entry.set(gimli::DW_AT_type, AttributeValue::ThisUnitEntryRef(dw_ty));
348             var_entry.set(gimli::DW_AT_location, AttributeValue::Exprloc(loc));
349         }
350
351         // FIXME make it more reliable and implement scopes before re-enabling this.
352         if false {
353             let value_labels_ranges = context.build_value_labels_ranges(isa).unwrap();
354
355             for (local, _local_decl) in self.mir.local_decls.iter_enumerated() {
356                 let ty = self.debug_context.tcx.subst_and_normalize_erasing_regions(
357                     self.instance.substs,
358                     ty::ParamEnv::reveal_all(),
359                     &self.mir.local_decls[local].ty,
360                 );
361                 let var_id = self.define_local(format!("{:?}", local), ty);
362
363                 let location = place_location(
364                     self,
365                     isa,
366                     context,
367                     &local_map,
368                     &value_labels_ranges,
369                     Place {
370                         local,
371                         projection: ty::List::empty(),
372                     },
373                 );
374
375                 let var_entry = self.debug_context.dwarf.unit.get_mut(var_id);
376                 var_entry.set(gimli::DW_AT_location, location);
377             }
378         }
379
380         // FIXME create locals for all entries in mir.var_debug_info
381     }
382 }
383
384 fn place_location<'a, 'tcx>(
385     func_debug_ctx: &mut FunctionDebugContext<'a, 'tcx>,
386     isa: &dyn TargetIsa,
387     context: &Context,
388     local_map: &FxHashMap<mir::Local, CPlace<'tcx>>,
389     #[allow(rustc::default_hash_types)]
390     value_labels_ranges: &std::collections::HashMap<ValueLabel, Vec<ValueLocRange>>,
391     place: Place<'tcx>,
392 ) -> AttributeValue {
393     assert!(place.projection.is_empty()); // FIXME implement them
394
395     match local_map[&place.local].inner() {
396         CPlaceInner::Var(local) => {
397             let value_label = cranelift_codegen::ir::ValueLabel::from_u32(local.as_u32());
398             if let Some(value_loc_ranges) = value_labels_ranges.get(&value_label) {
399                 let loc_list = LocationList(
400                     value_loc_ranges
401                         .iter()
402                         .map(|value_loc_range| Location::StartEnd {
403                             begin: Address::Symbol {
404                                 symbol: func_debug_ctx.symbol,
405                                 addend: i64::from(value_loc_range.start),
406                             },
407                             end: Address::Symbol {
408                                 symbol: func_debug_ctx.symbol,
409                                 addend: i64::from(value_loc_range.end),
410                             },
411                             data: Expression(
412                                 translate_loc(isa, value_loc_range.loc, &context.func.stack_slots).unwrap(),
413                             ),
414                         })
415                         .collect(),
416                 );
417                 let loc_list_id = func_debug_ctx.debug_context.dwarf.unit.locations.add(loc_list);
418
419                 AttributeValue::LocationListRef(loc_list_id)
420             } else {
421                 // FIXME set value labels for unused locals
422
423                 AttributeValue::Exprloc(Expression(vec![]))
424             }
425         }
426         CPlaceInner::Addr(_, _) => {
427             // FIXME implement this (used by arguments and returns)
428
429             AttributeValue::Exprloc(Expression(vec![]))
430
431             // For PointerBase::Stack:
432             //AttributeValue::Exprloc(Expression(translate_loc(ValueLoc::Stack(*stack_slot), &context.func.stack_slots).unwrap()))
433         }
434     }
435 }
436
437 // Adapted from https://github.com/CraneStation/wasmtime/blob/5a1845b4caf7a5dba8eda1fef05213a532ed4259/crates/debug/src/transform/expression.rs#L59-L137
438 fn translate_loc(isa: &dyn TargetIsa, loc: ValueLoc, stack_slots: &StackSlots) -> Option<Vec<u8>> {
439     match loc {
440         ValueLoc::Reg(reg) => {
441             let machine_reg = isa.map_dwarf_register(reg).unwrap();
442             assert!(machine_reg <= 32); // FIXME
443             Some(vec![gimli::constants::DW_OP_reg0.0 + machine_reg as u8])
444         }
445         ValueLoc::Stack(ss) => {
446             if let Some(ss_offset) = stack_slots[ss].offset {
447                 let endian = gimli::RunTimeEndian::Little;
448                 let mut writer = write::EndianVec::new(endian);
449                 writer
450                     .write_u8(gimli::constants::DW_OP_breg0.0 + X86_64::RBP.0 as u8)
451                     .expect("bp wr");
452                 writer.write_sleb128(ss_offset as i64 + 16).expect("ss wr");
453                 let buf = writer.into_vec();
454                 return Some(buf);
455             }
456             None
457         }
458         _ => None,
459     }
460 }