]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/util.rs
check lld version to choose correct flag for tests
[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") { format!("{}.exe", name) } else { name.to_string() }
48 }
49
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")
53 }
54
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")
59 }
60
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" }
65 }
66
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();
71     for path in path {
72         list.insert(0, path);
73     }
74     cmd.env(dylib_path_var(), t!(env::join_paths(list)));
75 }
76
77 include!("dylib_util.rs");
78
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();
82     for path in path {
83         list.insert(0, path);
84     }
85     cmd.env(link_lib_path_var(), t!(env::join_paths(list)));
86 }
87
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" }
92 }
93
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()) {
98         Some(v) => v,
99         None => return vec![],
100     };
101     env::split_paths(&var).collect()
102 }
103
104 pub struct TimeIt(bool, Instant);
105
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())
109 }
110
111 impl Drop for TimeIt {
112     fn drop(&mut self) {
113         let time = self.1.elapsed();
114         if !self.0 {
115             println!("\tfinished in {}.{:03} seconds", time.as_secs(), time.subsec_millis());
116         }
117     }
118 }
119
120 /// Used for download caching
121 pub(crate) fn program_out_of_date(stamp: &Path, key: &str) -> bool {
122     if !stamp.exists() {
123         return true;
124     }
125     t!(fs::read_to_string(stamp)) != key
126 }
127
128 /// Symlinks two directories, using junctions on Windows and normal symlinks on
129 /// Unix.
130 pub fn symlink_dir(config: &Config, src: &Path, dest: &Path) -> io::Result<()> {
131     if config.dry_run {
132         return Ok(());
133     }
134     let _ = fs::remove_dir(dest);
135     return symlink_dir_inner(src, dest);
136
137     #[cfg(not(windows))]
138     fn symlink_dir_inner(src: &Path, dest: &Path) -> io::Result<()> {
139         use std::os::unix::fs;
140         fs::symlink(src, dest)
141     }
142
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:
146     //
147     // http://www.flexhex.com/docs/articles/hard-links.phtml
148     #[cfg(windows)]
149     fn symlink_dir_inner(target: &Path, junction: &Path) -> io::Result<()> {
150         use std::ffi::OsStr;
151         use std::os::windows::ffi::OsStrExt;
152         use std::ptr;
153
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,
163         };
164
165         #[allow(non_snake_case)]
166         #[repr(C)]
167         struct REPARSE_MOUNTPOINT_DATA_BUFFER {
168             ReparseTag: DWORD,
169             ReparseDataLength: DWORD,
170             Reserved: WORD,
171             ReparseTargetLength: WORD,
172             ReparseTargetMaximumLength: WORD,
173             Reserved1: WORD,
174             ReparseTarget: WCHAR,
175         }
176
177         fn to_u16s<S: AsRef<OsStr>>(s: S) -> io::Result<Vec<u16>> {
178             Ok(s.as_ref().encode_wide().chain(Some(0)).collect())
179         }
180
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)?;
185
186         fs::create_dir(junction)?;
187
188         let path = to_u16s(junction)?;
189
190         unsafe {
191             let h = CreateFileW(
192                 path.as_ptr(),
193                 GENERIC_WRITE,
194                 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
195                 ptr::null_mut(),
196                 OPEN_EXISTING,
197                 FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS,
198                 ptr::null_mut(),
199             );
200
201             #[repr(C, align(8))]
202             struct Align8<T>(T);
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;
206             let mut i = 0;
207             // FIXME: this conversion is very hacky
208             let v = br"\??\";
209             let v = v.iter().map(|x| *x as u16);
210             for c in v.chain(target.as_os_str().encode_wide().skip(4)) {
211                 *buf.offset(i) = c;
212                 i += 1;
213             }
214             *buf.offset(i) = 0;
215             i += 1;
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;
220
221             let mut ret = 0;
222             let res = DeviceIoControl(
223                 h as *mut _,
224                 FSCTL_SET_REPARSE_POINT,
225                 db.cast(),
226                 (*db).ReparseDataLength + 8,
227                 ptr::null_mut(),
228                 0,
229                 &mut ret,
230                 ptr::null_mut(),
231             );
232
233             let out = if res == 0 { Err(io::Error::last_os_error()) } else { Ok(()) };
234             CloseHandle(h);
235             out
236         }
237     }
238 }
239
240 /// The CI environment rustbuild is running in. This mainly affects how the logs
241 /// are printed.
242 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
243 pub enum CiEnv {
244     /// Not a CI environment.
245     None,
246     /// The Azure Pipelines environment, for Linux (including Docker), Windows, and macOS builds.
247     AzurePipelines,
248     /// The GitHub Actions environment, for Linux (including Docker), Windows and macOS builds.
249     GitHubActions,
250 }
251
252 impl CiEnv {
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") {
258             CiEnv::GitHubActions
259         } else {
260             CiEnv::None
261         }
262     }
263
264     pub fn is_ci() -> bool {
265         Self::current() != CiEnv::None
266     }
267
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"]);
277         }
278     }
279 }
280
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,
286             other => {
287                 // Let's make sure typos don't go unnoticed
288                 panic!(
289                     "Unrecognized option '{}' set in \
290                         RUSTBUILD_FORCE_CLANG_BASED_TESTS",
291                     other
292                 )
293             }
294         }
295     } else {
296         false
297     }
298 }
299
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"))
310 }
311
312 pub fn is_valid_test_suite_arg<'a, P: AsRef<Path>>(
313     path: &'a Path,
314     suite_path: P,
315     builder: &Builder<'_>,
316 ) -> Option<&'a str> {
317     let suite_path = suite_path.as_ref();
318     let path = match path.strip_prefix(".") {
319         Ok(p) => p,
320         Err(_) => path,
321     };
322     if !path.starts_with(suite_path) {
323         return None;
324     }
325     let abs_path = builder.src.join(path);
326     let exists = abs_path.is_dir() || abs_path.is_file();
327     if !exists {
328         panic!(
329             "Invalid test suite filter \"{}\": file or directory does not exist",
330             abs_path.display()
331         );
332     }
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
338     // any following it.
339     match path.strip_prefix(suite_path).ok().and_then(|p| p.to_str()) {
340         Some(s) if !s.is_empty() => Some(s),
341         _ => None,
342     }
343 }
344
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);
348     }
349 }
350
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)),
355     };
356     if !status.success() && print_cmd_on_fail {
357         println!(
358             "\n\ncommand did not execute successfully: {:?}\n\
359              expected success, got: {}\n\n",
360             cmd, status
361         );
362     }
363     status.success()
364 }
365
366 pub fn check_run(cmd: &mut Command, print_cmd_on_fail: bool) -> bool {
367     let status = match cmd.status() {
368         Ok(status) => status,
369         Err(e) => {
370             println!("failed to execute command: {:?}\nerror: {}", cmd, e);
371             return false;
372         }
373     };
374     if !status.success() && print_cmd_on_fail {
375         println!(
376             "\n\ncommand did not execute successfully: {:?}\n\
377              expected success, got: {}\n\n",
378             cmd, status
379         );
380     }
381     status.success()
382 }
383
384 pub fn run_suppressed(cmd: &mut Command) {
385     if !try_run_suppressed(cmd) {
386         crate::detail_exit(1);
387     }
388 }
389
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)),
394     };
395     if !output.status.success() {
396         println!(
397             "\n\ncommand did not execute successfully: {:?}\n\
398              expected success, got: {}\n\n\
399              stdout ----\n{}\n\
400              stderr ----\n{}\n\n",
401             cmd,
402             output.status,
403             String::from_utf8_lossy(&output.stdout),
404             String::from_utf8_lossy(&output.stderr)
405         );
406     }
407     output.status.success()
408 }
409
410 pub fn make(host: &str) -> PathBuf {
411     if host.contains("dragonfly")
412         || host.contains("freebsd")
413         || host.contains("netbsd")
414         || host.contains("openbsd")
415     {
416         PathBuf::from("gmake")
417     } else {
418         PathBuf::from("make")
419     }
420 }
421
422 #[track_caller]
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)),
427     };
428     if !output.status.success() {
429         panic!(
430             "command did not execute successfully: {:?}\n\
431              expected success, got: {}",
432             cmd, output.status
433         );
434     }
435     String::from_utf8(output.stdout).unwrap()
436 }
437
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)
441 }
442
443 /// Returns `true` if `dst` is up to date given that the file or files in `src`
444 /// are used to generate it.
445 ///
446 /// Uses last-modified time checks to verify this.
447 pub fn up_to_date(src: &Path, dst: &Path) -> bool {
448     if !dst.exists() {
449         return false;
450     }
451     let threshold = mtime(dst);
452     let meta = match fs::metadata(src) {
453         Ok(meta) => meta,
454         Err(e) => panic!("source {:?} failed to get metadata: {}", src, e),
455     };
456     if meta.is_dir() {
457         dir_up_to_date(src, threshold)
458     } else {
459         meta.modified().unwrap_or(UNIX_EPOCH) <= threshold
460     }
461 }
462
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());
466         if meta.is_dir() {
467             dir_up_to_date(&e.path(), threshold)
468         } else {
469             meta.modified().unwrap_or(UNIX_EPOCH) < threshold
470         }
471     })
472 }
473
474 fn fail(s: &str) -> ! {
475     eprintln!("\n\n{}\n\n", s);
476     crate::detail_exit(1);
477 }
478
479 /// Copied from `std::path::absolute` until it stabilizes.
480 ///
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");
485     }
486     #[cfg(unix)]
487     {
488         t!(absolute_unix(path), format!("could not make path absolute: {}", path.display()))
489     }
490     #[cfg(windows)]
491     {
492         t!(absolute_windows(path), format!("could not make path absolute: {}", path.display()))
493     }
494     #[cfg(not(any(unix, windows)))]
495     {
496         println!("warning: bootstrap is not supported on non-unix platforms");
497         t!(std::fs::canonicalize(t!(std::env::current_dir()))).join(path)
498     }
499 }
500
501 #[cfg(unix)]
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
508
509     use std::os::unix::prelude::OsStrExt;
510     let mut components = path.components();
511     let path_os = path.as_os_str().as_bytes();
512
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>
518         // character."
519         if path_os.starts_with(b"//") && !path_os.starts_with(b"///") {
520             components.next();
521             PathBuf::from("//")
522         } else {
523             PathBuf::new()
524         }
525     } else {
526         env::current_dir()?
527     };
528     normalized.extend(components);
529
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".
536
537     if path_os.ends_with(b"/") {
538         normalized.push("");
539     }
540
541     Ok(normalized)
542 }
543
544 #[cfg(windows)]
545 fn absolute_windows(path: &std::path::Path) -> std::io::Result<std::path::PathBuf> {
546     use std::ffi::OsString;
547     use std::io::Error;
548     use std::os::windows::ffi::{OsStrExt, OsStringExt};
549     use std::ptr::null_mut;
550     #[link(name = "kernel32")]
551     extern "system" {
552         fn GetFullPathNameW(
553             lpFileName: *const u16,
554             nBufferLength: u32,
555             lpBuffer: *mut u16,
556             lpFilePart: *mut *const u16,
557         ) -> u32;
558     }
559
560     unsafe {
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.
565         loop {
566             // Try to get the absolute path
567             let len = GetFullPathNameW(
568                 path.as_ptr(),
569                 buffer.len().try_into().unwrap(),
570                 buffer.as_mut_ptr(),
571                 null_mut(),
572             );
573             match len as usize {
574                 // Failure
575                 0 => return Err(Error::last_os_error()),
576                 // Buffer is too small, resize.
577                 len if len > buffer.len() => buffer.resize(len, 0),
578                 // Success!
579                 len => {
580                     buffer.truncate(len);
581                     return Ok(OsString::from_wide(&buffer).into());
582                 }
583             }
584         }
585     }
586 }
587
588 /// Adapted from https://github.com/llvm/llvm-project/blob/782e91224601e461c019e0a4573bbccc6094fbcd/llvm/cmake/modules/HandleLLVMOptions.cmake#L1058-L1079
589 ///
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"]);
598
599     let clang_rt_builtins = output(&mut builtins_locator);
600     let clang_rt_builtins = Path::new(clang_rt_builtins.trim());
601     assert!(
602         clang_rt_builtins.exists(),
603         "`clang-cl` must correctly locate the library runtime directory"
604     );
605
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()
610 }
611
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,
618             _ => true,
619         };
620         if newer { ("/threads:1", "--threads=1") } else { ("/no-threads", "--no-threads") }
621     });
622     if is_windows { windows } else { other }
623 }