]> git.lizzy.rs Git - rust.git/blob - src/debuginfo/mod.rs
Simplify with make_file_info
[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     types: FxHashMap<Ty<'tcx>, UnitEntryId>,
39 }
40
41 impl<'tcx> DebugContext<'tcx> {
42     pub(crate) fn new(tcx: TyCtxt<'tcx>, address_size: u8) -> 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                 5
52             },
53             address_size,
54         };
55
56         let mut dwarf = DwarfUnit::new(encoding);
57
58         // FIXME: how to get version when building out of tree?
59         // Normally this would use option_env!("CFG_VERSION").
60         let producer = format!("cg_clif (rustc {})", "unknown version");
61         let comp_dir = tcx.sess.working_dir.0.to_string_lossy().into_owned();
62         let (name, file_info) = match tcx.sess.local_crate_source_file.clone() {
63             Some(path) => {
64                 let name = path.to_string_lossy().into_owned();
65                 let info = tcx.sess
66                     .source_map()
67                     .get_source_file(&FileName::Real(path))
68                     .map(|f| f.src_hash)
69                     .and_then(line_info::make_file_info);
70                 (name, info)
71             },
72             None => (tcx.crate_name(LOCAL_CRATE).to_string(), None),
73         };
74
75         let mut line_program = LineProgram::new(
76             encoding,
77             LineEncoding::default(),
78             LineString::new(comp_dir.as_bytes(), encoding, &mut dwarf.line_strings),
79             LineString::new(name.as_bytes(), encoding, &mut dwarf.line_strings),
80             file_info,
81         );
82         line_program.file_has_md5 = file_info.is_some();
83
84         dwarf.unit.line_program = line_program;
85
86         {
87             let name = dwarf.strings.add(name);
88             let comp_dir = dwarf.strings.add(comp_dir);
89
90             let root = dwarf.unit.root();
91             let root = dwarf.unit.get_mut(root);
92             root.set(
93                 gimli::DW_AT_producer,
94                 AttributeValue::StringRef(dwarf.strings.add(producer)),
95             );
96             root.set(
97                 gimli::DW_AT_language,
98                 AttributeValue::Language(gimli::DW_LANG_Rust),
99             );
100             root.set(gimli::DW_AT_name, AttributeValue::StringRef(name));
101             root.set(gimli::DW_AT_comp_dir, AttributeValue::StringRef(comp_dir));
102             root.set(
103                 gimli::DW_AT_low_pc,
104                 AttributeValue::Address(Address::Constant(0)),
105             );
106         }
107
108         DebugContext {
109             tcx,
110
111             endian: target_endian(tcx),
112             symbols: indexmap::IndexMap::new(),
113
114             dwarf,
115             unit_range_list: RangeList(Vec::new()),
116
117             types: FxHashMap::default(),
118         }
119     }
120
121     fn dwarf_ty(&mut self, ty: Ty<'tcx>) -> UnitEntryId {
122         if let Some(type_id) = self.types.get(ty) {
123             return *type_id;
124         }
125
126         let new_entry = |dwarf: &mut DwarfUnit, tag| dwarf.unit.add(dwarf.unit.root(), tag);
127
128         let primitive = |dwarf: &mut DwarfUnit, ate| {
129             let type_id = new_entry(dwarf, gimli::DW_TAG_base_type);
130             let type_entry = dwarf.unit.get_mut(type_id);
131             type_entry.set(gimli::DW_AT_encoding, AttributeValue::Encoding(ate));
132             type_id
133         };
134
135         let name = format!("{}", ty);
136         let layout = self.tcx.layout_of(ParamEnv::reveal_all().and(ty)).unwrap();
137
138         let type_id = match ty.kind {
139             ty::Bool => primitive(&mut self.dwarf, gimli::DW_ATE_boolean),
140             ty::Char => primitive(&mut self.dwarf, gimli::DW_ATE_UTF),
141             ty::Uint(_) => primitive(&mut self.dwarf, gimli::DW_ATE_unsigned),
142             ty::Int(_) => primitive(&mut self.dwarf, gimli::DW_ATE_signed),
143             ty::Float(_) => primitive(&mut self.dwarf, gimli::DW_ATE_float),
144             ty::Ref(_, pointee_ty, _mutbl)
145             | ty::RawPtr(ty::TypeAndMut {
146                 ty: pointee_ty,
147                 mutbl: _mutbl,
148             }) => {
149                 let type_id = new_entry(&mut self.dwarf, gimli::DW_TAG_pointer_type);
150
151                 // Ensure that type is inserted before recursing to avoid duplicates
152                 self.types.insert(ty, type_id);
153
154                 let pointee = self.dwarf_ty(pointee_ty);
155
156                 let type_entry = self.dwarf.unit.get_mut(type_id);
157
158                 //type_entry.set(gimli::DW_AT_mutable, AttributeValue::Flag(mutbl == rustc_hir::Mutability::Mut));
159                 type_entry.set(gimli::DW_AT_type, AttributeValue::ThisUnitEntryRef(pointee));
160
161                 type_id
162             }
163             ty::Adt(adt_def, _substs) if adt_def.is_struct() && !layout.is_unsized() => {
164                 let type_id = new_entry(&mut self.dwarf, gimli::DW_TAG_structure_type);
165
166                 // Ensure that type is inserted before recursing to avoid duplicates
167                 self.types.insert(ty, type_id);
168
169                 let variant = adt_def.non_enum_variant();
170
171                 for (field_idx, field_def) in variant.fields.iter().enumerate() {
172                     let field_offset = layout.fields.offset(field_idx);
173                     let field_layout = layout.field(&layout::LayoutCx {
174                         tcx: self.tcx,
175                         param_env: ParamEnv::reveal_all(),
176                     }, field_idx).unwrap();
177
178                     let field_type = self.dwarf_ty(field_layout.ty);
179
180                     let field_id = self.dwarf.unit.add(type_id, gimli::DW_TAG_member);
181                     let field_entry = self.dwarf.unit.get_mut(field_id);
182
183                     field_entry.set(gimli::DW_AT_name, AttributeValue::String(field_def.ident.as_str().to_string().into_bytes()));
184                     field_entry.set(gimli::DW_AT_data_member_location, AttributeValue::Udata(field_offset.bytes()));
185                     field_entry.set(gimli::DW_AT_type, AttributeValue::ThisUnitEntryRef(field_type));
186                 }
187
188                 type_id
189             }
190             _ => new_entry(&mut self.dwarf, gimli::DW_TAG_structure_type),
191         };
192
193         let type_entry = self.dwarf.unit.get_mut(type_id);
194
195         type_entry.set(gimli::DW_AT_name, AttributeValue::String(name.into_bytes()));
196         type_entry.set(
197             gimli::DW_AT_byte_size,
198             AttributeValue::Udata(layout.size.bytes()),
199         );
200
201         self.types.insert(ty, type_id);
202
203         type_id
204     }
205 }
206
207 pub(crate) struct FunctionDebugContext<'a, 'tcx> {
208     debug_context: &'a mut DebugContext<'tcx>,
209     entry_id: UnitEntryId,
210     symbol: usize,
211     instance: Instance<'tcx>,
212     mir: &'tcx mir::Body<'tcx>,
213 }
214
215 impl<'a, 'tcx> FunctionDebugContext<'a, 'tcx> {
216     pub(crate) fn new(
217         debug_context: &'a mut DebugContext<'tcx>,
218         instance: Instance<'tcx>,
219         func_id: FuncId,
220         name: &str,
221     ) -> Self {
222         let mir = *debug_context.tcx.instance_mir(instance.def);
223
224         let (symbol, _) = debug_context.symbols.insert_full(func_id, name.to_string());
225
226         // FIXME: add to appropriate scope intead of root
227         let scope = debug_context.dwarf.unit.root();
228
229         let entry_id = debug_context
230             .dwarf
231             .unit
232             .add(scope, gimli::DW_TAG_subprogram);
233         let entry = debug_context.dwarf.unit.get_mut(entry_id);
234         let name_id = debug_context.dwarf.strings.add(name);
235         entry.set(
236             gimli::DW_AT_linkage_name,
237             AttributeValue::StringRef(name_id),
238         );
239
240         FunctionDebugContext {
241             debug_context,
242             entry_id,
243             symbol,
244             instance,
245             mir,
246         }
247     }
248
249     fn define_local(&mut self, name: String, ty: Ty<'tcx>) -> UnitEntryId {
250         let ty = self.debug_context.tcx.subst_and_normalize_erasing_regions(
251             self.instance.substs,
252             ty::ParamEnv::reveal_all(),
253             &ty,
254         );
255         let dw_ty = self.debug_context.dwarf_ty(ty);
256
257         let var_id = self
258             .debug_context
259             .dwarf
260             .unit
261             .add(self.entry_id, gimli::DW_TAG_variable);
262         let var_entry = self.debug_context.dwarf.unit.get_mut(var_id);
263
264         var_entry.set(gimli::DW_AT_name, AttributeValue::String(name.into_bytes()));
265         var_entry.set(gimli::DW_AT_type, AttributeValue::ThisUnitEntryRef(dw_ty));
266
267         var_id
268     }
269
270     pub(crate) fn define(
271         &mut self,
272         context: &Context,
273         isa: &dyn TargetIsa,
274         source_info_set: &indexmap::IndexSet<SourceInfo>,
275         local_map: FxHashMap<mir::Local, CPlace<'tcx>>,
276     ) {
277         let end = self.create_debug_lines(context, isa, source_info_set);
278
279         self.debug_context
280             .unit_range_list
281             .0
282             .push(Range::StartLength {
283                 begin: Address::Symbol {
284                     symbol: self.symbol,
285                     addend: 0,
286                 },
287                 length: end as u64,
288             });
289
290         // FIXME make it more reliable and implement scopes before re-enabling this.
291         if false {
292             let value_labels_ranges = context.build_value_labels_ranges(isa).unwrap();
293
294             for (local, _local_decl) in self.mir.local_decls.iter_enumerated() {
295                 let var_id = self.define_local(format!("{:?}", local), &self.mir.local_decls[local].ty);
296
297                 let location = place_location(
298                     self,
299                     isa,
300                     context,
301                     &local_map,
302                     &value_labels_ranges,
303                     Place {
304                         local,
305                         projection: ty::List::empty(),
306                     },
307                 );
308
309                 let var_entry = self.debug_context.dwarf.unit.get_mut(var_id);
310                 var_entry.set(gimli::DW_AT_location, location);
311             }
312         }
313
314         // FIXME create locals for all entries in mir.var_debug_info
315     }
316 }
317
318 fn place_location<'a, 'tcx>(
319     func_debug_ctx: &mut FunctionDebugContext<'a, 'tcx>,
320     isa: &dyn TargetIsa,
321     context: &Context,
322     local_map: &FxHashMap<mir::Local, CPlace<'tcx>>,
323     #[allow(rustc::default_hash_types)]
324     value_labels_ranges: &std::collections::HashMap<ValueLabel, Vec<ValueLocRange>>,
325     place: Place<'tcx>,
326 ) -> AttributeValue {
327     assert!(place.projection.is_empty()); // FIXME implement them
328
329     match local_map[&place.local].inner() {
330         CPlaceInner::Var(local) => {
331             let value_label = cranelift_codegen::ir::ValueLabel::from_u32(local.as_u32());
332             if let Some(value_loc_ranges) = value_labels_ranges.get(&value_label) {
333                 let loc_list = LocationList(
334                     value_loc_ranges
335                         .iter()
336                         .map(|value_loc_range| Location::StartEnd {
337                             begin: Address::Symbol {
338                                 symbol: func_debug_ctx.symbol,
339                                 addend: i64::from(value_loc_range.start),
340                             },
341                             end: Address::Symbol {
342                                 symbol: func_debug_ctx.symbol,
343                                 addend: i64::from(value_loc_range.end),
344                             },
345                             data: Expression(
346                                 translate_loc(isa, value_loc_range.loc, &context.func.stack_slots).unwrap(),
347                             ),
348                         })
349                         .collect(),
350                 );
351                 let loc_list_id = func_debug_ctx.debug_context.dwarf.unit.locations.add(loc_list);
352
353                 AttributeValue::LocationListRef(loc_list_id)
354             } else {
355                 // FIXME set value labels for unused locals
356
357                 AttributeValue::Exprloc(Expression(vec![]))
358             }
359         }
360         CPlaceInner::Addr(_, _) => {
361             // FIXME implement this (used by arguments and returns)
362
363             AttributeValue::Exprloc(Expression(vec![]))
364
365             // For PointerBase::Stack:
366             //AttributeValue::Exprloc(Expression(translate_loc(ValueLoc::Stack(*stack_slot), &context.func.stack_slots).unwrap()))
367         }
368     }
369 }
370
371 // Adapted from https://github.com/CraneStation/wasmtime/blob/5a1845b4caf7a5dba8eda1fef05213a532ed4259/crates/debug/src/transform/expression.rs#L59-L137
372 fn translate_loc(isa: &dyn TargetIsa, loc: ValueLoc, stack_slots: &StackSlots) -> Option<Vec<u8>> {
373     match loc {
374         ValueLoc::Reg(reg) => {
375             let machine_reg = isa.map_dwarf_register(reg).unwrap();
376             assert!(machine_reg <= 32); // FIXME
377             Some(vec![gimli::constants::DW_OP_reg0.0 + machine_reg as u8])
378         }
379         ValueLoc::Stack(ss) => {
380             if let Some(ss_offset) = stack_slots[ss].offset {
381                 let endian = gimli::RunTimeEndian::Little;
382                 let mut writer = write::EndianVec::new(endian);
383                 writer
384                     .write_u8(gimli::constants::DW_OP_breg0.0 + X86_64::RBP.0 as u8)
385                     .expect("bp wr");
386                 writer.write_sleb128(ss_offset as i64 + 16).expect("ss wr");
387                 let buf = writer.into_vec();
388                 return Some(buf);
389             }
390             None
391         }
392         _ => None,
393     }
394 }