7 use cranelift_codegen::entity::EntityRef;
8 use cranelift_codegen::ir::{StackSlots, ValueLabel, ValueLoc};
9 use cranelift_codegen::isa::TargetIsa;
10 use cranelift_codegen::ValueLocRange;
13 Address, AttributeValue, DwarfUnit, Expression, LineProgram, LineString, Location,
14 LocationList, Range, RangeList, UnitEntryId,
16 use gimli::{Encoding, Format, LineEncoding, RunTimeEndian, X86_64};
18 pub(crate) use emit::{DebugReloc, DebugRelocName};
19 pub(crate) use unwind::UnwindContext;
21 fn target_endian(tcx: TyCtxt<'_>) -> RunTimeEndian {
22 use rustc_target::abi::Endian;
24 match tcx.data_layout.endian {
25 Endian::Big => RunTimeEndian::Big,
26 Endian::Little => RunTimeEndian::Little,
30 pub(crate) struct DebugContext<'tcx> {
33 endian: RunTimeEndian,
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>, isa: &dyn TargetIsa) -> 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
56 address_size: isa.frontend_config().pointer_bytes(),
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 None => (tcx.crate_name(LOCAL_CRATE).to_string(), None),
73 let mut line_program = LineProgram::new(
75 LineEncoding::default(),
76 LineString::new(comp_dir.as_bytes(), encoding, &mut dwarf.line_strings),
77 LineString::new(name.as_bytes(), encoding, &mut dwarf.line_strings),
80 line_program.file_has_md5 = file_info.is_some();
82 dwarf.unit.line_program = line_program;
85 let name = dwarf.strings.add(name);
86 let comp_dir = dwarf.strings.add(comp_dir);
88 let root = dwarf.unit.root();
89 let root = dwarf.unit.get_mut(root);
91 gimli::DW_AT_producer,
92 AttributeValue::StringRef(dwarf.strings.add(producer)),
95 gimli::DW_AT_language,
96 AttributeValue::Language(gimli::DW_LANG_Rust),
98 root.set(gimli::DW_AT_name, AttributeValue::StringRef(name));
99 root.set(gimli::DW_AT_comp_dir, AttributeValue::StringRef(comp_dir));
102 AttributeValue::Address(Address::Constant(0)),
109 endian: target_endian(tcx),
112 unit_range_list: RangeList(Vec::new()),
114 clif_types: FxHashMap::default(),
115 types: FxHashMap::default(),
119 fn dwarf_ty_for_clif_ty(&mut self, ty: Type) -> UnitEntryId {
120 if let Some(type_id) = self.clif_types.get(&ty) {
124 let new_entry = |dwarf: &mut DwarfUnit, tag| dwarf.unit.add(dwarf.unit.root(), tag);
126 let primitive = |dwarf: &mut DwarfUnit, ate| {
127 let type_id = new_entry(dwarf, gimli::DW_TAG_base_type);
128 let type_entry = dwarf.unit.get_mut(type_id);
129 type_entry.set(gimli::DW_AT_encoding, AttributeValue::Encoding(ate));
133 let type_id = if ty.is_bool() {
134 primitive(&mut self.dwarf, gimli::DW_ATE_boolean)
135 } else if ty.is_int() {
136 primitive(&mut self.dwarf, gimli::DW_ATE_address)
137 } else if ty.is_float() {
138 primitive(&mut self.dwarf, gimli::DW_ATE_float)
140 new_entry(&mut self.dwarf, gimli::DW_TAG_structure_type)
143 let type_entry = self.dwarf.unit.get_mut(type_id);
146 AttributeValue::String(format!("{}", ty).replace('i', "u").into_bytes()),
149 gimli::DW_AT_byte_size,
150 AttributeValue::Udata(u64::from(ty.bytes())),
156 fn dwarf_ty(&mut self, ty: Ty<'tcx>) -> UnitEntryId {
157 if let Some(type_id) = self.types.get(ty) {
161 let new_entry = |dwarf: &mut DwarfUnit, tag| dwarf.unit.add(dwarf.unit.root(), tag);
163 let primitive = |dwarf: &mut DwarfUnit, ate| {
164 let type_id = new_entry(dwarf, gimli::DW_TAG_base_type);
165 let type_entry = dwarf.unit.get_mut(type_id);
166 type_entry.set(gimli::DW_AT_encoding, AttributeValue::Encoding(ate));
170 let name = format!("{}", ty);
171 let layout = self.tcx.layout_of(ParamEnv::reveal_all().and(ty)).unwrap();
173 let type_id = match ty.kind {
174 ty::Bool => primitive(&mut self.dwarf, gimli::DW_ATE_boolean),
175 ty::Char => primitive(&mut self.dwarf, gimli::DW_ATE_UTF),
176 ty::Uint(_) => primitive(&mut self.dwarf, gimli::DW_ATE_unsigned),
177 ty::Int(_) => primitive(&mut self.dwarf, gimli::DW_ATE_signed),
178 ty::Float(_) => primitive(&mut self.dwarf, gimli::DW_ATE_float),
179 ty::Ref(_, pointee_ty, _mutbl)
180 | ty::RawPtr(ty::TypeAndMut {
184 let type_id = new_entry(&mut self.dwarf, gimli::DW_TAG_pointer_type);
186 // Ensure that type is inserted before recursing to avoid duplicates
187 self.types.insert(ty, type_id);
189 let pointee = self.dwarf_ty(pointee_ty);
191 let type_entry = self.dwarf.unit.get_mut(type_id);
193 //type_entry.set(gimli::DW_AT_mutable, AttributeValue::Flag(mutbl == rustc_hir::Mutability::Mut));
194 type_entry.set(gimli::DW_AT_type, AttributeValue::UnitRef(pointee));
198 ty::Adt(adt_def, _substs) if adt_def.is_struct() && !layout.is_unsized() => {
199 let type_id = new_entry(&mut self.dwarf, gimli::DW_TAG_structure_type);
201 // Ensure that type is inserted before recursing to avoid duplicates
202 self.types.insert(ty, type_id);
204 let variant = adt_def.non_enum_variant();
206 for (field_idx, field_def) in variant.fields.iter().enumerate() {
207 let field_offset = layout.fields.offset(field_idx);
208 let field_layout = layout
212 param_env: ParamEnv::reveal_all(),
218 let field_type = self.dwarf_ty(field_layout.ty);
220 let field_id = self.dwarf.unit.add(type_id, gimli::DW_TAG_member);
221 let field_entry = self.dwarf.unit.get_mut(field_id);
225 AttributeValue::String(field_def.ident.as_str().to_string().into_bytes()),
228 gimli::DW_AT_data_member_location,
229 AttributeValue::Udata(field_offset.bytes()),
231 field_entry.set(gimli::DW_AT_type, AttributeValue::UnitRef(field_type));
236 _ => new_entry(&mut self.dwarf, gimli::DW_TAG_structure_type),
239 let type_entry = self.dwarf.unit.get_mut(type_id);
241 type_entry.set(gimli::DW_AT_name, AttributeValue::String(name.into_bytes()));
243 gimli::DW_AT_byte_size,
244 AttributeValue::Udata(layout.size.bytes()),
247 self.types.insert(ty, type_id);
252 fn define_local(&mut self, scope: UnitEntryId, name: String, ty: Ty<'tcx>) -> UnitEntryId {
253 let dw_ty = self.dwarf_ty(ty);
255 let var_id = self.dwarf.unit.add(scope, gimli::DW_TAG_variable);
256 let var_entry = self.dwarf.unit.get_mut(var_id);
258 var_entry.set(gimli::DW_AT_name, AttributeValue::String(name.into_bytes()));
259 var_entry.set(gimli::DW_AT_type, AttributeValue::UnitRef(dw_ty));
264 pub(crate) fn define_function(
266 instance: Instance<'tcx>,
271 source_info_set: &indexmap::IndexSet<SourceInfo>,
272 local_map: FxHashMap<mir::Local, CPlace<'tcx>>,
274 let symbol = func_id.as_u32() as usize;
275 let mir = self.tcx.instance_mir(instance.def);
277 // FIXME: add to appropriate scope instead of root
278 let scope = self.dwarf.unit.root();
280 let entry_id = self.dwarf.unit.add(scope, gimli::DW_TAG_subprogram);
281 let entry = self.dwarf.unit.get_mut(entry_id);
282 let name_id = self.dwarf.strings.add(name);
283 // Gdb requires DW_AT_name. Otherwise the DW_TAG_subprogram is skipped.
284 entry.set(gimli::DW_AT_name, AttributeValue::StringRef(name_id));
286 gimli::DW_AT_linkage_name,
287 AttributeValue::StringRef(name_id),
291 self.create_debug_lines(isa, symbol, entry_id, context, mir.span, source_info_set);
293 self.unit_range_list.0.push(Range::StartLength {
294 begin: Address::Symbol { symbol, addend: 0 },
295 length: u64::from(end),
298 if isa.get_mach_backend().is_some() {
299 return; // Not yet implemented for the AArch64 backend.
302 let func_entry = self.dwarf.unit.get_mut(entry_id);
303 // Gdb requires both DW_AT_low_pc and DW_AT_high_pc. Otherwise the DW_TAG_subprogram is skipped.
306 AttributeValue::Address(Address::Symbol { symbol, addend: 0 }),
308 // Using Udata for DW_AT_high_pc requires at least DWARF4
309 func_entry.set(gimli::DW_AT_high_pc, AttributeValue::Udata(u64::from(end)));
311 // FIXME Remove once actual debuginfo for locals works.
312 for (i, (param, &val)) in context
321 .block_params(context.func.layout.entry_block().unwrap()),
325 use cranelift_codegen::ir::ArgumentPurpose;
326 let base_name = match param.purpose {
327 ArgumentPurpose::Normal => "arg",
328 ArgumentPurpose::StructArgument(_) => "struct_arg",
329 ArgumentPurpose::StructReturn => "sret",
330 ArgumentPurpose::Link
331 | ArgumentPurpose::FramePointer
332 | ArgumentPurpose::CalleeSaved => continue,
333 ArgumentPurpose::VMContext
334 | ArgumentPurpose::SignatureId
335 | ArgumentPurpose::StackLimit => unreachable!(),
337 let name = format!("{}{}", base_name, i);
339 let dw_ty = self.dwarf_ty_for_clif_ty(param.value_type);
341 translate_loc(isa, context.func.locations[val], &context.func.stack_slots).unwrap();
346 .add(entry_id, gimli::DW_TAG_formal_parameter);
347 let var_entry = self.dwarf.unit.get_mut(arg_id);
349 var_entry.set(gimli::DW_AT_name, AttributeValue::String(name.into_bytes()));
350 var_entry.set(gimli::DW_AT_type, AttributeValue::UnitRef(dw_ty));
351 var_entry.set(gimli::DW_AT_location, AttributeValue::Exprloc(loc));
354 // FIXME make it more reliable and implement scopes before re-enabling this.
356 let value_labels_ranges = context.build_value_labels_ranges(isa).unwrap();
358 for (local, _local_decl) in mir.local_decls.iter_enumerated() {
359 let ty = self.tcx.subst_and_normalize_erasing_regions(
361 ty::ParamEnv::reveal_all(),
362 &mir.local_decls[local].ty,
364 let var_id = self.define_local(entry_id, format!("{:?}", local), ty);
366 let location = place_location(
372 &value_labels_ranges,
375 projection: ty::List::empty(),
379 let var_entry = self.dwarf.unit.get_mut(var_id);
380 var_entry.set(gimli::DW_AT_location, location);
384 // FIXME create locals for all entries in mir.var_debug_info
388 fn place_location<'tcx>(
389 debug_context: &mut DebugContext<'tcx>,
393 local_map: &FxHashMap<mir::Local, CPlace<'tcx>>,
394 #[allow(rustc::default_hash_types)] value_labels_ranges: &std::collections::HashMap<
399 ) -> AttributeValue {
400 assert!(place.projection.is_empty()); // FIXME implement them
402 match local_map[&place.local].inner() {
403 CPlaceInner::Var(_local, var) => {
404 let value_label = cranelift_codegen::ir::ValueLabel::new(var.index());
405 if let Some(value_loc_ranges) = value_labels_ranges.get(&value_label) {
406 let loc_list = LocationList(
409 .map(|value_loc_range| Location::StartEnd {
410 begin: Address::Symbol {
412 addend: i64::from(value_loc_range.start),
414 end: Address::Symbol {
416 addend: i64::from(value_loc_range.end),
421 &context.func.stack_slots,
427 let loc_list_id = debug_context.dwarf.unit.locations.add(loc_list);
429 AttributeValue::LocationListRef(loc_list_id)
431 // FIXME set value labels for unused locals
433 AttributeValue::Exprloc(Expression::new())
436 CPlaceInner::VarPair(_, _, _) => {
437 // FIXME implement this
439 AttributeValue::Exprloc(Expression::new())
441 CPlaceInner::VarLane(_, _, _) => {
442 // FIXME implement this
444 AttributeValue::Exprloc(Expression::new())
446 CPlaceInner::Addr(_, _) => {
447 // FIXME implement this (used by arguments and returns)
449 AttributeValue::Exprloc(Expression::new())
451 // For PointerBase::Stack:
452 //AttributeValue::Exprloc(translate_loc(ValueLoc::Stack(*stack_slot), &context.func.stack_slots).unwrap())
457 // Adapted from https://github.com/CraneStation/wasmtime/blob/5a1845b4caf7a5dba8eda1fef05213a532ed4259/crates/debug/src/transform/expression.rs#L59-L137
461 stack_slots: &StackSlots,
462 ) -> Option<Expression> {
464 ValueLoc::Reg(reg) => {
465 let machine_reg = isa.map_dwarf_register(reg).unwrap();
466 let mut expr = Expression::new();
467 expr.op_reg(gimli::Register(machine_reg));
470 ValueLoc::Stack(ss) => {
471 if let Some(ss_offset) = stack_slots[ss].offset {
472 let mut expr = Expression::new();
473 expr.op_breg(X86_64::RBP, i64::from(ss_offset) + 16);