]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_cranelift/src/debuginfo/line_info.rs
Merge commit '3a31c6d8272c14388a34622193baf553636fe470' into sync_cg_clif-2021-07-07
[rust.git] / compiler / rustc_codegen_cranelift / src / debuginfo / line_info.rs
1 //! Line info generation (`.debug_line`)
2
3 use std::ffi::OsStr;
4 use std::path::{Component, Path};
5
6 use crate::prelude::*;
7
8 use rustc_span::{
9     FileName, Pos, SourceFile, SourceFileAndLine, SourceFileHash, SourceFileHashAlgorithm,
10 };
11
12 use cranelift_codegen::binemit::CodeOffset;
13 use cranelift_codegen::MachSrcLoc;
14
15 use gimli::write::{
16     Address, AttributeValue, FileId, FileInfo, LineProgram, LineString, LineStringTable,
17     UnitEntryId,
18 };
19
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,
25         component => {
26             panic!(
27                 "Path component {:?} of path {} is an invalid filename",
28                 component,
29                 path.display()
30             );
31         }
32     };
33     let parent = iter.as_path();
34     (parent, file_name)
35 }
36
37 // OPTIMIZATION: Avoid UTF-8 validation on UNIX.
38 fn osstr_as_utf8_bytes(path: &OsStr) -> &[u8] {
39     #[cfg(unix)]
40     {
41         use std::os::unix::ffi::OsStrExt;
42         path.as_bytes()
43     }
44     #[cfg(not(unix))]
45     {
46         path.to_str().unwrap().as_bytes()
47     }
48 }
49
50 pub(crate) const MD5_LEN: usize = 16;
51
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 })
57     } else {
58         None
59     }
60 }
61
62 fn line_program_add_file(
63     line_program: &mut LineProgram,
64     line_strings: &mut LineStringTable,
65     file: &SourceFile,
66 ) -> FileId {
67     match &file.name {
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);
72
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)
76             } else {
77                 line_program.default_directory()
78             };
79             let file_name = LineString::new(file_name, line_program.encoding(), line_strings);
80
81             let info = make_file_info(file.src_hash);
82
83             line_program.file_has_md5 &= info.is_some();
84             line_program.add_file(file_name, dir_id, info)
85         }
86         // FIXME give more appropriate file names
87         filename => {
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(),
92                 line_strings,
93             );
94             line_program.add_file(dummy_file_name, dir_id, None)
95         }
96     }
97 }
98
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());
102
103         let file_id = line_program_add_file(
104             &mut self.dwarf.unit.line_program,
105             &mut self.dwarf.line_strings,
106             &loc.file,
107         );
108
109         let entry = self.dwarf.unit.get_mut(entry_id);
110
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         // FIXME: probably omit this
114         entry.set(gimli::DW_AT_decl_column, AttributeValue::Udata(loc.col.to_usize() as u64));
115     }
116
117     pub(super) fn create_debug_lines(
118         &mut self,
119         symbol: usize,
120         entry_id: UnitEntryId,
121         context: &Context,
122         function_span: Span,
123         source_info_set: &indexmap::IndexSet<SourceInfo>,
124     ) -> CodeOffset {
125         let tcx = self.tcx;
126         let line_program = &mut self.dwarf.unit.line_program;
127
128         let line_strings = &mut self.dwarf.line_strings;
129         let mut last_span = None;
130         let mut last_file = None;
131         let mut create_row_for_span = |line_program: &mut LineProgram, span: Span| {
132             if let Some(last_span) = last_span {
133                 if span == last_span {
134                     line_program.generate_row();
135                     return;
136                 }
137             }
138             last_span = Some(span);
139
140             // Based on https://github.com/rust-lang/rust/blob/e369d87b015a84653343032833d65d0545fd3f26/src/librustc_codegen_ssa/mir/mod.rs#L116-L131
141             // In order to have a good line stepping behavior in debugger, we overwrite debug
142             // locations of macro expansions with that of the outermost expansion site
143             // (unless the crate is being compiled with `-Z debug-macros`).
144             let span = if !span.from_expansion() || tcx.sess.opts.debugging_opts.debug_macros {
145                 span
146             } else {
147                 // Walk up the macro expansion chain until we reach a non-expanded span.
148                 // We also stop at the function body level because no line stepping can occur
149                 // at the level above that.
150                 rustc_span::hygiene::walk_chain(span, function_span.ctxt())
151             };
152
153             let (file, line, col) = match tcx.sess.source_map().lookup_line(span.lo()) {
154                 Ok(SourceFileAndLine { sf: file, line }) => {
155                     let line_pos = file.line_begin_pos(span.lo());
156
157                     (
158                         file,
159                         u64::try_from(line).unwrap() + 1,
160                         u64::from((span.lo() - line_pos).to_u32()) + 1,
161                     )
162                 }
163                 Err(file) => (file, 0, 0),
164             };
165
166             // line_program_add_file is very slow.
167             // Optimize for the common case of the current file not being changed.
168             let current_file_changed = if let Some(last_file) = &last_file {
169                 // If the allocations are not equal, then the files may still be equal, but that
170                 // is not a problem, as this is just an optimization.
171                 !rustc_data_structures::sync::Lrc::ptr_eq(last_file, &file)
172             } else {
173                 true
174             };
175             if current_file_changed {
176                 let file_id = line_program_add_file(line_program, line_strings, &file);
177                 line_program.row().file = file_id;
178                 last_file = Some(file);
179             }
180
181             line_program.row().line = line;
182             line_program.row().column = col;
183             line_program.generate_row();
184         };
185
186         line_program.begin_sequence(Some(Address::Symbol { symbol, addend: 0 }));
187
188         let mut func_end = 0;
189
190         let mcr = context.mach_compile_result.as_ref().unwrap();
191         for &MachSrcLoc { start, end, loc } in mcr.buffer.get_srclocs_sorted() {
192             line_program.row().address_offset = u64::from(start);
193             if !loc.is_default() {
194                 let source_info = *source_info_set.get_index(loc.bits() as usize).unwrap();
195                 create_row_for_span(line_program, source_info.span);
196             } else {
197                 create_row_for_span(line_program, function_span);
198             }
199             func_end = end;
200         }
201
202         line_program.end_sequence(u64::from(func_end));
203
204         let func_end = mcr.buffer.total_size();
205
206         assert_ne!(func_end, 0);
207
208         let entry = self.dwarf.unit.get_mut(entry_id);
209         entry.set(
210             gimli::DW_AT_low_pc,
211             AttributeValue::Address(Address::Symbol { symbol, addend: 0 }),
212         );
213         entry.set(gimli::DW_AT_high_pc, AttributeValue::Udata(u64::from(func_end)));
214
215         self.emit_location(entry_id, function_span);
216
217         func_end
218     }
219 }