]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/util.rs
Rollup merge of #99915 - WaffleLapkin:recover_keyword_bounds, r=compiler-errors
[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
17 /// A helper macro to `unwrap` a result except also print out details like:
18 ///
19 /// * The file/line of the panic
20 /// * The expression that failed
21 /// * The error itself
22 ///
23 /// This is currently used judiciously throughout the build system rather than
24 /// using a `Result` with `try!`, but this may change one day...
25 #[macro_export]
26 macro_rules! t {
27     ($e:expr) => {
28         match $e {
29             Ok(e) => e,
30             Err(e) => panic!("{} failed with {}", stringify!($e), e),
31         }
32     };
33     // it can show extra info in the second parameter
34     ($e:expr, $extra:expr) => {
35         match $e {
36             Ok(e) => e,
37             Err(e) => panic!("{} failed with {} ({:?})", stringify!($e), e, $extra),
38         }
39     };
40 }
41 pub use t;
42
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() }
47 }
48
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")
52 }
53
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")
58 }
59
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" }
64 }
65
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();
70     for path in path {
71         list.insert(0, path);
72     }
73     cmd.env(dylib_path_var(), t!(env::join_paths(list)));
74 }
75
76 include!("dylib_util.rs");
77
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();
81     for path in path {
82         list.insert(0, path);
83     }
84     cmd.env(link_lib_path_var(), t!(env::join_paths(list)));
85 }
86
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" }
91 }
92
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()) {
97         Some(v) => v,
98         None => return vec![],
99     };
100     env::split_paths(&var).collect()
101 }
102
103 pub struct TimeIt(bool, Instant);
104
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())
108 }
109
110 impl Drop for TimeIt {
111     fn drop(&mut self) {
112         let time = self.1.elapsed();
113         if !self.0 {
114             println!("\tfinished in {}.{:03} seconds", time.as_secs(), time.subsec_millis());
115         }
116     }
117 }
118
119 /// Used for download caching
120 pub(crate) fn program_out_of_date(stamp: &Path, key: &str) -> bool {
121     if !stamp.exists() {
122         return true;
123     }
124     t!(fs::read_to_string(stamp)) != key
125 }
126
127 /// Symlinks two directories, using junctions on Windows and normal symlinks on
128 /// Unix.
129 pub fn symlink_dir(config: &Config, src: &Path, dest: &Path) -> io::Result<()> {
130     if config.dry_run {
131         return Ok(());
132     }
133     let _ = fs::remove_dir(dest);
134     return symlink_dir_inner(src, dest);
135
136     #[cfg(not(windows))]
137     fn symlink_dir_inner(src: &Path, dest: &Path) -> io::Result<()> {
138         use std::os::unix::fs;
139         fs::symlink(src, dest)
140     }
141
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:
145     //
146     // http://www.flexhex.com/docs/articles/hard-links.phtml
147     #[cfg(windows)]
148     fn symlink_dir_inner(target: &Path, junction: &Path) -> io::Result<()> {
149         use std::ffi::OsStr;
150         use std::os::windows::ffi::OsStrExt;
151         use std::ptr;
152
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,
162         };
163
164         #[allow(non_snake_case)]
165         #[repr(C)]
166         struct REPARSE_MOUNTPOINT_DATA_BUFFER {
167             ReparseTag: DWORD,
168             ReparseDataLength: DWORD,
169             Reserved: WORD,
170             ReparseTargetLength: WORD,
171             ReparseTargetMaximumLength: WORD,
172             Reserved1: WORD,
173             ReparseTarget: WCHAR,
174         }
175
176         fn to_u16s<S: AsRef<OsStr>>(s: S) -> io::Result<Vec<u16>> {
177             Ok(s.as_ref().encode_wide().chain(Some(0)).collect())
178         }
179
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)?;
184
185         fs::create_dir(junction)?;
186
187         let path = to_u16s(junction)?;
188
189         unsafe {
190             let h = CreateFileW(
191                 path.as_ptr(),
192                 GENERIC_WRITE,
193                 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
194                 ptr::null_mut(),
195                 OPEN_EXISTING,
196                 FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS,
197                 ptr::null_mut(),
198             );
199
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;
203             let mut i = 0;
204             // FIXME: this conversion is very hacky
205             let v = br"\??\";
206             let v = v.iter().map(|x| *x as u16);
207             for c in v.chain(target.as_os_str().encode_wide().skip(4)) {
208                 *buf.offset(i) = c;
209                 i += 1;
210             }
211             *buf.offset(i) = 0;
212             i += 1;
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;
217
218             let mut ret = 0;
219             let res = DeviceIoControl(
220                 h as *mut _,
221                 FSCTL_SET_REPARSE_POINT,
222                 data.as_ptr() as *mut _,
223                 (*db).ReparseDataLength + 8,
224                 ptr::null_mut(),
225                 0,
226                 &mut ret,
227                 ptr::null_mut(),
228             );
229
230             let out = if res == 0 { Err(io::Error::last_os_error()) } else { Ok(()) };
231             CloseHandle(h);
232             out
233         }
234     }
235 }
236
237 /// The CI environment rustbuild is running in. This mainly affects how the logs
238 /// are printed.
239 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
240 pub enum CiEnv {
241     /// Not a CI environment.
242     None,
243     /// The Azure Pipelines environment, for Linux (including Docker), Windows, and macOS builds.
244     AzurePipelines,
245     /// The GitHub Actions environment, for Linux (including Docker), Windows and macOS builds.
246     GitHubActions,
247 }
248
249 impl CiEnv {
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") {
255             CiEnv::GitHubActions
256         } else {
257             CiEnv::None
258         }
259     }
260
261     pub fn is_ci() -> bool {
262         Self::current() != CiEnv::None
263     }
264
265     /// If in a CI environment, forces the command to run with colors.
266     pub fn force_coloring_in_ci(self, cmd: &mut Command) {
267         if self != CiEnv::None {
268             // Due to use of stamp/docker, the output stream of rustbuild is not
269             // a TTY in CI, so coloring is by-default turned off.
270             // The explicit `TERM=xterm` environment is needed for
271             // `--color always` to actually work. This env var was lost when
272             // compiling through the Makefile. Very strange.
273             cmd.env("TERM", "xterm").args(&["--color", "always"]);
274         }
275     }
276 }
277
278 pub fn forcing_clang_based_tests() -> bool {
279     if let Some(var) = env::var_os("RUSTBUILD_FORCE_CLANG_BASED_TESTS") {
280         match &var.to_string_lossy().to_lowercase()[..] {
281             "1" | "yes" | "on" => true,
282             "0" | "no" | "off" => false,
283             other => {
284                 // Let's make sure typos don't go unnoticed
285                 panic!(
286                     "Unrecognized option '{}' set in \
287                         RUSTBUILD_FORCE_CLANG_BASED_TESTS",
288                     other
289                 )
290             }
291         }
292     } else {
293         false
294     }
295 }
296
297 pub fn use_host_linker(target: TargetSelection) -> bool {
298     // FIXME: this information should be gotten by checking the linker flavor
299     // of the rustc target
300     !(target.contains("emscripten")
301         || target.contains("wasm32")
302         || target.contains("nvptx")
303         || target.contains("fortanix")
304         || target.contains("fuchsia")
305         || target.contains("bpf")
306         || target.contains("switch"))
307 }
308
309 pub fn is_valid_test_suite_arg<'a, P: AsRef<Path>>(
310     path: &'a Path,
311     suite_path: P,
312     builder: &Builder<'_>,
313 ) -> Option<&'a str> {
314     let suite_path = suite_path.as_ref();
315     let path = match path.strip_prefix(".") {
316         Ok(p) => p,
317         Err(_) => path,
318     };
319     if !path.starts_with(suite_path) {
320         return None;
321     }
322     let abs_path = builder.src.join(path);
323     let exists = abs_path.is_dir() || abs_path.is_file();
324     if !exists {
325         panic!(
326             "Invalid test suite filter \"{}\": file or directory does not exist",
327             abs_path.display()
328         );
329     }
330     // Since test suite paths are themselves directories, if we don't
331     // specify a directory or file, we'll get an empty string here
332     // (the result of the test suite directory without its suite prefix).
333     // Therefore, we need to filter these out, as only the first --test-args
334     // flag is respected, so providing an empty --test-args conflicts with
335     // any following it.
336     match path.strip_prefix(suite_path).ok().and_then(|p| p.to_str()) {
337         Some(s) if !s.is_empty() => Some(s),
338         _ => None,
339     }
340 }
341
342 pub fn run(cmd: &mut Command, print_cmd_on_fail: bool) {
343     if !try_run(cmd, print_cmd_on_fail) {
344         crate::detail_exit(1);
345     }
346 }
347
348 pub fn try_run(cmd: &mut Command, print_cmd_on_fail: bool) -> bool {
349     let status = match cmd.status() {
350         Ok(status) => status,
351         Err(e) => fail(&format!("failed to execute command: {:?}\nerror: {}", cmd, e)),
352     };
353     if !status.success() && print_cmd_on_fail {
354         println!(
355             "\n\ncommand did not execute successfully: {:?}\n\
356              expected success, got: {}\n\n",
357             cmd, status
358         );
359     }
360     status.success()
361 }
362
363 pub fn check_run(cmd: &mut Command, print_cmd_on_fail: bool) -> bool {
364     let status = match cmd.status() {
365         Ok(status) => status,
366         Err(e) => {
367             println!("failed to execute command: {:?}\nerror: {}", cmd, e);
368             return false;
369         }
370     };
371     if !status.success() && print_cmd_on_fail {
372         println!(
373             "\n\ncommand did not execute successfully: {:?}\n\
374              expected success, got: {}\n\n",
375             cmd, status
376         );
377     }
378     status.success()
379 }
380
381 pub fn run_suppressed(cmd: &mut Command) {
382     if !try_run_suppressed(cmd) {
383         crate::detail_exit(1);
384     }
385 }
386
387 pub fn try_run_suppressed(cmd: &mut Command) -> bool {
388     let output = match cmd.output() {
389         Ok(status) => status,
390         Err(e) => fail(&format!("failed to execute command: {:?}\nerror: {}", cmd, e)),
391     };
392     if !output.status.success() {
393         println!(
394             "\n\ncommand did not execute successfully: {:?}\n\
395              expected success, got: {}\n\n\
396              stdout ----\n{}\n\
397              stderr ----\n{}\n\n",
398             cmd,
399             output.status,
400             String::from_utf8_lossy(&output.stdout),
401             String::from_utf8_lossy(&output.stderr)
402         );
403     }
404     output.status.success()
405 }
406
407 pub fn make(host: &str) -> PathBuf {
408     if host.contains("dragonfly")
409         || host.contains("freebsd")
410         || host.contains("netbsd")
411         || host.contains("openbsd")
412     {
413         PathBuf::from("gmake")
414     } else {
415         PathBuf::from("make")
416     }
417 }
418
419 #[track_caller]
420 pub fn output(cmd: &mut Command) -> String {
421     let output = match cmd.stderr(Stdio::inherit()).output() {
422         Ok(status) => status,
423         Err(e) => fail(&format!("failed to execute command: {:?}\nerror: {}", cmd, e)),
424     };
425     if !output.status.success() {
426         panic!(
427             "command did not execute successfully: {:?}\n\
428              expected success, got: {}",
429             cmd, output.status
430         );
431     }
432     String::from_utf8(output.stdout).unwrap()
433 }
434
435 /// Returns the last-modified time for `path`, or zero if it doesn't exist.
436 pub fn mtime(path: &Path) -> SystemTime {
437     fs::metadata(path).and_then(|f| f.modified()).unwrap_or(UNIX_EPOCH)
438 }
439
440 /// Returns `true` if `dst` is up to date given that the file or files in `src`
441 /// are used to generate it.
442 ///
443 /// Uses last-modified time checks to verify this.
444 pub fn up_to_date(src: &Path, dst: &Path) -> bool {
445     if !dst.exists() {
446         return false;
447     }
448     let threshold = mtime(dst);
449     let meta = match fs::metadata(src) {
450         Ok(meta) => meta,
451         Err(e) => panic!("source {:?} failed to get metadata: {}", src, e),
452     };
453     if meta.is_dir() {
454         dir_up_to_date(src, threshold)
455     } else {
456         meta.modified().unwrap_or(UNIX_EPOCH) <= threshold
457     }
458 }
459
460 fn dir_up_to_date(src: &Path, threshold: SystemTime) -> bool {
461     t!(fs::read_dir(src)).map(|e| t!(e)).all(|e| {
462         let meta = t!(e.metadata());
463         if meta.is_dir() {
464             dir_up_to_date(&e.path(), threshold)
465         } else {
466             meta.modified().unwrap_or(UNIX_EPOCH) < threshold
467         }
468     })
469 }
470
471 fn fail(s: &str) -> ! {
472     eprintln!("\n\n{}\n\n", s);
473     crate::detail_exit(1);
474 }
475
476 /// Copied from `std::path::absolute` until it stabilizes.
477 ///
478 /// FIXME: this shouldn't exist.
479 pub(crate) fn absolute(path: &Path) -> PathBuf {
480     if path.as_os_str().is_empty() {
481         panic!("can't make empty path absolute");
482     }
483     #[cfg(unix)]
484     {
485         t!(absolute_unix(path), format!("could not make path absolute: {}", path.display()))
486     }
487     #[cfg(windows)]
488     {
489         t!(absolute_windows(path), format!("could not make path absolute: {}", path.display()))
490     }
491     #[cfg(not(any(unix, windows)))]
492     {
493         println!("warning: bootstrap is not supported on non-unix platforms");
494         t!(std::fs::canonicalize(t!(std::env::current_dir()))).join(path)
495     }
496 }
497
498 #[cfg(unix)]
499 /// Make a POSIX path absolute without changing its semantics.
500 fn absolute_unix(path: &Path) -> io::Result<PathBuf> {
501     // This is mostly a wrapper around collecting `Path::components`, with
502     // exceptions made where this conflicts with the POSIX specification.
503     // See 4.13 Pathname Resolution, IEEE Std 1003.1-2017
504     // https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_13
505
506     use std::os::unix::prelude::OsStrExt;
507     let mut components = path.components();
508     let path_os = path.as_os_str().as_bytes();
509
510     let mut normalized = if path.is_absolute() {
511         // "If a pathname begins with two successive <slash> characters, the
512         // first component following the leading <slash> characters may be
513         // interpreted in an implementation-defined manner, although more than
514         // two leading <slash> characters shall be treated as a single <slash>
515         // character."
516         if path_os.starts_with(b"//") && !path_os.starts_with(b"///") {
517             components.next();
518             PathBuf::from("//")
519         } else {
520             PathBuf::new()
521         }
522     } else {
523         env::current_dir()?
524     };
525     normalized.extend(components);
526
527     // "Interfaces using pathname resolution may specify additional constraints
528     // when a pathname that does not name an existing directory contains at
529     // least one non- <slash> character and contains one or more trailing
530     // <slash> characters".
531     // A trailing <slash> is also meaningful if "a symbolic link is
532     // encountered during pathname resolution".
533
534     if path_os.ends_with(b"/") {
535         normalized.push("");
536     }
537
538     Ok(normalized)
539 }
540
541 #[cfg(windows)]
542 fn absolute_windows(path: &std::path::Path) -> std::io::Result<std::path::PathBuf> {
543     use std::ffi::OsString;
544     use std::io::Error;
545     use std::os::windows::ffi::{OsStrExt, OsStringExt};
546     use std::ptr::null_mut;
547     #[link(name = "kernel32")]
548     extern "system" {
549         fn GetFullPathNameW(
550             lpFileName: *const u16,
551             nBufferLength: u32,
552             lpBuffer: *mut u16,
553             lpFilePart: *mut *const u16,
554         ) -> u32;
555     }
556
557     unsafe {
558         // encode the path as UTF-16
559         let path: Vec<u16> = path.as_os_str().encode_wide().chain([0]).collect();
560         let mut buffer = Vec::new();
561         // Loop until either success or failure.
562         loop {
563             // Try to get the absolute path
564             let len = GetFullPathNameW(
565                 path.as_ptr(),
566                 buffer.len().try_into().unwrap(),
567                 buffer.as_mut_ptr(),
568                 null_mut(),
569             );
570             match len as usize {
571                 // Failure
572                 0 => return Err(Error::last_os_error()),
573                 // Buffer is too small, resize.
574                 len if len > buffer.len() => buffer.resize(len, 0),
575                 // Success!
576                 len => {
577                     buffer.truncate(len);
578                     return Ok(OsString::from_wide(&buffer).into());
579                 }
580             }
581         }
582     }
583 }
584
585 /// Adapted from https://github.com/llvm/llvm-project/blob/782e91224601e461c019e0a4573bbccc6094fbcd/llvm/cmake/modules/HandleLLVMOptions.cmake#L1058-L1079
586 ///
587 /// When `clang-cl` is used with instrumentation, we need to add clang's runtime library resource
588 /// directory to the linker flags, otherwise there will be linker errors about the profiler runtime
589 /// missing. This function returns the path to that directory.
590 pub fn get_clang_cl_resource_dir(clang_cl_path: &str) -> PathBuf {
591     // Similar to how LLVM does it, to find clang's library runtime directory:
592     // - we ask `clang-cl` to locate the `clang_rt.builtins` lib.
593     let mut builtins_locator = Command::new(clang_cl_path);
594     builtins_locator.args(&["/clang:-print-libgcc-file-name", "/clang:--rtlib=compiler-rt"]);
595
596     let clang_rt_builtins = output(&mut builtins_locator);
597     let clang_rt_builtins = Path::new(clang_rt_builtins.trim());
598     assert!(
599         clang_rt_builtins.exists(),
600         "`clang-cl` must correctly locate the library runtime directory"
601     );
602
603     // - the profiler runtime will be located in the same directory as the builtins lib, like
604     // `$LLVM_DISTRO_ROOT/lib/clang/$LLVM_VERSION/lib/windows`.
605     let clang_rt_dir = clang_rt_builtins.parent().expect("The clang lib folder should exist");
606     clang_rt_dir.to_path_buf()
607 }