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