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