]> git.lizzy.rs Git - rust.git/blob - src/debuginfo/mod.rs
Always emit .eh_frame section
[rust.git] / src / debuginfo / mod.rs
1 mod emit;
2 mod line_info;
3 mod unwind;
4
5 use crate::prelude::*;
6
7 use rustc_span::FileName;
8
9 use cranelift_codegen::ir::{StackSlots, ValueLabel, ValueLoc};
10 use cranelift_codegen::isa::TargetIsa;
11 use cranelift_codegen::ValueLocRange;
12
13 use gimli::write::{
14     self, Address, AttributeValue, DwarfUnit, Expression, LineProgram,
15     LineString, Location, LocationList, Range, RangeList, UnitEntryId, Writer,
16 };
17 use gimli::{Encoding, Format, LineEncoding, RunTimeEndian, X86_64};
18
19 pub(crate) use emit::{DebugReloc, DebugRelocName};
20 pub(crate) use unwind::UnwindContext;
21
22 fn target_endian(tcx: TyCtxt<'_>) -> RunTimeEndian {
23     use rustc_target::abi::Endian;
24
25     match tcx.data_layout.endian {
26         Endian::Big => RunTimeEndian::Big,
27         Endian::Little => RunTimeEndian::Little,
28     }
29 }
30
31 pub(crate) struct DebugContext<'tcx> {
32     tcx: TyCtxt<'tcx>,
33
34     endian: RunTimeEndian,
35
36     dwarf: DwarfUnit,
37     unit_range_list: RangeList,
38
39     clif_types: FxHashMap<Type, UnitEntryId>,
40     types: FxHashMap<Ty<'tcx>, UnitEntryId>,
41 }
42
43 impl<'tcx> DebugContext<'tcx> {
44     pub(crate) fn new(tcx: TyCtxt<'tcx>, isa: &dyn TargetIsa) -> Self {
45         let encoding = Encoding {
46             format: Format::Dwarf32,
47             // TODO: this should be configurable
48             // macOS doesn't seem to support DWARF > 3
49             // 5 version is required for md5 file hash
50             version: if tcx.sess.target.target.options.is_like_osx {
51                 3
52             } else {
53                 // FIXME change to version 5 once the gdb and lldb shipping with the latest debian
54                 // support it.
55                 4
56             },
57             address_size: isa.frontend_config().pointer_bytes(),
58         };
59
60         let mut dwarf = DwarfUnit::new(encoding);
61
62         // FIXME: how to get version when building out of tree?
63         // Normally this would use option_env!("CFG_VERSION").
64         let producer = format!("cg_clif (rustc {})", "unknown version");
65         let comp_dir = tcx.sess.working_dir.0.to_string_lossy().into_owned();
66         let (name, file_info) = match tcx.sess.local_crate_source_file.clone() {
67             Some(path) => {
68                 let name = path.to_string_lossy().into_owned();
69                 let info = tcx.sess
70                     .source_map()
71                     .get_source_file(&FileName::Real(path))
72                     .map(|f| f.src_hash)
73                     .and_then(line_info::make_file_info);
74                 (name, info)
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(
97                 gimli::DW_AT_producer,
98                 AttributeValue::StringRef(dwarf.strings.add(producer)),
99             );
100             root.set(
101                 gimli::DW_AT_language,
102                 AttributeValue::Language(gimli::DW_LANG_Rust),
103             );
104             root.set(gimli::DW_AT_name, AttributeValue::StringRef(name));
105             root.set(gimli::DW_AT_comp_dir, AttributeValue::StringRef(comp_dir));
106             root.set(
107                 gimli::DW_AT_low_pc,
108                 AttributeValue::Address(Address::Constant(0)),
109             );
110         }
111
112         DebugContext {
113             tcx,
114
115             endian: target_endian(tcx),
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         // FIXME: add to appropriate scope intead of root
263         let scope = debug_context.dwarf.unit.root();
264
265         let entry_id = debug_context
266             .dwarf
267             .unit
268             .add(scope, gimli::DW_TAG_subprogram);
269         let entry = debug_context.dwarf.unit.get_mut(entry_id);
270         let name_id = debug_context.dwarf.strings.add(name);
271         // Gdb requires DW_AT_name. Otherwise the DW_TAG_subprogram is skipped.
272         entry.set(
273             gimli::DW_AT_name,
274             AttributeValue::StringRef(name_id),
275         );
276         entry.set(
277             gimli::DW_AT_linkage_name,
278             AttributeValue::StringRef(name_id),
279         );
280
281         FunctionDebugContext {
282             debug_context,
283             entry_id,
284             symbol: func_id.as_u32() as usize,
285             instance,
286             mir,
287         }
288     }
289
290     fn define_local(&mut self, name: String, ty: Ty<'tcx>) -> UnitEntryId {
291         let dw_ty = self.debug_context.dwarf_ty(ty);
292
293         let var_id = self
294             .debug_context
295             .dwarf
296             .unit
297             .add(self.entry_id, gimli::DW_TAG_variable);
298         let var_entry = self.debug_context.dwarf.unit.get_mut(var_id);
299
300         var_entry.set(gimli::DW_AT_name, AttributeValue::String(name.into_bytes()));
301         var_entry.set(gimli::DW_AT_type, AttributeValue::ThisUnitEntryRef(dw_ty));
302
303         var_id
304     }
305
306     pub(crate) fn define(
307         &mut self,
308         context: &Context,
309         isa: &dyn TargetIsa,
310         source_info_set: &indexmap::IndexSet<SourceInfo>,
311         local_map: FxHashMap<mir::Local, CPlace<'tcx>>,
312     ) {
313         let end = self.create_debug_lines(context, isa, source_info_set);
314
315         self.debug_context
316             .unit_range_list
317             .0
318             .push(Range::StartLength {
319                 begin: Address::Symbol {
320                     symbol: self.symbol,
321                     addend: 0,
322                 },
323                 length: u64::from(end),
324             });
325
326         if isa.get_mach_backend().is_some() {
327             return; // Not yet implemented for the AArch64 backend.
328         }
329
330         let func_entry = self.debug_context.dwarf.unit.get_mut(self.entry_id);
331         // Gdb requires both DW_AT_low_pc and DW_AT_high_pc. Otherwise the DW_TAG_subprogram is skipped.
332         func_entry.set(gimli::DW_AT_low_pc, AttributeValue::Address(Address::Symbol {
333             symbol: self.symbol,
334             addend: 0,
335         }));
336         // Using Udata for DW_AT_high_pc requires at least DWARF4
337         func_entry.set(gimli::DW_AT_high_pc, AttributeValue::Udata(u64::from(end)));
338
339         // FIXME Remove once actual debuginfo for locals works.
340         for (i, (param, &val)) in context.func.signature.params.iter().zip(context.func.dfg.block_params(context.func.layout.entry_block().unwrap())).enumerate() {
341             use cranelift_codegen::ir::ArgumentPurpose;
342             let base_name = match param.purpose {
343                 ArgumentPurpose::Normal => "arg",
344                 ArgumentPurpose::StructReturn => "sret",
345                 ArgumentPurpose::Link | ArgumentPurpose::FramePointer | ArgumentPurpose::CalleeSaved => continue,
346                 ArgumentPurpose::VMContext | ArgumentPurpose::SignatureId | ArgumentPurpose::StackLimit => unreachable!(),
347             };
348             let name = format!("{}{}", base_name, i);
349
350             let dw_ty = self.debug_context.dwarf_ty_for_clif_ty(param.value_type);
351             let loc = Expression(
352                 translate_loc(isa, context.func.locations[val], &context.func.stack_slots).unwrap(),
353             );
354
355             let arg_id = self.debug_context.dwarf.unit.add(self.entry_id, gimli::DW_TAG_formal_parameter);
356             let var_entry = self.debug_context.dwarf.unit.get_mut(arg_id);
357
358             var_entry.set(gimli::DW_AT_name, AttributeValue::String(name.into_bytes()));
359             var_entry.set(gimli::DW_AT_type, AttributeValue::ThisUnitEntryRef(dw_ty));
360             var_entry.set(gimli::DW_AT_location, AttributeValue::Exprloc(loc));
361         }
362
363         // FIXME make it more reliable and implement scopes before re-enabling this.
364         if false {
365             let value_labels_ranges = context.build_value_labels_ranges(isa).unwrap();
366
367             for (local, _local_decl) in self.mir.local_decls.iter_enumerated() {
368                 let ty = self.debug_context.tcx.subst_and_normalize_erasing_regions(
369                     self.instance.substs,
370                     ty::ParamEnv::reveal_all(),
371                     &self.mir.local_decls[local].ty,
372                 );
373                 let var_id = self.define_local(format!("{:?}", local), ty);
374
375                 let location = place_location(
376                     self,
377                     isa,
378                     context,
379                     &local_map,
380                     &value_labels_ranges,
381                     Place {
382                         local,
383                         projection: ty::List::empty(),
384                     },
385                 );
386
387                 let var_entry = self.debug_context.dwarf.unit.get_mut(var_id);
388                 var_entry.set(gimli::DW_AT_location, location);
389             }
390         }
391
392         // FIXME create locals for all entries in mir.var_debug_info
393     }
394 }
395
396 fn place_location<'a, 'tcx>(
397     func_debug_ctx: &mut FunctionDebugContext<'a, 'tcx>,
398     isa: &dyn TargetIsa,
399     context: &Context,
400     local_map: &FxHashMap<mir::Local, CPlace<'tcx>>,
401     #[allow(rustc::default_hash_types)]
402     value_labels_ranges: &std::collections::HashMap<ValueLabel, Vec<ValueLocRange>>,
403     place: Place<'tcx>,
404 ) -> AttributeValue {
405     assert!(place.projection.is_empty()); // FIXME implement them
406
407     match local_map[&place.local].inner() {
408         CPlaceInner::Var(local) => {
409             let value_label = cranelift_codegen::ir::ValueLabel::from_u32(local.as_u32());
410             if let Some(value_loc_ranges) = value_labels_ranges.get(&value_label) {
411                 let loc_list = LocationList(
412                     value_loc_ranges
413                         .iter()
414                         .map(|value_loc_range| Location::StartEnd {
415                             begin: Address::Symbol {
416                                 symbol: func_debug_ctx.symbol,
417                                 addend: i64::from(value_loc_range.start),
418                             },
419                             end: Address::Symbol {
420                                 symbol: func_debug_ctx.symbol,
421                                 addend: i64::from(value_loc_range.end),
422                             },
423                             data: Expression(
424                                 translate_loc(isa, value_loc_range.loc, &context.func.stack_slots).unwrap(),
425                             ),
426                         })
427                         .collect(),
428                 );
429                 let loc_list_id = func_debug_ctx.debug_context.dwarf.unit.locations.add(loc_list);
430
431                 AttributeValue::LocationListRef(loc_list_id)
432             } else {
433                 // FIXME set value labels for unused locals
434
435                 AttributeValue::Exprloc(Expression(vec![]))
436             }
437         }
438         CPlaceInner::Addr(_, _) => {
439             // FIXME implement this (used by arguments and returns)
440
441             AttributeValue::Exprloc(Expression(vec![]))
442
443             // For PointerBase::Stack:
444             //AttributeValue::Exprloc(Expression(translate_loc(ValueLoc::Stack(*stack_slot), &context.func.stack_slots).unwrap()))
445         }
446     }
447 }
448
449 // Adapted from https://github.com/CraneStation/wasmtime/blob/5a1845b4caf7a5dba8eda1fef05213a532ed4259/crates/debug/src/transform/expression.rs#L59-L137
450 fn translate_loc(isa: &dyn TargetIsa, loc: ValueLoc, stack_slots: &StackSlots) -> Option<Vec<u8>> {
451     match loc {
452         ValueLoc::Reg(reg) => {
453             let machine_reg = isa.map_dwarf_register(reg).unwrap();
454             assert!(machine_reg <= 32); // FIXME
455             Some(vec![gimli::constants::DW_OP_reg0.0 + machine_reg as u8])
456         }
457         ValueLoc::Stack(ss) => {
458             if let Some(ss_offset) = stack_slots[ss].offset {
459                 let endian = gimli::RunTimeEndian::Little;
460                 let mut writer = write::EndianVec::new(endian);
461                 writer
462                     .write_u8(gimli::constants::DW_OP_breg0.0 + X86_64::RBP.0 as u8)
463                     .expect("bp wr");
464                 writer.write_sleb128(ss_offset as i64 + 16).expect("ss wr");
465                 let buf = writer.into_vec();
466                 return Some(buf);
467             }
468             None
469         }
470         _ => None,
471     }
472 }