]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/util.rs
Bump ui_test crate
[rust.git] / src / bootstrap / util.rs
1 //! Various utility functions used throughout rustbuild.
2 //!
3 //! Simple things like testing the various filesystem operations here and there,
4 //! not a lot of interesting happenings here unfortunately.
5
6 use std::env;
7 use std::fs;
8 use std::io;
9 use std::path::{Path, PathBuf};
10 use std::process::{Command, Stdio};
11 use std::str;
12 use std::time::{Instant, SystemTime, UNIX_EPOCH};
13
14 use crate::builder::Builder;
15 use crate::config::{Config, TargetSelection};
16 use crate::OnceCell;
17
18 /// A helper macro to `unwrap` a result except also print out details like:
19 ///
20 /// * The file/line of the panic
21 /// * The expression that failed
22 /// * The error itself
23 ///
24 /// This is currently used judiciously throughout the build system rather than
25 /// using a `Result` with `try!`, but this may change one day...
26 #[macro_export]
27 macro_rules! t {
28     ($e:expr) => {
29         match $e {
30             Ok(e) => e,
31             Err(e) => panic!("{} failed with {}", stringify!($e), e),
32         }
33     };
34     // it can show extra info in the second parameter
35     ($e:expr, $extra:expr) => {
36         match $e {
37             Ok(e) => e,
38             Err(e) => panic!("{} failed with {} ({:?})", stringify!($e), e, $extra),
39         }
40     };
41 }
42 pub use t;
43
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)
51     } else {
52         name.to_string()
53     }
54 }
55
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")
59 }
60
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")
65 }
66
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" }
71 }
72
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();
77     for path in path {
78         list.insert(0, path);
79     }
80     cmd.env(dylib_path_var(), t!(env::join_paths(list)));
81 }
82
83 include!("dylib_util.rs");
84
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();
88     for path in path {
89         list.insert(0, path);
90     }
91     cmd.env(link_lib_path_var(), t!(env::join_paths(list)));
92 }
93
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" }
98 }
99
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()) {
104         Some(v) => v,
105         None => return vec![],
106     };
107     env::split_paths(&var).collect()
108 }
109
110 pub struct TimeIt(bool, Instant);
111
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())
115 }
116
117 impl Drop for TimeIt {
118     fn drop(&mut self) {
119         let time = self.1.elapsed();
120         if !self.0 {
121             println!("\tfinished in {}.{:03} seconds", time.as_secs(), time.subsec_millis());
122         }
123     }
124 }
125
126 /// Used for download caching
127 pub(crate) fn program_out_of_date(stamp: &Path, key: &str) -> bool {
128     if !stamp.exists() {
129         return true;
130     }
131     t!(fs::read_to_string(stamp)) != key
132 }
133
134 /// Symlinks two directories, using junctions on Windows and normal symlinks on
135 /// Unix.
136 pub fn symlink_dir(config: &Config, src: &Path, dest: &Path) -> io::Result<()> {
137     if config.dry_run() {
138         return Ok(());
139     }
140     let _ = fs::remove_dir(dest);
141     return symlink_dir_inner(src, dest);
142
143     #[cfg(not(windows))]
144     fn symlink_dir_inner(src: &Path, dest: &Path) -> io::Result<()> {
145         use std::os::unix::fs;
146         fs::symlink(src, dest)
147     }
148
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:
152     //
153     // http://www.flexhex.com/docs/articles/hard-links.phtml
154     #[cfg(windows)]
155     fn symlink_dir_inner(target: &Path, junction: &Path) -> io::Result<()> {
156         use std::ffi::OsStr;
157         use std::os::windows::ffi::OsStrExt;
158         use std::ptr;
159
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,
169         };
170
171         #[allow(non_snake_case)]
172         #[repr(C)]
173         struct REPARSE_MOUNTPOINT_DATA_BUFFER {
174             ReparseTag: DWORD,
175             ReparseDataLength: DWORD,
176             Reserved: WORD,
177             ReparseTargetLength: WORD,
178             ReparseTargetMaximumLength: WORD,
179             Reserved1: WORD,
180             ReparseTarget: WCHAR,
181         }
182
183         fn to_u16s<S: AsRef<OsStr>>(s: S) -> io::Result<Vec<u16>> {
184             Ok(s.as_ref().encode_wide().chain(Some(0)).collect())
185         }
186
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)?;
191
192         fs::create_dir(junction)?;
193
194         let path = to_u16s(junction)?;
195
196         unsafe {
197             let h = CreateFileW(
198                 path.as_ptr(),
199                 GENERIC_WRITE,
200                 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
201                 ptr::null_mut(),
202                 OPEN_EXISTING,
203                 FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS,
204                 ptr::null_mut(),
205             );
206
207             #[repr(C, align(8))]
208             struct Align8<T>(T);
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;
212             let mut i = 0;
213             // FIXME: this conversion is very hacky
214             let v = br"\??\";
215             let v = v.iter().map(|x| *x as u16);
216             for c in v.chain(target.as_os_str().encode_wide().skip(4)) {
217                 *buf.offset(i) = c;
218                 i += 1;
219             }
220             *buf.offset(i) = 0;
221             i += 1;
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;
226
227             let mut ret = 0;
228             let res = DeviceIoControl(
229                 h as *mut _,
230                 FSCTL_SET_REPARSE_POINT,
231                 db.cast(),
232                 (*db).ReparseDataLength + 8,
233                 ptr::null_mut(),
234                 0,
235                 &mut ret,
236                 ptr::null_mut(),
237             );
238
239             let out = if res == 0 { Err(io::Error::last_os_error()) } else { Ok(()) };
240             CloseHandle(h);
241             out
242         }
243     }
244 }
245
246 /// The CI environment rustbuild is running in. This mainly affects how the logs
247 /// are printed.
248 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
249 pub enum CiEnv {
250     /// Not a CI environment.
251     None,
252     /// The Azure Pipelines environment, for Linux (including Docker), Windows, and macOS builds.
253     AzurePipelines,
254     /// The GitHub Actions environment, for Linux (including Docker), Windows and macOS builds.
255     GitHubActions,
256 }
257
258 impl CiEnv {
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") {
264             CiEnv::GitHubActions
265         } else {
266             CiEnv::None
267         }
268     }
269
270     pub fn is_ci() -> bool {
271         Self::current() != CiEnv::None
272     }
273
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"]);
283         }
284     }
285 }
286
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,
292             other => {
293                 // Let's make sure typos don't go unnoticed
294                 panic!(
295                     "Unrecognized option '{}' set in \
296                         RUSTBUILD_FORCE_CLANG_BASED_TESTS",
297                     other
298                 )
299             }
300         }
301     } else {
302         false
303     }
304 }
305
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"))
316 }
317
318 pub fn is_valid_test_suite_arg<'a, P: AsRef<Path>>(
319     path: &'a Path,
320     suite_path: P,
321     builder: &Builder<'_>,
322 ) -> Option<&'a str> {
323     let suite_path = suite_path.as_ref();
324     let path = match path.strip_prefix(".") {
325         Ok(p) => p,
326         Err(_) => path,
327     };
328     if !path.starts_with(suite_path) {
329         return None;
330     }
331     let abs_path = builder.src.join(path);
332     let exists = abs_path.is_dir() || abs_path.is_file();
333     if !exists {
334         panic!(
335             "Invalid test suite filter \"{}\": file or directory does not exist",
336             abs_path.display()
337         );
338     }
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
344     // any following it.
345     match path.strip_prefix(suite_path).ok().and_then(|p| p.to_str()) {
346         Some(s) if !s.is_empty() => Some(s),
347         _ => None,
348     }
349 }
350
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);
354     }
355 }
356
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)),
361     };
362     if !status.success() && print_cmd_on_fail {
363         println!(
364             "\n\ncommand did not execute successfully: {:?}\n\
365              expected success, got: {}\n\n",
366             cmd, status
367         );
368     }
369     status.success()
370 }
371
372 pub fn check_run(cmd: &mut Command, print_cmd_on_fail: bool) -> bool {
373     let status = match cmd.status() {
374         Ok(status) => status,
375         Err(e) => {
376             println!("failed to execute command: {:?}\nerror: {}", cmd, e);
377             return false;
378         }
379     };
380     if !status.success() && print_cmd_on_fail {
381         println!(
382             "\n\ncommand did not execute successfully: {:?}\n\
383              expected success, got: {}\n\n",
384             cmd, status
385         );
386     }
387     status.success()
388 }
389
390 pub fn run_suppressed(cmd: &mut Command) {
391     if !try_run_suppressed(cmd) {
392         crate::detail_exit(1);
393     }
394 }
395
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)),
400     };
401     if !output.status.success() {
402         println!(
403             "\n\ncommand did not execute successfully: {:?}\n\
404              expected success, got: {}\n\n\
405              stdout ----\n{}\n\
406              stderr ----\n{}\n\n",
407             cmd,
408             output.status,
409             String::from_utf8_lossy(&output.stdout),
410             String::from_utf8_lossy(&output.stderr)
411         );
412     }
413     output.status.success()
414 }
415
416 pub fn make(host: &str) -> PathBuf {
417     if host.contains("dragonfly")
418         || host.contains("freebsd")
419         || host.contains("netbsd")
420         || host.contains("openbsd")
421     {
422         PathBuf::from("gmake")
423     } else {
424         PathBuf::from("make")
425     }
426 }
427
428 #[track_caller]
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)),
433     };
434     if !output.status.success() {
435         panic!(
436             "command did not execute successfully: {:?}\n\
437              expected success, got: {}",
438             cmd, output.status
439         );
440     }
441     String::from_utf8(output.stdout).unwrap()
442 }
443
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)
447 }
448
449 /// Returns `true` if `dst` is up to date given that the file or files in `src`
450 /// are used to generate it.
451 ///
452 /// Uses last-modified time checks to verify this.
453 pub fn up_to_date(src: &Path, dst: &Path) -> bool {
454     if !dst.exists() {
455         return false;
456     }
457     let threshold = mtime(dst);
458     let meta = match fs::metadata(src) {
459         Ok(meta) => meta,
460         Err(e) => panic!("source {:?} failed to get metadata: {}", src, e),
461     };
462     if meta.is_dir() {
463         dir_up_to_date(src, threshold)
464     } else {
465         meta.modified().unwrap_or(UNIX_EPOCH) <= threshold
466     }
467 }
468
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());
472         if meta.is_dir() {
473             dir_up_to_date(&e.path(), threshold)
474         } else {
475             meta.modified().unwrap_or(UNIX_EPOCH) < threshold
476         }
477     })
478 }
479
480 fn fail(s: &str) -> ! {
481     eprintln!("\n\n{}\n\n", s);
482     crate::detail_exit(1);
483 }
484
485 /// Copied from `std::path::absolute` until it stabilizes.
486 ///
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");
491     }
492     #[cfg(unix)]
493     {
494         t!(absolute_unix(path), format!("could not make path absolute: {}", path.display()))
495     }
496     #[cfg(windows)]
497     {
498         t!(absolute_windows(path), format!("could not make path absolute: {}", path.display()))
499     }
500     #[cfg(not(any(unix, windows)))]
501     {
502         println!("warning: bootstrap is not supported on non-unix platforms");
503         t!(std::fs::canonicalize(t!(std::env::current_dir()))).join(path)
504     }
505 }
506
507 #[cfg(unix)]
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
514
515     use std::os::unix::prelude::OsStrExt;
516     let mut components = path.components();
517     let path_os = path.as_os_str().as_bytes();
518
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>
524         // character."
525         if path_os.starts_with(b"//") && !path_os.starts_with(b"///") {
526             components.next();
527             PathBuf::from("//")
528         } else {
529             PathBuf::new()
530         }
531     } else {
532         env::current_dir()?
533     };
534     normalized.extend(components);
535
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".
542
543     if path_os.ends_with(b"/") {
544         normalized.push("");
545     }
546
547     Ok(normalized)
548 }
549
550 #[cfg(windows)]
551 fn absolute_windows(path: &std::path::Path) -> std::io::Result<std::path::PathBuf> {
552     use std::ffi::OsString;
553     use std::io::Error;
554     use std::os::windows::ffi::{OsStrExt, OsStringExt};
555     use std::ptr::null_mut;
556     #[link(name = "kernel32")]
557     extern "system" {
558         fn GetFullPathNameW(
559             lpFileName: *const u16,
560             nBufferLength: u32,
561             lpBuffer: *mut u16,
562             lpFilePart: *mut *const u16,
563         ) -> u32;
564     }
565
566     unsafe {
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.
571         loop {
572             // Try to get the absolute path
573             let len = GetFullPathNameW(
574                 path.as_ptr(),
575                 buffer.len().try_into().unwrap(),
576                 buffer.as_mut_ptr(),
577                 null_mut(),
578             );
579             match len as usize {
580                 // Failure
581                 0 => return Err(Error::last_os_error()),
582                 // Buffer is too small, resize.
583                 len if len > buffer.len() => buffer.resize(len, 0),
584                 // Success!
585                 len => {
586                     buffer.truncate(len);
587                     return Ok(OsString::from_wide(&buffer).into());
588                 }
589             }
590         }
591     }
592 }
593
594 /// Adapted from https://github.com/llvm/llvm-project/blob/782e91224601e461c019e0a4573bbccc6094fbcd/llvm/cmake/modules/HandleLLVMOptions.cmake#L1058-L1079
595 ///
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"]);
604
605     let clang_rt_builtins = output(&mut builtins_locator);
606     let clang_rt_builtins = Path::new(clang_rt_builtins.trim());
607     assert!(
608         clang_rt_builtins.exists(),
609         "`clang-cl` must correctly locate the library runtime directory"
610     );
611
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()
616 }
617
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,
624             _ => true,
625         };
626         if newer { ("/threads:1", "--threads=1") } else { ("/no-threads", "--no-threads") }
627     });
628     if is_windows { windows } else { other }
629 }