6 use rustc_span::FileName;
8 use cranelift_codegen::ir::{StackSlots, ValueLabel, ValueLoc};
9 use cranelift_codegen::isa::TargetIsa;
10 use cranelift_codegen::ValueLocRange;
13 self, Address, AttributeValue, DwarfUnit, Expression, LineProgram, LineString, Location,
14 LocationList, Range, RangeList, UnitEntryId, Writer,
16 use gimli::{Encoding, Format, LineEncoding, RunTimeEndian, X86_64};
18 pub(crate) use emit::{DebugReloc, DebugRelocName};
20 fn target_endian(tcx: TyCtxt<'_>) -> RunTimeEndian {
21 use rustc_target::abi::Endian;
23 match tcx.data_layout.endian {
24 Endian::Big => RunTimeEndian::Big,
25 Endian::Little => RunTimeEndian::Little,
29 pub(crate) struct DebugContext<'tcx> {
32 endian: RunTimeEndian,
33 symbols: indexmap::IndexMap<FuncId, String>,
36 unit_range_list: RangeList,
38 clif_types: FxHashMap<Type, UnitEntryId>,
39 types: FxHashMap<Ty<'tcx>, UnitEntryId>,
42 impl<'tcx> DebugContext<'tcx> {
43 pub(crate) fn new(tcx: TyCtxt<'tcx>, address_size: u8) -> Self {
44 let encoding = Encoding {
45 format: Format::Dwarf32,
46 // TODO: this should be configurable
47 // macOS doesn't seem to support DWARF > 3
48 // 5 version is required for md5 file hash
49 version: if tcx.sess.target.target.options.is_like_osx {
52 // FIXME change to version 5 once the gdb and lldb shipping with the latest debian
59 let mut dwarf = DwarfUnit::new(encoding);
61 // FIXME: how to get version when building out of tree?
62 // Normally this would use option_env!("CFG_VERSION").
63 let producer = format!("cg_clif (rustc {})", "unknown version");
64 let comp_dir = tcx.sess.working_dir.0.to_string_lossy().into_owned();
65 let (name, file_info) = match tcx.sess.local_crate_source_file.clone() {
67 let name = path.to_string_lossy().into_owned();
70 .get_source_file(&FileName::Real(path))
72 .and_then(line_info::make_file_info);
75 None => (tcx.crate_name(LOCAL_CRATE).to_string(), None),
78 let mut line_program = LineProgram::new(
80 LineEncoding::default(),
81 LineString::new(comp_dir.as_bytes(), encoding, &mut dwarf.line_strings),
82 LineString::new(name.as_bytes(), encoding, &mut dwarf.line_strings),
85 line_program.file_has_md5 = file_info.is_some();
87 dwarf.unit.line_program = line_program;
90 let name = dwarf.strings.add(name);
91 let comp_dir = dwarf.strings.add(comp_dir);
93 let root = dwarf.unit.root();
94 let root = dwarf.unit.get_mut(root);
96 gimli::DW_AT_producer,
97 AttributeValue::StringRef(dwarf.strings.add(producer)),
100 gimli::DW_AT_language,
101 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));
107 AttributeValue::Address(Address::Constant(0)),
114 endian: target_endian(tcx),
115 symbols: indexmap::IndexMap::new(),
118 unit_range_list: RangeList(Vec::new()),
120 clif_types: FxHashMap::default(),
121 types: FxHashMap::default(),
125 fn dwarf_ty_for_clif_ty(&mut self, ty: Type) -> UnitEntryId {
126 if let Some(type_id) = self.clif_types.get(&ty) {
130 let new_entry = |dwarf: &mut DwarfUnit, tag| dwarf.unit.add(dwarf.unit.root(), tag);
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));
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)
146 new_entry(&mut self.dwarf, gimli::DW_TAG_structure_type)
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()));
152 gimli::DW_AT_byte_size,
153 AttributeValue::Udata(u64::from(ty.bytes())),
159 fn dwarf_ty(&mut self, ty: Ty<'tcx>) -> UnitEntryId {
160 if let Some(type_id) = self.types.get(ty) {
164 let new_entry = |dwarf: &mut DwarfUnit, tag| dwarf.unit.add(dwarf.unit.root(), tag);
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));
173 let name = format!("{}", ty);
174 let layout = self.tcx.layout_of(ParamEnv::reveal_all().and(ty)).unwrap();
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 {
187 let type_id = new_entry(&mut self.dwarf, gimli::DW_TAG_pointer_type);
189 // Ensure that type is inserted before recursing to avoid duplicates
190 self.types.insert(ty, type_id);
192 let pointee = self.dwarf_ty(pointee_ty);
194 let type_entry = self.dwarf.unit.get_mut(type_id);
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));
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);
204 // Ensure that type is inserted before recursing to avoid duplicates
205 self.types.insert(ty, type_id);
207 let variant = adt_def.non_enum_variant();
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 {
213 param_env: ParamEnv::reveal_all(),
214 }, field_idx).unwrap();
216 let field_type = self.dwarf_ty(field_layout.ty);
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);
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));
228 _ => new_entry(&mut self.dwarf, gimli::DW_TAG_structure_type),
231 let type_entry = self.dwarf.unit.get_mut(type_id);
233 type_entry.set(gimli::DW_AT_name, AttributeValue::String(name.into_bytes()));
235 gimli::DW_AT_byte_size,
236 AttributeValue::Udata(layout.size.bytes()),
239 self.types.insert(ty, type_id);
245 pub(crate) struct FunctionDebugContext<'a, 'tcx> {
246 debug_context: &'a mut DebugContext<'tcx>,
247 entry_id: UnitEntryId,
249 instance: Instance<'tcx>,
250 mir: &'tcx mir::Body<'tcx>,
253 impl<'a, 'tcx> FunctionDebugContext<'a, 'tcx> {
255 debug_context: &'a mut DebugContext<'tcx>,
256 instance: Instance<'tcx>,
260 let mir = *debug_context.tcx.instance_mir(instance.def);
262 let (symbol, _) = debug_context.symbols.insert_full(func_id, name.to_string());
264 // FIXME: add to appropriate scope intead of root
265 let scope = debug_context.dwarf.unit.root();
267 let entry_id = debug_context
270 .add(scope, gimli::DW_TAG_subprogram);
271 let entry = debug_context.dwarf.unit.get_mut(entry_id);
272 let name_id = debug_context.dwarf.strings.add(name);
273 // Gdb requires DW_AT_name. Otherwise the DW_TAG_subprogram is skipped.
276 AttributeValue::StringRef(name_id),
279 gimli::DW_AT_linkage_name,
280 AttributeValue::StringRef(name_id),
283 FunctionDebugContext {
292 fn define_local(&mut self, name: String, ty: Ty<'tcx>) -> UnitEntryId {
293 let dw_ty = self.debug_context.dwarf_ty(ty);
299 .add(self.entry_id, gimli::DW_TAG_variable);
300 let var_entry = self.debug_context.dwarf.unit.get_mut(var_id);
302 var_entry.set(gimli::DW_AT_name, AttributeValue::String(name.into_bytes()));
303 var_entry.set(gimli::DW_AT_type, AttributeValue::ThisUnitEntryRef(dw_ty));
308 pub(crate) fn define(
312 source_info_set: &indexmap::IndexSet<SourceInfo>,
313 local_map: FxHashMap<mir::Local, CPlace<'tcx>>,
315 if isa.get_mach_backend().is_some() {
316 return; // The AArch64 backend doesn't support line debuginfo yet.
319 let end = self.create_debug_lines(context, isa, source_info_set);
324 .push(Range::StartLength {
325 begin: Address::Symbol {
329 length: u64::from(end),
332 let func_entry = self.debug_context.dwarf.unit.get_mut(self.entry_id);
333 // Gdb requires both DW_AT_low_pc and DW_AT_high_pc. Otherwise the DW_TAG_subprogram is skipped.
334 func_entry.set(gimli::DW_AT_low_pc, AttributeValue::Address(Address::Symbol {
338 // Using Udata for DW_AT_high_pc requires at least DWARF4
339 func_entry.set(gimli::DW_AT_high_pc, AttributeValue::Udata(u64::from(end)));
341 // FIXME Remove once actual debuginfo for locals works.
342 for (i, (param, &val)) in context.func.signature.params.iter().zip(context.func.dfg.block_params(context.func.layout.entry_block().unwrap())).enumerate() {
343 use cranelift_codegen::ir::ArgumentPurpose;
344 let base_name = match param.purpose {
345 ArgumentPurpose::Normal => "arg",
346 ArgumentPurpose::StructReturn => "sret",
347 ArgumentPurpose::Link | ArgumentPurpose::FramePointer | ArgumentPurpose::CalleeSaved => continue,
348 ArgumentPurpose::VMContext | ArgumentPurpose::SignatureId | ArgumentPurpose::StackLimit => unreachable!(),
350 let name = format!("{}{}", base_name, i);
352 let dw_ty = self.debug_context.dwarf_ty_for_clif_ty(param.value_type);
353 let loc = Expression(
354 translate_loc(isa, context.func.locations[val], &context.func.stack_slots).unwrap(),
357 let arg_id = self.debug_context.dwarf.unit.add(self.entry_id, gimli::DW_TAG_formal_parameter);
358 let var_entry = self.debug_context.dwarf.unit.get_mut(arg_id);
360 var_entry.set(gimli::DW_AT_name, AttributeValue::String(name.into_bytes()));
361 var_entry.set(gimli::DW_AT_type, AttributeValue::ThisUnitEntryRef(dw_ty));
362 var_entry.set(gimli::DW_AT_location, AttributeValue::Exprloc(loc));
365 // FIXME make it more reliable and implement scopes before re-enabling this.
367 let value_labels_ranges = context.build_value_labels_ranges(isa).unwrap();
369 for (local, _local_decl) in self.mir.local_decls.iter_enumerated() {
370 let ty = self.debug_context.tcx.subst_and_normalize_erasing_regions(
371 self.instance.substs,
372 ty::ParamEnv::reveal_all(),
373 &self.mir.local_decls[local].ty,
375 let var_id = self.define_local(format!("{:?}", local), ty);
377 let location = place_location(
382 &value_labels_ranges,
385 projection: ty::List::empty(),
389 let var_entry = self.debug_context.dwarf.unit.get_mut(var_id);
390 var_entry.set(gimli::DW_AT_location, location);
394 // FIXME create locals for all entries in mir.var_debug_info
398 fn place_location<'a, 'tcx>(
399 func_debug_ctx: &mut FunctionDebugContext<'a, 'tcx>,
402 local_map: &FxHashMap<mir::Local, CPlace<'tcx>>,
403 #[allow(rustc::default_hash_types)]
404 value_labels_ranges: &std::collections::HashMap<ValueLabel, Vec<ValueLocRange>>,
406 ) -> AttributeValue {
407 assert!(place.projection.is_empty()); // FIXME implement them
409 match local_map[&place.local].inner() {
410 CPlaceInner::Var(local) => {
411 let value_label = cranelift_codegen::ir::ValueLabel::from_u32(local.as_u32());
412 if let Some(value_loc_ranges) = value_labels_ranges.get(&value_label) {
413 let loc_list = LocationList(
416 .map(|value_loc_range| Location::StartEnd {
417 begin: Address::Symbol {
418 symbol: func_debug_ctx.symbol,
419 addend: i64::from(value_loc_range.start),
421 end: Address::Symbol {
422 symbol: func_debug_ctx.symbol,
423 addend: i64::from(value_loc_range.end),
426 translate_loc(isa, value_loc_range.loc, &context.func.stack_slots).unwrap(),
431 let loc_list_id = func_debug_ctx.debug_context.dwarf.unit.locations.add(loc_list);
433 AttributeValue::LocationListRef(loc_list_id)
435 // FIXME set value labels for unused locals
437 AttributeValue::Exprloc(Expression(vec![]))
440 CPlaceInner::Addr(_, _) => {
441 // FIXME implement this (used by arguments and returns)
443 AttributeValue::Exprloc(Expression(vec![]))
445 // For PointerBase::Stack:
446 //AttributeValue::Exprloc(Expression(translate_loc(ValueLoc::Stack(*stack_slot), &context.func.stack_slots).unwrap()))
451 // Adapted from https://github.com/CraneStation/wasmtime/blob/5a1845b4caf7a5dba8eda1fef05213a532ed4259/crates/debug/src/transform/expression.rs#L59-L137
452 fn translate_loc(isa: &dyn TargetIsa, loc: ValueLoc, stack_slots: &StackSlots) -> Option<Vec<u8>> {
454 ValueLoc::Reg(reg) => {
455 let machine_reg = isa.map_dwarf_register(reg).unwrap();
456 assert!(machine_reg <= 32); // FIXME
457 Some(vec![gimli::constants::DW_OP_reg0.0 + machine_reg as u8])
459 ValueLoc::Stack(ss) => {
460 if let Some(ss_offset) = stack_slots[ss].offset {
461 let endian = gimli::RunTimeEndian::Little;
462 let mut writer = write::EndianVec::new(endian);
464 .write_u8(gimli::constants::DW_OP_breg0.0 + X86_64::RBP.0 as u8)
466 writer.write_sleb128(ss_offset as i64 + 16).expect("ss wr");
467 let buf = writer.into_vec();