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};
17 /// A helper macro to `unwrap` a result except also print out details like:
19 /// * The file/line of the panic
20 /// * The expression that failed
21 /// * The error itself
23 /// This is currently used judiciously throughout the build system rather than
24 /// using a `Result` with `try!`, but this may change one day...
30 Err(e) => panic!("{} failed with {}", stringify!($e), e),
33 // it can show extra info in the second parameter
34 ($e:expr, $extra:expr) => {
37 Err(e) => panic!("{} failed with {} ({:?})", stringify!($e), e, $extra),
43 /// Given an executable called `name`, return the filename for the
44 /// executable for a particular target.
45 pub fn exe(name: &str, target: TargetSelection) -> String {
46 if target.contains("windows") { format!("{}.exe", name) } else { name.to_string() }
49 /// Returns `true` if the file name given looks like a dynamic library.
50 pub fn is_dylib(name: &str) -> bool {
51 name.ends_with(".dylib") || name.ends_with(".so") || name.ends_with(".dll")
54 /// Returns `true` if the file name given looks like a debug info file
55 pub fn is_debug_info(name: &str) -> bool {
56 // FIXME: consider split debug info on other platforms (e.g., Linux, macOS)
57 name.ends_with(".pdb")
60 /// Returns the corresponding relative library directory that the compiler's
61 /// dylibs will be found in.
62 pub fn libdir(target: TargetSelection) -> &'static str {
63 if target.contains("windows") { "bin" } else { "lib" }
66 /// Adds a list of lookup paths to `cmd`'s dynamic library lookup path.
67 /// If the dylib_path_var is already set for this cmd, the old value will be overwritten!
68 pub fn add_dylib_path(path: Vec<PathBuf>, cmd: &mut Command) {
69 let mut list = dylib_path();
73 cmd.env(dylib_path_var(), t!(env::join_paths(list)));
76 include!("dylib_util.rs");
78 /// Adds a list of lookup paths to `cmd`'s link library lookup path.
79 pub fn add_link_lib_path(path: Vec<PathBuf>, cmd: &mut Command) {
80 let mut list = link_lib_path();
84 cmd.env(link_lib_path_var(), t!(env::join_paths(list)));
87 /// Returns the environment variable which the link library lookup path
88 /// resides in for this platform.
89 fn link_lib_path_var() -> &'static str {
90 if cfg!(target_env = "msvc") { "LIB" } else { "LIBRARY_PATH" }
93 /// Parses the `link_lib_path_var()` environment variable, returning a list of
94 /// paths that are members of this lookup path.
95 fn link_lib_path() -> Vec<PathBuf> {
96 let var = match env::var_os(link_lib_path_var()) {
98 None => return vec![],
100 env::split_paths(&var).collect()
103 pub struct TimeIt(bool, Instant);
105 /// Returns an RAII structure that prints out how long it took to drop.
106 pub fn timeit(builder: &Builder<'_>) -> TimeIt {
107 TimeIt(builder.config.dry_run, Instant::now())
110 impl Drop for TimeIt {
112 let time = self.1.elapsed();
114 println!("\tfinished in {}.{:03} seconds", time.as_secs(), time.subsec_millis());
119 /// Used for download caching
120 pub(crate) fn program_out_of_date(stamp: &Path, key: &str) -> bool {
124 t!(fs::read_to_string(stamp)) != key
127 /// Symlinks two directories, using junctions on Windows and normal symlinks on
129 pub fn symlink_dir(config: &Config, src: &Path, dest: &Path) -> io::Result<()> {
133 let _ = fs::remove_dir(dest);
134 return symlink_dir_inner(src, dest);
137 fn symlink_dir_inner(src: &Path, dest: &Path) -> io::Result<()> {
138 use std::os::unix::fs;
139 fs::symlink(src, dest)
142 // Creating a directory junction on windows involves dealing with reparse
143 // points and the DeviceIoControl function, and this code is a skeleton of
144 // what can be found here:
146 // http://www.flexhex.com/docs/articles/hard-links.phtml
148 fn symlink_dir_inner(target: &Path, junction: &Path) -> io::Result<()> {
150 use std::os::windows::ffi::OsStrExt;
153 use winapi::shared::minwindef::{DWORD, WORD};
154 use winapi::um::fileapi::{CreateFileW, OPEN_EXISTING};
155 use winapi::um::handleapi::CloseHandle;
156 use winapi::um::ioapiset::DeviceIoControl;
157 use winapi::um::winbase::{FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT};
158 use winapi::um::winioctl::FSCTL_SET_REPARSE_POINT;
159 use winapi::um::winnt::{
160 FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE, GENERIC_WRITE,
161 IO_REPARSE_TAG_MOUNT_POINT, MAXIMUM_REPARSE_DATA_BUFFER_SIZE, WCHAR,
164 #[allow(non_snake_case)]
166 struct REPARSE_MOUNTPOINT_DATA_BUFFER {
168 ReparseDataLength: DWORD,
170 ReparseTargetLength: WORD,
171 ReparseTargetMaximumLength: WORD,
173 ReparseTarget: WCHAR,
176 fn to_u16s<S: AsRef<OsStr>>(s: S) -> io::Result<Vec<u16>> {
177 Ok(s.as_ref().encode_wide().chain(Some(0)).collect())
180 // We're using low-level APIs to create the junction, and these are more
181 // picky about paths. For example, forward slashes cannot be used as a
182 // path separator, so we should try to canonicalize the path first.
183 let target = fs::canonicalize(target)?;
185 fs::create_dir(junction)?;
187 let path = to_u16s(junction)?;
193 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
196 FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS,
200 let mut data = [0u8; MAXIMUM_REPARSE_DATA_BUFFER_SIZE as usize];
201 let db = data.as_mut_ptr() as *mut REPARSE_MOUNTPOINT_DATA_BUFFER;
202 let buf = &mut (*db).ReparseTarget as *mut u16;
204 // FIXME: this conversion is very hacky
206 let v = v.iter().map(|x| *x as u16);
207 for c in v.chain(target.as_os_str().encode_wide().skip(4)) {
213 (*db).ReparseTag = IO_REPARSE_TAG_MOUNT_POINT;
214 (*db).ReparseTargetMaximumLength = (i * 2) as WORD;
215 (*db).ReparseTargetLength = ((i - 1) * 2) as WORD;
216 (*db).ReparseDataLength = (*db).ReparseTargetLength as DWORD + 12;
219 let res = DeviceIoControl(
221 FSCTL_SET_REPARSE_POINT,
222 data.as_ptr() as *mut _,
223 (*db).ReparseDataLength + 8,
230 let out = if res == 0 { Err(io::Error::last_os_error()) } else { Ok(()) };
237 /// The CI environment rustbuild is running in. This mainly affects how the logs
239 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
241 /// Not a CI environment.
243 /// The Azure Pipelines environment, for Linux (including Docker), Windows, and macOS builds.
245 /// The GitHub Actions environment, for Linux (including Docker), Windows and macOS builds.
250 /// Obtains the current CI environment.
251 pub fn current() -> CiEnv {
252 if env::var("TF_BUILD").map_or(false, |e| e == "True") {
253 CiEnv::AzurePipelines
254 } else if env::var("GITHUB_ACTIONS").map_or(false, |e| e == "true") {
261 /// If in a CI environment, forces the command to run with colors.
262 pub fn force_coloring_in_ci(self, cmd: &mut Command) {
263 if self != CiEnv::None {
264 // Due to use of stamp/docker, the output stream of rustbuild is not
265 // a TTY in CI, so coloring is by-default turned off.
266 // The explicit `TERM=xterm` environment is needed for
267 // `--color always` to actually work. This env var was lost when
268 // compiling through the Makefile. Very strange.
269 cmd.env("TERM", "xterm").args(&["--color", "always"]);
274 pub fn forcing_clang_based_tests() -> bool {
275 if let Some(var) = env::var_os("RUSTBUILD_FORCE_CLANG_BASED_TESTS") {
276 match &var.to_string_lossy().to_lowercase()[..] {
277 "1" | "yes" | "on" => true,
278 "0" | "no" | "off" => false,
280 // Let's make sure typos don't go unnoticed
282 "Unrecognized option '{}' set in \
283 RUSTBUILD_FORCE_CLANG_BASED_TESTS",
293 pub fn use_host_linker(target: TargetSelection) -> bool {
294 // FIXME: this information should be gotten by checking the linker flavor
295 // of the rustc target
296 !(target.contains("emscripten")
297 || target.contains("wasm32")
298 || target.contains("nvptx")
299 || target.contains("fortanix")
300 || target.contains("fuchsia")
301 || target.contains("bpf"))
304 pub fn is_valid_test_suite_arg<'a, P: AsRef<Path>>(
307 builder: &Builder<'_>,
308 ) -> Option<&'a str> {
309 let suite_path = suite_path.as_ref();
310 let path = match path.strip_prefix(".") {
314 if !path.starts_with(suite_path) {
317 let abs_path = builder.src.join(path);
318 let exists = abs_path.is_dir() || abs_path.is_file();
321 "Invalid test suite filter \"{}\": file or directory does not exist",
325 // Since test suite paths are themselves directories, if we don't
326 // specify a directory or file, we'll get an empty string here
327 // (the result of the test suite directory without its suite prefix).
328 // Therefore, we need to filter these out, as only the first --test-args
329 // flag is respected, so providing an empty --test-args conflicts with
331 match path.strip_prefix(suite_path).ok().and_then(|p| p.to_str()) {
332 Some(s) if !s.is_empty() => Some(s),
337 pub fn run(cmd: &mut Command, print_cmd_on_fail: bool) {
338 if !try_run(cmd, print_cmd_on_fail) {
339 crate::detail_exit(1);
343 pub fn try_run(cmd: &mut Command, print_cmd_on_fail: bool) -> bool {
344 let status = match cmd.status() {
345 Ok(status) => status,
346 Err(e) => fail(&format!("failed to execute command: {:?}\nerror: {}", cmd, e)),
348 if !status.success() && print_cmd_on_fail {
350 "\n\ncommand did not execute successfully: {:?}\n\
351 expected success, got: {}\n\n",
358 pub fn check_run(cmd: &mut Command, print_cmd_on_fail: bool) -> bool {
359 let status = match cmd.status() {
360 Ok(status) => status,
362 println!("failed to execute command: {:?}\nerror: {}", cmd, e);
366 if !status.success() && print_cmd_on_fail {
368 "\n\ncommand did not execute successfully: {:?}\n\
369 expected success, got: {}\n\n",
376 pub fn run_suppressed(cmd: &mut Command) {
377 if !try_run_suppressed(cmd) {
378 crate::detail_exit(1);
382 pub fn try_run_suppressed(cmd: &mut Command) -> bool {
383 let output = match cmd.output() {
384 Ok(status) => status,
385 Err(e) => fail(&format!("failed to execute command: {:?}\nerror: {}", cmd, e)),
387 if !output.status.success() {
389 "\n\ncommand did not execute successfully: {:?}\n\
390 expected success, got: {}\n\n\
392 stderr ----\n{}\n\n",
395 String::from_utf8_lossy(&output.stdout),
396 String::from_utf8_lossy(&output.stderr)
399 output.status.success()
402 pub fn make(host: &str) -> PathBuf {
403 if host.contains("dragonfly")
404 || host.contains("freebsd")
405 || host.contains("netbsd")
406 || host.contains("openbsd")
408 PathBuf::from("gmake")
410 PathBuf::from("make")
415 pub fn output(cmd: &mut Command) -> String {
416 let output = match cmd.stderr(Stdio::inherit()).output() {
417 Ok(status) => status,
418 Err(e) => fail(&format!("failed to execute command: {:?}\nerror: {}", cmd, e)),
420 if !output.status.success() {
422 "command did not execute successfully: {:?}\n\
423 expected success, got: {}",
427 String::from_utf8(output.stdout).unwrap()
430 /// Returns the last-modified time for `path`, or zero if it doesn't exist.
431 pub fn mtime(path: &Path) -> SystemTime {
432 fs::metadata(path).and_then(|f| f.modified()).unwrap_or(UNIX_EPOCH)
435 /// Returns `true` if `dst` is up to date given that the file or files in `src`
436 /// are used to generate it.
438 /// Uses last-modified time checks to verify this.
439 pub fn up_to_date(src: &Path, dst: &Path) -> bool {
443 let threshold = mtime(dst);
444 let meta = match fs::metadata(src) {
446 Err(e) => panic!("source {:?} failed to get metadata: {}", src, e),
449 dir_up_to_date(src, threshold)
451 meta.modified().unwrap_or(UNIX_EPOCH) <= threshold
455 fn dir_up_to_date(src: &Path, threshold: SystemTime) -> bool {
456 t!(fs::read_dir(src)).map(|e| t!(e)).all(|e| {
457 let meta = t!(e.metadata());
459 dir_up_to_date(&e.path(), threshold)
461 meta.modified().unwrap_or(UNIX_EPOCH) < threshold
466 fn fail(s: &str) -> ! {
467 eprintln!("\n\n{}\n\n", s);
468 crate::detail_exit(1);
471 /// Copied from `std::path::absolute` until it stabilizes.
473 /// FIXME: this shouldn't exist.
474 pub(crate) fn absolute(path: &Path) -> PathBuf {
475 if path.as_os_str().is_empty() {
476 panic!("can't make empty path absolute");
480 t!(absolute_unix(path), format!("could not make path absolute: {}", path.display()))
484 t!(absolute_windows(path), format!("could not make path absolute: {}", path.display()))
486 #[cfg(not(any(unix, windows)))]
488 println!("warning: bootstrap is not supported on non-unix platforms");
489 t!(std::fs::canonicalize(t!(std::env::current_dir()))).join(path)
494 /// Make a POSIX path absolute without changing its semantics.
495 fn absolute_unix(path: &Path) -> io::Result<PathBuf> {
496 // This is mostly a wrapper around collecting `Path::components`, with
497 // exceptions made where this conflicts with the POSIX specification.
498 // See 4.13 Pathname Resolution, IEEE Std 1003.1-2017
499 // https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_13
501 use std::os::unix::prelude::OsStrExt;
502 let mut components = path.components();
503 let path_os = path.as_os_str().as_bytes();
505 let mut normalized = if path.is_absolute() {
506 // "If a pathname begins with two successive <slash> characters, the
507 // first component following the leading <slash> characters may be
508 // interpreted in an implementation-defined manner, although more than
509 // two leading <slash> characters shall be treated as a single <slash>
511 if path_os.starts_with(b"//") && !path_os.starts_with(b"///") {
520 normalized.extend(components);
522 // "Interfaces using pathname resolution may specify additional constraints
523 // when a pathname that does not name an existing directory contains at
524 // least one non- <slash> character and contains one or more trailing
525 // <slash> characters".
526 // A trailing <slash> is also meaningful if "a symbolic link is
527 // encountered during pathname resolution".
529 if path_os.ends_with(b"/") {
537 fn absolute_windows(path: &std::path::Path) -> std::io::Result<std::path::PathBuf> {
538 use std::ffi::OsString;
540 use std::os::windows::ffi::{OsStrExt, OsStringExt};
541 use std::ptr::null_mut;
542 #[link(name = "kernel32")]
545 lpFileName: *const u16,
548 lpFilePart: *mut *const u16,
553 // encode the path as UTF-16
554 let path: Vec<u16> = path.as_os_str().encode_wide().chain([0]).collect();
555 let mut buffer = Vec::new();
556 // Loop until either success or failure.
558 // Try to get the absolute path
559 let len = GetFullPathNameW(
561 buffer.len().try_into().unwrap(),
567 0 => return Err(Error::last_os_error()),
568 // Buffer is too small, resize.
569 len if len > buffer.len() => buffer.resize(len, 0),
572 buffer.truncate(len);
573 return Ok(OsString::from_wide(&buffer).into());