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.
259 /// Obtains the current CI environment.
260 pub fn current() -> CiEnv {
261 if env::var("TF_BUILD").map_or(false, |e| e == "True") {
262 CiEnv::AzurePipelines
263 } else if env::var("GITHUB_ACTIONS").map_or(false, |e| e == "true") {
270 pub fn is_ci() -> bool {
271 Self::current() != CiEnv::None
274 /// If in a CI environment, forces the command to run with colors.
275 pub fn force_coloring_in_ci(self, cmd: &mut Command) {
276 if self != CiEnv::None {
277 // Due to use of stamp/docker, the output stream of rustbuild is not
278 // a TTY in CI, so coloring is by-default turned off.
279 // The explicit `TERM=xterm` environment is needed for
280 // `--color always` to actually work. This env var was lost when
281 // compiling through the Makefile. Very strange.
282 cmd.env("TERM", "xterm").args(&["--color", "always"]);
287 pub fn forcing_clang_based_tests() -> bool {
288 if let Some(var) = env::var_os("RUSTBUILD_FORCE_CLANG_BASED_TESTS") {
289 match &var.to_string_lossy().to_lowercase()[..] {
290 "1" | "yes" | "on" => true,
291 "0" | "no" | "off" => false,
293 // Let's make sure typos don't go unnoticed
295 "Unrecognized option '{}' set in \
296 RUSTBUILD_FORCE_CLANG_BASED_TESTS",
306 pub fn use_host_linker(target: TargetSelection) -> bool {
307 // FIXME: this information should be gotten by checking the linker flavor
308 // of the rustc target
309 !(target.contains("emscripten")
310 || target.contains("wasm32")
311 || target.contains("nvptx")
312 || target.contains("fortanix")
313 || target.contains("fuchsia")
314 || target.contains("bpf")
315 || target.contains("switch"))
318 pub fn is_valid_test_suite_arg<'a, P: AsRef<Path>>(
321 builder: &Builder<'_>,
322 ) -> Option<&'a str> {
323 let suite_path = suite_path.as_ref();
324 let path = match path.strip_prefix(".") {
328 if !path.starts_with(suite_path) {
331 let abs_path = builder.src.join(path);
332 let exists = abs_path.is_dir() || abs_path.is_file();
335 "Invalid test suite filter \"{}\": file or directory does not exist",
339 // Since test suite paths are themselves directories, if we don't
340 // specify a directory or file, we'll get an empty string here
341 // (the result of the test suite directory without its suite prefix).
342 // Therefore, we need to filter these out, as only the first --test-args
343 // flag is respected, so providing an empty --test-args conflicts with
345 match path.strip_prefix(suite_path).ok().and_then(|p| p.to_str()) {
346 Some(s) if !s.is_empty() => Some(s),
351 pub fn run(cmd: &mut Command, print_cmd_on_fail: bool) {
352 if !try_run(cmd, print_cmd_on_fail) {
353 crate::detail_exit(1);
357 pub fn try_run(cmd: &mut Command, print_cmd_on_fail: bool) -> bool {
358 let status = match cmd.status() {
359 Ok(status) => status,
360 Err(e) => fail(&format!("failed to execute command: {:?}\nerror: {}", cmd, e)),
362 if !status.success() && print_cmd_on_fail {
364 "\n\ncommand did not execute successfully: {:?}\n\
365 expected success, got: {}\n\n",
372 pub fn check_run(cmd: &mut Command, print_cmd_on_fail: bool) -> bool {
373 let status = match cmd.status() {
374 Ok(status) => status,
376 println!("failed to execute command: {:?}\nerror: {}", cmd, e);
380 if !status.success() && print_cmd_on_fail {
382 "\n\ncommand did not execute successfully: {:?}\n\
383 expected success, got: {}\n\n",
390 pub fn run_suppressed(cmd: &mut Command) {
391 if !try_run_suppressed(cmd) {
392 crate::detail_exit(1);
396 pub fn try_run_suppressed(cmd: &mut Command) -> bool {
397 let output = match cmd.output() {
398 Ok(status) => status,
399 Err(e) => fail(&format!("failed to execute command: {:?}\nerror: {}", cmd, e)),
401 if !output.status.success() {
403 "\n\ncommand did not execute successfully: {:?}\n\
404 expected success, got: {}\n\n\
406 stderr ----\n{}\n\n",
409 String::from_utf8_lossy(&output.stdout),
410 String::from_utf8_lossy(&output.stderr)
413 output.status.success()
416 pub fn make(host: &str) -> PathBuf {
417 if host.contains("dragonfly")
418 || host.contains("freebsd")
419 || host.contains("netbsd")
420 || host.contains("openbsd")
422 PathBuf::from("gmake")
424 PathBuf::from("make")
429 pub fn output(cmd: &mut Command) -> String {
430 let output = match cmd.stderr(Stdio::inherit()).output() {
431 Ok(status) => status,
432 Err(e) => fail(&format!("failed to execute command: {:?}\nerror: {}", cmd, e)),
434 if !output.status.success() {
436 "command did not execute successfully: {:?}\n\
437 expected success, got: {}",
441 String::from_utf8(output.stdout).unwrap()
444 /// Returns the last-modified time for `path`, or zero if it doesn't exist.
445 pub fn mtime(path: &Path) -> SystemTime {
446 fs::metadata(path).and_then(|f| f.modified()).unwrap_or(UNIX_EPOCH)
449 /// Returns `true` if `dst` is up to date given that the file or files in `src`
450 /// are used to generate it.
452 /// Uses last-modified time checks to verify this.
453 pub fn up_to_date(src: &Path, dst: &Path) -> bool {
457 let threshold = mtime(dst);
458 let meta = match fs::metadata(src) {
460 Err(e) => panic!("source {:?} failed to get metadata: {}", src, e),
463 dir_up_to_date(src, threshold)
465 meta.modified().unwrap_or(UNIX_EPOCH) <= threshold
469 fn dir_up_to_date(src: &Path, threshold: SystemTime) -> bool {
470 t!(fs::read_dir(src)).map(|e| t!(e)).all(|e| {
471 let meta = t!(e.metadata());
473 dir_up_to_date(&e.path(), threshold)
475 meta.modified().unwrap_or(UNIX_EPOCH) < threshold
480 fn fail(s: &str) -> ! {
481 eprintln!("\n\n{}\n\n", s);
482 crate::detail_exit(1);
485 /// Copied from `std::path::absolute` until it stabilizes.
487 /// FIXME: this shouldn't exist.
488 pub(crate) fn absolute(path: &Path) -> PathBuf {
489 if path.as_os_str().is_empty() {
490 panic!("can't make empty path absolute");
494 t!(absolute_unix(path), format!("could not make path absolute: {}", path.display()))
498 t!(absolute_windows(path), format!("could not make path absolute: {}", path.display()))
500 #[cfg(not(any(unix, windows)))]
502 println!("warning: bootstrap is not supported on non-unix platforms");
503 t!(std::fs::canonicalize(t!(std::env::current_dir()))).join(path)
508 /// Make a POSIX path absolute without changing its semantics.
509 fn absolute_unix(path: &Path) -> io::Result<PathBuf> {
510 // This is mostly a wrapper around collecting `Path::components`, with
511 // exceptions made where this conflicts with the POSIX specification.
512 // See 4.13 Pathname Resolution, IEEE Std 1003.1-2017
513 // https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_13
515 use std::os::unix::prelude::OsStrExt;
516 let mut components = path.components();
517 let path_os = path.as_os_str().as_bytes();
519 let mut normalized = if path.is_absolute() {
520 // "If a pathname begins with two successive <slash> characters, the
521 // first component following the leading <slash> characters may be
522 // interpreted in an implementation-defined manner, although more than
523 // two leading <slash> characters shall be treated as a single <slash>
525 if path_os.starts_with(b"//") && !path_os.starts_with(b"///") {
534 normalized.extend(components);
536 // "Interfaces using pathname resolution may specify additional constraints
537 // when a pathname that does not name an existing directory contains at
538 // least one non- <slash> character and contains one or more trailing
539 // <slash> characters".
540 // A trailing <slash> is also meaningful if "a symbolic link is
541 // encountered during pathname resolution".
543 if path_os.ends_with(b"/") {
551 fn absolute_windows(path: &std::path::Path) -> std::io::Result<std::path::PathBuf> {
552 use std::ffi::OsString;
554 use std::os::windows::ffi::{OsStrExt, OsStringExt};
555 use std::ptr::null_mut;
556 #[link(name = "kernel32")]
559 lpFileName: *const u16,
562 lpFilePart: *mut *const u16,
567 // encode the path as UTF-16
568 let path: Vec<u16> = path.as_os_str().encode_wide().chain([0]).collect();
569 let mut buffer = Vec::new();
570 // Loop until either success or failure.
572 // Try to get the absolute path
573 let len = GetFullPathNameW(
575 buffer.len().try_into().unwrap(),
581 0 => return Err(Error::last_os_error()),
582 // Buffer is too small, resize.
583 len if len > buffer.len() => buffer.resize(len, 0),
586 buffer.truncate(len);
587 return Ok(OsString::from_wide(&buffer).into());
594 /// Adapted from https://github.com/llvm/llvm-project/blob/782e91224601e461c019e0a4573bbccc6094fbcd/llvm/cmake/modules/HandleLLVMOptions.cmake#L1058-L1079
596 /// When `clang-cl` is used with instrumentation, we need to add clang's runtime library resource
597 /// directory to the linker flags, otherwise there will be linker errors about the profiler runtime
598 /// missing. This function returns the path to that directory.
599 pub fn get_clang_cl_resource_dir(clang_cl_path: &str) -> PathBuf {
600 // Similar to how LLVM does it, to find clang's library runtime directory:
601 // - we ask `clang-cl` to locate the `clang_rt.builtins` lib.
602 let mut builtins_locator = Command::new(clang_cl_path);
603 builtins_locator.args(&["/clang:-print-libgcc-file-name", "/clang:--rtlib=compiler-rt"]);
605 let clang_rt_builtins = output(&mut builtins_locator);
606 let clang_rt_builtins = Path::new(clang_rt_builtins.trim());
608 clang_rt_builtins.exists(),
609 "`clang-cl` must correctly locate the library runtime directory"
612 // - the profiler runtime will be located in the same directory as the builtins lib, like
613 // `$LLVM_DISTRO_ROOT/lib/clang/$LLVM_VERSION/lib/windows`.
614 let clang_rt_dir = clang_rt_builtins.parent().expect("The clang lib folder should exist");
615 clang_rt_dir.to_path_buf()
618 pub fn lld_flag_no_threads(is_windows: bool) -> &'static str {
619 static LLD_NO_THREADS: OnceCell<(&'static str, &'static str)> = OnceCell::new();
620 let (windows, other) = LLD_NO_THREADS.get_or_init(|| {
621 let out = output(Command::new("lld").arg("-flavor").arg("ld").arg("--version"));
622 let newer = match (out.find(char::is_numeric), out.find('.')) {
623 (Some(b), Some(e)) => out.as_str()[b..e].parse::<i32>().ok().unwrap_or(14) > 10,
626 if newer { ("/threads:1", "--threads=1") } else { ("/no-threads", "--no-threads") }
628 if is_windows { windows } else { other }