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"]) { |
Haibo Huang | 430b055 | 2020-11-19 06:58:19 -0800 | [diff] [blame] | 87 | if let Some(line) = path.lines().next() { |
| 88 | paths.push(line.into()); |
| 89 | } |
Chih-Hung Hsieh | fab4380 | 2020-04-07 14:24:01 -0700 | [diff] [blame] | 90 | } |
| 91 | if cfg!(target_os = "macos") { |
| 92 | if let Ok((path, _)) = run("xcodebuild", &["-find", "clang"]) { |
Haibo Huang | 430b055 | 2020-11-19 06:58:19 -0800 | [diff] [blame] | 93 | if let Some(line) = path.lines().next() { |
| 94 | paths.push(line.into()); |
| 95 | } |
Chih-Hung Hsieh | fab4380 | 2020-04-07 14:24:01 -0700 | [diff] [blame] | 96 | } |
| 97 | } |
| 98 | paths.extend(env::split_paths(&env::var("PATH").unwrap())); |
| 99 | |
| 100 | let default = format!("clang{}", env::consts::EXE_SUFFIX); |
| 101 | let versioned = format!("clang-[0-9]*{}", env::consts::EXE_SUFFIX); |
| 102 | let patterns = &[&default[..], &versioned[..]]; |
| 103 | for path in paths { |
| 104 | if let Some(path) = find(&path, patterns) { |
| 105 | return Some(Clang::new(path, args)); |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | None |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | //================================================ |
| 114 | // Functions |
| 115 | //================================================ |
| 116 | |
| 117 | /// Returns the first match to the supplied glob patterns in the supplied |
| 118 | /// directory if there are any matches. |
| 119 | fn find(directory: &Path, patterns: &[&str]) -> Option<PathBuf> { |
| 120 | for pattern in patterns { |
| 121 | let pattern = directory.join(pattern).to_string_lossy().into_owned(); |
| 122 | if let Some(path) = try_opt!(glob::glob(&pattern).ok()) |
| 123 | .filter_map(|p| p.ok()) |
| 124 | .next() |
| 125 | { |
| 126 | if path.is_file() && is_executable(&path).unwrap_or(false) { |
| 127 | return Some(path); |
| 128 | } |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | None |
| 133 | } |
| 134 | |
| 135 | #[cfg(unix)] |
| 136 | fn is_executable(path: &Path) -> io::Result<bool> { |
| 137 | use std::ffi::CString; |
| 138 | use std::os::unix::ffi::OsStrExt; |
| 139 | |
| 140 | let path = CString::new(path.as_os_str().as_bytes())?; |
| 141 | unsafe { Ok(libc::access(path.as_ptr(), libc::X_OK) == 0) } |
| 142 | } |
| 143 | |
| 144 | #[cfg(not(unix))] |
| 145 | fn is_executable(_: &Path) -> io::Result<bool> { |
| 146 | Ok(true) |
| 147 | } |
| 148 | |
| 149 | /// Attempts to run an executable, returning the `stdout` and `stderr` output if |
| 150 | /// successful. |
| 151 | fn run(executable: &str, arguments: &[&str]) -> Result<(String, String), String> { |
| 152 | Command::new(executable) |
| 153 | .args(arguments) |
| 154 | .output() |
| 155 | .map(|o| { |
| 156 | let stdout = String::from_utf8_lossy(&o.stdout).into_owned(); |
| 157 | let stderr = String::from_utf8_lossy(&o.stderr).into_owned(); |
| 158 | (stdout, stderr) |
| 159 | }) |
| 160 | .map_err(|e| format!("could not run executable `{}`: {}", executable, e)) |
| 161 | } |
| 162 | |
| 163 | /// Runs `clang`, returning the `stdout` and `stderr` output. |
| 164 | fn run_clang(path: &Path, arguments: &[&str]) -> (String, String) { |
| 165 | run(&path.to_string_lossy().into_owned(), arguments).unwrap() |
| 166 | } |
| 167 | |
| 168 | /// Runs `llvm-config`, returning the `stdout` output if successful. |
| 169 | fn run_llvm_config(arguments: &[&str]) -> Result<String, String> { |
| 170 | let config = env::var("LLVM_CONFIG_PATH").unwrap_or_else(|_| "llvm-config".to_string()); |
| 171 | run(&config, arguments).map(|(o, _)| o) |
| 172 | } |
| 173 | |
| 174 | /// Parses a version number if possible, ignoring trailing non-digit characters. |
| 175 | fn parse_version_number(number: &str) -> Option<c_int> { |
| 176 | number |
| 177 | .chars() |
| 178 | .take_while(|c| c.is_digit(10)) |
| 179 | .collect::<String>() |
| 180 | .parse() |
| 181 | .ok() |
| 182 | } |
| 183 | |
| 184 | /// Parses the version from the output of a `clang` executable if possible. |
| 185 | fn parse_version(path: &Path) -> Option<CXVersion> { |
| 186 | let output = run_clang(path, &["--version"]).0; |
| 187 | let start = try_opt!(output.find("version ")) + 8; |
Haibo Huang | 8b9513e | 2020-07-13 22:05:39 -0700 | [diff] [blame] | 188 | let mut numbers = try_opt!(output[start..].split_whitespace().next()).split('.'); |
Chih-Hung Hsieh | fab4380 | 2020-04-07 14:24:01 -0700 | [diff] [blame] | 189 | let major = try_opt!(numbers.next().and_then(parse_version_number)); |
| 190 | let minor = try_opt!(numbers.next().and_then(parse_version_number)); |
| 191 | let subminor = numbers.next().and_then(parse_version_number).unwrap_or(0); |
| 192 | Some(CXVersion { |
| 193 | Major: major, |
| 194 | Minor: minor, |
| 195 | Subminor: subminor, |
| 196 | }) |
| 197 | } |
| 198 | |
| 199 | /// Parses the search paths from the output of a `clang` executable if possible. |
| 200 | fn parse_search_paths(path: &Path, language: &str, args: &[String]) -> Option<Vec<PathBuf>> { |
| 201 | let mut clang_args = vec!["-E", "-x", language, "-", "-v"]; |
| 202 | clang_args.extend(args.iter().map(|s| &**s)); |
| 203 | let output = run_clang(path, &clang_args).1; |
| 204 | let start = try_opt!(output.find("#include <...> search starts here:")) + 34; |
| 205 | let end = try_opt!(output.find("End of search list.")); |
| 206 | let paths = output[start..end].replace("(framework directory)", ""); |
| 207 | Some( |
| 208 | paths |
| 209 | .lines() |
| 210 | .filter(|l| !l.is_empty()) |
| 211 | .map(|l| Path::new(l.trim()).into()) |
| 212 | .collect(), |
| 213 | ) |
| 214 | } |