1 //! Handling of everything related to debuginfo.
9 use rustc_index::vec::IndexVec;
11 use cranelift_codegen::entity::EntityRef;
12 use cranelift_codegen::ir::{StackSlots, ValueLabel, ValueLoc};
13 use cranelift_codegen::isa::TargetIsa;
14 use cranelift_codegen::ValueLocRange;
17 Address, AttributeValue, DwarfUnit, Expression, LineProgram, LineString, Location,
18 LocationList, Range, RangeList, UnitEntryId,
20 use gimli::{Encoding, Format, LineEncoding, RunTimeEndian, X86_64};
22 pub(crate) use emit::{DebugReloc, DebugRelocName};
23 pub(crate) use unwind::UnwindContext;
25 fn target_endian(tcx: TyCtxt<'_>) -> RunTimeEndian {
26 use rustc_target::abi::Endian;
28 match tcx.data_layout.endian {
29 Endian::Big => RunTimeEndian::Big,
30 Endian::Little => RunTimeEndian::Little,
34 pub(crate) struct DebugContext<'tcx> {
37 endian: RunTimeEndian,
40 unit_range_list: RangeList,
42 clif_types: FxHashMap<Type, UnitEntryId>,
43 types: FxHashMap<Ty<'tcx>, UnitEntryId>,
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 // TODO: 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 {
56 // FIXME change to version 5 once the gdb and lldb shipping with the latest debian
60 address_size: isa.frontend_config().pointer_bytes(),
63 let mut dwarf = DwarfUnit::new(encoding);
65 // FIXME: how to get version when building out of tree?
66 // Normally this would use option_env!("CFG_VERSION").
67 let producer = format!("cg_clif (rustc {})", "unknown version");
68 let comp_dir = tcx.sess.working_dir.0.to_string_lossy().into_owned();
69 let (name, file_info) = match tcx.sess.local_crate_source_file.clone() {
71 let name = path.to_string_lossy().into_owned();
74 None => (tcx.crate_name(LOCAL_CRATE).to_string(), None),
77 let mut line_program = LineProgram::new(
79 LineEncoding::default(),
80 LineString::new(comp_dir.as_bytes(), encoding, &mut dwarf.line_strings),
81 LineString::new(name.as_bytes(), encoding, &mut dwarf.line_strings),
84 line_program.file_has_md5 = file_info.is_some();
86 dwarf.unit.line_program = line_program;
89 let name = dwarf.strings.add(name);
90 let comp_dir = dwarf.strings.add(comp_dir);
92 let root = dwarf.unit.root();
93 let root = dwarf.unit.get_mut(root);
95 gimli::DW_AT_producer,
96 AttributeValue::StringRef(dwarf.strings.add(producer)),
99 gimli::DW_AT_language,
100 AttributeValue::Language(gimli::DW_LANG_Rust),
102 root.set(gimli::DW_AT_name, AttributeValue::StringRef(name));
103 root.set(gimli::DW_AT_comp_dir, AttributeValue::StringRef(comp_dir));
106 AttributeValue::Address(Address::Constant(0)),
113 endian: target_endian(tcx),
116 unit_range_list: RangeList(Vec::new()),
118 clif_types: FxHashMap::default(),
119 types: FxHashMap::default(),
123 fn dwarf_ty_for_clif_ty(&mut self, ty: Type) -> UnitEntryId {
124 if let Some(type_id) = self.clif_types.get(&ty) {
128 let new_entry = |dwarf: &mut DwarfUnit, tag| dwarf.unit.add(dwarf.unit.root(), tag);
130 let primitive = |dwarf: &mut DwarfUnit, ate| {
131 let type_id = new_entry(dwarf, gimli::DW_TAG_base_type);
132 let type_entry = dwarf.unit.get_mut(type_id);
133 type_entry.set(gimli::DW_AT_encoding, AttributeValue::Encoding(ate));
137 let type_id = if ty.is_bool() {
138 primitive(&mut self.dwarf, gimli::DW_ATE_boolean)
139 } else if ty.is_int() {
140 primitive(&mut self.dwarf, gimli::DW_ATE_address)
141 } else if ty.is_float() {
142 primitive(&mut self.dwarf, gimli::DW_ATE_float)
144 new_entry(&mut self.dwarf, gimli::DW_TAG_structure_type)
147 let type_entry = self.dwarf.unit.get_mut(type_id);
150 AttributeValue::String(format!("{}", ty).replace('i', "u").into_bytes()),
153 gimli::DW_AT_byte_size,
154 AttributeValue::Udata(u64::from(ty.bytes())),
160 fn dwarf_ty(&mut self, ty: Ty<'tcx>) -> UnitEntryId {
161 if let Some(type_id) = self.types.get(ty) {
165 let new_entry = |dwarf: &mut DwarfUnit, tag| dwarf.unit.add(dwarf.unit.root(), tag);
167 let primitive = |dwarf: &mut DwarfUnit, ate| {
168 let type_id = new_entry(dwarf, gimli::DW_TAG_base_type);
169 let type_entry = dwarf.unit.get_mut(type_id);
170 type_entry.set(gimli::DW_AT_encoding, AttributeValue::Encoding(ate));
174 let name = format!("{}", ty);
175 let layout = self.tcx.layout_of(ParamEnv::reveal_all().and(ty)).unwrap();
177 let type_id = match ty.kind() {
178 ty::Bool => primitive(&mut self.dwarf, gimli::DW_ATE_boolean),
179 ty::Char => primitive(&mut self.dwarf, gimli::DW_ATE_UTF),
180 ty::Uint(_) => primitive(&mut self.dwarf, gimli::DW_ATE_unsigned),
181 ty::Int(_) => primitive(&mut self.dwarf, gimli::DW_ATE_signed),
182 ty::Float(_) => primitive(&mut self.dwarf, gimli::DW_ATE_float),
183 ty::Ref(_, pointee_ty, _mutbl)
184 | ty::RawPtr(ty::TypeAndMut {
188 let type_id = new_entry(&mut self.dwarf, gimli::DW_TAG_pointer_type);
190 // Ensure that type is inserted before recursing to avoid duplicates
191 self.types.insert(ty, type_id);
193 let pointee = self.dwarf_ty(pointee_ty);
195 let type_entry = self.dwarf.unit.get_mut(type_id);
197 //type_entry.set(gimli::DW_AT_mutable, AttributeValue::Flag(mutbl == rustc_hir::Mutability::Mut));
198 type_entry.set(gimli::DW_AT_type, AttributeValue::UnitRef(pointee));
202 ty::Adt(adt_def, _substs) if adt_def.is_struct() && !layout.is_unsized() => {
203 let type_id = new_entry(&mut self.dwarf, gimli::DW_TAG_structure_type);
205 // Ensure that type is inserted before recursing to avoid duplicates
206 self.types.insert(ty, type_id);
208 let variant = adt_def.non_enum_variant();
210 for (field_idx, field_def) in variant.fields.iter().enumerate() {
211 let field_offset = layout.fields.offset(field_idx);
212 let field_layout = layout
216 param_env: ParamEnv::reveal_all(),
222 let field_type = self.dwarf_ty(field_layout.ty);
224 let field_id = self.dwarf.unit.add(type_id, gimli::DW_TAG_member);
225 let field_entry = self.dwarf.unit.get_mut(field_id);
229 AttributeValue::String(field_def.ident.as_str().to_string().into_bytes()),
232 gimli::DW_AT_data_member_location,
233 AttributeValue::Udata(field_offset.bytes()),
235 field_entry.set(gimli::DW_AT_type, AttributeValue::UnitRef(field_type));
240 _ => new_entry(&mut self.dwarf, gimli::DW_TAG_structure_type),
243 let type_entry = self.dwarf.unit.get_mut(type_id);
245 type_entry.set(gimli::DW_AT_name, AttributeValue::String(name.into_bytes()));
247 gimli::DW_AT_byte_size,
248 AttributeValue::Udata(layout.size.bytes()),
251 self.types.insert(ty, type_id);
256 fn define_local(&mut self, scope: UnitEntryId, name: String, ty: Ty<'tcx>) -> UnitEntryId {
257 let dw_ty = self.dwarf_ty(ty);
259 let var_id = self.dwarf.unit.add(scope, gimli::DW_TAG_variable);
260 let var_entry = self.dwarf.unit.get_mut(var_id);
262 var_entry.set(gimli::DW_AT_name, AttributeValue::String(name.into_bytes()));
263 var_entry.set(gimli::DW_AT_type, AttributeValue::UnitRef(dw_ty));
268 pub(crate) fn define_function(
270 instance: Instance<'tcx>,
275 source_info_set: &indexmap::IndexSet<SourceInfo>,
276 local_map: IndexVec<mir::Local, CPlace<'tcx>>,
278 let symbol = func_id.as_u32() as usize;
279 let mir = self.tcx.instance_mir(instance.def);
281 // FIXME: add to appropriate scope instead of root
282 let scope = self.dwarf.unit.root();
284 let entry_id = self.dwarf.unit.add(scope, gimli::DW_TAG_subprogram);
285 let entry = self.dwarf.unit.get_mut(entry_id);
286 let name_id = self.dwarf.strings.add(name);
287 // Gdb requires DW_AT_name. Otherwise the DW_TAG_subprogram is skipped.
288 entry.set(gimli::DW_AT_name, AttributeValue::StringRef(name_id));
290 gimli::DW_AT_linkage_name,
291 AttributeValue::StringRef(name_id),
295 self.create_debug_lines(isa, symbol, entry_id, context, mir.span, source_info_set);
297 self.unit_range_list.0.push(Range::StartLength {
298 begin: Address::Symbol { symbol, addend: 0 },
299 length: u64::from(end),
302 if isa.get_mach_backend().is_some() {
303 return; // Not yet implemented for the AArch64 backend.
306 let func_entry = self.dwarf.unit.get_mut(entry_id);
307 // Gdb requires both DW_AT_low_pc and DW_AT_high_pc. Otherwise the DW_TAG_subprogram is skipped.
310 AttributeValue::Address(Address::Symbol { symbol, addend: 0 }),
312 // Using Udata for DW_AT_high_pc requires at least DWARF4
313 func_entry.set(gimli::DW_AT_high_pc, AttributeValue::Udata(u64::from(end)));
315 // FIXME Remove once actual debuginfo for locals works.
316 for (i, (param, &val)) in context
325 .block_params(context.func.layout.entry_block().unwrap()),
329 use cranelift_codegen::ir::ArgumentPurpose;
330 let base_name = match param.purpose {
331 ArgumentPurpose::Normal => "arg",
332 ArgumentPurpose::StructArgument(_) => "struct_arg",
333 ArgumentPurpose::StructReturn => "sret",
334 ArgumentPurpose::Link
335 | ArgumentPurpose::FramePointer
336 | ArgumentPurpose::CalleeSaved => continue,
337 ArgumentPurpose::VMContext
338 | ArgumentPurpose::SignatureId
339 | ArgumentPurpose::CallerTLS
340 | ArgumentPurpose::CalleeTLS
341 | ArgumentPurpose::StackLimit => unreachable!(),
343 let name = format!("{}{}", base_name, i);
345 let dw_ty = self.dwarf_ty_for_clif_ty(param.value_type);
347 translate_loc(isa, context.func.locations[val], &context.func.stack_slots).unwrap();
352 .add(entry_id, gimli::DW_TAG_formal_parameter);
353 let var_entry = self.dwarf.unit.get_mut(arg_id);
355 var_entry.set(gimli::DW_AT_name, AttributeValue::String(name.into_bytes()));
356 var_entry.set(gimli::DW_AT_type, AttributeValue::UnitRef(dw_ty));
357 var_entry.set(gimli::DW_AT_location, AttributeValue::Exprloc(loc));
360 // FIXME make it more reliable and implement scopes before re-enabling this.
362 let value_labels_ranges = context.build_value_labels_ranges(isa).unwrap();
364 for (local, _local_decl) in mir.local_decls.iter_enumerated() {
365 let ty = self.tcx.subst_and_normalize_erasing_regions(
367 ty::ParamEnv::reveal_all(),
368 mir.local_decls[local].ty,
370 let var_id = self.define_local(entry_id, format!("{:?}", local), ty);
372 let location = place_location(
378 &value_labels_ranges,
381 projection: ty::List::empty(),
385 let var_entry = self.dwarf.unit.get_mut(var_id);
386 var_entry.set(gimli::DW_AT_location, location);
390 // FIXME create locals for all entries in mir.var_debug_info
394 fn place_location<'tcx>(
395 debug_context: &mut DebugContext<'tcx>,
399 local_map: &IndexVec<mir::Local, CPlace<'tcx>>,
400 #[allow(rustc::default_hash_types)] value_labels_ranges: &std::collections::HashMap<
405 ) -> AttributeValue {
406 assert!(place.projection.is_empty()); // FIXME implement them
408 match local_map[place.local].inner() {
409 CPlaceInner::Var(_local, var) => {
410 let value_label = cranelift_codegen::ir::ValueLabel::new(var.index());
411 if let Some(value_loc_ranges) = value_labels_ranges.get(&value_label) {
412 let loc_list = LocationList(
415 .map(|value_loc_range| Location::StartEnd {
416 begin: Address::Symbol {
418 addend: i64::from(value_loc_range.start),
420 end: Address::Symbol {
422 addend: i64::from(value_loc_range.end),
427 &context.func.stack_slots,
433 let loc_list_id = debug_context.dwarf.unit.locations.add(loc_list);
435 AttributeValue::LocationListRef(loc_list_id)
437 // FIXME set value labels for unused locals
439 AttributeValue::Exprloc(Expression::new())
442 CPlaceInner::VarPair(_, _, _) => {
443 // FIXME implement this
445 AttributeValue::Exprloc(Expression::new())
447 CPlaceInner::VarLane(_, _, _) => {
448 // FIXME implement this
450 AttributeValue::Exprloc(Expression::new())
452 CPlaceInner::Addr(_, _) => {
453 // FIXME implement this (used by arguments and returns)
455 AttributeValue::Exprloc(Expression::new())
457 // For PointerBase::Stack:
458 //AttributeValue::Exprloc(translate_loc(ValueLoc::Stack(*stack_slot), &context.func.stack_slots).unwrap())
463 // Adapted from https://github.com/CraneStation/wasmtime/blob/5a1845b4caf7a5dba8eda1fef05213a532ed4259/crates/debug/src/transform/expression.rs#L59-L137
467 stack_slots: &StackSlots,
468 ) -> Option<Expression> {
470 ValueLoc::Reg(reg) => {
471 let machine_reg = isa.map_dwarf_register(reg).unwrap();
472 let mut expr = Expression::new();
473 expr.op_reg(gimli::Register(machine_reg));
476 ValueLoc::Stack(ss) => {
477 if let Some(ss_offset) = stack_slots[ss].offset {
478 let mut expr = Expression::new();
479 expr.op_breg(X86_64::RBP, i64::from(ss_offset) + 16);