forked from AFLplusplus/LibAFL
-
Notifications
You must be signed in to change notification settings - Fork 1
/
build.rs
430 lines (382 loc) · 13.7 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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
use std::{
env,
fs::File,
io::Write,
path::{Path, PathBuf},
process::Command,
str,
};
#[cfg(target_vendor = "apple")]
use glob::glob;
use which::which;
/// The max version of `LLVM` we're looking for
#[cfg(not(target_vendor = "apple"))]
const LLVM_VERSION_MAX: u32 = 33;
/// The min version of `LLVM` we're looking for
#[cfg(not(target_vendor = "apple"))]
const LLVM_VERSION_MIN: u32 = 6;
/// Get the extension for a shared object
fn dll_extension<'a>() -> &'a str {
if let Ok(vendor) = env::var("CARGO_CFG_TARGET_VENDOR") {
if vendor == "apple" {
return "dylib";
}
}
let family = env::var("CARGO_CFG_TARGET_FAMILY").unwrap();
match family.as_str() {
"windows" => "dll",
"unix" => "so",
_ => panic!("Unsupported target family: {family}"),
}
}
/// Github Actions for `MacOS` seems to have troubles finding `llvm-config`.
/// Hence, we go look for it ourselves.
#[cfg(target_vendor = "apple")]
fn find_llvm_config_brew() -> Result<PathBuf, String> {
match Command::new("brew").arg("--cellar").output() {
Ok(output) => {
let brew_cellar_location = str::from_utf8(&output.stdout).unwrap_or_default().trim();
if brew_cellar_location.is_empty() {
return Err("Empty return from brew --cellar".to_string());
}
let location_suffix = "*/bin/llvm-config";
let cellar_glob = vec![
// location for explicitly versioned brew formulae
format!("{brew_cellar_location}/llvm@*/{location_suffix}"),
// location for current release brew formulae
format!("{brew_cellar_location}/llvm/{location_suffix}"),
];
let glob_results = cellar_glob.iter().flat_map(|location| {
glob(location).unwrap_or_else(|err| {
panic!("Could not read glob path {location} ({err})");
})
});
match glob_results.last() {
Some(path) => Ok(path.unwrap()),
None => Err(format!(
"No llvm-config found in brew cellar with patterns {}",
cellar_glob.join(" ")
)),
}
}
Err(err) => Err(format!("Could not execute brew --cellar: {err:?}")),
}
}
fn find_llvm_config() -> Result<String, String> {
if let Ok(var) = env::var("LLVM_CONFIG") {
return Ok(var);
}
// for Github Actions, we check if we find llvm-config in brew.
#[cfg(target_vendor = "apple")]
match find_llvm_config_brew() {
Ok(llvm_dir) => return Ok(llvm_dir.to_str().unwrap().to_string()),
Err(err) => {
println!("cargo:warning={err}");
}
};
#[cfg(not(target_vendor = "apple"))]
for version in (LLVM_VERSION_MIN..=LLVM_VERSION_MAX).rev() {
let llvm_config_name: String = format!("llvm-config-{version}");
if which(&llvm_config_name).is_ok() {
return Ok(llvm_config_name);
}
}
if which("llvm-config").is_ok() {
return Ok("llvm-config".to_owned());
}
Err("could not find llvm-config".to_owned())
}
fn exec_llvm_config(args: &[&str]) -> String {
let llvm_config = find_llvm_config().expect("Unexpected error");
match Command::new(llvm_config).args(args).output() {
Ok(output) => String::from_utf8(output.stdout)
.expect("Unexpected llvm-config output")
.trim()
.to_string(),
Err(e) => panic!("Could not execute llvm-config: {e}"),
}
}
/// Use `xcrun` to get the path to the Xcode SDK tools library path, for linking
fn find_macos_sdk_libs() -> String {
let sdk_path_out = Command::new("xcrun")
.arg("--show-sdk-path")
.output()
.expect("Failed to execute xcrun. Make sure you have Xcode installed and executed `sudo xcode-select --install`");
format!(
"-L{}/usr/lib",
String::from_utf8(sdk_path_out.stdout).unwrap().trim()
)
}
fn find_llvm_version() -> Option<i32> {
let llvm_env_version = env::var("LLVM_VERSION");
let output = if let Ok(version) = llvm_env_version {
version
} else {
exec_llvm_config(&["--version"])
};
if let Some(major) = output.split('.').collect::<Vec<&str>>().first() {
if let Ok(res) = major.parse::<i32>() {
return Some(res);
}
}
None
}
#[allow(clippy::too_many_arguments)]
fn build_pass(
bindir_path: &Path,
out_dir: &Path,
cxxflags: &Vec<String>,
ldflags: &Vec<&str>,
src_dir: &Path,
src_file: &str,
additional_srcfiles: Option<&Vec<&str>>,
optional: bool,
) {
let dot_offset = src_file.rfind('.').unwrap();
let src_stub = &src_file[..dot_offset];
let additionals = if let Some(x) = additional_srcfiles {
x.iter().map(|f| src_dir.join(f)).collect::<Vec<PathBuf>>()
} else {
Vec::new()
};
println!("cargo:rerun-if-changed=src/{src_file}");
let r = if cfg!(unix) {
let r = Command::new(bindir_path.join("clang++"))
.arg("-v")
.args(cxxflags)
.arg(src_dir.join(src_file))
.args(additionals)
.args(ldflags)
.arg("-o")
.arg(out_dir.join(format!("{src_stub}.{}", dll_extension())))
.status();
Some(r)
} else if cfg!(windows) {
let r = Command::new(bindir_path.join("clang-cl.exe"))
.arg("-v")
.args(cxxflags)
.arg(src_dir.join(src_file))
.args(additionals)
.arg("/link")
.args(ldflags)
.arg(format!(
"/OUT:{}",
out_dir
.join(format!("{src_stub}.{}", dll_extension()))
.display()
))
.status();
Some(r)
} else {
None
};
match r {
Some(r) => match r {
Ok(s) => {
if !s.success() {
if optional {
println!("cargo:warning=Skipping src/{src_file}");
} else {
panic!("Failed to compile {src_file}");
}
}
}
Err(_) => {
if optional {
println!("cargo:warning=Skipping src/{src_file}");
} else {
panic!("Failed to compile {src_file}");
}
}
},
None => {
println!("cargo:warning=Skipping src/{src_file}");
}
}
}
#[allow(clippy::single_element_loop)]
#[allow(clippy::too_many_lines)]
fn main() {
let out_dir = env::var_os("OUT_DIR").unwrap();
let out_dir = Path::new(&out_dir);
let src_dir = Path::new("src");
let dest_path = Path::new(&out_dir).join("clang_constants.rs");
let mut clang_constants_file = File::create(dest_path).expect("Could not create file");
println!("cargo:rerun-if-env-changed=LLVM_CONFIG");
println!("cargo:rerun-if-env-changed=LLVM_BINDIR");
println!("cargo:rerun-if-env-changed=LLVM_CXXFLAGS");
println!("cargo:rerun-if-env-changed=LLVM_LDFLAGS");
println!("cargo:rerun-if-env-changed=LLVM_VERSION");
println!("cargo:rerun-if-env-changed=LIBAFL_EDGES_MAP_SIZE");
println!("cargo:rerun-if-env-changed=LIBAFL_ACCOUNTING_MAP_SIZE");
println!("cargo:rerun-if-changed=src/common-llvm.h");
println!("cargo:rerun-if-changed=build.rs");
let llvm_bindir = env::var("LLVM_BINDIR");
let llvm_cxxflags = env::var("LLVM_CXXFLAGS");
let llvm_ldflags = env::var("LLVM_LDFLAGS");
let llvm_version = env::var("LLVM_VERSION");
// test if llvm-config is available and we can compile the passes
if find_llvm_config().is_err()
&& !(llvm_bindir.is_ok()
&& llvm_cxxflags.is_ok()
&& llvm_ldflags.is_ok()
&& llvm_version.is_ok())
{
println!(
"cargo:warning=Failed to find llvm-config, we will not build LLVM passes. If you need them, set the LLVM_CONFIG environment variable to a recent llvm-config."
);
write!(
clang_constants_file,
"// These constants are autogenerated by build.rs
/// The path to the `clang` executable
pub const CLANG_PATH: &str = \"clang\";
/// The path to the `clang++` executable
pub const CLANGXX_PATH: &str = \"clang++\";
/// The llvm version used to build llvm passes
pub const LIBAFL_CC_LLVM_VERSION: Option<usize> = None;
"
)
.expect("Could not write file");
return;
}
let llvm_bindir = if let Ok(bindir) = llvm_bindir {
bindir
} else {
exec_llvm_config(&["--bindir"])
};
let bindir_path = Path::new(&llvm_bindir);
let clang;
let clangcpp;
if cfg!(windows) {
clang = bindir_path.join("clang.exe");
clangcpp = bindir_path.join("clang++.exe");
} else {
clang = bindir_path.join("clang");
clangcpp = bindir_path.join("clang++");
}
if !clang.exists() {
println!("cargo:warning=Failed to find clang frontend.");
return;
}
if !clangcpp.exists() {
println!("cargo:warning=Failed to find clang++ frontend.");
return;
}
let cxxflags = if let Ok(flags) = llvm_cxxflags {
flags
} else {
exec_llvm_config(&["--cxxflags"])
};
let mut cxxflags: Vec<String> = cxxflags.split_whitespace().map(String::from).collect();
let edges_map_size: usize = option_env!("LIBAFL_EDGES_MAP_SIZE")
.map_or(Ok(65536), str::parse)
.expect("Could not parse LIBAFL_EDGES_MAP_SIZE");
cxxflags.push(format!("-DLIBAFL_EDGES_MAP_SIZE={edges_map_size}"));
let acc_map_size: usize = option_env!("LIBAFL_ACCOUNTING_MAP_SIZE")
.map_or(Ok(65536), str::parse)
.expect("Could not parse LIBAFL_ACCOUNTING_MAP_SIZE");
cxxflags.push(format!("-DLIBAFL_ACCOUNTING_MAP_SIZE={acc_map_size}"));
let llvm_version = find_llvm_version();
if let Some(ver) = llvm_version {
if ver >= 14 {
cxxflags.push(String::from("-DUSE_NEW_PM"));
}
}
write!(
clang_constants_file,
"// These constants are autogenerated by build.rs
/// The path to the `clang` executable
pub const CLANG_PATH: &str = {clang:?};
/// The path to the `clang++` executable
pub const CLANGXX_PATH: &str = {clangcpp:?};
/// The size of the edges map
pub const EDGES_MAP_SIZE: usize = {edges_map_size};
/// The size of the accounting maps
pub const ACCOUNTING_MAP_SIZE: usize = {acc_map_size};
/// The llvm version used to build llvm passes
pub const LIBAFL_CC_LLVM_VERSION: Option<usize> = {llvm_version:?};
",
)
.expect("Could not write file");
let mut llvm_config_ld = vec![];
if cfg!(target_vendor = "apple") {
llvm_config_ld.push("--libs");
}
if cfg!(windows) {
llvm_config_ld.push("--libs");
llvm_config_ld.push("--system-libs");
}
llvm_config_ld.push("--ldflags");
let ldflags = if let Ok(flags) = llvm_ldflags {
flags
} else {
exec_llvm_config(&llvm_config_ld)
};
let mut ldflags: Vec<&str> = ldflags.split_whitespace().collect();
if cfg!(unix) {
cxxflags.push(String::from("-shared"));
cxxflags.push(String::from("-fPIC"));
}
if cfg!(windows) {
cxxflags.push(String::from("-fuse-ld=lld"));
cxxflags.push(String::from("/LD"));
/* clang on Windows links against the libcmt.lib runtime
* however, the distributed binaries are compiled against msvcrt.lib
* we need to also use msvcrt.lib instead of libcmt.lib when building the optimization passes
* first, we tell clang-cl (and indirectly link) to ignore libcmt.lib via -nodefaultlib:libcmt
* second, we pass the /MD flag to clang-cl to use the msvcrt.lib runtime instead when generating the object file
*/
ldflags.push("-nodefaultlib:libcmt");
cxxflags.push(String::from("/MD"));
/* the include directories are not always added correctly when running --cxxflags or --includedir on windows
* this is somehow related to where/how llvm was compiled (vm, docker container, host)
* add the option of setting additional flags via the LLVM_CXXFLAGS variable
*/
if let Some(env_cxxflags) = option_env!("LLVM_CXXFLAGS") {
cxxflags.append(&mut env_cxxflags.split_whitespace().map(String::from).collect());
}
}
let sdk_path;
if env::var("CARGO_CFG_TARGET_VENDOR").unwrap().as_str() == "apple" {
// Needed on macos.
// Explanation at https://github.com/banach-space/llvm-tutor/blob/787b09ed31ff7f0e7bdd42ae20547d27e2991512/lib/CMakeLists.txt#L59
ldflags.push("-undefined");
ldflags.push("dynamic_lookup");
// In case the system is configured oddly, we may have trouble finding the SDK. Manually add the linker flag, just in case.
sdk_path = find_macos_sdk_libs();
ldflags.push(&sdk_path);
};
for pass in &[
"cmplog-routines-pass.cc",
"afl-coverage-pass.cc",
"autotokens-pass.cc",
"coverage-accounting-pass.cc",
] {
build_pass(
bindir_path,
out_dir,
&cxxflags,
&ldflags,
src_dir,
pass,
None,
false,
);
}
// Optional pass
for pass in &["dump-cfg-pass.cc"] {
build_pass(
bindir_path,
out_dir,
&cxxflags,
&ldflags,
src_dir,
pass,
None,
true,
);
}
cc::Build::new()
.file(src_dir.join("no-link-rt.c"))
.compile("no-link-rt");
}