7 use rustc_span::FileName;
9 use cranelift_codegen::ir::{StackSlots, ValueLabel, ValueLoc};
10 use cranelift_codegen::isa::TargetIsa;
11 use cranelift_codegen::ValueLocRange;
14 self, Address, AttributeValue, DwarfUnit, Expression, LineProgram,
15 LineString, Location, LocationList, Range, RangeList, UnitEntryId, Writer,
17 use gimli::{Encoding, Format, LineEncoding, RunTimeEndian, X86_64};
19 pub(crate) use emit::{DebugReloc, DebugRelocName};
20 pub(crate) use unwind::UnwindContext;
22 fn target_endian(tcx: TyCtxt<'_>) -> RunTimeEndian {
23 use rustc_target::abi::Endian;
25 match tcx.data_layout.endian {
26 Endian::Big => RunTimeEndian::Big,
27 Endian::Little => RunTimeEndian::Little,
31 pub(crate) struct DebugContext<'tcx> {
34 endian: RunTimeEndian,
37 unit_range_list: RangeList,
39 clif_types: FxHashMap<Type, UnitEntryId>,
40 types: FxHashMap<Ty<'tcx>, UnitEntryId>,
43 impl<'tcx> DebugContext<'tcx> {
44 pub(crate) fn new(tcx: TyCtxt<'tcx>, isa: &dyn TargetIsa) -> 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 {
53 // FIXME change to version 5 once the gdb and lldb shipping with the latest debian
57 address_size: isa.frontend_config().pointer_bytes(),
60 let mut dwarf = DwarfUnit::new(encoding);
62 // FIXME: how to get version when building out of tree?
63 // Normally this would use option_env!("CFG_VERSION").
64 let producer = format!("cg_clif (rustc {})", "unknown version");
65 let comp_dir = tcx.sess.working_dir.0.to_string_lossy().into_owned();
66 let (name, file_info) = match tcx.sess.local_crate_source_file.clone() {
68 let name = path.to_string_lossy().into_owned();
71 .get_source_file(&FileName::Real(path))
73 .and_then(line_info::make_file_info);
76 None => (tcx.crate_name(LOCAL_CRATE).to_string(), None),
79 let mut line_program = LineProgram::new(
81 LineEncoding::default(),
82 LineString::new(comp_dir.as_bytes(), encoding, &mut dwarf.line_strings),
83 LineString::new(name.as_bytes(), encoding, &mut dwarf.line_strings),
86 line_program.file_has_md5 = file_info.is_some();
88 dwarf.unit.line_program = line_program;
91 let name = dwarf.strings.add(name);
92 let comp_dir = dwarf.strings.add(comp_dir);
94 let root = dwarf.unit.root();
95 let root = dwarf.unit.get_mut(root);
97 gimli::DW_AT_producer,
98 AttributeValue::StringRef(dwarf.strings.add(producer)),
101 gimli::DW_AT_language,
102 AttributeValue::Language(gimli::DW_LANG_Rust),
104 root.set(gimli::DW_AT_name, AttributeValue::StringRef(name));
105 root.set(gimli::DW_AT_comp_dir, AttributeValue::StringRef(comp_dir));
108 AttributeValue::Address(Address::Constant(0)),
115 endian: target_endian(tcx),
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 // FIXME: add to appropriate scope intead of root
263 let scope = debug_context.dwarf.unit.root();
265 let entry_id = debug_context
268 .add(scope, gimli::DW_TAG_subprogram);
269 let entry = debug_context.dwarf.unit.get_mut(entry_id);
270 let name_id = debug_context.dwarf.strings.add(name);
271 // Gdb requires DW_AT_name. Otherwise the DW_TAG_subprogram is skipped.
274 AttributeValue::StringRef(name_id),
277 gimli::DW_AT_linkage_name,
278 AttributeValue::StringRef(name_id),
281 FunctionDebugContext {
284 symbol: func_id.as_u32() as usize,
290 fn define_local(&mut self, name: String, ty: Ty<'tcx>) -> UnitEntryId {
291 let dw_ty = self.debug_context.dwarf_ty(ty);
297 .add(self.entry_id, gimli::DW_TAG_variable);
298 let var_entry = self.debug_context.dwarf.unit.get_mut(var_id);
300 var_entry.set(gimli::DW_AT_name, AttributeValue::String(name.into_bytes()));
301 var_entry.set(gimli::DW_AT_type, AttributeValue::ThisUnitEntryRef(dw_ty));
306 pub(crate) fn define(
310 source_info_set: &indexmap::IndexSet<SourceInfo>,
311 local_map: FxHashMap<mir::Local, CPlace<'tcx>>,
313 let end = self.create_debug_lines(context, isa, source_info_set);
318 .push(Range::StartLength {
319 begin: Address::Symbol {
323 length: u64::from(end),
326 if isa.get_mach_backend().is_some() {
327 return; // Not yet implemented for the AArch64 backend.
330 let func_entry = self.debug_context.dwarf.unit.get_mut(self.entry_id);
331 // Gdb requires both DW_AT_low_pc and DW_AT_high_pc. Otherwise the DW_TAG_subprogram is skipped.
332 func_entry.set(gimli::DW_AT_low_pc, AttributeValue::Address(Address::Symbol {
336 // Using Udata for DW_AT_high_pc requires at least DWARF4
337 func_entry.set(gimli::DW_AT_high_pc, AttributeValue::Udata(u64::from(end)));
339 // FIXME Remove once actual debuginfo for locals works.
340 for (i, (param, &val)) in context.func.signature.params.iter().zip(context.func.dfg.block_params(context.func.layout.entry_block().unwrap())).enumerate() {
341 use cranelift_codegen::ir::ArgumentPurpose;
342 let base_name = match param.purpose {
343 ArgumentPurpose::Normal => "arg",
344 ArgumentPurpose::StructReturn => "sret",
345 ArgumentPurpose::Link | ArgumentPurpose::FramePointer | ArgumentPurpose::CalleeSaved => continue,
346 ArgumentPurpose::VMContext | ArgumentPurpose::SignatureId | ArgumentPurpose::StackLimit => unreachable!(),
348 let name = format!("{}{}", base_name, i);
350 let dw_ty = self.debug_context.dwarf_ty_for_clif_ty(param.value_type);
351 let loc = Expression(
352 translate_loc(isa, context.func.locations[val], &context.func.stack_slots).unwrap(),
355 let arg_id = self.debug_context.dwarf.unit.add(self.entry_id, gimli::DW_TAG_formal_parameter);
356 let var_entry = self.debug_context.dwarf.unit.get_mut(arg_id);
358 var_entry.set(gimli::DW_AT_name, AttributeValue::String(name.into_bytes()));
359 var_entry.set(gimli::DW_AT_type, AttributeValue::ThisUnitEntryRef(dw_ty));
360 var_entry.set(gimli::DW_AT_location, AttributeValue::Exprloc(loc));
363 // FIXME make it more reliable and implement scopes before re-enabling this.
365 let value_labels_ranges = context.build_value_labels_ranges(isa).unwrap();
367 for (local, _local_decl) in self.mir.local_decls.iter_enumerated() {
368 let ty = self.debug_context.tcx.subst_and_normalize_erasing_regions(
369 self.instance.substs,
370 ty::ParamEnv::reveal_all(),
371 &self.mir.local_decls[local].ty,
373 let var_id = self.define_local(format!("{:?}", local), ty);
375 let location = place_location(
380 &value_labels_ranges,
383 projection: ty::List::empty(),
387 let var_entry = self.debug_context.dwarf.unit.get_mut(var_id);
388 var_entry.set(gimli::DW_AT_location, location);
392 // FIXME create locals for all entries in mir.var_debug_info
396 fn place_location<'a, 'tcx>(
397 func_debug_ctx: &mut FunctionDebugContext<'a, 'tcx>,
400 local_map: &FxHashMap<mir::Local, CPlace<'tcx>>,
401 #[allow(rustc::default_hash_types)]
402 value_labels_ranges: &std::collections::HashMap<ValueLabel, Vec<ValueLocRange>>,
404 ) -> AttributeValue {
405 assert!(place.projection.is_empty()); // FIXME implement them
407 match local_map[&place.local].inner() {
408 CPlaceInner::Var(local) => {
409 let value_label = cranelift_codegen::ir::ValueLabel::from_u32(local.as_u32());
410 if let Some(value_loc_ranges) = value_labels_ranges.get(&value_label) {
411 let loc_list = LocationList(
414 .map(|value_loc_range| Location::StartEnd {
415 begin: Address::Symbol {
416 symbol: func_debug_ctx.symbol,
417 addend: i64::from(value_loc_range.start),
419 end: Address::Symbol {
420 symbol: func_debug_ctx.symbol,
421 addend: i64::from(value_loc_range.end),
424 translate_loc(isa, value_loc_range.loc, &context.func.stack_slots).unwrap(),
429 let loc_list_id = func_debug_ctx.debug_context.dwarf.unit.locations.add(loc_list);
431 AttributeValue::LocationListRef(loc_list_id)
433 // FIXME set value labels for unused locals
435 AttributeValue::Exprloc(Expression(vec![]))
438 CPlaceInner::Addr(_, _) => {
439 // FIXME implement this (used by arguments and returns)
441 AttributeValue::Exprloc(Expression(vec![]))
443 // For PointerBase::Stack:
444 //AttributeValue::Exprloc(Expression(translate_loc(ValueLoc::Stack(*stack_slot), &context.func.stack_slots).unwrap()))
449 // Adapted from https://github.com/CraneStation/wasmtime/blob/5a1845b4caf7a5dba8eda1fef05213a532ed4259/crates/debug/src/transform/expression.rs#L59-L137
450 fn translate_loc(isa: &dyn TargetIsa, loc: ValueLoc, stack_slots: &StackSlots) -> Option<Vec<u8>> {
452 ValueLoc::Reg(reg) => {
453 let machine_reg = isa.map_dwarf_register(reg).unwrap();
454 assert!(machine_reg <= 32); // FIXME
455 Some(vec![gimli::constants::DW_OP_reg0.0 + machine_reg as u8])
457 ValueLoc::Stack(ss) => {
458 if let Some(ss_offset) = stack_slots[ss].offset {
459 let endian = gimli::RunTimeEndian::Little;
460 let mut writer = write::EndianVec::new(endian);
462 .write_u8(gimli::constants::DW_OP_breg0.0 + X86_64::RBP.0 as u8)
464 writer.write_sleb128(ss_offset as i64 + 16).expect("ss wr");
465 let buf = writer.into_vec();