7 use cranelift_codegen::ir::{StackSlots, ValueLabel, ValueLoc};
8 use cranelift_codegen::isa::TargetIsa;
9 use cranelift_codegen::ValueLocRange;
12 self, Address, AttributeValue, DwarfUnit, Expression, LineProgram,
13 LineString, Location, LocationList, Range, RangeList, UnitEntryId, Writer,
15 use gimli::{Encoding, Format, LineEncoding, RunTimeEndian, X86_64};
17 pub(crate) use emit::{DebugReloc, DebugRelocName};
18 pub(crate) use unwind::UnwindContext;
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,
35 unit_range_list: RangeList,
37 clif_types: FxHashMap<Type, UnitEntryId>,
38 types: FxHashMap<Ty<'tcx>, UnitEntryId>,
41 impl<'tcx> DebugContext<'tcx> {
42 pub(crate) fn new(tcx: TyCtxt<'tcx>, isa: &dyn TargetIsa) -> 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 {
51 // FIXME change to version 5 once the gdb and lldb shipping with the latest debian
55 address_size: isa.frontend_config().pointer_bytes(),
58 let mut dwarf = DwarfUnit::new(encoding);
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, file_info) = match tcx.sess.local_crate_source_file.clone() {
66 let name = path.to_string_lossy().into_owned();
69 None => (tcx.crate_name(LOCAL_CRATE).to_string(), None),
72 let mut line_program = LineProgram::new(
74 LineEncoding::default(),
75 LineString::new(comp_dir.as_bytes(), encoding, &mut dwarf.line_strings),
76 LineString::new(name.as_bytes(), encoding, &mut dwarf.line_strings),
79 line_program.file_has_md5 = file_info.is_some();
81 dwarf.unit.line_program = line_program;
84 let name = dwarf.strings.add(name);
85 let comp_dir = dwarf.strings.add(comp_dir);
87 let root = dwarf.unit.root();
88 let root = dwarf.unit.get_mut(root);
90 gimli::DW_AT_producer,
91 AttributeValue::StringRef(dwarf.strings.add(producer)),
94 gimli::DW_AT_language,
95 AttributeValue::Language(gimli::DW_LANG_Rust),
97 root.set(gimli::DW_AT_name, AttributeValue::StringRef(name));
98 root.set(gimli::DW_AT_comp_dir, AttributeValue::StringRef(comp_dir));
101 AttributeValue::Address(Address::Constant(0)),
108 endian: target_endian(tcx),
111 unit_range_list: RangeList(Vec::new()),
113 clif_types: FxHashMap::default(),
114 types: FxHashMap::default(),
118 fn dwarf_ty_for_clif_ty(&mut self, ty: Type) -> UnitEntryId {
119 if let Some(type_id) = self.clif_types.get(&ty) {
123 let new_entry = |dwarf: &mut DwarfUnit, tag| dwarf.unit.add(dwarf.unit.root(), tag);
125 let primitive = |dwarf: &mut DwarfUnit, ate| {
126 let type_id = new_entry(dwarf, gimli::DW_TAG_base_type);
127 let type_entry = dwarf.unit.get_mut(type_id);
128 type_entry.set(gimli::DW_AT_encoding, AttributeValue::Encoding(ate));
132 let type_id = if ty.is_bool() {
133 primitive(&mut self.dwarf, gimli::DW_ATE_boolean)
134 } else if ty.is_int() {
135 primitive(&mut self.dwarf, gimli::DW_ATE_address)
136 } else if ty.is_float() {
137 primitive(&mut self.dwarf, gimli::DW_ATE_float)
139 new_entry(&mut self.dwarf, gimli::DW_TAG_structure_type)
142 let type_entry = self.dwarf.unit.get_mut(type_id);
143 type_entry.set(gimli::DW_AT_name, AttributeValue::String(format!("{}", ty).replace('i', "u").into_bytes()));
145 gimli::DW_AT_byte_size,
146 AttributeValue::Udata(u64::from(ty.bytes())),
152 fn dwarf_ty(&mut self, ty: Ty<'tcx>) -> UnitEntryId {
153 if let Some(type_id) = self.types.get(ty) {
157 let new_entry = |dwarf: &mut DwarfUnit, tag| dwarf.unit.add(dwarf.unit.root(), tag);
159 let primitive = |dwarf: &mut DwarfUnit, ate| {
160 let type_id = new_entry(dwarf, gimli::DW_TAG_base_type);
161 let type_entry = dwarf.unit.get_mut(type_id);
162 type_entry.set(gimli::DW_AT_encoding, AttributeValue::Encoding(ate));
166 let name = format!("{}", ty);
167 let layout = self.tcx.layout_of(ParamEnv::reveal_all().and(ty)).unwrap();
169 let type_id = match ty.kind {
170 ty::Bool => primitive(&mut self.dwarf, gimli::DW_ATE_boolean),
171 ty::Char => primitive(&mut self.dwarf, gimli::DW_ATE_UTF),
172 ty::Uint(_) => primitive(&mut self.dwarf, gimli::DW_ATE_unsigned),
173 ty::Int(_) => primitive(&mut self.dwarf, gimli::DW_ATE_signed),
174 ty::Float(_) => primitive(&mut self.dwarf, gimli::DW_ATE_float),
175 ty::Ref(_, pointee_ty, _mutbl)
176 | ty::RawPtr(ty::TypeAndMut {
180 let type_id = new_entry(&mut self.dwarf, gimli::DW_TAG_pointer_type);
182 // Ensure that type is inserted before recursing to avoid duplicates
183 self.types.insert(ty, type_id);
185 let pointee = self.dwarf_ty(pointee_ty);
187 let type_entry = self.dwarf.unit.get_mut(type_id);
189 //type_entry.set(gimli::DW_AT_mutable, AttributeValue::Flag(mutbl == rustc_hir::Mutability::Mut));
190 type_entry.set(gimli::DW_AT_type, AttributeValue::ThisUnitEntryRef(pointee));
194 ty::Adt(adt_def, _substs) if adt_def.is_struct() && !layout.is_unsized() => {
195 let type_id = new_entry(&mut self.dwarf, gimli::DW_TAG_structure_type);
197 // Ensure that type is inserted before recursing to avoid duplicates
198 self.types.insert(ty, type_id);
200 let variant = adt_def.non_enum_variant();
202 for (field_idx, field_def) in variant.fields.iter().enumerate() {
203 let field_offset = layout.fields.offset(field_idx);
204 let field_layout = layout.field(&layout::LayoutCx {
206 param_env: ParamEnv::reveal_all(),
207 }, field_idx).unwrap();
209 let field_type = self.dwarf_ty(field_layout.ty);
211 let field_id = self.dwarf.unit.add(type_id, gimli::DW_TAG_member);
212 let field_entry = self.dwarf.unit.get_mut(field_id);
214 field_entry.set(gimli::DW_AT_name, AttributeValue::String(field_def.ident.as_str().to_string().into_bytes()));
215 field_entry.set(gimli::DW_AT_data_member_location, AttributeValue::Udata(field_offset.bytes()));
216 field_entry.set(gimli::DW_AT_type, AttributeValue::ThisUnitEntryRef(field_type));
221 _ => new_entry(&mut self.dwarf, gimli::DW_TAG_structure_type),
224 let type_entry = self.dwarf.unit.get_mut(type_id);
226 type_entry.set(gimli::DW_AT_name, AttributeValue::String(name.into_bytes()));
228 gimli::DW_AT_byte_size,
229 AttributeValue::Udata(layout.size.bytes()),
232 self.types.insert(ty, type_id);
238 pub(crate) struct FunctionDebugContext<'a, 'tcx> {
239 debug_context: &'a mut DebugContext<'tcx>,
240 entry_id: UnitEntryId,
242 instance: Instance<'tcx>,
243 mir: &'tcx mir::Body<'tcx>,
246 impl<'a, 'tcx> FunctionDebugContext<'a, 'tcx> {
248 debug_context: &'a mut DebugContext<'tcx>,
249 instance: Instance<'tcx>,
253 let mir = debug_context.tcx.instance_mir(instance.def);
255 // FIXME: add to appropriate scope intead of root
256 let scope = debug_context.dwarf.unit.root();
258 let entry_id = debug_context
261 .add(scope, gimli::DW_TAG_subprogram);
262 let entry = debug_context.dwarf.unit.get_mut(entry_id);
263 let name_id = debug_context.dwarf.strings.add(name);
264 // Gdb requires DW_AT_name. Otherwise the DW_TAG_subprogram is skipped.
267 AttributeValue::StringRef(name_id),
270 gimli::DW_AT_linkage_name,
271 AttributeValue::StringRef(name_id),
274 FunctionDebugContext {
277 symbol: func_id.as_u32() as usize,
283 fn define_local(&mut self, name: String, ty: Ty<'tcx>) -> UnitEntryId {
284 let dw_ty = self.debug_context.dwarf_ty(ty);
290 .add(self.entry_id, gimli::DW_TAG_variable);
291 let var_entry = self.debug_context.dwarf.unit.get_mut(var_id);
293 var_entry.set(gimli::DW_AT_name, AttributeValue::String(name.into_bytes()));
294 var_entry.set(gimli::DW_AT_type, AttributeValue::ThisUnitEntryRef(dw_ty));
299 pub(crate) fn define(
303 source_info_set: &indexmap::IndexSet<SourceInfo>,
304 local_map: FxHashMap<mir::Local, CPlace<'tcx>>,
306 let end = self.create_debug_lines(context, isa, source_info_set);
311 .push(Range::StartLength {
312 begin: Address::Symbol {
316 length: u64::from(end),
319 if isa.get_mach_backend().is_some() {
320 return; // Not yet implemented for the AArch64 backend.
323 let func_entry = self.debug_context.dwarf.unit.get_mut(self.entry_id);
324 // Gdb requires both DW_AT_low_pc and DW_AT_high_pc. Otherwise the DW_TAG_subprogram is skipped.
325 func_entry.set(gimli::DW_AT_low_pc, AttributeValue::Address(Address::Symbol {
329 // Using Udata for DW_AT_high_pc requires at least DWARF4
330 func_entry.set(gimli::DW_AT_high_pc, AttributeValue::Udata(u64::from(end)));
332 // FIXME Remove once actual debuginfo for locals works.
333 for (i, (param, &val)) in context.func.signature.params.iter().zip(context.func.dfg.block_params(context.func.layout.entry_block().unwrap())).enumerate() {
334 use cranelift_codegen::ir::ArgumentPurpose;
335 let base_name = match param.purpose {
336 ArgumentPurpose::Normal => "arg",
337 ArgumentPurpose::StructReturn => "sret",
338 ArgumentPurpose::Link | ArgumentPurpose::FramePointer | ArgumentPurpose::CalleeSaved => continue,
339 ArgumentPurpose::VMContext | ArgumentPurpose::SignatureId | ArgumentPurpose::StackLimit => unreachable!(),
341 let name = format!("{}{}", base_name, i);
343 let dw_ty = self.debug_context.dwarf_ty_for_clif_ty(param.value_type);
344 let loc = Expression(
345 translate_loc(isa, context.func.locations[val], &context.func.stack_slots).unwrap(),
348 let arg_id = self.debug_context.dwarf.unit.add(self.entry_id, gimli::DW_TAG_formal_parameter);
349 let var_entry = self.debug_context.dwarf.unit.get_mut(arg_id);
351 var_entry.set(gimli::DW_AT_name, AttributeValue::String(name.into_bytes()));
352 var_entry.set(gimli::DW_AT_type, AttributeValue::ThisUnitEntryRef(dw_ty));
353 var_entry.set(gimli::DW_AT_location, AttributeValue::Exprloc(loc));
356 // FIXME make it more reliable and implement scopes before re-enabling this.
358 let value_labels_ranges = context.build_value_labels_ranges(isa).unwrap();
360 for (local, _local_decl) in self.mir.local_decls.iter_enumerated() {
361 let ty = self.debug_context.tcx.subst_and_normalize_erasing_regions(
362 self.instance.substs,
363 ty::ParamEnv::reveal_all(),
364 &self.mir.local_decls[local].ty,
366 let var_id = self.define_local(format!("{:?}", local), ty);
368 let location = place_location(
373 &value_labels_ranges,
376 projection: ty::List::empty(),
380 let var_entry = self.debug_context.dwarf.unit.get_mut(var_id);
381 var_entry.set(gimli::DW_AT_location, location);
385 // FIXME create locals for all entries in mir.var_debug_info
389 fn place_location<'a, 'tcx>(
390 func_debug_ctx: &mut FunctionDebugContext<'a, 'tcx>,
393 local_map: &FxHashMap<mir::Local, CPlace<'tcx>>,
394 #[allow(rustc::default_hash_types)]
395 value_labels_ranges: &std::collections::HashMap<ValueLabel, Vec<ValueLocRange>>,
397 ) -> AttributeValue {
398 assert!(place.projection.is_empty()); // FIXME implement them
400 match local_map[&place.local].inner() {
401 CPlaceInner::Var(local) => {
402 let value_label = cranelift_codegen::ir::ValueLabel::from_u32(local.as_u32());
403 if let Some(value_loc_ranges) = value_labels_ranges.get(&value_label) {
404 let loc_list = LocationList(
407 .map(|value_loc_range| Location::StartEnd {
408 begin: Address::Symbol {
409 symbol: func_debug_ctx.symbol,
410 addend: i64::from(value_loc_range.start),
412 end: Address::Symbol {
413 symbol: func_debug_ctx.symbol,
414 addend: i64::from(value_loc_range.end),
417 translate_loc(isa, value_loc_range.loc, &context.func.stack_slots).unwrap(),
422 let loc_list_id = func_debug_ctx.debug_context.dwarf.unit.locations.add(loc_list);
424 AttributeValue::LocationListRef(loc_list_id)
426 // FIXME set value labels for unused locals
428 AttributeValue::Exprloc(Expression(vec![]))
431 CPlaceInner::Addr(_, _) => {
432 // FIXME implement this (used by arguments and returns)
434 AttributeValue::Exprloc(Expression(vec![]))
436 // For PointerBase::Stack:
437 //AttributeValue::Exprloc(Expression(translate_loc(ValueLoc::Stack(*stack_slot), &context.func.stack_slots).unwrap()))
442 // Adapted from https://github.com/CraneStation/wasmtime/blob/5a1845b4caf7a5dba8eda1fef05213a532ed4259/crates/debug/src/transform/expression.rs#L59-L137
443 fn translate_loc(isa: &dyn TargetIsa, loc: ValueLoc, stack_slots: &StackSlots) -> Option<Vec<u8>> {
445 ValueLoc::Reg(reg) => {
446 let machine_reg = isa.map_dwarf_register(reg).unwrap();
447 assert!(machine_reg <= 32); // FIXME
448 Some(vec![gimli::constants::DW_OP_reg0.0 + machine_reg as u8])
450 ValueLoc::Stack(ss) => {
451 if let Some(ss_offset) = stack_slots[ss].offset {
452 let endian = gimli::RunTimeEndian::Little;
453 let mut writer = write::EndianVec::new(endian);
455 .write_u8(gimli::constants::DW_OP_breg0.0 + X86_64::RBP.0 as u8)
457 writer.write_sleb128(ss_offset as i64 + 16).expect("ss wr");
458 let buf = writer.into_vec();