Chih-Hung Hsieh | fab4380 | 2020-04-07 14:24:01 -0700 | [diff] [blame] | 1 | // Copyright 2016 Kyle Mayes |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | //! Provides helper functionality. |
| 16 | |
| 17 | use std::path::{Path, PathBuf}; |
| 18 | use std::process::Command; |
| 19 | use std::{env, io}; |
| 20 | |
| 21 | use glob; |
| 22 | |
| 23 | use libc::c_int; |
| 24 | |
| 25 | use super::CXVersion; |
| 26 | |
| 27 | //================================================ |
| 28 | // Macros |
| 29 | //================================================ |
| 30 | |
| 31 | macro_rules! try_opt { |
| 32 | ($option:expr) => {{ |
| 33 | match $option { |
| 34 | Some(some) => some, |
| 35 | None => return None, |
| 36 | } |
| 37 | }}; |
| 38 | } |
| 39 | |
| 40 | //================================================ |
| 41 | // Structs |
| 42 | //================================================ |
| 43 | |
| 44 | /// A `clang` executable. |
| 45 | #[derive(Clone, Debug)] |
| 46 | pub struct Clang { |
| 47 | /// The path to this `clang` executable. |
| 48 | pub path: PathBuf, |
| 49 | /// The version of this `clang` executable if it could be parsed. |
| 50 | pub version: Option<CXVersion>, |
| 51 | /// The directories searched by this `clang` executable for C headers if |
| 52 | /// they could be parsed. |
| 53 | pub c_search_paths: Option<Vec<PathBuf>>, |
| 54 | /// The directories searched by this `clang` executable for C++ headers if |
| 55 | /// they could be parsed. |
| 56 | pub cpp_search_paths: Option<Vec<PathBuf>>, |
| 57 | } |
| 58 | |
| 59 | impl Clang { |
| 60 | fn new(path: impl AsRef<Path>, args: &[String]) -> Self { |
| 61 | Self { |
| 62 | path: path.as_ref().into(), |
| 63 | version: parse_version(path.as_ref()), |
| 64 | c_search_paths: parse_search_paths(path.as_ref(), "c", args), |
| 65 | cpp_search_paths: parse_search_paths(path.as_ref(), "c++", args), |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | /// Returns a `clang` executable if one can be found. |
| 70 | /// |
| 71 | /// If the `CLANG_PATH` environment variable is set, that is the instance of |
| 72 | /// `clang` used. Otherwise, a series of directories are searched. First, if |
| 73 | /// a path is supplied, that is the first directory searched. Then, the |
| 74 | /// directory returned by `llvm-config --bindir` is searched. On macOS |
| 75 | /// systems, `xcodebuild -find clang` will next be queried. Last, the |
| 76 | /// directories in the system's `PATH` are searched. |
| 77 | pub fn find(path: Option<&Path>, args: &[String]) -> Option<Clang> { |
| 78 | if let Ok(path) = env::var("CLANG_PATH") { |
| 79 | return Some(Clang::new(path, args)); |
| 80 | } |
| 81 | |
| 82 | let mut paths = vec![]; |
| 83 | if let Some(path) = path { |
| 84 | paths.push(path.into()); |
| 85 | } |
| 86 | if let Ok(path) = run_llvm_config(&["--bindir"]) { |
| 87 | paths.push(path.into()); |
| 88 | } |
| 89 | if cfg!(target_os = "macos") { |
| 90 | if let Ok((path, _)) = run("xcodebuild", &["-find", "clang"]) { |
| 91 | paths.push(path.into()); |
| 92 | } |
| 93 | } |
| 94 | paths.extend(env::split_paths(&env::var("PATH").unwrap())); |
| 95 | |
| 96 | let default = format!("clang{}", env::consts::EXE_SUFFIX); |
| 97 | let versioned = format!("clang-[0-9]*{}", env::consts::EXE_SUFFIX); |
| 98 | let patterns = &[&default[..], &versioned[..]]; |
| 99 | for path in paths { |
| 100 | if let Some(path) = find(&path, patterns) { |
| 101 | return Some(Clang::new(path, args)); |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | None |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | //================================================ |
| 110 | // Functions |
| 111 | //================================================ |
| 112 | |
| 113 | /// Returns the first match to the supplied glob patterns in the supplied |
| 114 | /// directory if there are any matches. |
| 115 | fn find(directory: &Path, patterns: &[&str]) -> Option<PathBuf> { |
| 116 | for pattern in patterns { |
| 117 | let pattern = directory.join(pattern).to_string_lossy().into_owned(); |
| 118 | if let Some(path) = try_opt!(glob::glob(&pattern).ok()) |
| 119 | .filter_map(|p| p.ok()) |
| 120 | .next() |
| 121 | { |
| 122 | if path.is_file() && is_executable(&path).unwrap_or(false) { |
| 123 | return Some(path); |
| 124 | } |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | None |
| 129 | } |
| 130 | |
| 131 | #[cfg(unix)] |
| 132 | fn is_executable(path: &Path) -> io::Result<bool> { |
| 133 | use std::ffi::CString; |
| 134 | use std::os::unix::ffi::OsStrExt; |
| 135 | |
| 136 | let path = CString::new(path.as_os_str().as_bytes())?; |
| 137 | unsafe { Ok(libc::access(path.as_ptr(), libc::X_OK) == 0) } |
| 138 | } |
| 139 | |
| 140 | #[cfg(not(unix))] |
| 141 | fn is_executable(_: &Path) -> io::Result<bool> { |
| 142 | Ok(true) |
| 143 | } |
| 144 | |
| 145 | /// Attempts to run an executable, returning the `stdout` and `stderr` output if |
| 146 | /// successful. |
| 147 | fn run(executable: &str, arguments: &[&str]) -> Result<(String, String), String> { |
| 148 | Command::new(executable) |
| 149 | .args(arguments) |
| 150 | .output() |
| 151 | .map(|o| { |
| 152 | let stdout = String::from_utf8_lossy(&o.stdout).into_owned(); |
| 153 | let stderr = String::from_utf8_lossy(&o.stderr).into_owned(); |
| 154 | (stdout, stderr) |
| 155 | }) |
| 156 | .map_err(|e| format!("could not run executable `{}`: {}", executable, e)) |
| 157 | } |
| 158 | |
| 159 | /// Runs `clang`, returning the `stdout` and `stderr` output. |
| 160 | fn run_clang(path: &Path, arguments: &[&str]) -> (String, String) { |
| 161 | run(&path.to_string_lossy().into_owned(), arguments).unwrap() |
| 162 | } |
| 163 | |
| 164 | /// Runs `llvm-config`, returning the `stdout` output if successful. |
| 165 | fn run_llvm_config(arguments: &[&str]) -> Result<String, String> { |
| 166 | let config = env::var("LLVM_CONFIG_PATH").unwrap_or_else(|_| "llvm-config".to_string()); |
| 167 | run(&config, arguments).map(|(o, _)| o) |
| 168 | } |
| 169 | |
| 170 | /// Parses a version number if possible, ignoring trailing non-digit characters. |
| 171 | fn parse_version_number(number: &str) -> Option<c_int> { |
| 172 | number |
| 173 | .chars() |
| 174 | .take_while(|c| c.is_digit(10)) |
| 175 | .collect::<String>() |
| 176 | .parse() |
| 177 | .ok() |
| 178 | } |
| 179 | |
| 180 | /// Parses the version from the output of a `clang` executable if possible. |
| 181 | fn parse_version(path: &Path) -> Option<CXVersion> { |
| 182 | let output = run_clang(path, &["--version"]).0; |
| 183 | let start = try_opt!(output.find("version ")) + 8; |
| 184 | let mut numbers = try_opt!(output[start..].split_whitespace().nth(0)).split('.'); |
| 185 | let major = try_opt!(numbers.next().and_then(parse_version_number)); |
| 186 | let minor = try_opt!(numbers.next().and_then(parse_version_number)); |
| 187 | let subminor = numbers.next().and_then(parse_version_number).unwrap_or(0); |
| 188 | Some(CXVersion { |
| 189 | Major: major, |
| 190 | Minor: minor, |
| 191 | Subminor: subminor, |
| 192 | }) |
| 193 | } |
| 194 | |
| 195 | /// Parses the search paths from the output of a `clang` executable if possible. |
| 196 | fn parse_search_paths(path: &Path, language: &str, args: &[String]) -> Option<Vec<PathBuf>> { |
| 197 | let mut clang_args = vec!["-E", "-x", language, "-", "-v"]; |
| 198 | clang_args.extend(args.iter().map(|s| &**s)); |
| 199 | let output = run_clang(path, &clang_args).1; |
| 200 | let start = try_opt!(output.find("#include <...> search starts here:")) + 34; |
| 201 | let end = try_opt!(output.find("End of search list.")); |
| 202 | let paths = output[start..end].replace("(framework directory)", ""); |
| 203 | Some( |
| 204 | paths |
| 205 | .lines() |
| 206 | .filter(|l| !l.is_empty()) |
| 207 | .map(|l| Path::new(l.trim()).into()) |
| 208 | .collect(), |
| 209 | ) |
| 210 | } |