1 //! Various utility functions used throughout rustbuild.
3 //! Simple things like testing the various filesystem operations here and there,
4 //! not a lot of interesting happenings here unfortunately.
9 use std::path::{Path, PathBuf};
10 use std::process::{Command, Stdio};
12 use std::time::{Instant, SystemTime, UNIX_EPOCH};
14 use crate::builder::Builder;
15 use crate::config::{Config, TargetSelection};
18 /// A helper macro to `unwrap` a result except also print out details like:
20 /// * The file/line of the panic
21 /// * The expression that failed
22 /// * The error itself
24 /// This is currently used judiciously throughout the build system rather than
25 /// using a `Result` with `try!`, but this may change one day...
31 Err(e) => panic!("{} failed with {}", stringify!($e), e),
34 // it can show extra info in the second parameter
35 ($e:expr, $extra:expr) => {
38 Err(e) => panic!("{} failed with {} ({:?})", stringify!($e), e, $extra),
44 /// Given an executable called `name`, return the filename for the
45 /// executable for a particular target.
46 pub fn exe(name: &str, target: TargetSelection) -> String {
47 if target.contains("windows") {
48 format!("{}.exe", name)
49 } else if target.contains("uefi") {
50 format!("{}.efi", name)
56 /// Returns `true` if the file name given looks like a dynamic library.
57 pub fn is_dylib(name: &str) -> bool {
58 name.ends_with(".dylib") || name.ends_with(".so") || name.ends_with(".dll")
61 /// Returns `true` if the file name given looks like a debug info file
62 pub fn is_debug_info(name: &str) -> bool {
63 // FIXME: consider split debug info on other platforms (e.g., Linux, macOS)
64 name.ends_with(".pdb")
67 /// Returns the corresponding relative library directory that the compiler's
68 /// dylibs will be found in.
69 pub fn libdir(target: TargetSelection) -> &'static str {
70 if target.contains("windows") { "bin" } else { "lib" }
73 /// Adds a list of lookup paths to `cmd`'s dynamic library lookup path.
74 /// If the dylib_path_var is already set for this cmd, the old value will be overwritten!
75 pub fn add_dylib_path(path: Vec<PathBuf>, cmd: &mut Command) {
76 let mut list = dylib_path();
80 cmd.env(dylib_path_var(), t!(env::join_paths(list)));
83 include!("dylib_util.rs");
85 /// Adds a list of lookup paths to `cmd`'s link library lookup path.
86 pub fn add_link_lib_path(path: Vec<PathBuf>, cmd: &mut Command) {
87 let mut list = link_lib_path();
91 cmd.env(link_lib_path_var(), t!(env::join_paths(list)));
94 /// Returns the environment variable which the link library lookup path
95 /// resides in for this platform.
96 fn link_lib_path_var() -> &'static str {
97 if cfg!(target_env = "msvc") { "LIB" } else { "LIBRARY_PATH" }
100 /// Parses the `link_lib_path_var()` environment variable, returning a list of
101 /// paths that are members of this lookup path.
102 fn link_lib_path() -> Vec<PathBuf> {
103 let var = match env::var_os(link_lib_path_var()) {
105 None => return vec![],
107 env::split_paths(&var).collect()
110 pub struct TimeIt(bool, Instant);
112 /// Returns an RAII structure that prints out how long it took to drop.
113 pub fn timeit(builder: &Builder<'_>) -> TimeIt {
114 TimeIt(builder.config.dry_run(), Instant::now())
117 impl Drop for TimeIt {
119 let time = self.1.elapsed();
121 println!("\tfinished in {}.{:03} seconds", time.as_secs(), time.subsec_millis());
126 /// Used for download caching
127 pub(crate) fn program_out_of_date(stamp: &Path, key: &str) -> bool {
131 t!(fs::read_to_string(stamp)) != key
134 /// Symlinks two directories, using junctions on Windows and normal symlinks on
136 pub fn symlink_dir(config: &Config, src: &Path, dest: &Path) -> io::Result<()> {
137 if config.dry_run() {
140 let _ = fs::remove_dir(dest);
141 return symlink_dir_inner(src, dest);
144 fn symlink_dir_inner(src: &Path, dest: &Path) -> io::Result<()> {
145 use std::os::unix::fs;
146 fs::symlink(src, dest)
149 // Creating a directory junction on windows involves dealing with reparse
150 // points and the DeviceIoControl function, and this code is a skeleton of
151 // what can be found here:
153 // http://www.flexhex.com/docs/articles/hard-links.phtml
155 fn symlink_dir_inner(target: &Path, junction: &Path) -> io::Result<()> {
157 use std::os::windows::ffi::OsStrExt;
160 use winapi::shared::minwindef::{DWORD, WORD};
161 use winapi::um::fileapi::{CreateFileW, OPEN_EXISTING};
162 use winapi::um::handleapi::CloseHandle;
163 use winapi::um::ioapiset::DeviceIoControl;
164 use winapi::um::winbase::{FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT};
165 use winapi::um::winioctl::FSCTL_SET_REPARSE_POINT;
166 use winapi::um::winnt::{
167 FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE, GENERIC_WRITE,
168 IO_REPARSE_TAG_MOUNT_POINT, MAXIMUM_REPARSE_DATA_BUFFER_SIZE, WCHAR,
171 #[allow(non_snake_case)]
173 struct REPARSE_MOUNTPOINT_DATA_BUFFER {
175 ReparseDataLength: DWORD,
177 ReparseTargetLength: WORD,
178 ReparseTargetMaximumLength: WORD,
180 ReparseTarget: WCHAR,
183 fn to_u16s<S: AsRef<OsStr>>(s: S) -> io::Result<Vec<u16>> {
184 Ok(s.as_ref().encode_wide().chain(Some(0)).collect())
187 // We're using low-level APIs to create the junction, and these are more
188 // picky about paths. For example, forward slashes cannot be used as a
189 // path separator, so we should try to canonicalize the path first.
190 let target = fs::canonicalize(target)?;
192 fs::create_dir(junction)?;
194 let path = to_u16s(junction)?;
200 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
203 FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS,
209 let mut data = Align8([0u8; MAXIMUM_REPARSE_DATA_BUFFER_SIZE as usize]);
210 let db = data.0.as_mut_ptr() as *mut REPARSE_MOUNTPOINT_DATA_BUFFER;
211 let buf = core::ptr::addr_of_mut!((*db).ReparseTarget) as *mut u16;
213 // FIXME: this conversion is very hacky
215 let v = v.iter().map(|x| *x as u16);
216 for c in v.chain(target.as_os_str().encode_wide().skip(4)) {
222 (*db).ReparseTag = IO_REPARSE_TAG_MOUNT_POINT;
223 (*db).ReparseTargetMaximumLength = (i * 2) as WORD;
224 (*db).ReparseTargetLength = ((i - 1) * 2) as WORD;
225 (*db).ReparseDataLength = (*db).ReparseTargetLength as DWORD + 12;
228 let res = DeviceIoControl(
230 FSCTL_SET_REPARSE_POINT,
232 (*db).ReparseDataLength + 8,
239 let out = if res == 0 { Err(io::Error::last_os_error()) } else { Ok(()) };
246 /// The CI environment rustbuild is running in. This mainly affects how the logs
248 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
250 /// Not a CI environment.
252 /// The Azure Pipelines environment, for Linux (including Docker), Windows, and macOS builds.
254 /// The GitHub Actions environment, for Linux (including Docker), Windows and macOS builds.
258 pub fn forcing_clang_based_tests() -> bool {
259 if let Some(var) = env::var_os("RUSTBUILD_FORCE_CLANG_BASED_TESTS") {
260 match &var.to_string_lossy().to_lowercase()[..] {
261 "1" | "yes" | "on" => true,
262 "0" | "no" | "off" => false,
264 // Let's make sure typos don't go unnoticed
266 "Unrecognized option '{}' set in \
267 RUSTBUILD_FORCE_CLANG_BASED_TESTS",
277 pub fn use_host_linker(target: TargetSelection) -> bool {
278 // FIXME: this information should be gotten by checking the linker flavor
279 // of the rustc target
280 !(target.contains("emscripten")
281 || target.contains("wasm32")
282 || target.contains("nvptx")
283 || target.contains("fortanix")
284 || target.contains("fuchsia")
285 || target.contains("bpf")
286 || target.contains("switch"))
289 pub fn is_valid_test_suite_arg<'a, P: AsRef<Path>>(
292 builder: &Builder<'_>,
293 ) -> Option<&'a str> {
294 let suite_path = suite_path.as_ref();
295 let path = match path.strip_prefix(".") {
299 if !path.starts_with(suite_path) {
302 let abs_path = builder.src.join(path);
303 let exists = abs_path.is_dir() || abs_path.is_file();
306 "Invalid test suite filter \"{}\": file or directory does not exist",
310 // Since test suite paths are themselves directories, if we don't
311 // specify a directory or file, we'll get an empty string here
312 // (the result of the test suite directory without its suite prefix).
313 // Therefore, we need to filter these out, as only the first --test-args
314 // flag is respected, so providing an empty --test-args conflicts with
316 match path.strip_prefix(suite_path).ok().and_then(|p| p.to_str()) {
317 Some(s) if !s.is_empty() => Some(s),
322 pub fn run(cmd: &mut Command, print_cmd_on_fail: bool) {
323 if !try_run(cmd, print_cmd_on_fail) {
324 crate::detail_exit(1);
328 pub fn try_run(cmd: &mut Command, print_cmd_on_fail: bool) -> bool {
329 let status = match cmd.status() {
330 Ok(status) => status,
331 Err(e) => fail(&format!("failed to execute command: {:?}\nerror: {}", cmd, e)),
333 if !status.success() && print_cmd_on_fail {
335 "\n\ncommand did not execute successfully: {:?}\n\
336 expected success, got: {}\n\n",
343 pub fn check_run(cmd: &mut Command, print_cmd_on_fail: bool) -> bool {
344 let status = match cmd.status() {
345 Ok(status) => status,
347 println!("failed to execute command: {:?}\nerror: {}", cmd, e);
351 if !status.success() && print_cmd_on_fail {
353 "\n\ncommand did not execute successfully: {:?}\n\
354 expected success, got: {}\n\n",
361 pub fn run_suppressed(cmd: &mut Command) {
362 if !try_run_suppressed(cmd) {
363 crate::detail_exit(1);
367 pub fn try_run_suppressed(cmd: &mut Command) -> bool {
368 let output = match cmd.output() {
369 Ok(status) => status,
370 Err(e) => fail(&format!("failed to execute command: {:?}\nerror: {}", cmd, e)),
372 if !output.status.success() {
374 "\n\ncommand did not execute successfully: {:?}\n\
375 expected success, got: {}\n\n\
377 stderr ----\n{}\n\n",
380 String::from_utf8_lossy(&output.stdout),
381 String::from_utf8_lossy(&output.stderr)
384 output.status.success()
387 pub fn make(host: &str) -> PathBuf {
388 if host.contains("dragonfly")
389 || host.contains("freebsd")
390 || host.contains("netbsd")
391 || host.contains("openbsd")
393 PathBuf::from("gmake")
395 PathBuf::from("make")
400 pub fn output(cmd: &mut Command) -> String {
401 let output = match cmd.stderr(Stdio::inherit()).output() {
402 Ok(status) => status,
403 Err(e) => fail(&format!("failed to execute command: {:?}\nerror: {}", cmd, e)),
405 if !output.status.success() {
407 "command did not execute successfully: {:?}\n\
408 expected success, got: {}",
412 String::from_utf8(output.stdout).unwrap()
415 pub fn output_result(cmd: &mut Command) -> Result<String, String> {
416 let output = match cmd.stderr(Stdio::inherit()).output() {
417 Ok(status) => status,
418 Err(e) => return Err(format!("failed to run command: {:?}: {}", cmd, e)),
420 if !output.status.success() {
422 "command did not execute successfully: {:?}\n\
423 expected success, got: {}\n{}",
426 String::from_utf8(output.stderr).map_err(|err| format!("{err:?}"))?
429 Ok(String::from_utf8(output.stdout).map_err(|err| format!("{err:?}"))?)
432 /// Returns the last-modified time for `path`, or zero if it doesn't exist.
433 pub fn mtime(path: &Path) -> SystemTime {
434 fs::metadata(path).and_then(|f| f.modified()).unwrap_or(UNIX_EPOCH)
437 /// Returns `true` if `dst` is up to date given that the file or files in `src`
438 /// are used to generate it.
440 /// Uses last-modified time checks to verify this.
441 pub fn up_to_date(src: &Path, dst: &Path) -> bool {
445 let threshold = mtime(dst);
446 let meta = match fs::metadata(src) {
448 Err(e) => panic!("source {:?} failed to get metadata: {}", src, e),
451 dir_up_to_date(src, threshold)
453 meta.modified().unwrap_or(UNIX_EPOCH) <= threshold
457 fn dir_up_to_date(src: &Path, threshold: SystemTime) -> bool {
458 t!(fs::read_dir(src)).map(|e| t!(e)).all(|e| {
459 let meta = t!(e.metadata());
461 dir_up_to_date(&e.path(), threshold)
463 meta.modified().unwrap_or(UNIX_EPOCH) < threshold
468 fn fail(s: &str) -> ! {
469 eprintln!("\n\n{}\n\n", s);
470 crate::detail_exit(1);
473 /// Copied from `std::path::absolute` until it stabilizes.
475 /// FIXME: this shouldn't exist.
476 pub(crate) fn absolute(path: &Path) -> PathBuf {
477 if path.as_os_str().is_empty() {
478 panic!("can't make empty path absolute");
482 t!(absolute_unix(path), format!("could not make path absolute: {}", path.display()))
486 t!(absolute_windows(path), format!("could not make path absolute: {}", path.display()))
488 #[cfg(not(any(unix, windows)))]
490 println!("warning: bootstrap is not supported on non-unix platforms");
491 t!(std::fs::canonicalize(t!(std::env::current_dir()))).join(path)
496 /// Make a POSIX path absolute without changing its semantics.
497 fn absolute_unix(path: &Path) -> io::Result<PathBuf> {
498 // This is mostly a wrapper around collecting `Path::components`, with
499 // exceptions made where this conflicts with the POSIX specification.
500 // See 4.13 Pathname Resolution, IEEE Std 1003.1-2017
501 // https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_13
503 use std::os::unix::prelude::OsStrExt;
504 let mut components = path.components();
505 let path_os = path.as_os_str().as_bytes();
507 let mut normalized = if path.is_absolute() {
508 // "If a pathname begins with two successive <slash> characters, the
509 // first component following the leading <slash> characters may be
510 // interpreted in an implementation-defined manner, although more than
511 // two leading <slash> characters shall be treated as a single <slash>
513 if path_os.starts_with(b"//") && !path_os.starts_with(b"///") {
522 normalized.extend(components);
524 // "Interfaces using pathname resolution may specify additional constraints
525 // when a pathname that does not name an existing directory contains at
526 // least one non- <slash> character and contains one or more trailing
527 // <slash> characters".
528 // A trailing <slash> is also meaningful if "a symbolic link is
529 // encountered during pathname resolution".
531 if path_os.ends_with(b"/") {
539 fn absolute_windows(path: &std::path::Path) -> std::io::Result<std::path::PathBuf> {
540 use std::ffi::OsString;
542 use std::os::windows::ffi::{OsStrExt, OsStringExt};
543 use std::ptr::null_mut;
544 #[link(name = "kernel32")]
547 lpFileName: *const u16,
550 lpFilePart: *mut *const u16,
555 // encode the path as UTF-16
556 let path: Vec<u16> = path.as_os_str().encode_wide().chain([0]).collect();
557 let mut buffer = Vec::new();
558 // Loop until either success or failure.
560 // Try to get the absolute path
561 let len = GetFullPathNameW(
563 buffer.len().try_into().unwrap(),
569 0 => return Err(Error::last_os_error()),
570 // Buffer is too small, resize.
571 len if len > buffer.len() => buffer.resize(len, 0),
574 buffer.truncate(len);
575 return Ok(OsString::from_wide(&buffer).into());
582 /// Adapted from https://github.com/llvm/llvm-project/blob/782e91224601e461c019e0a4573bbccc6094fbcd/llvm/cmake/modules/HandleLLVMOptions.cmake#L1058-L1079
584 /// When `clang-cl` is used with instrumentation, we need to add clang's runtime library resource
585 /// directory to the linker flags, otherwise there will be linker errors about the profiler runtime
586 /// missing. This function returns the path to that directory.
587 pub fn get_clang_cl_resource_dir(clang_cl_path: &str) -> PathBuf {
588 // Similar to how LLVM does it, to find clang's library runtime directory:
589 // - we ask `clang-cl` to locate the `clang_rt.builtins` lib.
590 let mut builtins_locator = Command::new(clang_cl_path);
591 builtins_locator.args(&["/clang:-print-libgcc-file-name", "/clang:--rtlib=compiler-rt"]);
593 let clang_rt_builtins = output(&mut builtins_locator);
594 let clang_rt_builtins = Path::new(clang_rt_builtins.trim());
596 clang_rt_builtins.exists(),
597 "`clang-cl` must correctly locate the library runtime directory"
600 // - the profiler runtime will be located in the same directory as the builtins lib, like
601 // `$LLVM_DISTRO_ROOT/lib/clang/$LLVM_VERSION/lib/windows`.
602 let clang_rt_dir = clang_rt_builtins.parent().expect("The clang lib folder should exist");
603 clang_rt_dir.to_path_buf()
606 pub fn lld_flag_no_threads(is_windows: bool) -> &'static str {
607 static LLD_NO_THREADS: OnceCell<(&'static str, &'static str)> = OnceCell::new();
608 let (windows, other) = LLD_NO_THREADS.get_or_init(|| {
609 let out = output(Command::new("lld").arg("-flavor").arg("ld").arg("--version"));
610 let newer = match (out.find(char::is_numeric), out.find('.')) {
611 (Some(b), Some(e)) => out.as_str()[b..e].parse::<i32>().ok().unwrap_or(14) > 10,
614 if newer { ("/threads:1", "--threads=1") } else { ("/no-threads", "--no-threads") }
616 if is_windows { windows } else { other }