1 //! Line info generation (`.debug_line`)
4 use std::path::{Component, Path};
9 FileName, Pos, SourceFile, SourceFileAndLine, SourceFileHash, SourceFileHashAlgorithm,
12 use cranelift_codegen::binemit::CodeOffset;
13 use cranelift_codegen::MachSrcLoc;
16 Address, AttributeValue, FileId, FileInfo, LineProgram, LineString, LineStringTable,
20 // OPTIMIZATION: It is cheaper to do this in one pass than using `.parent()` and `.file_name()`.
21 fn split_path_dir_and_file(path: &Path) -> (&Path, &OsStr) {
22 let mut iter = path.components();
23 let file_name = match iter.next_back() {
24 Some(Component::Normal(p)) => p,
27 "Path component {:?} of path {} is an invalid filename",
33 let parent = iter.as_path();
37 // OPTIMIZATION: Avoid UTF-8 validation on UNIX.
38 fn osstr_as_utf8_bytes(path: &OsStr) -> &[u8] {
41 use std::os::unix::ffi::OsStrExt;
46 path.to_str().unwrap().as_bytes()
50 pub(crate) const MD5_LEN: usize = 16;
52 pub(crate) fn make_file_info(hash: SourceFileHash) -> Option<FileInfo> {
53 if hash.kind == SourceFileHashAlgorithm::Md5 {
54 let mut buf = [0u8; MD5_LEN];
55 buf.copy_from_slice(hash.hash_bytes());
56 Some(FileInfo { timestamp: 0, size: 0, md5: buf })
62 fn line_program_add_file(
63 line_program: &mut LineProgram,
64 line_strings: &mut LineStringTable,
68 FileName::Real(path) => {
69 let (dir_path, file_name) = split_path_dir_and_file(path.remapped_path_if_available());
70 let dir_name = osstr_as_utf8_bytes(dir_path.as_os_str());
71 let file_name = osstr_as_utf8_bytes(file_name);
73 let dir_id = if !dir_name.is_empty() {
74 let dir_name = LineString::new(dir_name, line_program.encoding(), line_strings);
75 line_program.add_directory(dir_name)
77 line_program.default_directory()
79 let file_name = LineString::new(file_name, line_program.encoding(), line_strings);
81 let info = make_file_info(file.src_hash);
83 line_program.file_has_md5 &= info.is_some();
84 line_program.add_file(file_name, dir_id, info)
86 // FIXME give more appropriate file names
88 let dir_id = line_program.default_directory();
89 let dummy_file_name = LineString::new(
90 filename.prefer_remapped().to_string().into_bytes(),
91 line_program.encoding(),
94 line_program.add_file(dummy_file_name, dir_id, None)
99 impl<'tcx> DebugContext<'tcx> {
100 pub(super) fn emit_location(&mut self, entry_id: UnitEntryId, span: Span) {
101 let loc = self.tcx.sess.source_map().lookup_char_pos(span.lo());
103 let file_id = line_program_add_file(
104 &mut self.dwarf.unit.line_program,
105 &mut self.dwarf.line_strings,
109 let entry = self.dwarf.unit.get_mut(entry_id);
111 entry.set(gimli::DW_AT_decl_file, AttributeValue::FileIndex(Some(file_id)));
112 entry.set(gimli::DW_AT_decl_line, AttributeValue::Udata(loc.line as u64));
113 entry.set(gimli::DW_AT_decl_column, AttributeValue::Udata(loc.col.to_usize() as u64));
116 pub(super) fn create_debug_lines(
119 entry_id: UnitEntryId,
122 source_info_set: &indexmap::IndexSet<SourceInfo>,
125 let line_program = &mut self.dwarf.unit.line_program;
127 let line_strings = &mut self.dwarf.line_strings;
128 let mut last_span = None;
129 let mut last_file = None;
130 let mut create_row_for_span = |line_program: &mut LineProgram, span: Span| {
131 if let Some(last_span) = last_span {
132 if span == last_span {
133 line_program.generate_row();
137 last_span = Some(span);
139 // Based on https://github.com/rust-lang/rust/blob/e369d87b015a84653343032833d65d0545fd3f26/src/librustc_codegen_ssa/mir/mod.rs#L116-L131
140 // In order to have a good line stepping behavior in debugger, we overwrite debug
141 // locations of macro expansions with that of the outermost expansion site
142 // (unless the crate is being compiled with `-Z debug-macros`).
143 let span = if !span.from_expansion() || tcx.sess.opts.debugging_opts.debug_macros {
146 // Walk up the macro expansion chain until we reach a non-expanded span.
147 // We also stop at the function body level because no line stepping can occur
148 // at the level above that.
149 rustc_span::hygiene::walk_chain(span, function_span.ctxt())
152 let (file, line, col) = match tcx.sess.source_map().lookup_line(span.lo()) {
153 Ok(SourceFileAndLine { sf: file, line }) => {
154 let line_pos = file.line_begin_pos(span.lo());
158 u64::try_from(line).unwrap() + 1,
159 u64::from((span.lo() - line_pos).to_u32()) + 1,
162 Err(file) => (file, 0, 0),
165 // line_program_add_file is very slow.
166 // Optimize for the common case of the current file not being changed.
167 let current_file_changed = if let Some(last_file) = &last_file {
168 // If the allocations are not equal, then the files may still be equal, but that
169 // is not a problem, as this is just an optimization.
170 !rustc_data_structures::sync::Lrc::ptr_eq(last_file, &file)
174 if current_file_changed {
175 let file_id = line_program_add_file(line_program, line_strings, &file);
176 line_program.row().file = file_id;
177 last_file = Some(file);
180 line_program.row().line = line;
181 line_program.row().column = col;
182 line_program.generate_row();
185 line_program.begin_sequence(Some(Address::Symbol { symbol, addend: 0 }));
187 let mut func_end = 0;
189 let mcr = context.mach_compile_result.as_ref().unwrap();
190 for &MachSrcLoc { start, end, loc } in mcr.buffer.get_srclocs_sorted() {
191 line_program.row().address_offset = u64::from(start);
192 if !loc.is_default() {
193 let source_info = *source_info_set.get_index(loc.bits() as usize).unwrap();
194 create_row_for_span(line_program, source_info.span);
196 create_row_for_span(line_program, function_span);
201 line_program.end_sequence(u64::from(func_end));
203 let func_end = mcr.buffer.total_size();
205 assert_ne!(func_end, 0);
207 let entry = self.dwarf.unit.get_mut(entry_id);
210 AttributeValue::Address(Address::Symbol { symbol, addend: 0 }),
212 entry.set(gimli::DW_AT_high_pc, AttributeValue::Udata(u64::from(func_end)));
214 self.emit_location(entry_id, function_span);