4 use std::convert::TryFrom;
8 use rustc_span::FileName;
10 use cranelift_codegen::ir::{StackSlots, ValueLabel, ValueLoc};
11 use cranelift_codegen::isa::TargetIsa;
12 use cranelift_codegen::ValueLocRange;
15 self, Address, AttributeValue, DwarfUnit, Expression, LineProgram, LineString, Location,
16 LocationList, Range, RangeList, UnitEntryId, Writer, FileInfo,
18 use gimli::{Encoding, Format, LineEncoding, RunTimeEndian, X86_64};
20 pub(crate) use emit::{DebugReloc, DebugRelocName};
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,
35 symbols: indexmap::IndexMap<FuncId, String>,
38 unit_range_list: RangeList,
40 types: FxHashMap<Ty<'tcx>, UnitEntryId>,
43 impl<'tcx> DebugContext<'tcx> {
44 pub(crate) fn new(tcx: TyCtxt<'tcx>, address_size: u8) -> 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 {
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_hash) = match tcx.sess.local_crate_source_file.clone() {
66 let name = path.to_string_lossy().into_owned();
69 .get_source_file(&FileName::Real(path))
70 .and_then(|f| line_info::FileHash::try_from(f.src_hash).ok());
73 None => (tcx.crate_name(LOCAL_CRATE).to_string(), None),
76 let mut line_program = LineProgram::new(
78 LineEncoding::default(),
79 LineString::new(comp_dir.as_bytes(), encoding, &mut dwarf.line_strings),
80 LineString::new(name.as_bytes(), encoding, &mut dwarf.line_strings),
84 md5: file_hash.unwrap_or_default().inner(),
87 line_program.file_has_md5 = file_hash.is_some();
89 dwarf.unit.line_program = line_program;
92 let name = dwarf.strings.add(name);
93 let comp_dir = dwarf.strings.add(comp_dir);
95 let root = dwarf.unit.root();
96 let root = dwarf.unit.get_mut(root);
98 gimli::DW_AT_producer,
99 AttributeValue::StringRef(dwarf.strings.add(producer)),
102 gimli::DW_AT_language,
103 AttributeValue::Language(gimli::DW_LANG_Rust),
105 root.set(gimli::DW_AT_name, AttributeValue::StringRef(name));
106 root.set(gimli::DW_AT_comp_dir, AttributeValue::StringRef(comp_dir));
109 AttributeValue::Address(Address::Constant(0)),
116 endian: target_endian(tcx),
117 symbols: indexmap::IndexMap::new(),
120 unit_range_list: RangeList(Vec::new()),
122 types: FxHashMap::default(),
126 fn dwarf_ty(&mut self, ty: Ty<'tcx>) -> UnitEntryId {
127 if let Some(type_id) = self.types.get(ty) {
131 let new_entry = |dwarf: &mut DwarfUnit, tag| dwarf.unit.add(dwarf.unit.root(), tag);
133 let primitive = |dwarf: &mut DwarfUnit, ate| {
134 let type_id = new_entry(dwarf, gimli::DW_TAG_base_type);
135 let type_entry = dwarf.unit.get_mut(type_id);
136 type_entry.set(gimli::DW_AT_encoding, AttributeValue::Encoding(ate));
140 let name = format!("{}", ty);
141 let layout = self.tcx.layout_of(ParamEnv::reveal_all().and(ty)).unwrap();
143 let type_id = match ty.kind {
144 ty::Bool => primitive(&mut self.dwarf, gimli::DW_ATE_boolean),
145 ty::Char => primitive(&mut self.dwarf, gimli::DW_ATE_UTF),
146 ty::Uint(_) => primitive(&mut self.dwarf, gimli::DW_ATE_unsigned),
147 ty::Int(_) => primitive(&mut self.dwarf, gimli::DW_ATE_signed),
148 ty::Float(_) => primitive(&mut self.dwarf, gimli::DW_ATE_float),
149 ty::Ref(_, pointee_ty, _mutbl)
150 | ty::RawPtr(ty::TypeAndMut {
154 let type_id = new_entry(&mut self.dwarf, gimli::DW_TAG_pointer_type);
156 // Ensure that type is inserted before recursing to avoid duplicates
157 self.types.insert(ty, type_id);
159 let pointee = self.dwarf_ty(pointee_ty);
161 let type_entry = self.dwarf.unit.get_mut(type_id);
163 //type_entry.set(gimli::DW_AT_mutable, AttributeValue::Flag(mutbl == rustc_hir::Mutability::Mut));
164 type_entry.set(gimli::DW_AT_type, AttributeValue::ThisUnitEntryRef(pointee));
168 ty::Adt(adt_def, _substs) if adt_def.is_struct() && !layout.is_unsized() => {
169 let type_id = new_entry(&mut self.dwarf, gimli::DW_TAG_structure_type);
171 // Ensure that type is inserted before recursing to avoid duplicates
172 self.types.insert(ty, type_id);
174 let variant = adt_def.non_enum_variant();
176 for (field_idx, field_def) in variant.fields.iter().enumerate() {
177 let field_offset = layout.fields.offset(field_idx);
178 let field_layout = layout.field(&layout::LayoutCx {
180 param_env: ParamEnv::reveal_all(),
181 }, field_idx).unwrap();
183 let field_type = self.dwarf_ty(field_layout.ty);
185 let field_id = self.dwarf.unit.add(type_id, gimli::DW_TAG_member);
186 let field_entry = self.dwarf.unit.get_mut(field_id);
188 field_entry.set(gimli::DW_AT_name, AttributeValue::String(field_def.ident.as_str().to_string().into_bytes()));
189 field_entry.set(gimli::DW_AT_data_member_location, AttributeValue::Udata(field_offset.bytes()));
190 field_entry.set(gimli::DW_AT_type, AttributeValue::ThisUnitEntryRef(field_type));
195 _ => new_entry(&mut self.dwarf, gimli::DW_TAG_structure_type),
198 let type_entry = self.dwarf.unit.get_mut(type_id);
200 type_entry.set(gimli::DW_AT_name, AttributeValue::String(name.into_bytes()));
202 gimli::DW_AT_byte_size,
203 AttributeValue::Udata(layout.size.bytes()),
206 self.types.insert(ty, type_id);
212 pub(crate) struct FunctionDebugContext<'a, 'tcx> {
213 debug_context: &'a mut DebugContext<'tcx>,
214 entry_id: UnitEntryId,
216 instance: Instance<'tcx>,
217 mir: &'tcx mir::Body<'tcx>,
220 impl<'a, 'tcx> FunctionDebugContext<'a, 'tcx> {
222 debug_context: &'a mut DebugContext<'tcx>,
223 instance: Instance<'tcx>,
227 let mir = *debug_context.tcx.instance_mir(instance.def);
229 let (symbol, _) = debug_context.symbols.insert_full(func_id, name.to_string());
231 // FIXME: add to appropriate scope intead of root
232 let scope = debug_context.dwarf.unit.root();
234 let entry_id = debug_context
237 .add(scope, gimli::DW_TAG_subprogram);
238 let entry = debug_context.dwarf.unit.get_mut(entry_id);
239 let name_id = debug_context.dwarf.strings.add(name);
241 gimli::DW_AT_linkage_name,
242 AttributeValue::StringRef(name_id),
245 FunctionDebugContext {
254 fn define_local(&mut self, name: String, ty: Ty<'tcx>) -> UnitEntryId {
255 let ty = self.debug_context.tcx.subst_and_normalize_erasing_regions(
256 self.instance.substs,
257 ty::ParamEnv::reveal_all(),
260 let dw_ty = self.debug_context.dwarf_ty(ty);
266 .add(self.entry_id, gimli::DW_TAG_variable);
267 let var_entry = self.debug_context.dwarf.unit.get_mut(var_id);
269 var_entry.set(gimli::DW_AT_name, AttributeValue::String(name.into_bytes()));
270 var_entry.set(gimli::DW_AT_type, AttributeValue::ThisUnitEntryRef(dw_ty));
275 pub(crate) fn define(
279 source_info_set: &indexmap::IndexSet<SourceInfo>,
280 local_map: FxHashMap<mir::Local, CPlace<'tcx>>,
282 let end = self.create_debug_lines(context, isa, source_info_set);
287 .push(Range::StartLength {
288 begin: Address::Symbol {
295 // FIXME make it more reliable and implement scopes before re-enabling this.
297 let value_labels_ranges = context.build_value_labels_ranges(isa).unwrap();
299 for (local, _local_decl) in self.mir.local_decls.iter_enumerated() {
300 let var_id = self.define_local(format!("{:?}", local), &self.mir.local_decls[local].ty);
302 let location = place_location(
307 &value_labels_ranges,
310 projection: ty::List::empty(),
314 let var_entry = self.debug_context.dwarf.unit.get_mut(var_id);
315 var_entry.set(gimli::DW_AT_location, location);
319 // FIXME create locals for all entries in mir.var_debug_info
323 fn place_location<'a, 'tcx>(
324 func_debug_ctx: &mut FunctionDebugContext<'a, 'tcx>,
327 local_map: &FxHashMap<mir::Local, CPlace<'tcx>>,
328 #[allow(rustc::default_hash_types)]
329 value_labels_ranges: &std::collections::HashMap<ValueLabel, Vec<ValueLocRange>>,
331 ) -> AttributeValue {
332 assert!(place.projection.is_empty()); // FIXME implement them
334 match local_map[&place.local].inner() {
335 CPlaceInner::Var(local) => {
336 let value_label = cranelift_codegen::ir::ValueLabel::from_u32(local.as_u32());
337 if let Some(value_loc_ranges) = value_labels_ranges.get(&value_label) {
338 let loc_list = LocationList(
341 .map(|value_loc_range| Location::StartEnd {
342 begin: Address::Symbol {
343 symbol: func_debug_ctx.symbol,
344 addend: i64::from(value_loc_range.start),
346 end: Address::Symbol {
347 symbol: func_debug_ctx.symbol,
348 addend: i64::from(value_loc_range.end),
351 translate_loc(isa, value_loc_range.loc, &context.func.stack_slots).unwrap(),
356 let loc_list_id = func_debug_ctx.debug_context.dwarf.unit.locations.add(loc_list);
358 AttributeValue::LocationListRef(loc_list_id)
360 // FIXME set value labels for unused locals
362 AttributeValue::Exprloc(Expression(vec![]))
365 CPlaceInner::Addr(_, _) => {
366 // FIXME implement this (used by arguments and returns)
368 AttributeValue::Exprloc(Expression(vec![]))
370 // For PointerBase::Stack:
371 //AttributeValue::Exprloc(Expression(translate_loc(ValueLoc::Stack(*stack_slot), &context.func.stack_slots).unwrap()))
376 // Adapted from https://github.com/CraneStation/wasmtime/blob/5a1845b4caf7a5dba8eda1fef05213a532ed4259/crates/debug/src/transform/expression.rs#L59-L137
377 fn translate_loc(isa: &dyn TargetIsa, loc: ValueLoc, stack_slots: &StackSlots) -> Option<Vec<u8>> {
379 ValueLoc::Reg(reg) => {
380 let machine_reg = isa.map_dwarf_register(reg).unwrap();
381 assert!(machine_reg <= 32); // FIXME
382 Some(vec![gimli::constants::DW_OP_reg0.0 + machine_reg as u8])
384 ValueLoc::Stack(ss) => {
385 if let Some(ss_offset) = stack_slots[ss].offset {
386 let endian = gimli::RunTimeEndian::Little;
387 let mut writer = write::EndianVec::new(endian);
389 .write_u8(gimli::constants::DW_OP_breg0.0 + X86_64::RBP.0 as u8)
391 writer.write_sleb128(ss_offset as i64 + 16).expect("ss wr");
392 let buf = writer.into_vec();