-
Notifications
You must be signed in to change notification settings - Fork 36
/
build.rs
308 lines (266 loc) · 9.03 KB
/
build.rs
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
use std::collections::HashSet;
use std::env;
use std::fs;
use std::io::{self, BufRead, Write};
use std::path::{self, Path};
fn get_crate_dir() -> io::Result<path::PathBuf> {
Ok(path::PathBuf::from(
env::var("CARGO_MANIFEST_DIR")
.map_err(|_| io::Error::new(io::ErrorKind::Other, "no CARGO_MANIFEST_DIR"))?,
))
}
fn get_out_dir() -> io::Result<path::PathBuf> {
Ok(path::PathBuf::from(env::var("OUT_DIR").map_err(|_| {
io::Error::new(io::ErrorKind::Other, "no OUT_DIR")
})?))
}
fn get_crate_test_path(file_name: &str) -> io::Result<path::PathBuf> {
let mut test_path = get_crate_dir()?;
test_path.push("tests");
assert!(test_path.is_dir());
test_path.push(file_name);
Ok(test_path)
}
fn get_test_path(file_name: &str) -> io::Result<path::PathBuf> {
let mut test_path = get_out_dir()?;
assert!(test_path.is_dir());
test_path.push(file_name);
Ok(test_path)
}
/// Generate tests that ensure that we don't panic when parsing and demangling
/// the seed test cases that we pass to AFL.rs assert (including the failing
/// test cases historically found by AFL.rs).
fn generate_sanity_tests_from_afl_seeds() -> io::Result<()> {
let mut in_dir = get_crate_dir()?;
in_dir.push("in");
if !in_dir.is_dir() {
// We are in `cargo publish` and the `in/` directory isn't included in
// the distributed package.
return Ok(());
}
let test_path = get_test_path("afl_seeds.rs")?;
let mut test_file = fs::File::create(test_path)?;
writeln!(
&mut test_file,
"
extern crate cpp_demangle;
use std::fs;
use std::io::Read;
"
)?;
println!("cargo:rerun-if-changed=tests/afl_seeds.rs");
let entries = fs::read_dir(in_dir)?;
for entry in entries {
let entry = entry?;
let path = entry.path();
let file_name = path.file_name().ok_or_else(|| {
io::Error::new(
io::ErrorKind::Other,
"no file name for AFL.rs seed test case",
)
})?;
println!(
"cargo:rerun-if-changed=in/{}",
Path::new(file_name).display()
);
// properly escape windows paths
let path = path.to_string_lossy().replace("\\", "\\\\");
writeln!(
&mut test_file,
r#"
#[test]
fn test_afl_seed_{}() {{
let mut file = fs::File::open("{}").unwrap();
let mut contents = Vec::new();
file.read_to_end(&mut contents).unwrap();
let _ = cpp_demangle::Symbol::new(contents);
assert!(true, "did not panic when parsing");
}}
"#,
file_name.to_string_lossy(),
path
)?;
}
Ok(())
}
/// Read `tests/libiberty-demangle-expected`, parse its input mangled symbols,
/// and expected output demangled symbols, and generate test cases for them.
///
/// We do not support all of the options that the libiberty demangler does,
/// therefore we skip tests that use options we do not intend to
/// support. Basically, we only support `--format=gnu-v3` (which is the System V
/// C++ ABI), and none of the legacy C/C++ compiler formats, nor Java/D/etc
/// language symbol mangling.
fn generate_compatibility_tests_from_libiberty() -> io::Result<()> {
let mut tests_dir = get_crate_dir()?;
tests_dir.push("tests");
if !tests_dir.is_dir() {
// We are in `cargo publish` and the `tests/` directory isn't included
// in the distributed package.
return Ok(());
}
println!("cargo:rerun-if-changed=tests/libiberty-demangle-expected");
let test_path = get_test_path("libiberty.rs")?;
let _ = fs::remove_file(&test_path);
let mut test_file = fs::File::create(test_path)?;
writeln!(
&mut test_file,
"
extern crate cpp_demangle;
extern crate diff;
use std::fmt::Write;
"
)?;
// The set of libiberty tests that pass. This should only ever grow!
let libiberty_passing_tests = {
let mut s: HashSet<_> = (0..86).collect();
s.extend(87..89);
s.extend(91..93);
s.extend(94..113);
s.extend(115..118);
s.extend(119..120);
s.extend(121..123);
s.extend(127..131);
s.extend(133..134);
s.extend(137..138);
s.extend(139..140);
s.extend(141..144);
s.extend(146..147);
s.extend(149..154);
s.extend(158..168);
s.extend(169..180);
s.extend(181..183);
s.extend(184..186);
s.extend(187..190);
s.extend(199..200);
s.extend(201..202);
s.extend(203..204);
s
};
let libiberty_tests = get_crate_test_path("libiberty-demangle-expected")?;
let libiberty_tests = fs::File::open(libiberty_tests)?;
let libiberty_tests = io::BufReader::new(libiberty_tests);
let mut lines = libiberty_tests
.lines()
.filter(|line| line.as_ref().map(|l| !l.starts_with('#')).unwrap_or(true));
let mut n = 0;
loop {
let options = match lines.next() {
None => break,
Some(Ok(line)) => line,
Some(Err(e)) => return Err(e),
};
let mangled = match lines.next() {
Some(Ok(line)) => line,
None => {
return Err(io::Error::new(
io::ErrorKind::Other,
"expected a line with a mangled symbol",
))
}
Some(Err(e)) => return Err(e),
};
let demangled = match lines.next() {
Some(Ok(line)) => line,
None => {
return Err(io::Error::new(
io::ErrorKind::Other,
"expected a line with the demangled symbol",
))
}
Some(Err(e)) => return Err(e),
};
if options.contains("--no-params") {
// This line is the expected demangled output without function and
// template parameters, but we don't currently have such an option
// in `cpp_demangle`, so just consume and ignore the line.
match lines.next() {
Some(Ok(_)) => {}
None => {
return Err(io::Error::new(
io::ErrorKind::Other,
"expected a line with the demangled symbol without parameters",
))
}
Some(Err(e)) => return Err(e),
}
}
// Skip tests for unsupported languages or options.
if !options.contains("--format=gnu-v3")
|| options.contains("--is-v3-ctor")
|| options.contains("--is-v3-dtor")
|| options.contains("--ret-postfix")
{
continue;
}
let cfg = if libiberty_passing_tests.contains(&n) {
""
} else {
r###"#[cfg(feature = "run_libiberty_tests")]"###
};
writeln!(
test_file,
r###"
{}
#[test]
fn test_libiberty_demangle_{}_() {{
let mangled = br#"{}"#;
let mangled_str = String::from_utf8_lossy(mangled).into_owned();
println!("Parsing mangled symbol: {{}}", mangled_str);
let expected = r#"{}"#;
let sym = match cpp_demangle::Symbol::new(&mangled[..]) {{
Ok(sym) => sym,
Err(_) if mangled_str == expected => return,
Err(e) => panic!("Should parse mangled symbol {{}}", e),
}};
let mut actual = String::new();
if let Err(e) = write!(&mut actual, "{{}}", sym) {{
panic!("Error while demangling '{{}}': {{}}",
mangled_str,
e);
}}
println!(" Expect demangled symbol: {{}}", expected);
println!("Actually demangled symbol as: {{}}", actual);
if expected != actual {{
println!("");
println!("Diff:");
println!("--- expected");
print!("+++ actual");
let mut last = None;
for cmp in diff::chars(expected, &actual) {{
match (last, cmp.clone()) {{
(Some(diff::Result::Left(_)), diff::Result::Left(_)) |
(Some(diff::Result::Both(..)), diff::Result::Both(..)) |
(Some(diff::Result::Right(_)), diff::Result::Right(_)) => {{}}
(_, diff::Result::Left(_)) => print!("\n-"),
(_, diff::Result::Both(..)) => print!("\n "),
(_, diff::Result::Right(_)) => print!("\n+"),
}};
match cmp.clone() {{
diff::Result::Left(c) |
diff::Result::Both(c, _) |
diff::Result::Right(c) => print!("{{}}", c),
}}
last = Some(cmp);
}}
println!("");
}}
assert_eq!(expected, actual);
}}
"###,
cfg,
n,
mangled.trim(),
demangled.trim()
)?;
n += 1;
}
Ok(())
}
fn main() {
println!("cargo:rerun-if-changed=build.rs");
generate_sanity_tests_from_afl_seeds()
.expect("should generate sanity tests from AFL.rs seed test cases");
generate_compatibility_tests_from_libiberty()
.expect("should generate compatibility tests from tests/libiberty-demangle-expected");
}