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