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") { format!("{}.exe", name) } else { name.to_string() }
50 /// Returns `true` if the file name given looks like a dynamic library.
51 pub fn is_dylib(name: &str) -> bool {
52 name.ends_with(".dylib") || name.ends_with(".so") || name.ends_with(".dll")
55 /// Returns `true` if the file name given looks like a debug info file
56 pub fn is_debug_info(name: &str) -> bool {
57 // FIXME: consider split debug info on other platforms (e.g., Linux, macOS)
58 name.ends_with(".pdb")
61 /// Returns the corresponding relative library directory that the compiler's
62 /// dylibs will be found in.
63 pub fn libdir(target: TargetSelection) -> &'static str {
64 if target.contains("windows") { "bin" } else { "lib" }
67 /// Adds a list of lookup paths to `cmd`'s dynamic library lookup path.
68 /// If the dylib_path_var is already set for this cmd, the old value will be overwritten!
69 pub fn add_dylib_path(path: Vec<PathBuf>, cmd: &mut Command) {
70 let mut list = dylib_path();
74 cmd.env(dylib_path_var(), t!(env::join_paths(list)));
77 include!("dylib_util.rs");
79 /// Adds a list of lookup paths to `cmd`'s link library lookup path.
80 pub fn add_link_lib_path(path: Vec<PathBuf>, cmd: &mut Command) {
81 let mut list = link_lib_path();
85 cmd.env(link_lib_path_var(), t!(env::join_paths(list)));
88 /// Returns the environment variable which the link library lookup path
89 /// resides in for this platform.
90 fn link_lib_path_var() -> &'static str {
91 if cfg!(target_env = "msvc") { "LIB" } else { "LIBRARY_PATH" }
94 /// Parses the `link_lib_path_var()` environment variable, returning a list of
95 /// paths that are members of this lookup path.
96 fn link_lib_path() -> Vec<PathBuf> {
97 let var = match env::var_os(link_lib_path_var()) {
99 None => return vec![],
101 env::split_paths(&var).collect()
104 pub struct TimeIt(bool, Instant);
106 /// Returns an RAII structure that prints out how long it took to drop.
107 pub fn timeit(builder: &Builder<'_>) -> TimeIt {
108 TimeIt(builder.config.dry_run(), Instant::now())
111 impl Drop for TimeIt {
113 let time = self.1.elapsed();
115 println!("\tfinished in {}.{:03} seconds", time.as_secs(), time.subsec_millis());
120 /// Used for download caching
121 pub(crate) fn program_out_of_date(stamp: &Path, key: &str) -> bool {
125 t!(fs::read_to_string(stamp)) != key
128 /// Symlinks two directories, using junctions on Windows and normal symlinks on
130 pub fn symlink_dir(config: &Config, src: &Path, dest: &Path) -> io::Result<()> {
131 if config.dry_run() {
134 let _ = fs::remove_dir(dest);
135 return symlink_dir_inner(src, dest);
138 fn symlink_dir_inner(src: &Path, dest: &Path) -> io::Result<()> {
139 use std::os::unix::fs;
140 fs::symlink(src, dest)
143 // Creating a directory junction on windows involves dealing with reparse
144 // points and the DeviceIoControl function, and this code is a skeleton of
145 // what can be found here:
147 // http://www.flexhex.com/docs/articles/hard-links.phtml
149 fn symlink_dir_inner(target: &Path, junction: &Path) -> io::Result<()> {
151 use std::os::windows::ffi::OsStrExt;
154 use winapi::shared::minwindef::{DWORD, WORD};
155 use winapi::um::fileapi::{CreateFileW, OPEN_EXISTING};
156 use winapi::um::handleapi::CloseHandle;
157 use winapi::um::ioapiset::DeviceIoControl;
158 use winapi::um::winbase::{FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT};
159 use winapi::um::winioctl::FSCTL_SET_REPARSE_POINT;
160 use winapi::um::winnt::{
161 FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE, GENERIC_WRITE,
162 IO_REPARSE_TAG_MOUNT_POINT, MAXIMUM_REPARSE_DATA_BUFFER_SIZE, WCHAR,
165 #[allow(non_snake_case)]
167 struct REPARSE_MOUNTPOINT_DATA_BUFFER {
169 ReparseDataLength: DWORD,
171 ReparseTargetLength: WORD,
172 ReparseTargetMaximumLength: WORD,
174 ReparseTarget: WCHAR,
177 fn to_u16s<S: AsRef<OsStr>>(s: S) -> io::Result<Vec<u16>> {
178 Ok(s.as_ref().encode_wide().chain(Some(0)).collect())
181 // We're using low-level APIs to create the junction, and these are more
182 // picky about paths. For example, forward slashes cannot be used as a
183 // path separator, so we should try to canonicalize the path first.
184 let target = fs::canonicalize(target)?;
186 fs::create_dir(junction)?;
188 let path = to_u16s(junction)?;
194 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
197 FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS,
203 let mut data = Align8([0u8; MAXIMUM_REPARSE_DATA_BUFFER_SIZE as usize]);
204 let db = data.0.as_mut_ptr() as *mut REPARSE_MOUNTPOINT_DATA_BUFFER;
205 let buf = core::ptr::addr_of_mut!((*db).ReparseTarget) as *mut u16;
207 // FIXME: this conversion is very hacky
209 let v = v.iter().map(|x| *x as u16);
210 for c in v.chain(target.as_os_str().encode_wide().skip(4)) {
216 (*db).ReparseTag = IO_REPARSE_TAG_MOUNT_POINT;
217 (*db).ReparseTargetMaximumLength = (i * 2) as WORD;
218 (*db).ReparseTargetLength = ((i - 1) * 2) as WORD;
219 (*db).ReparseDataLength = (*db).ReparseTargetLength as DWORD + 12;
222 let res = DeviceIoControl(
224 FSCTL_SET_REPARSE_POINT,
226 (*db).ReparseDataLength + 8,
233 let out = if res == 0 { Err(io::Error::last_os_error()) } else { Ok(()) };
240 /// The CI environment rustbuild is running in. This mainly affects how the logs
242 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
244 /// Not a CI environment.
246 /// The Azure Pipelines environment, for Linux (including Docker), Windows, and macOS builds.
248 /// The GitHub Actions environment, for Linux (including Docker), Windows and macOS builds.
253 /// Obtains the current CI environment.
254 pub fn current() -> CiEnv {
255 if env::var("TF_BUILD").map_or(false, |e| e == "True") {
256 CiEnv::AzurePipelines
257 } else if env::var("GITHUB_ACTIONS").map_or(false, |e| e == "true") {
264 pub fn is_ci() -> bool {
265 Self::current() != CiEnv::None
268 /// If in a CI environment, forces the command to run with colors.
269 pub fn force_coloring_in_ci(self, cmd: &mut Command) {
270 if self != CiEnv::None {
271 // Due to use of stamp/docker, the output stream of rustbuild is not
272 // a TTY in CI, so coloring is by-default turned off.
273 // The explicit `TERM=xterm` environment is needed for
274 // `--color always` to actually work. This env var was lost when
275 // compiling through the Makefile. Very strange.
276 cmd.env("TERM", "xterm").args(&["--color", "always"]);
281 pub fn forcing_clang_based_tests() -> bool {
282 if let Some(var) = env::var_os("RUSTBUILD_FORCE_CLANG_BASED_TESTS") {
283 match &var.to_string_lossy().to_lowercase()[..] {
284 "1" | "yes" | "on" => true,
285 "0" | "no" | "off" => false,
287 // Let's make sure typos don't go unnoticed
289 "Unrecognized option '{}' set in \
290 RUSTBUILD_FORCE_CLANG_BASED_TESTS",
300 pub fn use_host_linker(target: TargetSelection) -> bool {
301 // FIXME: this information should be gotten by checking the linker flavor
302 // of the rustc target
303 !(target.contains("emscripten")
304 || target.contains("wasm32")
305 || target.contains("nvptx")
306 || target.contains("fortanix")
307 || target.contains("fuchsia")
308 || target.contains("bpf")
309 || target.contains("switch"))
312 pub fn is_valid_test_suite_arg<'a, P: AsRef<Path>>(
315 builder: &Builder<'_>,
316 ) -> Option<&'a str> {
317 let suite_path = suite_path.as_ref();
318 let path = match path.strip_prefix(".") {
322 if !path.starts_with(suite_path) {
325 let abs_path = builder.src.join(path);
326 let exists = abs_path.is_dir() || abs_path.is_file();
329 "Invalid test suite filter \"{}\": file or directory does not exist",
333 // Since test suite paths are themselves directories, if we don't
334 // specify a directory or file, we'll get an empty string here
335 // (the result of the test suite directory without its suite prefix).
336 // Therefore, we need to filter these out, as only the first --test-args
337 // flag is respected, so providing an empty --test-args conflicts with
339 match path.strip_prefix(suite_path).ok().and_then(|p| p.to_str()) {
340 Some(s) if !s.is_empty() => Some(s),
345 pub fn run(cmd: &mut Command, print_cmd_on_fail: bool) {
346 if !try_run(cmd, print_cmd_on_fail) {
347 crate::detail_exit(1);
351 pub fn try_run(cmd: &mut Command, print_cmd_on_fail: bool) -> bool {
352 let status = match cmd.status() {
353 Ok(status) => status,
354 Err(e) => fail(&format!("failed to execute command: {:?}\nerror: {}", cmd, e)),
356 if !status.success() && print_cmd_on_fail {
358 "\n\ncommand did not execute successfully: {:?}\n\
359 expected success, got: {}\n\n",
366 pub fn check_run(cmd: &mut Command, print_cmd_on_fail: bool) -> bool {
367 let status = match cmd.status() {
368 Ok(status) => status,
370 println!("failed to execute command: {:?}\nerror: {}", cmd, e);
374 if !status.success() && print_cmd_on_fail {
376 "\n\ncommand did not execute successfully: {:?}\n\
377 expected success, got: {}\n\n",
384 pub fn run_suppressed(cmd: &mut Command) {
385 if !try_run_suppressed(cmd) {
386 crate::detail_exit(1);
390 pub fn try_run_suppressed(cmd: &mut Command) -> bool {
391 let output = match cmd.output() {
392 Ok(status) => status,
393 Err(e) => fail(&format!("failed to execute command: {:?}\nerror: {}", cmd, e)),
395 if !output.status.success() {
397 "\n\ncommand did not execute successfully: {:?}\n\
398 expected success, got: {}\n\n\
400 stderr ----\n{}\n\n",
403 String::from_utf8_lossy(&output.stdout),
404 String::from_utf8_lossy(&output.stderr)
407 output.status.success()
410 pub fn make(host: &str) -> PathBuf {
411 if host.contains("dragonfly")
412 || host.contains("freebsd")
413 || host.contains("netbsd")
414 || host.contains("openbsd")
416 PathBuf::from("gmake")
418 PathBuf::from("make")
423 pub fn output(cmd: &mut Command) -> String {
424 let output = match cmd.stderr(Stdio::inherit()).output() {
425 Ok(status) => status,
426 Err(e) => fail(&format!("failed to execute command: {:?}\nerror: {}", cmd, e)),
428 if !output.status.success() {
430 "command did not execute successfully: {:?}\n\
431 expected success, got: {}",
435 String::from_utf8(output.stdout).unwrap()
438 /// Returns the last-modified time for `path`, or zero if it doesn't exist.
439 pub fn mtime(path: &Path) -> SystemTime {
440 fs::metadata(path).and_then(|f| f.modified()).unwrap_or(UNIX_EPOCH)
443 /// Returns `true` if `dst` is up to date given that the file or files in `src`
444 /// are used to generate it.
446 /// Uses last-modified time checks to verify this.
447 pub fn up_to_date(src: &Path, dst: &Path) -> bool {
451 let threshold = mtime(dst);
452 let meta = match fs::metadata(src) {
454 Err(e) => panic!("source {:?} failed to get metadata: {}", src, e),
457 dir_up_to_date(src, threshold)
459 meta.modified().unwrap_or(UNIX_EPOCH) <= threshold
463 fn dir_up_to_date(src: &Path, threshold: SystemTime) -> bool {
464 t!(fs::read_dir(src)).map(|e| t!(e)).all(|e| {
465 let meta = t!(e.metadata());
467 dir_up_to_date(&e.path(), threshold)
469 meta.modified().unwrap_or(UNIX_EPOCH) < threshold
474 fn fail(s: &str) -> ! {
475 eprintln!("\n\n{}\n\n", s);
476 crate::detail_exit(1);
479 /// Copied from `std::path::absolute` until it stabilizes.
481 /// FIXME: this shouldn't exist.
482 pub(crate) fn absolute(path: &Path) -> PathBuf {
483 if path.as_os_str().is_empty() {
484 panic!("can't make empty path absolute");
488 t!(absolute_unix(path), format!("could not make path absolute: {}", path.display()))
492 t!(absolute_windows(path), format!("could not make path absolute: {}", path.display()))
494 #[cfg(not(any(unix, windows)))]
496 println!("warning: bootstrap is not supported on non-unix platforms");
497 t!(std::fs::canonicalize(t!(std::env::current_dir()))).join(path)
502 /// Make a POSIX path absolute without changing its semantics.
503 fn absolute_unix(path: &Path) -> io::Result<PathBuf> {
504 // This is mostly a wrapper around collecting `Path::components`, with
505 // exceptions made where this conflicts with the POSIX specification.
506 // See 4.13 Pathname Resolution, IEEE Std 1003.1-2017
507 // https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_13
509 use std::os::unix::prelude::OsStrExt;
510 let mut components = path.components();
511 let path_os = path.as_os_str().as_bytes();
513 let mut normalized = if path.is_absolute() {
514 // "If a pathname begins with two successive <slash> characters, the
515 // first component following the leading <slash> characters may be
516 // interpreted in an implementation-defined manner, although more than
517 // two leading <slash> characters shall be treated as a single <slash>
519 if path_os.starts_with(b"//") && !path_os.starts_with(b"///") {
528 normalized.extend(components);
530 // "Interfaces using pathname resolution may specify additional constraints
531 // when a pathname that does not name an existing directory contains at
532 // least one non- <slash> character and contains one or more trailing
533 // <slash> characters".
534 // A trailing <slash> is also meaningful if "a symbolic link is
535 // encountered during pathname resolution".
537 if path_os.ends_with(b"/") {
545 fn absolute_windows(path: &std::path::Path) -> std::io::Result<std::path::PathBuf> {
546 use std::ffi::OsString;
548 use std::os::windows::ffi::{OsStrExt, OsStringExt};
549 use std::ptr::null_mut;
550 #[link(name = "kernel32")]
553 lpFileName: *const u16,
556 lpFilePart: *mut *const u16,
561 // encode the path as UTF-16
562 let path: Vec<u16> = path.as_os_str().encode_wide().chain([0]).collect();
563 let mut buffer = Vec::new();
564 // Loop until either success or failure.
566 // Try to get the absolute path
567 let len = GetFullPathNameW(
569 buffer.len().try_into().unwrap(),
575 0 => return Err(Error::last_os_error()),
576 // Buffer is too small, resize.
577 len if len > buffer.len() => buffer.resize(len, 0),
580 buffer.truncate(len);
581 return Ok(OsString::from_wide(&buffer).into());
588 /// Adapted from https://github.com/llvm/llvm-project/blob/782e91224601e461c019e0a4573bbccc6094fbcd/llvm/cmake/modules/HandleLLVMOptions.cmake#L1058-L1079
590 /// When `clang-cl` is used with instrumentation, we need to add clang's runtime library resource
591 /// directory to the linker flags, otherwise there will be linker errors about the profiler runtime
592 /// missing. This function returns the path to that directory.
593 pub fn get_clang_cl_resource_dir(clang_cl_path: &str) -> PathBuf {
594 // Similar to how LLVM does it, to find clang's library runtime directory:
595 // - we ask `clang-cl` to locate the `clang_rt.builtins` lib.
596 let mut builtins_locator = Command::new(clang_cl_path);
597 builtins_locator.args(&["/clang:-print-libgcc-file-name", "/clang:--rtlib=compiler-rt"]);
599 let clang_rt_builtins = output(&mut builtins_locator);
600 let clang_rt_builtins = Path::new(clang_rt_builtins.trim());
602 clang_rt_builtins.exists(),
603 "`clang-cl` must correctly locate the library runtime directory"
606 // - the profiler runtime will be located in the same directory as the builtins lib, like
607 // `$LLVM_DISTRO_ROOT/lib/clang/$LLVM_VERSION/lib/windows`.
608 let clang_rt_dir = clang_rt_builtins.parent().expect("The clang lib folder should exist");
609 clang_rt_dir.to_path_buf()
612 pub fn lld_flag_no_threads(is_windows: bool) -> &'static str {
613 static LLD_NO_THREADS: OnceCell<(&'static str, &'static str)> = OnceCell::new();
614 let (windows, other) = LLD_NO_THREADS.get_or_init(|| {
615 let out = output(Command::new("lld").arg("-flavor").arg("ld").arg("--version"));
616 let newer = match (out.find(char::is_numeric), out.find('.')) {
617 (Some(b), Some(e)) => out.as_str()[b..e].parse::<i32>().ok().unwrap_or(14) > 10,
620 if newer { ("/threads:1", "--threads=1") } else { ("/no-threads", "--no-threads") }
622 if is_windows { windows } else { other }