Debian Codegraph @

debian/rust-vendor/clang-sys/build/common.rs

raw
1 // SPDX-License-Identifier: Apache-2.0
2
3 use std::cell::RefCell;
4 use std::collections::HashMap;
5 use std::env;
6 use std::path::{Path, PathBuf};
7 use std::process::Command;
8
9 use glob::{MatchOptions, Pattern};
10
11 //================================================
12 // Commands
13 //================================================
14
15 thread_local! {
16 /// The errors encountered by the build script while executing commands.
17 static COMMAND_ERRORS: RefCell<HashMap<String, Vec<String>>> = RefCell::default();
18 }
19
20 /// Adds an error encountered by the build script while executing a command.
21 fn add_command_error(name: &str, path: &str, arguments: &[&str], message: String) {
22 COMMAND_ERRORS.with(|e| {
23 e.borrow_mut().entry(name.into()).or_default().push(format!(
24 "couldn't execute `{} {}` (path={}) ({})",
25 name,
26 arguments.join(" "),
27 path,
28 message,
29 ))
30 });
31 }
32
33 /// A struct that prints the errors encountered by the build script while
34 /// executing commands when dropped (unless explictly discarded).
35 ///
36 /// This is handy because we only want to print these errors when the build
37 /// script fails to link to an instance of `libclang`. For example, if
38 /// `llvm-config` couldn't be executed but an instance of `libclang` was found
39 /// anyway we don't want to pollute the build output with irrelevant errors.
40 #[derive(Default)]
41 pub struct CommandErrorPrinter {
42 discard: bool,
43 }
44
45 impl CommandErrorPrinter {
46 pub fn discard(mut self) {
47 self.discard = true;
48 }
49 }
50
51 impl Drop for CommandErrorPrinter {
52 fn drop(&mut self) {
53 if self.discard {
54 return;
55 }
56
57 let errors = COMMAND_ERRORS.with(|e| e.borrow().clone());
58
59 if let Some(errors) = errors.get("llvm-config") {
60 println!(
61 "cargo:warning=could not execute `llvm-config` one or more \
62 times, if the LLVM_CONFIG_PATH environment variable is set to \
63 a full path to valid `llvm-config` executable it will be used \
64 to try to find an instance of `libclang` on your system: {}",
65 errors
66 .iter()
67 .map(|e| format!("\"{}\"", e))
68 .collect::<Vec<_>>()
69 .join("\n "),
70 )
71 }
72
73 if let Some(errors) = errors.get("xcode-select") {
74 println!(
75 "cargo:warning=could not execute `xcode-select` one or more \
76 times, if a valid instance of this executable is on your PATH \
77 it will be used to try to find an instance of `libclang` on \
78 your system: {}",
79 errors
80 .iter()
81 .map(|e| format!("\"{}\"", e))
82 .collect::<Vec<_>>()
83 .join("\n "),
84 )
85 }
86 }
87 }
88
89 #[cfg(test)]
90 lazy_static::lazy_static! {
91 pub static ref RUN_COMMAND_MOCK: std::sync::Mutex<
92 Option<Box<dyn Fn(&str, &str, &[&str]) -> Option<String> + Send + Sync + 'static>>,
93 > = std::sync::Mutex::new(None);
94 }
95
96 /// Executes a command and returns the `stdout` output if the command was
97 /// successfully executed (errors are added to `COMMAND_ERRORS`).
98 fn run_command(name: &str, path: &str, arguments: &[&str]) -> Option<String> {
99 #[cfg(test)]
100 if let Some(command) = &*RUN_COMMAND_MOCK.lock().unwrap() {
101 return command(name, path, arguments);
102 }
103
104 let output = match Command::new(path).args(arguments).output() {
105 Ok(output) => output,
106 Err(error) => {
107 let message = format!("error: {}", error);
108 add_command_error(name, path, arguments, message);
109 return None;
110 }
111 };
112
113 if output.status.success() {
114 Some(String::from_utf8_lossy(&output.stdout).into_owned())
115 } else {
116 let message = format!("exit code: {}", output.status);
117 add_command_error(name, path, arguments, message);
118 None
119 }
120 }
121
122 /// Executes the `llvm-config` command and returns the `stdout` output if the
123 /// command was successfully executed (errors are added to `COMMAND_ERRORS`).
124 pub fn run_llvm_config(arguments: &[&str]) -> Option<String> {
125 let path = env::var("LLVM_CONFIG_PATH").unwrap_or_else(|_| "llvm-config".into());
126 run_command("llvm-config", &path, arguments)
127 }
128
129 /// Executes the `xcode-select` command and returns the `stdout` output if the
130 /// command was successfully executed (errors are added to `COMMAND_ERRORS`).
131 pub fn run_xcode_select(arguments: &[&str]) -> Option<String> {
132 run_command("xcode-select", "xcode-select", arguments)
133 }
134
135 //================================================
136 // Search Directories
137 //================================================
138 // These search directories are listed in order of
139 // preference, so if multiple `libclang` instances
140 // are found when searching matching directories,
141 // the `libclang` instances from earlier
142 // directories will be preferred (though version
143 // takes precedence over location).
144 //================================================
145
146 /// `libclang` directory patterns for Haiku.
147 const DIRECTORIES_HAIKU: &[&str] = &[
148 "/boot/home/config/non-packaged/develop/lib",
149 "/boot/home/config/non-packaged/lib",
150 "/boot/system/non-packaged/develop/lib",
151 "/boot/system/non-packaged/lib",
152 "/boot/system/develop/lib",
153 "/boot/system/lib",
154 ];
155
156 /// `libclang` directory patterns for Linux (and FreeBSD).
157 const DIRECTORIES_LINUX: &[&str] = &[
158 "/usr/local/llvm*/lib*",
159 "/usr/local/lib*/*/*",
160 "/usr/local/lib*/*",
161 "/usr/local/lib*",
162 "/usr/lib*/*/*",
163 "/usr/lib*/*",
164 "/usr/lib*",
165 ];
166
167 /// `libclang` directory patterns for macOS.
168 const DIRECTORIES_MACOS: &[&str] = &[
169 "/usr/local/opt/llvm*/lib/llvm*/lib",
170 "/Library/Developer/CommandLineTools/usr/lib",
171 "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib",
172 "/usr/local/opt/llvm*/lib",
173 ];
174
175 /// `libclang` directory patterns for Windows.
176 ///
177 /// The boolean indicates whether the directory pattern should be used when
178 /// compiling for an MSVC target environment.
179 const DIRECTORIES_WINDOWS: &[(&str, bool)] = &[
180 // LLVM + Clang can be installed using Scoop (https://scoop.sh).
181 // Other Windows package managers install LLVM + Clang to other listed
182 // system-wide directories.
183 ("C:\\Users\\*\\scoop\\apps\\llvm\\current\\lib", true),
184 ("C:\\MSYS*\\MinGW*\\lib", false),
185 ("C:\\MSYS*\\clang*\\lib", false),
186 ("C:\\Program Files*\\LLVM\\lib", true),
187 ("C:\\LLVM\\lib", true),
188 // LLVM + Clang can be installed as a component of Visual Studio.
189 // https://github.com/KyleMayes/clang-sys/issues/121
190 (
191 "C:\\Program Files*\\Microsoft Visual Studio\\**\\VC\\Tools\\Llvm\\**\\lib",
192 true,
193 ),
194 ];
195
196 /// `libclang` directory patterns for illumos
197 const DIRECTORIES_ILLUMOS: &[&str] = &["/opt/ooce/llvm-*/lib", "/opt/ooce/clang-*/lib"];
198
199 //================================================
200 // Searching
201 //================================================
202
203 /// Finds the files in a directory that match one or more filename glob patterns
204 /// and returns the paths to and filenames of those files.
205 fn search_directory(directory: &Path, filenames: &[String]) -> Vec<(PathBuf, String)> {
206 // Escape the specified directory in case it contains characters that have
207 // special meaning in glob patterns (e.g., `[` or `]`).
208 let directory = Pattern::escape(directory.to_str().unwrap());
209 let directory = Path::new(&directory);
210
211 // Join the escaped directory to the filename glob patterns to obtain
212 // complete glob patterns for the files being searched for.
213 let paths = filenames
214 .iter()
215 .map(|f| directory.join(f).to_str().unwrap().to_owned());
216
217 // Prevent wildcards from matching path separators to ensure that the search
218 // is limited to the specified directory.
219 let mut options = MatchOptions::new();
220 options.require_literal_separator = true;
221
222 paths
223 .map(|p| glob::glob_with(&p, options))
224 .filter_map(Result::ok)
225 .flatten()
226 .filter_map(|p| {
227 let path = p.ok()?;
228 let filename = path.file_name()?.to_str().unwrap();
229
230 // The `libclang_shared` library has been renamed to `libclang-cpp`
231 // in Clang 10. This can cause instances of this library (e.g.,
232 // `libclang-cpp.so.10`) to be matched by patterns looking for
233 // instances of `libclang`.
234 if filename.contains("-cpp.") {
235 return None;
236 }
237
238 Some((path.parent().unwrap().to_owned(), filename.into()))
239 })
240 .collect::<Vec<_>>()
241 }
242
243 /// Finds the files in a directory (and any relevant sibling directories) that
244 /// match one or more filename glob patterns and returns the paths to and
245 /// filenames of those files.
246 fn search_directories(directory: &Path, filenames: &[String]) -> Vec<(PathBuf, String)> {
247 let mut results = search_directory(directory, filenames);
248
249 // On Windows, `libclang.dll` is usually found in the LLVM `bin` directory
250 // while `libclang.lib` is usually found in the LLVM `lib` directory. To
251 // keep things consistent with other platforms, only LLVM `lib` directories
252 // are included in the backup search directory globs so we need to search
253 // the LLVM `bin` directory here.
254 if target_os!("windows") && directory.ends_with("lib") {
255 let sibling = directory.parent().unwrap().join("bin");
256 results.extend(search_directory(&sibling, filenames));
257 }
258
259 results
260 }
261
262 /// Finds the `libclang` static or dynamic libraries matching one or more
263 /// filename glob patterns and returns the paths to and filenames of those files.
264 pub fn search_libclang_directories(filenames: &[String], variable: &str) -> Vec<(PathBuf, String)> {
265 // Search only the path indicated by the relevant environment variable
266 // (e.g., `LIBCLANG_PATH`) if it is set.
267 if let Ok(path) = env::var(variable).map(|d| Path::new(&d).to_path_buf()) {
268 // Check if the path is a matching file.
269 if let Some(parent) = path.parent() {
270 let filename = path.file_name().unwrap().to_str().unwrap();
271 let libraries = search_directories(parent, filenames);
272 if libraries.iter().any(|(_, f)| f == filename) {
273 return vec![(parent.into(), filename.into())];
274 }
275 }
276
277 // Check if the path is directory containing a matching file.
278 return search_directories(&path, filenames);
279 }
280
281 let mut found = vec![];
282
283 // Search the `bin` and `lib` directories in the directory returned by
284 // `llvm-config --prefix`.
285 if let Some(output) = run_llvm_config(&["--prefix"]) {
286 let directory = Path::new(output.lines().next().unwrap()).to_path_buf();
287 found.extend(search_directories(&directory.join("bin"), filenames));
288 found.extend(search_directories(&directory.join("lib"), filenames));
289 found.extend(search_directories(&directory.join("lib64"), filenames));
290 }
291
292 // Search the toolchain directory in the directory returned by
293 // `xcode-select --print-path`.
294 if target_os!("macos") {
295 if let Some(output) = run_xcode_select(&["--print-path"]) {
296 let directory = Path::new(output.lines().next().unwrap()).to_path_buf();
297 let directory = directory.join("Toolchains/XcodeDefault.xctoolchain/usr/lib");
298 found.extend(search_directories(&directory, filenames));
299 }
300 }
301
302 // Search the directories in the `LD_LIBRARY_PATH` environment variable.
303 if let Ok(path) = env::var("LD_LIBRARY_PATH") {
304 for directory in env::split_paths(&path) {
305 found.extend(search_directories(&directory, filenames));
306 }
307 }
308
309 // Search the directories in the `LIBRARY_PATH` environment variable,
310 // used by GCC to find libraries to link.
311 if let Ok(path) = env::var("LIBRARY_PATH") {
312 for directory in env::split_paths(&path) {
313 found.extend(search_directories(&directory, filenames));
314 }
315 }
316
317 // Determine the `libclang` directory patterns.
318 let directories: Vec<&str> = if target_os!("haiku") {
319 DIRECTORIES_HAIKU.into()
320 } else if target_os!("linux") || target_os!("freebsd") {
321 DIRECTORIES_LINUX.into()
322 } else if target_os!("macos") {
323 DIRECTORIES_MACOS.into()
324 } else if target_os!("windows") {
325 let msvc = target_env!("msvc");
326 DIRECTORIES_WINDOWS
327 .iter()
328 .filter(|d| d.1 || !msvc)
329 .map(|d| d.0)
330 .collect()
331 } else if target_os!("cygwin") {
332 // For Cygwin/MSYS environments, the filesystem layout is Unix-like.
333 DIRECTORIES_LINUX.into()
334 } else if target_os!("illumos") {
335 DIRECTORIES_ILLUMOS.into()
336 } else {
337 vec![]
338 };
339
340 // We use temporary directories when testing the build script so we'll
341 // remove the prefixes that make the directories absolute.
342 let directories = if test!() {
343 directories
344 .iter()
345 .map(|d| {
346 d.strip_prefix('/')
347 .or_else(|| d.strip_prefix("C:\\"))
348 .unwrap_or(d)
349 })
350 .collect::<Vec<_>>()
351 } else {
352 directories
353 };
354
355 // Search the directories provided by the `libclang` directory patterns.
356 let mut options = MatchOptions::new();
357 options.case_sensitive = false;
358 options.require_literal_separator = true;
359 for directory in directories.iter() {
360 if let Ok(directories) = glob::glob_with(directory, options) {
361 for directory in directories.filter_map(Result::ok).filter(|p| p.is_dir()) {
362 found.extend(search_directories(&directory, filenames));
363 }
364 }
365 }
366
367 found
368 }