puffin_build/utils/
clang.rs

1use std::process::Command;
2
3pub fn runtime_dir() -> String {
4    // NOTE the current process for finding the runtime-dir might be incomplete
5    //
6    //     We try the following in order:
7    //       - `clang --print-runtime-dir` (clang >= 13)
8    //       - `clang --print-resource-dir`/lib/<os>
9    //       - panic
10    //
11    //     Note that extracting the directory path directly from the result of
12    //     `--print-file-name=libclang_rt.asan-<arch>.<dylib_suffix>` would be
13    //     an alternative solution but it was broken for a long time on Apple
14    //     clang.
15    //
16    //     - see https://github.com/llvm/llvm-project/commit/aafc3f7be804d117a632365489a18c3e484a3931
17    let output = Command::new("clang")
18        .args(["--print-runtime-dir"])
19        .output()
20        .expect("failed to get runtime dir from `clang --print-runtime-dir`. Is clang in PATH?");
21
22    let clang_runtime_dir = if output.status.success() {
23        std::str::from_utf8(&output.stdout).unwrap().trim()
24    } else {
25        ""
26    };
27
28    if clang_runtime_dir.is_empty() {
29        return runtime_dir_fallback();
30    }
31
32    clang_runtime_dir.to_string()
33}
34
35fn runtime_dir_fallback() -> String {
36    let output = Command::new("clang")
37        .args(["--print-resource-dir"])
38        .output()
39        .expect("failed to get resource dir from `clang --print-resource-dir`. Is clang in PATH?");
40
41    let clang_resource_dir = output
42        .status
43        .success()
44        .then(|| std::str::from_utf8(&output.stdout).unwrap().trim())
45        .expect("failed to get resource dir from `clang --print-resource-dir`");
46
47    let clang_sysname = match std::env::consts::OS {
48        "macos" => "darwin",
49        "linux" => "linux",
50        _ => panic!("cannot get compiler runtime dir: unsupported os"),
51    };
52
53    let runtime_dir = format!("{}/lib/{}/", clang_resource_dir, clang_sysname);
54    if !std::path::Path::new(&runtime_dir).exists() {
55        panic!("failed to find clang runtime dir");
56    }
57
58    runtime_dir
59}