]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/util.rs
Rollup merge of #107740 - oli-obk:lock_tcx, r=petrochenkov
[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 pub fn forcing_clang_based_tests() -> bool {
259     if let Some(var) = env::var_os("RUSTBUILD_FORCE_CLANG_BASED_TESTS") {
260         match &var.to_string_lossy().to_lowercase()[..] {
261             "1" | "yes" | "on" => true,
262             "0" | "no" | "off" => false,
263             other => {
264                 // Let's make sure typos don't go unnoticed
265                 panic!(
266                     "Unrecognized option '{}' set in \
267                         RUSTBUILD_FORCE_CLANG_BASED_TESTS",
268                     other
269                 )
270             }
271         }
272     } else {
273         false
274     }
275 }
276
277 pub fn use_host_linker(target: TargetSelection) -> bool {
278     // FIXME: this information should be gotten by checking the linker flavor
279     // of the rustc target
280     !(target.contains("emscripten")
281         || target.contains("wasm32")
282         || target.contains("nvptx")
283         || target.contains("fortanix")
284         || target.contains("fuchsia")
285         || target.contains("bpf")
286         || target.contains("switch"))
287 }
288
289 pub fn is_valid_test_suite_arg<'a, P: AsRef<Path>>(
290     path: &'a Path,
291     suite_path: P,
292     builder: &Builder<'_>,
293 ) -> Option<&'a str> {
294     let suite_path = suite_path.as_ref();
295     let path = match path.strip_prefix(".") {
296         Ok(p) => p,
297         Err(_) => path,
298     };
299     if !path.starts_with(suite_path) {
300         return None;
301     }
302     let abs_path = builder.src.join(path);
303     let exists = abs_path.is_dir() || abs_path.is_file();
304     if !exists {
305         panic!(
306             "Invalid test suite filter \"{}\": file or directory does not exist",
307             abs_path.display()
308         );
309     }
310     // Since test suite paths are themselves directories, if we don't
311     // specify a directory or file, we'll get an empty string here
312     // (the result of the test suite directory without its suite prefix).
313     // Therefore, we need to filter these out, as only the first --test-args
314     // flag is respected, so providing an empty --test-args conflicts with
315     // any following it.
316     match path.strip_prefix(suite_path).ok().and_then(|p| p.to_str()) {
317         Some(s) if !s.is_empty() => Some(s),
318         _ => None,
319     }
320 }
321
322 pub fn run(cmd: &mut Command, print_cmd_on_fail: bool) {
323     if !try_run(cmd, print_cmd_on_fail) {
324         crate::detail_exit(1);
325     }
326 }
327
328 pub fn try_run(cmd: &mut Command, print_cmd_on_fail: bool) -> bool {
329     let status = match cmd.status() {
330         Ok(status) => status,
331         Err(e) => fail(&format!("failed to execute command: {:?}\nerror: {}", cmd, e)),
332     };
333     if !status.success() && print_cmd_on_fail {
334         println!(
335             "\n\ncommand did not execute successfully: {:?}\n\
336              expected success, got: {}\n\n",
337             cmd, status
338         );
339     }
340     status.success()
341 }
342
343 pub fn check_run(cmd: &mut Command, print_cmd_on_fail: bool) -> bool {
344     let status = match cmd.status() {
345         Ok(status) => status,
346         Err(e) => {
347             println!("failed to execute command: {:?}\nerror: {}", cmd, e);
348             return false;
349         }
350     };
351     if !status.success() && print_cmd_on_fail {
352         println!(
353             "\n\ncommand did not execute successfully: {:?}\n\
354              expected success, got: {}\n\n",
355             cmd, status
356         );
357     }
358     status.success()
359 }
360
361 pub fn run_suppressed(cmd: &mut Command) {
362     if !try_run_suppressed(cmd) {
363         crate::detail_exit(1);
364     }
365 }
366
367 pub fn try_run_suppressed(cmd: &mut Command) -> bool {
368     let output = match cmd.output() {
369         Ok(status) => status,
370         Err(e) => fail(&format!("failed to execute command: {:?}\nerror: {}", cmd, e)),
371     };
372     if !output.status.success() {
373         println!(
374             "\n\ncommand did not execute successfully: {:?}\n\
375              expected success, got: {}\n\n\
376              stdout ----\n{}\n\
377              stderr ----\n{}\n\n",
378             cmd,
379             output.status,
380             String::from_utf8_lossy(&output.stdout),
381             String::from_utf8_lossy(&output.stderr)
382         );
383     }
384     output.status.success()
385 }
386
387 pub fn make(host: &str) -> PathBuf {
388     if host.contains("dragonfly")
389         || host.contains("freebsd")
390         || host.contains("netbsd")
391         || host.contains("openbsd")
392     {
393         PathBuf::from("gmake")
394     } else {
395         PathBuf::from("make")
396     }
397 }
398
399 #[track_caller]
400 pub fn output(cmd: &mut Command) -> String {
401     let output = match cmd.stderr(Stdio::inherit()).output() {
402         Ok(status) => status,
403         Err(e) => fail(&format!("failed to execute command: {:?}\nerror: {}", cmd, e)),
404     };
405     if !output.status.success() {
406         panic!(
407             "command did not execute successfully: {:?}\n\
408              expected success, got: {}",
409             cmd, output.status
410         );
411     }
412     String::from_utf8(output.stdout).unwrap()
413 }
414
415 pub fn output_result(cmd: &mut Command) -> Result<String, String> {
416     let output = match cmd.stderr(Stdio::inherit()).output() {
417         Ok(status) => status,
418         Err(e) => return Err(format!("failed to run command: {:?}: {}", cmd, e)),
419     };
420     if !output.status.success() {
421         return Err(format!(
422             "command did not execute successfully: {:?}\n\
423              expected success, got: {}\n{}",
424             cmd,
425             output.status,
426             String::from_utf8(output.stderr).map_err(|err| format!("{err:?}"))?
427         ));
428     }
429     Ok(String::from_utf8(output.stdout).map_err(|err| format!("{err:?}"))?)
430 }
431
432 /// Returns the last-modified time for `path`, or zero if it doesn't exist.
433 pub fn mtime(path: &Path) -> SystemTime {
434     fs::metadata(path).and_then(|f| f.modified()).unwrap_or(UNIX_EPOCH)
435 }
436
437 /// Returns `true` if `dst` is up to date given that the file or files in `src`
438 /// are used to generate it.
439 ///
440 /// Uses last-modified time checks to verify this.
441 pub fn up_to_date(src: &Path, dst: &Path) -> bool {
442     if !dst.exists() {
443         return false;
444     }
445     let threshold = mtime(dst);
446     let meta = match fs::metadata(src) {
447         Ok(meta) => meta,
448         Err(e) => panic!("source {:?} failed to get metadata: {}", src, e),
449     };
450     if meta.is_dir() {
451         dir_up_to_date(src, threshold)
452     } else {
453         meta.modified().unwrap_or(UNIX_EPOCH) <= threshold
454     }
455 }
456
457 fn dir_up_to_date(src: &Path, threshold: SystemTime) -> bool {
458     t!(fs::read_dir(src)).map(|e| t!(e)).all(|e| {
459         let meta = t!(e.metadata());
460         if meta.is_dir() {
461             dir_up_to_date(&e.path(), threshold)
462         } else {
463             meta.modified().unwrap_or(UNIX_EPOCH) < threshold
464         }
465     })
466 }
467
468 fn fail(s: &str) -> ! {
469     eprintln!("\n\n{}\n\n", s);
470     crate::detail_exit(1);
471 }
472
473 /// Copied from `std::path::absolute` until it stabilizes.
474 ///
475 /// FIXME: this shouldn't exist.
476 pub(crate) fn absolute(path: &Path) -> PathBuf {
477     if path.as_os_str().is_empty() {
478         panic!("can't make empty path absolute");
479     }
480     #[cfg(unix)]
481     {
482         t!(absolute_unix(path), format!("could not make path absolute: {}", path.display()))
483     }
484     #[cfg(windows)]
485     {
486         t!(absolute_windows(path), format!("could not make path absolute: {}", path.display()))
487     }
488     #[cfg(not(any(unix, windows)))]
489     {
490         println!("warning: bootstrap is not supported on non-unix platforms");
491         t!(std::fs::canonicalize(t!(std::env::current_dir()))).join(path)
492     }
493 }
494
495 #[cfg(unix)]
496 /// Make a POSIX path absolute without changing its semantics.
497 fn absolute_unix(path: &Path) -> io::Result<PathBuf> {
498     // This is mostly a wrapper around collecting `Path::components`, with
499     // exceptions made where this conflicts with the POSIX specification.
500     // See 4.13 Pathname Resolution, IEEE Std 1003.1-2017
501     // https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_13
502
503     use std::os::unix::prelude::OsStrExt;
504     let mut components = path.components();
505     let path_os = path.as_os_str().as_bytes();
506
507     let mut normalized = if path.is_absolute() {
508         // "If a pathname begins with two successive <slash> characters, the
509         // first component following the leading <slash> characters may be
510         // interpreted in an implementation-defined manner, although more than
511         // two leading <slash> characters shall be treated as a single <slash>
512         // character."
513         if path_os.starts_with(b"//") && !path_os.starts_with(b"///") {
514             components.next();
515             PathBuf::from("//")
516         } else {
517             PathBuf::new()
518         }
519     } else {
520         env::current_dir()?
521     };
522     normalized.extend(components);
523
524     // "Interfaces using pathname resolution may specify additional constraints
525     // when a pathname that does not name an existing directory contains at
526     // least one non- <slash> character and contains one or more trailing
527     // <slash> characters".
528     // A trailing <slash> is also meaningful if "a symbolic link is
529     // encountered during pathname resolution".
530
531     if path_os.ends_with(b"/") {
532         normalized.push("");
533     }
534
535     Ok(normalized)
536 }
537
538 #[cfg(windows)]
539 fn absolute_windows(path: &std::path::Path) -> std::io::Result<std::path::PathBuf> {
540     use std::ffi::OsString;
541     use std::io::Error;
542     use std::os::windows::ffi::{OsStrExt, OsStringExt};
543     use std::ptr::null_mut;
544     #[link(name = "kernel32")]
545     extern "system" {
546         fn GetFullPathNameW(
547             lpFileName: *const u16,
548             nBufferLength: u32,
549             lpBuffer: *mut u16,
550             lpFilePart: *mut *const u16,
551         ) -> u32;
552     }
553
554     unsafe {
555         // encode the path as UTF-16
556         let path: Vec<u16> = path.as_os_str().encode_wide().chain([0]).collect();
557         let mut buffer = Vec::new();
558         // Loop until either success or failure.
559         loop {
560             // Try to get the absolute path
561             let len = GetFullPathNameW(
562                 path.as_ptr(),
563                 buffer.len().try_into().unwrap(),
564                 buffer.as_mut_ptr(),
565                 null_mut(),
566             );
567             match len as usize {
568                 // Failure
569                 0 => return Err(Error::last_os_error()),
570                 // Buffer is too small, resize.
571                 len if len > buffer.len() => buffer.resize(len, 0),
572                 // Success!
573                 len => {
574                     buffer.truncate(len);
575                     return Ok(OsString::from_wide(&buffer).into());
576                 }
577             }
578         }
579     }
580 }
581
582 /// Adapted from https://github.com/llvm/llvm-project/blob/782e91224601e461c019e0a4573bbccc6094fbcd/llvm/cmake/modules/HandleLLVMOptions.cmake#L1058-L1079
583 ///
584 /// When `clang-cl` is used with instrumentation, we need to add clang's runtime library resource
585 /// directory to the linker flags, otherwise there will be linker errors about the profiler runtime
586 /// missing. This function returns the path to that directory.
587 pub fn get_clang_cl_resource_dir(clang_cl_path: &str) -> PathBuf {
588     // Similar to how LLVM does it, to find clang's library runtime directory:
589     // - we ask `clang-cl` to locate the `clang_rt.builtins` lib.
590     let mut builtins_locator = Command::new(clang_cl_path);
591     builtins_locator.args(&["/clang:-print-libgcc-file-name", "/clang:--rtlib=compiler-rt"]);
592
593     let clang_rt_builtins = output(&mut builtins_locator);
594     let clang_rt_builtins = Path::new(clang_rt_builtins.trim());
595     assert!(
596         clang_rt_builtins.exists(),
597         "`clang-cl` must correctly locate the library runtime directory"
598     );
599
600     // - the profiler runtime will be located in the same directory as the builtins lib, like
601     // `$LLVM_DISTRO_ROOT/lib/clang/$LLVM_VERSION/lib/windows`.
602     let clang_rt_dir = clang_rt_builtins.parent().expect("The clang lib folder should exist");
603     clang_rt_dir.to_path_buf()
604 }
605
606 pub fn lld_flag_no_threads(is_windows: bool) -> &'static str {
607     static LLD_NO_THREADS: OnceCell<(&'static str, &'static str)> = OnceCell::new();
608     let (windows, other) = LLD_NO_THREADS.get_or_init(|| {
609         let out = output(Command::new("lld").arg("-flavor").arg("ld").arg("--version"));
610         let newer = match (out.find(char::is_numeric), out.find('.')) {
611             (Some(b), Some(e)) => out.as_str()[b..e].parse::<i32>().ok().unwrap_or(14) > 10,
612             _ => true,
613         };
614         if newer { ("/threads:1", "--threads=1") } else { ("/no-threads", "--no-threads") }
615     });
616     if is_windows { windows } else { other }
617 }