]> git.lizzy.rs Git - rust.git/blob - src/debuginfo/line_info.rs
Fix assert_assignable for array types
[rust.git] / 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         entry.set(gimli::DW_AT_decl_column, AttributeValue::Udata(loc.col.to_usize() as u64));
114     }
115
116     pub(super) fn create_debug_lines(
117         &mut self,
118         symbol: usize,
119         entry_id: UnitEntryId,
120         context: &Context,
121         function_span: Span,
122         source_info_set: &indexmap::IndexSet<SourceInfo>,
123     ) -> CodeOffset {
124         let tcx = self.tcx;
125         let line_program = &mut self.dwarf.unit.line_program;
126
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();
134                     return;
135                 }
136             }
137             last_span = Some(span);
138
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 {
144                 span
145             } else {
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())
150             };
151
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());
155
156                     (
157                         file,
158                         u64::try_from(line).unwrap() + 1,
159                         u64::from((span.lo() - line_pos).to_u32()) + 1,
160                     )
161                 }
162                 Err(file) => (file, 0, 0),
163             };
164
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)
171             } else {
172                 true
173             };
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);
178             }
179
180             line_program.row().line = line;
181             line_program.row().column = col;
182             line_program.generate_row();
183         };
184
185         line_program.begin_sequence(Some(Address::Symbol { symbol, addend: 0 }));
186
187         let mut func_end = 0;
188
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);
195             } else {
196                 create_row_for_span(line_program, function_span);
197             }
198             func_end = end;
199         }
200
201         line_program.end_sequence(u64::from(func_end));
202
203         let func_end = mcr.buffer.total_size();
204
205         assert_ne!(func_end, 0);
206
207         let entry = self.dwarf.unit.get_mut(entry_id);
208         entry.set(
209             gimli::DW_AT_low_pc,
210             AttributeValue::Address(Address::Symbol { symbol, addend: 0 }),
211         );
212         entry.set(gimli::DW_AT_high_pc, AttributeValue::Udata(u64::from(func_end)));
213
214         self.emit_location(entry_id, function_span);
215
216         func_end
217     }
218 }