1// SPDX-License-Identifier: Apache-2.0
2
3//! Provides helper functionality.
4
5use std::path::{Path, PathBuf};
6use std::process::Command;
7use std::{env, io};
8
9use glob::{self, Pattern};
10
11use libc::c_int;
12
13use super::CXVersion;
14
15//================================================
16// Structs
17//================================================
18
19/// A `clang` executable.
20#[derive(Clone, Debug)]
21pub struct Clang {
22    /// The path to this `clang` executable.
23    pub path: PathBuf,
24    /// The version of this `clang` executable if it could be parsed.
25    pub version: Option<CXVersion>,
26    /// The directories searched by this `clang` executable for C headers if
27    /// they could be parsed.
28    pub c_search_paths: Option<Vec<PathBuf>>,
29    /// The directories searched by this `clang` executable for C++ headers if
30    /// they could be parsed.
31    pub cpp_search_paths: Option<Vec<PathBuf>>,
32}
33
34impl Clang {
35    fn new(path: impl AsRef<Path>, args: &[String]) -> Self {
36        Self {
37            path: path.as_ref().into(),
38            version: parse_version(path.as_ref()),
39            c_search_paths: parse_search_paths(path.as_ref(), "c", args),
40            cpp_search_paths: parse_search_paths(path.as_ref(), "c++", args),
41        }
42    }
43
44    /// Returns a `clang` executable if one can be found.
45    ///
46    /// If the `CLANG_PATH` environment variable is set, that is the instance of
47    /// `clang` used. Otherwise, a series of directories are searched. First, if
48    /// a path is supplied, that is the first directory searched. Then, the
49    /// directory returned by `llvm-config --bindir` is searched. On macOS
50    /// systems, `xcodebuild -find clang` will next be queried. Last, the
51    /// directories in the system's `PATH` are searched.
52    ///
53    /// ## Cross-compilation
54    ///
55    /// If target arguments are provided (e.g., `-target` followed by a target
56    /// like `x86_64-unknown-linux-gnu`) then this method will prefer a
57    /// target-prefixed instance of `clang` (e.g.,
58    /// `x86_64-unknown-linux-gnu-clang` for the above example).
59    pub fn find(path: Option<&Path>, args: &[String]) -> Option<Clang> {
60        if let Ok(path) = env::var("CLANG_PATH") {
61            let p = Path::new(&path);
62            if p.is_file() && is_executable(&p).unwrap_or(false) {
63                return Some(Clang::new(p, args));
64            }
65        }
66
67        // Determine the cross-compilation target, if any.
68
69        let mut target = None;
70        for i in 0..args.len() {
71            if args[i] == "-target" && i + 1 < args.len() {
72                target = Some(&args[i + 1]);
73            }
74        }
75
76        // Collect the paths to search for a `clang` executable in.
77
78        let mut paths = vec![];
79
80        if let Some(path) = path {
81            paths.push(path.into());
82        }
83
84        if let Ok(path) = run_llvm_config(&["--bindir"]) {
85            if let Some(line) = path.lines().next() {
86                paths.push(line.into());
87            }
88        }
89
90        if cfg!(target_os = "macos") {
91            if let Ok((path, _)) = run("xcodebuild", &["-find", "clang"]) {
92                if let Some(line) = path.lines().next() {
93                    paths.push(line.into());
94                }
95            }
96        }
97
98        if let Ok(path) = env::var("PATH") {
99            paths.extend(env::split_paths(&path));
100        }
101
102        // First, look for a target-prefixed `clang` executable.
103
104        if let Some(target) = target {
105            let default = format!("{}-clang{}", target, env::consts::EXE_SUFFIX);
106            let versioned = format!("{}-clang-[0-9]*{}", target, env::consts::EXE_SUFFIX);
107            let patterns = &[&default[..], &versioned[..]];
108            for path in &paths {
109                if let Some(path) = find(path, patterns) {
110                    return Some(Clang::new(path, args));
111                }
112            }
113        }
114
115        // Otherwise, look for any other `clang` executable.
116
117        let default = format!("clang{}", env::consts::EXE_SUFFIX);
118        let versioned = format!("clang-[0-9]*{}", env::consts::EXE_SUFFIX);
119        let patterns = &[&default[..], &versioned[..]];
120        for path in paths {
121            if let Some(path) = find(&path, patterns) {
122                return Some(Clang::new(path, args));
123            }
124        }
125
126        None
127    }
128}
129
130//================================================
131// Functions
132//================================================
133
134/// Returns the first match to the supplied glob patterns in the supplied
135/// directory if there are any matches.
136fn find(directory: &Path, patterns: &[&str]) -> Option<PathBuf> {
137    // Escape the directory in case it contains characters that have special
138    // meaning in glob patterns (e.g., `[` or `]`).
139    let directory = if let Some(directory) = directory.to_str() {
140        Path::new(&Pattern::escape(directory)).to_owned()
141    } else {
142        return None;
143    };
144
145    for pattern in patterns {
146        let pattern = directory.join(pattern).to_string_lossy().into_owned();
147        if let Some(path) = glob::glob(&pattern).ok()?.filter_map(|p| p.ok()).next() {
148            if path.is_file() && is_executable(&path).unwrap_or(false) {
149                return Some(path);
150            }
151        }
152    }
153
154    None
155}
156
157#[cfg(unix)]
158fn is_executable(path: &Path) -> io::Result<bool> {
159    use std::ffi::CString;
160    use std::os::unix::ffi::OsStrExt;
161
162    let path = CString::new(path.as_os_str().as_bytes())?;
163    unsafe { Ok(libc::access(path.as_ptr(), libc::X_OK) == 0) }
164}
165
166#[cfg(not(unix))]
167fn is_executable(_: &Path) -> io::Result<bool> {
168    Ok(true)
169}
170
171/// Attempts to run an executable, returning the `stdout` and `stderr` output if
172/// successful.
173fn run(executable: &str, arguments: &[&str]) -> Result<(String, String), String> {
174    Command::new(executable)
175        .args(arguments)
176        .output()
177        .map(|o| {
178            let stdout = String::from_utf8_lossy(&o.stdout).into_owned();
179            let stderr = String::from_utf8_lossy(&o.stderr).into_owned();
180            (stdout, stderr)
181        })
182        .map_err(|e| format!("could not run executable `{}`: {}", executable, e))
183}
184
185/// Runs `clang`, returning the `stdout` and `stderr` output.
186fn run_clang(path: &Path, arguments: &[&str]) -> (String, String) {
187    run(&path.to_string_lossy().into_owned(), arguments).unwrap()
188}
189
190/// Runs `llvm-config`, returning the `stdout` output if successful.
191fn run_llvm_config(arguments: &[&str]) -> Result<String, String> {
192    let config = env::var("LLVM_CONFIG_PATH").unwrap_or_else(|_| "llvm-config".to_string());
193    run(&config, arguments).map(|(o, _)| o)
194}
195
196/// Parses a version number if possible, ignoring trailing non-digit characters.
197fn parse_version_number(number: &str) -> Option<c_int> {
198    number
199        .chars()
200        .take_while(|c| c.is_digit(10))
201        .collect::<String>()
202        .parse()
203        .ok()
204}
205
206/// Parses the version from the output of a `clang` executable if possible.
207fn parse_version(path: &Path) -> Option<CXVersion> {
208    let output = run_clang(path, &["--version"]).0;
209    let start = output.find("version ")? + 8;
210    let mut numbers = output[start..].split_whitespace().next()?.split('.');
211    let major = numbers.next().and_then(parse_version_number)?;
212    let minor = numbers.next().and_then(parse_version_number)?;
213    let subminor = numbers.next().and_then(parse_version_number).unwrap_or(0);
214    Some(CXVersion {
215        Major: major,
216        Minor: minor,
217        Subminor: subminor,
218    })
219}
220
221/// Parses the search paths from the output of a `clang` executable if possible.
222fn parse_search_paths(path: &Path, language: &str, args: &[String]) -> Option<Vec<PathBuf>> {
223    let mut clang_args = vec!["-E", "-x", language, "-", "-v"];
224    clang_args.extend(args.iter().map(|s| &**s));
225    let output = run_clang(path, &clang_args).1;
226    let start = output.find("#include <...> search starts here:")? + 34;
227    let end = output.find("End of search list.")?;
228    let paths = output[start..end].replace("(framework directory)", "");
229    Some(
230        paths
231            .lines()
232            .filter(|l| !l.is_empty())
233            .map(|l| Path::new(l.trim()).into())
234            .collect(),
235    )
236}
237