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...
29 Err(e) => panic!("{} failed with {}", stringify!($e), e),
32 // it can show extra info in the second parameter
33 ($e:expr, $extra:expr) => {
36 Err(e) => panic!("{} failed with {} ({:?})", stringify!($e), e, $extra),
42 /// Given an executable called `name`, return the filename for the
43 /// executable for a particular target.
44 pub fn exe(name: &str, target: TargetSelection) -> String {
45 if target.contains("windows") { format!("{}.exe", name) } else { name.to_string() }
48 /// Returns `true` if the file name given looks like a dynamic library.
49 pub fn is_dylib(name: &str) -> bool {
50 name.ends_with(".dylib") || name.ends_with(".so") || name.ends_with(".dll")
53 /// Returns `true` if the file name given looks like a debug info file
54 pub fn is_debug_info(name: &str) -> bool {
55 // FIXME: consider split debug info on other platforms (e.g., Linux, macOS)
56 name.ends_with(".pdb")
59 /// Returns the corresponding relative library directory that the compiler's
60 /// dylibs will be found in.
61 pub fn libdir(target: TargetSelection) -> &'static str {
62 if target.contains("windows") { "bin" } else { "lib" }
65 /// Adds a list of lookup paths to `cmd`'s dynamic library lookup path.
66 /// If the dylib_path_var is already set for this cmd, the old value will be overwritten!
67 pub fn add_dylib_path(path: Vec<PathBuf>, cmd: &mut Command) {
68 let mut list = dylib_path();
72 cmd.env(dylib_path_var(), t!(env::join_paths(list)));
75 include!("dylib_util.rs");
77 /// Adds a list of lookup paths to `cmd`'s link library lookup path.
78 pub fn add_link_lib_path(path: Vec<PathBuf>, cmd: &mut Command) {
79 let mut list = link_lib_path();
83 cmd.env(link_lib_path_var(), t!(env::join_paths(list)));
86 /// Returns the environment variable which the link library lookup path
87 /// resides in for this platform.
88 fn link_lib_path_var() -> &'static str {
89 if cfg!(target_env = "msvc") { "LIB" } else { "LIBRARY_PATH" }
92 /// Parses the `link_lib_path_var()` environment variable, returning a list of
93 /// paths that are members of this lookup path.
94 fn link_lib_path() -> Vec<PathBuf> {
95 let var = match env::var_os(link_lib_path_var()) {
97 None => return vec![],
99 env::split_paths(&var).collect()
102 pub struct TimeIt(bool, Instant);
104 /// Returns an RAII structure that prints out how long it took to drop.
105 pub fn timeit(builder: &Builder<'_>) -> TimeIt {
106 TimeIt(builder.config.dry_run, Instant::now())
109 impl Drop for TimeIt {
111 let time = self.1.elapsed();
113 println!("\tfinished in {}.{:03} seconds", time.as_secs(), time.subsec_millis());
118 /// Used for download caching
119 pub(crate) fn program_out_of_date(stamp: &Path, key: &str) -> bool {
123 t!(fs::read_to_string(stamp)) != key
126 /// Symlinks two directories, using junctions on Windows and normal symlinks on
128 pub fn symlink_dir(config: &Config, src: &Path, dest: &Path) -> io::Result<()> {
132 let _ = fs::remove_dir(dest);
133 return symlink_dir_inner(src, dest);
136 fn symlink_dir_inner(src: &Path, dest: &Path) -> io::Result<()> {
137 use std::os::unix::fs;
138 fs::symlink(src, dest)
141 // Creating a directory junction on windows involves dealing with reparse
142 // points and the DeviceIoControl function, and this code is a skeleton of
143 // what can be found here:
145 // http://www.flexhex.com/docs/articles/hard-links.phtml
147 fn symlink_dir_inner(target: &Path, junction: &Path) -> io::Result<()> {
149 use std::os::windows::ffi::OsStrExt;
152 use winapi::shared::minwindef::{DWORD, WORD};
153 use winapi::um::fileapi::{CreateFileW, OPEN_EXISTING};
154 use winapi::um::handleapi::CloseHandle;
155 use winapi::um::ioapiset::DeviceIoControl;
156 use winapi::um::winbase::{FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT};
157 use winapi::um::winioctl::FSCTL_SET_REPARSE_POINT;
158 use winapi::um::winnt::{
159 FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE, GENERIC_WRITE,
160 IO_REPARSE_TAG_MOUNT_POINT, MAXIMUM_REPARSE_DATA_BUFFER_SIZE, WCHAR,
163 #[allow(non_snake_case)]
165 struct REPARSE_MOUNTPOINT_DATA_BUFFER {
167 ReparseDataLength: DWORD,
169 ReparseTargetLength: WORD,
170 ReparseTargetMaximumLength: WORD,
172 ReparseTarget: WCHAR,
175 fn to_u16s<S: AsRef<OsStr>>(s: S) -> io::Result<Vec<u16>> {
176 Ok(s.as_ref().encode_wide().chain(Some(0)).collect())
179 // We're using low-level APIs to create the junction, and these are more
180 // picky about paths. For example, forward slashes cannot be used as a
181 // path separator, so we should try to canonicalize the path first.
182 let target = fs::canonicalize(target)?;
184 fs::create_dir(junction)?;
186 let path = to_u16s(junction)?;
192 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
195 FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS,
199 let mut data = [0u8; MAXIMUM_REPARSE_DATA_BUFFER_SIZE as usize];
200 let db = data.as_mut_ptr() as *mut REPARSE_MOUNTPOINT_DATA_BUFFER;
201 let buf = &mut (*db).ReparseTarget as *mut u16;
203 // FIXME: this conversion is very hacky
205 let v = v.iter().map(|x| *x as u16);
206 for c in v.chain(target.as_os_str().encode_wide().skip(4)) {
212 (*db).ReparseTag = IO_REPARSE_TAG_MOUNT_POINT;
213 (*db).ReparseTargetMaximumLength = (i * 2) as WORD;
214 (*db).ReparseTargetLength = ((i - 1) * 2) as WORD;
215 (*db).ReparseDataLength = (*db).ReparseTargetLength as DWORD + 12;
218 let res = DeviceIoControl(
220 FSCTL_SET_REPARSE_POINT,
221 data.as_ptr() as *mut _,
222 (*db).ReparseDataLength + 8,
229 let out = if res == 0 { Err(io::Error::last_os_error()) } else { Ok(()) };
236 /// The CI environment rustbuild is running in. This mainly affects how the logs
238 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
240 /// Not a CI environment.
242 /// The Azure Pipelines environment, for Linux (including Docker), Windows, and macOS builds.
244 /// The GitHub Actions environment, for Linux (including Docker), Windows and macOS builds.
249 /// Obtains the current CI environment.
250 pub fn current() -> CiEnv {
251 if env::var("TF_BUILD").map_or(false, |e| e == "True") {
252 CiEnv::AzurePipelines
253 } else if env::var("GITHUB_ACTIONS").map_or(false, |e| e == "true") {
260 /// If in a CI environment, forces the command to run with colors.
261 pub fn force_coloring_in_ci(self, cmd: &mut Command) {
262 if self != CiEnv::None {
263 // Due to use of stamp/docker, the output stream of rustbuild is not
264 // a TTY in CI, so coloring is by-default turned off.
265 // The explicit `TERM=xterm` environment is needed for
266 // `--color always` to actually work. This env var was lost when
267 // compiling through the Makefile. Very strange.
268 cmd.env("TERM", "xterm").args(&["--color", "always"]);
273 pub fn forcing_clang_based_tests() -> bool {
274 if let Some(var) = env::var_os("RUSTBUILD_FORCE_CLANG_BASED_TESTS") {
275 match &var.to_string_lossy().to_lowercase()[..] {
276 "1" | "yes" | "on" => true,
277 "0" | "no" | "off" => false,
279 // Let's make sure typos don't go unnoticed
281 "Unrecognized option '{}' set in \
282 RUSTBUILD_FORCE_CLANG_BASED_TESTS",
292 pub fn use_host_linker(target: TargetSelection) -> bool {
293 // FIXME: this information should be gotten by checking the linker flavor
294 // of the rustc target
295 !(target.contains("emscripten")
296 || target.contains("wasm32")
297 || target.contains("nvptx")
298 || target.contains("fortanix")
299 || target.contains("fuchsia")
300 || target.contains("bpf"))
303 pub fn is_valid_test_suite_arg<'a, P: AsRef<Path>>(
306 builder: &Builder<'_>,
307 ) -> Option<&'a str> {
308 let suite_path = suite_path.as_ref();
309 let path = match path.strip_prefix(".") {
313 if !path.starts_with(suite_path) {
316 let abs_path = builder.src.join(path);
317 let exists = abs_path.is_dir() || abs_path.is_file();
320 "Invalid test suite filter \"{}\": file or directory does not exist",
324 // Since test suite paths are themselves directories, if we don't
325 // specify a directory or file, we'll get an empty string here
326 // (the result of the test suite directory without its suite prefix).
327 // Therefore, we need to filter these out, as only the first --test-args
328 // flag is respected, so providing an empty --test-args conflicts with
330 match path.strip_prefix(suite_path).ok().and_then(|p| p.to_str()) {
331 Some(s) if !s.is_empty() => Some(s),
336 pub fn run(cmd: &mut Command, print_cmd_on_fail: bool) {
337 if !try_run(cmd, print_cmd_on_fail) {
338 std::process::exit(1);
342 pub fn try_run(cmd: &mut Command, print_cmd_on_fail: bool) -> bool {
343 let status = match cmd.status() {
344 Ok(status) => status,
345 Err(e) => fail(&format!("failed to execute command: {:?}\nerror: {}", cmd, e)),
347 if !status.success() && print_cmd_on_fail {
349 "\n\ncommand did not execute successfully: {:?}\n\
350 expected success, got: {}\n\n",
357 pub fn check_run(cmd: &mut Command, print_cmd_on_fail: bool) -> bool {
358 let status = match cmd.status() {
359 Ok(status) => status,
361 println!("failed to execute command: {:?}\nerror: {}", cmd, e);
365 if !status.success() && print_cmd_on_fail {
367 "\n\ncommand did not execute successfully: {:?}\n\
368 expected success, got: {}\n\n",
375 pub fn run_suppressed(cmd: &mut Command) {
376 if !try_run_suppressed(cmd) {
377 std::process::exit(1);
381 pub fn try_run_suppressed(cmd: &mut Command) -> bool {
382 let output = match cmd.output() {
383 Ok(status) => status,
384 Err(e) => fail(&format!("failed to execute command: {:?}\nerror: {}", cmd, e)),
386 if !output.status.success() {
388 "\n\ncommand did not execute successfully: {:?}\n\
389 expected success, got: {}\n\n\
391 stderr ----\n{}\n\n",
394 String::from_utf8_lossy(&output.stdout),
395 String::from_utf8_lossy(&output.stderr)
398 output.status.success()
401 pub fn make(host: &str) -> PathBuf {
402 if host.contains("dragonfly")
403 || host.contains("freebsd")
404 || host.contains("netbsd")
405 || host.contains("openbsd")
407 PathBuf::from("gmake")
409 PathBuf::from("make")
414 pub fn output(cmd: &mut Command) -> String {
415 let output = match cmd.stderr(Stdio::inherit()).output() {
416 Ok(status) => status,
417 Err(e) => fail(&format!("failed to execute command: {:?}\nerror: {}", cmd, e)),
419 if !output.status.success() {
421 "command did not execute successfully: {:?}\n\
422 expected success, got: {}",
426 String::from_utf8(output.stdout).unwrap()
429 /// Returns the last-modified time for `path`, or zero if it doesn't exist.
430 pub fn mtime(path: &Path) -> SystemTime {
431 fs::metadata(path).and_then(|f| f.modified()).unwrap_or(UNIX_EPOCH)
434 /// Returns `true` if `dst` is up to date given that the file or files in `src`
435 /// are used to generate it.
437 /// Uses last-modified time checks to verify this.
438 pub fn up_to_date(src: &Path, dst: &Path) -> bool {
442 let threshold = mtime(dst);
443 let meta = match fs::metadata(src) {
445 Err(e) => panic!("source {:?} failed to get metadata: {}", src, e),
448 dir_up_to_date(src, threshold)
450 meta.modified().unwrap_or(UNIX_EPOCH) <= threshold
454 fn dir_up_to_date(src: &Path, threshold: SystemTime) -> bool {
455 t!(fs::read_dir(src)).map(|e| t!(e)).all(|e| {
456 let meta = t!(e.metadata());
458 dir_up_to_date(&e.path(), threshold)
460 meta.modified().unwrap_or(UNIX_EPOCH) < threshold
465 fn fail(s: &str) -> ! {
466 eprintln!("\n\n{}\n\n", s);
467 std::process::exit(1);
470 /// Copied from `std::path::absolute` until it stabilizes.
472 /// FIXME: this shouldn't exist.
473 pub(crate) fn absolute(path: &Path) -> PathBuf {
474 if path.as_os_str().is_empty() {
475 panic!("can't make empty path absolute");
479 t!(absolute_unix(path), format!("could not make path absolute: {}", path.display()))
483 t!(absolute_windows(path), format!("could not make path absolute: {}", path.display()))
485 #[cfg(not(any(unix, windows)))]
487 println!("warning: bootstrap is not supported on non-unix platforms");
488 t!(std::fs::canonicalize(t!(std::env::current_dir()))).join(path)
493 /// Make a POSIX path absolute without changing its semantics.
494 fn absolute_unix(path: &Path) -> io::Result<PathBuf> {
495 // This is mostly a wrapper around collecting `Path::components`, with
496 // exceptions made where this conflicts with the POSIX specification.
497 // See 4.13 Pathname Resolution, IEEE Std 1003.1-2017
498 // https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_13
500 use std::os::unix::prelude::OsStrExt;
501 let mut components = path.components();
502 let path_os = path.as_os_str().as_bytes();
504 let mut normalized = if path.is_absolute() {
505 // "If a pathname begins with two successive <slash> characters, the
506 // first component following the leading <slash> characters may be
507 // interpreted in an implementation-defined manner, although more than
508 // two leading <slash> characters shall be treated as a single <slash>
510 if path_os.starts_with(b"//") && !path_os.starts_with(b"///") {
519 normalized.extend(components);
521 // "Interfaces using pathname resolution may specify additional constraints
522 // when a pathname that does not name an existing directory contains at
523 // least one non- <slash> character and contains one or more trailing
524 // <slash> characters".
525 // A trailing <slash> is also meaningful if "a symbolic link is
526 // encountered during pathname resolution".
528 if path_os.ends_with(b"/") {
536 fn absolute_windows(path: &std::path::Path) -> std::io::Result<std::path::PathBuf> {
537 use std::ffi::OsString;
539 use std::os::windows::ffi::{OsStrExt, OsStringExt};
540 use std::ptr::null_mut;
541 #[link(name = "kernel32")]
544 lpFileName: *const u16,
547 lpFilePart: *mut *const u16,
552 // encode the path as UTF-16
553 let path: Vec<u16> = path.as_os_str().encode_wide().chain([0]).collect();
554 let mut buffer = Vec::new();
555 // Loop until either success or failure.
557 // Try to get the absolute path
558 let len = GetFullPathNameW(
560 buffer.len().try_into().unwrap(),
566 0 => return Err(Error::last_os_error()),
567 // Buffer is too small, resize.
568 len if len > buffer.len() => buffer.resize(len, 0),
571 buffer.truncate(len);
572 return Ok(OsString::from_wide(&buffer).into());