1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
use self::ast::*;
use super::ast;
use options::*;
/// Parses the body of a function `path` from the `function_line`
fn function_body(function_lines: Vec<String>, path: &str) -> ast::Function {
let mut function = Function {
id: path.to_string(),
file: None,
loc: None,
statements: Vec::new(),
};
let mut current_loc: Option<Loc> = None;
// Parse assembly lines of the function.
//
// The first line corresponds to the function path, we skip it since we
// already know it.
for (line_off, line) in function_lines
.into_iter()
.skip(1)
.map(|l| l.trim().to_string())
.filter(|l| !l.is_empty())
.enumerate()
{
debug!("parsing line: {}", line);
// If the line contains a comment, split the line at the comment.
let (node_str, comment_str) =
if let Some(comment_start) = line.find(';') {
debug!(" * contains a comment at: {:?}", comment_start);
let (node_str, comment_str) = line.split_at(comment_start);
(node_str, comment_str)
} else {
(line.as_str(), "")
};
// If the line contains a comment, we parse that first:
if let Some(comment) = Comment::new(comment_str) {
debug!(" * parsing comment: {:?}", comment);
function.statements.push(Statement::Comment(comment));
}
// Then we parse the AST statements.
if let Some(directive) = Directive::new(node_str) {
debug!(" * parsed directive: {:?}", directive);
// We set the first .file directive we parse as the functions file
// path:
if function.file.is_none() {
if let Some(file) = directive.file() {
debug!(" * file directive: {:?}", file);
// If there is a function location already set, we set the
// file only if the file index matches the location. Many
// functions don't have a .file directive set at the
// beginnin (only a location) but they contain .file
// directives in the body when code from other files gets
// inlined:
if let &Some(ref loc) = &function.loc {
if loc.file_index == file.index {
function.file = Some(file);
}
} else {
// If no location is set, the .file directive likely
// belongs to the function: when a .file directive for
// the function is generated these come before the
// first .loc directive.
function.file = Some(file);
}
}
}
// If we find a .loc directive we parse the loc offset and set its
// value as the current one:
if let Some(new_loc) = directive.loc() {
debug!(" * loc directive: {:?}", new_loc);
current_loc = Some(new_loc);
// The function location is the first location that we find
// while parsing the function body:
if function.loc.is_none() {
// If there is a function file already set, we check
// that the new location matches the file idx.
if let &Some(ref file) = &function.file {
assert_eq!(new_loc.file_index, file.index);
}
function.loc = Some(new_loc);
}
}
let dir = Statement::Directive(directive);
debug!(" * appending directive: {:?}", dir);
function.statements.push(dir);
continue;
}
if let Some(label) = Label::new(node_str, current_loc) {
debug!(" * parsed label: {:?}", label);
function.statements.push(Statement::Label(label));
continue;
}
if let Some(instruction) = Instruction::new(node_str, current_loc) {
debug!(" * parsed instruction: {:?}", instruction);
function
.statements
.push(Statement::Instruction(instruction));
continue;
}
panic!(
"cannot parse function: {}\n line off: {}\n{}",
path, line_off, line
);
}
function
}
/// Result of parsing a function, either a match, or a table of functions in
/// the file.
pub enum Result {
Found(ast::Function, ::std::collections::HashMap<usize, ast::File>),
NotFound(Vec<String>),
}
/// Parses the assembly function at `path` from the file `file`.
#[cfg_attr(feature = "cargo-clippy", allow(use_debug))]
pub fn function(file: &::std::path::Path) -> Result {
let path = if let Some(path) = opts.path() {
path
} else {
"".to_owned()
};
use std::io::BufRead;
let fh = ::std::fs::File::open(file).unwrap();
let file_buf = ::std::io::BufReader::new(&fh);
// We keep here the file ids of the already parsed files:
let mut file_directive_table =
::std::collections::HashMap::<usize, ast::File>::new();
// This is the AST of the function we are looking for:
let mut function: Option<ast::Function> = None;
let mut line_iter = file_buf.lines();
let mut function_table = Vec::<String>::new();
fn function_label_pattern() -> &'static str {
let t = ::target::target();
if t.contains("apple") {
"__"
} else {
"_"
}
}
fn function_end_pattern() -> &'static str {
let t = ::target::target();
if t.contains("windows") {
".seh_endproc" // TODO: does this work with panic=abort ?
} else {
".cfi_endproc"
}
}
// This is the pattern at the beginning of an assembly label
// that identifies the label as a function:
let function_label_pattern = function_label_pattern();
// This is the pattern that we match to know that we have finished
// searching the function
let function_end_pattern = function_end_pattern();
while let Some(line) = line_iter.next() {
let line = line.unwrap().trim().to_string();
if function.is_none() && line.starts_with(function_label_pattern) {
// We haven't found the function yet:
//
// Assembly functions are labels that start with `_` or `__`
// and have mangled names.
if let Some(label) = ast::Label::new(&line, None) {
let demangled_function_name = ::demangle::demangle(&label.id);
function_table.push(demangled_function_name.clone());
if demangled_function_name != path {
continue;
}
// We have found the function, collect its lines and build
// an AST:
let mut lines = Vec::<String>::new();
while let Some(l) = line_iter.next() {
let l = l.unwrap().trim().to_string();
if l.starts_with(function_end_pattern) {
break;
}
lines.push(l);
}
debug!("Function found: {}", path);
if opts.debug_mode() {
for l in &lines {
debug!("## {}", l);
}
}
function = Some(function_body(lines, &path));
// If the function contained a .file directive, we are
// done:
if let &Some(ref function) = &function {
if function.file.is_some() {
break;
}
}
// If the function did not contain a .loc directive
// either, we can't finde its
// corresponding Rust code so we are done:
if let &Some(ref function) = &function {
if function.loc.is_none() {
break;
}
}
// Otherwise we continue parsing the assembly file to try
// to find a .file directive for the
// function
continue;
}
panic!(
"line starts with _ but we failed to parse the label: {}",
line
);
}
// If the line does not begin an assembly function try to parse the
// line as a .file directive.
if let Some(file) = ast::File::new(&line) {
debug!("found file directive: {:?}", file);
let idx = file.index;
// If the file directive is already in the table, check that
// the paths match:
if file_directive_table.contains_key(&idx) {
let f = &file_directive_table[&idx];
assert_eq!(f.path, file.path);
continue;
}
// The file directive is not in the table: insert it:
file_directive_table.insert(idx, file);
}
// If we have found the function but landed here, the function contains
// at least one .loc directive but we haven't found its corresponding
// file yet, so we see if its present in the HashMap:
if let Some(ref mut function) = function {
assert!(function.file.is_none());
assert!(function.loc.is_some());
let file_index = function.loc.unwrap().file_index;
if let Some(file) = file_directive_table.remove(&file_index) {
function.file = Some(file);
break;
}
}
}
if function.is_none() {
// If the function is not found we have visited the whole file so the
// function table is complete.
return Result::NotFound(function_table);
}
let function = function.unwrap();
// Add all local .file directives in the body of the function to the table:
if let &Some(ref f) = &function.file {
file_directive_table
.entry(f.index)
.or_insert_with(|| f.clone());
}
for s in &function.statements {
if let &Statement::Directive(Directive::File(ref f)) = s {
file_directive_table
.entry(f.index)
.or_insert_with(|| f.clone());
}
}
// Check that we have found all .file directives for all .loc statements
// within the function:
let mut done = true;
for s in &function.statements {
if let &Statement::Directive(Directive::Loc(ref l)) = s {
if !file_directive_table.contains_key(&l.file_index) {
done = false;
error!(
"File directive for location not found! Location: {:?}",
l
);
}
}
}
if done {
return Result::Found(function, file_directive_table);
}
unimplemented!(
"TODO: need to continue scanning the file for file directives"
)
}