Skip to main content

bootstrap/utils/
helpers.rs

1//! Various utility functions used throughout bootstrap.
2//!
3//! Simple things like testing the various filesystem operations here and there,
4//! not a lot of interesting happenings here unfortunately.
5
6use std::ffi::OsStr;
7use std::path::{Path, PathBuf};
8use std::sync::OnceLock;
9use std::thread::panicking;
10use std::time::{Instant, SystemTime, UNIX_EPOCH};
11use std::{env, fs, io, panic, str};
12
13use build_helper::ci::CiEnv;
14use object::read::archive::ArchiveFile;
15pub(crate) use shim_utils::{dylib_path, dylib_path_var};
16
17pub(crate) use self::macros::t;
18use crate::core::builder::{Builder, StepStack};
19use crate::core::config::{BootstrapOverrideLld, Config, TargetSelection};
20use crate::utils::exec::{BootstrapCommand, command};
21
22#[cfg(test)]
23mod tests;
24
25/// A wrapper around `std::panic::Location` used to track the location of panics
26/// triggered by `t` macro usage.
27pub struct PanicTracker<'a>(pub &'a panic::Location<'a>);
28
29impl Drop for PanicTracker<'_> {
30    fn drop(&mut self) {
31        if panicking() {
32            eprintln!(
33                "Panic was initiated from {}:{}:{}",
34                self.0.file(),
35                self.0.line(),
36                self.0.column()
37            );
38        }
39    }
40}
41
42mod macros {
43    /// A helper macro to `unwrap` a result except also print out details like:
44    ///
45    /// * The file/line of the panic
46    /// * The expression that failed
47    /// * The error itself
48    ///
49    /// This is currently used judiciously throughout the build system rather than
50    /// using a `Result` with `try!`, but this may change one day...
51    macro_rules! t {
52        ($e:expr) => {{
53            let _panic_guard = $crate::utils::helpers::PanicTracker(std::panic::Location::caller());
54            match $e {
55                Ok(e) => e,
56                Err(e) => panic!("{} failed with {}", stringify!($e), e),
57            }
58        }};
59        // it can show extra info in the second parameter
60        ($e:expr, $extra:expr) => {{
61            let _panic_guard = $crate::utils::helpers::PanicTracker(std::panic::Location::caller());
62            match $e {
63                Ok(e) => e,
64                Err(e) => panic!("{} failed with {} ({:?})", stringify!($e), e, $extra),
65            }
66        }};
67    }
68
69    pub(crate) use t;
70}
71
72pub fn exe(name: &str, target: TargetSelection) -> String {
73    shim_utils::exe(name, &target.triple)
74}
75
76/// Returns the path to the split debug info for the specified file if it exists.
77pub fn split_debuginfo(name: impl Into<PathBuf>) -> Option<PathBuf> {
78    // FIXME: only msvc is currently supported
79
80    let path = name.into();
81    let pdb = path.with_extension("pdb");
82    if pdb.exists() {
83        return Some(pdb);
84    }
85
86    // pdbs get named with '-' replaced by '_'
87    let file_name = pdb.file_name()?.to_str()?.replace("-", "_");
88
89    let pdb: PathBuf = [path.parent()?, Path::new(&file_name)].into_iter().collect();
90    pdb.exists().then_some(pdb)
91}
92
93/// Returns `true` if the file name given looks like a dynamic library.
94pub fn is_dylib(path: &Path) -> bool {
95    path.extension().and_then(|ext| ext.to_str()).is_some_and(|ext| {
96        ext == "dylib" || ext == "so" || ext == "dll" || (ext == "a" && is_aix_shared_archive(path))
97    })
98}
99
100/// Return the path to the containing submodule if available.
101pub fn submodule_path_of(builder: &Builder<'_>, path: &str) -> Option<String> {
102    submodule_path_of_paths(builder.submodule_paths(), path)
103}
104
105fn submodule_path_of_paths(submodule_paths: &[String], path: &str) -> Option<String> {
106    let path = Path::new(path);
107    submodule_paths.iter().find_map(|submodule_path| {
108        if path.starts_with(submodule_path) { Some(submodule_path.to_string()) } else { None }
109    })
110}
111
112fn is_aix_shared_archive(path: &Path) -> bool {
113    let file = match fs::File::open(path) {
114        Ok(file) => file,
115        Err(_) => return false,
116    };
117    let reader = object::ReadCache::new(file);
118    let archive = match ArchiveFile::parse(&reader) {
119        Ok(result) => result,
120        Err(_) => return false,
121    };
122
123    archive
124        .members()
125        .filter_map(Result::ok)
126        .any(|entry| String::from_utf8_lossy(entry.name()).contains(".so"))
127}
128
129/// Returns `true` if the file name given looks like a debug info file
130pub fn is_debug_info(name: &str) -> bool {
131    // FIXME: consider split debug info on other platforms (e.g., Linux, macOS)
132    name.ends_with(".pdb")
133}
134
135/// Returns the corresponding relative library directory that the compiler's
136/// dylibs will be found in.
137pub fn libdir(target: TargetSelection) -> &'static str {
138    if target.is_windows() || target.contains("cygwin") { "bin" } else { "lib" }
139}
140
141/// Adds a list of lookup paths to `cmd`'s dynamic library lookup path.
142/// If the dylib_path_var is already set for this cmd, the old value will be overwritten!
143pub fn add_dylib_path(path: Vec<PathBuf>, cmd: &mut BootstrapCommand) {
144    let paths = path.into_iter().chain(dylib_path());
145    cmd.env(dylib_path_var(), t!(env::join_paths(paths)));
146}
147
148pub struct TimeIt(bool, Instant);
149
150/// Returns an RAII structure that prints out how long it took to drop.
151pub fn timeit(builder: &Builder<'_>) -> TimeIt {
152    TimeIt(builder.config.dry_run(), Instant::now())
153}
154
155impl Drop for TimeIt {
156    fn drop(&mut self) {
157        let time = self.1.elapsed();
158        if !self.0 {
159            println!("\tfinished in {}.{:03} seconds", time.as_secs(), time.subsec_millis());
160        }
161    }
162}
163
164/// Symlinks two directories, using junctions on Windows and normal symlinks on
165/// Unix.
166pub fn symlink_dir(config: &Config, original: &Path, link: &Path) -> io::Result<()> {
167    if config.dry_run() {
168        return Ok(());
169    }
170    let _ = fs::remove_dir_all(link);
171    return symlink_dir_inner(original, link);
172
173    #[cfg(not(windows))]
174    fn symlink_dir_inner(original: &Path, link: &Path) -> io::Result<()> {
175        use std::os::unix::fs;
176        fs::symlink(original, link)
177    }
178
179    #[cfg(windows)]
180    fn symlink_dir_inner(target: &Path, junction: &Path) -> io::Result<()> {
181        junction::create(target, junction)
182    }
183}
184
185/// Detects a symlink or a junction on Windows
186pub fn is_symlink_dir(_metadata: &fs::Metadata) -> bool {
187    #[cfg(windows)]
188    {
189        use std::os::windows::fs::FileTypeExt;
190        _metadata.file_type().is_symlink_dir()
191    }
192    #[cfg(not(windows))]
193    false
194}
195
196/// Return the host target on which we are currently running.
197pub fn get_host_target() -> TargetSelection {
198    TargetSelection::from_user(env!("BUILD_TRIPLE"))
199}
200
201/// Rename a file if from and to are in the same filesystem or
202/// copy and remove the file otherwise
203pub fn move_file<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
204    match fs::rename(&from, &to) {
205        Err(e) if e.kind() == io::ErrorKind::CrossesDevices => {
206            std::fs::copy(&from, &to)?;
207            std::fs::remove_file(&from)
208        }
209        r => r,
210    }
211}
212
213pub fn forcing_clang_based_tests() -> bool {
214    if let Some(var) = env::var_os("RUSTBUILD_FORCE_CLANG_BASED_TESTS") {
215        match &var.to_string_lossy().to_lowercase()[..] {
216            "1" | "yes" | "on" => true,
217            "0" | "no" | "off" => false,
218            other => {
219                // Let's make sure typos don't go unnoticed
220                panic!(
221                    "Unrecognized option '{other}' set in \
222                        RUSTBUILD_FORCE_CLANG_BASED_TESTS"
223                )
224            }
225        }
226    } else {
227        false
228    }
229}
230
231pub fn use_host_linker(target: TargetSelection) -> bool {
232    // FIXME: this information should be gotten by checking the linker flavor
233    // of the rustc target
234    !(target.contains("emscripten")
235        || target.contains("wasm32")
236        || target.contains("nvptx")
237        || target.contains("fortanix")
238        || target.contains("fuchsia")
239        || target.contains("bpf")
240        || target.contains("switch")
241        || target.contains("l4re"))
242}
243
244pub fn target_supports_cranelift_backend(target: TargetSelection) -> bool {
245    if target.contains("linux") {
246        target.contains("x86_64")
247            || target.contains("aarch64")
248            || target.contains("s390x")
249            || target.contains("riscv64gc")
250    } else if target.contains("darwin") {
251        target.contains("x86_64") || target.contains("aarch64")
252    } else if target.is_windows() {
253        target.contains("x86_64")
254    } else {
255        false
256    }
257}
258
259/// Value returned from [`is_valid_test_suite_arg`], which figures out which paths start with the
260/// suite name (and therefore which should be run).
261pub enum TestFilterCategory<'a> {
262    /// If a path is equal to the name of the suite, this is returned.
263    Fullsuite,
264    /// If a path starts with the suite, the suite prefix is stripped and the rest is returned as
265    /// this variant.
266    Arg(&'a str),
267    /// For paths that don't start with the suite.
268    Uninteresting,
269}
270
271pub fn is_valid_test_suite_arg<'a, P: AsRef<Path>>(
272    path: &'a Path,
273    suite_path: P,
274    builder: &Builder<'_>,
275) -> TestFilterCategory<'a> {
276    let suite_path = suite_path.as_ref();
277    let path = match path.strip_prefix(".") {
278        Ok(p) => p,
279        Err(_) => path,
280    };
281    if !path.starts_with(suite_path) {
282        return TestFilterCategory::Uninteresting;
283    }
284    let abs_path = builder.src.join(path);
285    let exists = abs_path.is_dir() || abs_path.is_file();
286    if !exists {
287        panic!(
288            "Invalid test suite filter \"{}\": file or directory does not exist",
289            abs_path.display()
290        );
291    }
292    // Since test suite paths are themselves directories, if we don't
293    // specify a directory or file, we'll get an empty string here
294    // (the result of the test suite directory without its suite prefix).
295    // Therefore, we need to filter these out, as only the first --test-args
296    // flag is respected, so providing an empty --test-args conflicts with
297    // any following it.
298    match path.strip_prefix(suite_path).ok().and_then(|p| p.to_str()) {
299        Some(s) if !s.is_empty() => TestFilterCategory::Arg(s),
300        _ => TestFilterCategory::Fullsuite,
301    }
302}
303
304pub fn make(host: &str) -> PathBuf {
305    if host.contains("dragonfly")
306        || host.contains("freebsd")
307        || host.contains("netbsd")
308        || host.contains("openbsd")
309    {
310        PathBuf::from("gmake")
311    } else {
312        PathBuf::from("make")
313    }
314}
315
316/// Returns the last-modified time for `path`, or zero if it doesn't exist.
317pub fn mtime(path: &Path) -> SystemTime {
318    fs::metadata(path).and_then(|f| f.modified()).unwrap_or(UNIX_EPOCH)
319}
320
321/// Returns `true` if `dst` is up to date given that the file or files in `src`
322/// are used to generate it.
323///
324/// Uses last-modified time checks to verify this.
325pub fn up_to_date(src: &Path, dst: &Path) -> bool {
326    if !dst.exists() {
327        return false;
328    }
329    let threshold = mtime(dst);
330    let meta = match fs::metadata(src) {
331        Ok(meta) => meta,
332        Err(e) => panic!("source {src:?} failed to get metadata: {e}"),
333    };
334    if meta.is_dir() {
335        dir_up_to_date(src, threshold)
336    } else {
337        meta.modified().unwrap_or(UNIX_EPOCH) <= threshold
338    }
339}
340
341/// Returns the filename without the hash prefix added by the cc crate.
342///
343/// Since v1.0.78 of the cc crate, object files are prefixed with a 16-character hash
344/// to avoid filename collisions.
345pub fn unhashed_basename(obj: &Path) -> &str {
346    let basename = obj.file_stem().unwrap().to_str().expect("UTF-8 file name");
347    basename.split_once('-').unwrap().1
348}
349
350fn dir_up_to_date(src: &Path, threshold: SystemTime) -> bool {
351    t!(fs::read_dir(src)).map(|e| t!(e)).all(|e| {
352        let meta = t!(e.metadata());
353        if meta.is_dir() {
354            dir_up_to_date(&e.path(), threshold)
355        } else {
356            meta.modified().unwrap_or(UNIX_EPOCH) < threshold
357        }
358    })
359}
360
361/// Adapted from <https://github.com/llvm/llvm-project/blob/782e91224601e461c019e0a4573bbccc6094fbcd/llvm/cmake/modules/HandleLLVMOptions.cmake#L1058-L1079>
362///
363/// When `clang-cl` is used with instrumentation, we need to add clang's runtime library resource
364/// directory to the linker flags, otherwise there will be linker errors about the profiler runtime
365/// missing. This function returns the path to that directory.
366pub fn get_clang_cl_resource_dir(builder: &Builder<'_>, clang_cl_path: &str) -> PathBuf {
367    // Similar to how LLVM does it, to find clang's library runtime directory:
368    // - we ask `clang-cl` to locate the `clang_rt.builtins` lib.
369    let mut builtins_locator = command(clang_cl_path);
370    builtins_locator.args(["/clang:-print-libgcc-file-name", "/clang:--rtlib=compiler-rt"]);
371
372    let clang_rt_builtins = builtins_locator.run_capture_stdout(builder).stdout();
373    let clang_rt_builtins = Path::new(clang_rt_builtins.trim());
374    assert!(
375        clang_rt_builtins.exists(),
376        "`clang-cl` must correctly locate the library runtime directory"
377    );
378
379    // - the profiler runtime will be located in the same directory as the builtins lib, like
380    // `$LLVM_DISTRO_ROOT/lib/clang/$LLVM_VERSION/lib/windows`.
381    let clang_rt_dir = clang_rt_builtins.parent().expect("The clang lib folder should exist");
382    clang_rt_dir.to_path_buf()
383}
384
385/// Returns a flag that configures LLD to use only a single thread.
386/// If we use an external LLD, we need to find out which version is it to know which flag should we
387/// pass to it (LLD older than version 10 had a different flag).
388fn lld_flag_no_threads(
389    builder: &Builder<'_>,
390    bootstrap_override_lld: BootstrapOverrideLld,
391    is_windows: bool,
392) -> &'static str {
393    static LLD_NO_THREADS: OnceLock<(&'static str, &'static str)> = OnceLock::new();
394
395    let new_flags = ("/threads:1", "--threads=1");
396    let old_flags = ("/no-threads", "--no-threads");
397
398    let (windows_flag, other_flag) = LLD_NO_THREADS.get_or_init(|| {
399        let newer_version = match bootstrap_override_lld {
400            BootstrapOverrideLld::External => {
401                let mut cmd = command("lld");
402                cmd.arg("-flavor").arg("ld").arg("--version");
403                let out = cmd.run_capture_stdout(builder).stdout();
404                match (out.find(char::is_numeric), out.find('.')) {
405                    (Some(b), Some(e)) => out.as_str()[b..e].parse::<i32>().ok().unwrap_or(14) > 10,
406                    _ => true,
407                }
408            }
409            _ => true,
410        };
411        if newer_version { new_flags } else { old_flags }
412    });
413    if is_windows { windows_flag } else { other_flag }
414}
415
416pub fn dir_is_empty(dir: &Path) -> bool {
417    t!(std::fs::read_dir(dir), dir).next().is_none()
418}
419
420/// Extract the beta revision from the full version string.
421///
422/// The full version string looks like "a.b.c-beta.y". And we need to extract
423/// the "y" part from the string.
424pub fn extract_beta_rev(version: &str) -> Option<String> {
425    let parts = version.splitn(2, "-beta.").collect::<Vec<_>>();
426    parts.get(1).and_then(|s| s.find(' ').map(|p| s[..p].to_string()))
427}
428
429pub enum LldThreads {
430    Yes,
431    No,
432}
433
434/// Returns the linker arguments for rustc/rustdoc for the given builder and target.
435pub fn linker_args(
436    builder: &Builder<'_>,
437    target: TargetSelection,
438    lld_threads: LldThreads,
439) -> Vec<String> {
440    let mut args = linker_flags(builder, target, lld_threads);
441
442    if let Some(linker) = builder.linker(target) {
443        args.push(format!("-Clinker={}", linker.display()));
444    }
445
446    args
447}
448
449/// Returns the linker arguments for rustc/rustdoc for the given builder and target, without the
450/// -Clinker flag.
451pub fn linker_flags(
452    builder: &Builder<'_>,
453    target: TargetSelection,
454    lld_threads: LldThreads,
455) -> Vec<String> {
456    let mut args = vec![];
457    if !builder.is_lld_direct_linker(target) && builder.config.bootstrap_override_lld.is_used() {
458        match builder.config.bootstrap_override_lld {
459            BootstrapOverrideLld::External => {
460                args.push("-Clinker-features=+lld".to_string());
461                args.push("-Clink-self-contained=-linker".to_string());
462                args.push("-Zunstable-options".to_string());
463            }
464            BootstrapOverrideLld::SelfContained => {
465                args.push("-Clinker-features=+lld".to_string());
466                args.push("-Clink-self-contained=+linker".to_string());
467                args.push("-Zunstable-options".to_string());
468            }
469            BootstrapOverrideLld::None => unreachable!(),
470        };
471
472        if matches!(lld_threads, LldThreads::No) {
473            args.push(format!(
474                "-Clink-arg=-Wl,{}",
475                lld_flag_no_threads(
476                    builder,
477                    builder.config.bootstrap_override_lld,
478                    target.is_windows()
479                )
480            ));
481        }
482    }
483    args
484}
485
486pub fn add_rustdoc_cargo_linker_args(
487    cmd: &mut BootstrapCommand,
488    builder: &Builder<'_>,
489    target: TargetSelection,
490    lld_threads: LldThreads,
491) {
492    let args = linker_args(builder, target, lld_threads);
493    let mut flags = cmd
494        .get_envs()
495        .find_map(|(k, v)| if k == OsStr::new("RUSTDOCFLAGS") { v } else { None })
496        .unwrap_or_default()
497        .to_os_string();
498    for arg in args {
499        if !flags.is_empty() {
500            flags.push(" ");
501        }
502        flags.push(arg);
503    }
504    if !flags.is_empty() {
505        cmd.env("RUSTDOCFLAGS", flags);
506    }
507}
508
509/// Converts `T` into a hexadecimal `String`.
510pub fn hex_encode<T>(input: T) -> String
511where
512    T: AsRef<[u8]>,
513{
514    use std::fmt::Write;
515
516    input.as_ref().iter().fold(String::with_capacity(input.as_ref().len() * 2), |mut acc, &byte| {
517        write!(&mut acc, "{byte:02x}").expect("Failed to write byte to the hex String.");
518        acc
519    })
520}
521
522/// Create a `--check-cfg` argument invocation for a given name
523/// and it's values.
524pub fn check_cfg_arg(name: &str, values: Option<&[&str]>) -> String {
525    // Creating a string of the values by concatenating each value:
526    // ',values("tvos","watchos")' or '' (nothing) when there are no values.
527    let next = match values {
528        Some(values) => {
529            let mut tmp = values.iter().flat_map(|val| [",", "\"", val, "\""]).collect::<String>();
530
531            tmp.insert_str(1, "values(");
532            tmp.push(')');
533            tmp
534        }
535        None => "".to_string(),
536    };
537    format!("--check-cfg=cfg({name}{next})")
538}
539
540/// Prepares `BootstrapCommand` that runs git inside the source directory if given.
541///
542/// Whenever a git invocation is needed, this function should be preferred over
543/// manually building a git `BootstrapCommand`. This approach allows us to manage
544/// bootstrap-specific needs/hacks from a single source, rather than applying them on next to every
545/// git command creation, which is painful to ensure that the required change is applied
546/// on each one of them correctly.
547#[track_caller]
548pub fn git(source_dir: Option<&Path>) -> BootstrapCommand {
549    let mut git = command("git");
550    // git commands are almost always read-only, so cache them by default
551    git.cached();
552
553    if let Some(source_dir) = source_dir {
554        git.current_dir(source_dir);
555        // If we are running inside git (e.g. via a hook), `GIT_DIR` is set and takes precedence
556        // over the current dir. Un-set it to make the current dir matter.
557        git.env_remove("GIT_DIR");
558        // Also un-set some other variables, to be on the safe side (based on cargo's
559        // `fetch_with_cli`). In particular un-setting `GIT_INDEX_FILE` is required to fix some odd
560        // misbehavior.
561        git.env_remove("GIT_WORK_TREE")
562            .env_remove("GIT_INDEX_FILE")
563            .env_remove("GIT_OBJECT_DIRECTORY")
564            .env_remove("GIT_ALTERNATE_OBJECT_DIRECTORIES");
565    }
566
567    git
568}
569
570/// Sets the file times for a given file at `path`.
571pub fn set_file_times<P: AsRef<Path>>(path: P, times: fs::FileTimes) -> io::Result<()> {
572    // Windows requires file to be writable to modify file times. But on Linux CI the file does not
573    // need to be writable to modify file times and might be read-only.
574    let f = if cfg!(windows) {
575        fs::File::options().write(true).open(path)?
576    } else {
577        fs::File::open(path)?
578    };
579    f.set_times(times)
580}
581
582/// Converts a target-tuple or other string into
583/// [the form expected by cargo environment variable names][cargo-env].
584///
585/// For example:
586/// - `x86_64-unknown-linux-gnu` => `X86_64_UNKNOWN_LINUX_GNU`.
587///
588/// [cargo-env]: https://doc.rust-lang.org/cargo/reference/config.html#environment-variables
589pub(crate) fn envify(s: &str) -> String {
590    // Converting foo-bar to FOO_BAR is a fairly idomatic mapping to an environment variable name.
591    // We also convert '.' to '_' to fix https://github.com/rust-lang/rust/issues/158090
592    s.chars()
593        .map(|c| match c {
594            '-' | '.' => '_',
595            c => c,
596        })
597        .flat_map(|c| c.to_uppercase())
598        .collect()
599}
600
601/// Exits the process by calling [`std::process::exit`].
602///
603/// In CI, extra information will be printed to make failures easier to investigate.
604///
605/// If `cfg!(test)` is true, this will panic instead of exiting the process.
606/// Doing so avoids disturbing other tests in the process, and allows `#[should_panic]`
607/// to detect expected failures.
608pub(crate) fn exit_process(code: i32) -> ! {
609    // In bootstrap unit tests, panic instead of killing the whole test process.
610    if cfg!(test) {
611        panic!("status code: {code}");
612    } else {
613        // If we're in CI, print the current bootstrap invocation command, to make it easier to
614        // figure out what exactly has failed.
615        if CiEnv::is_ci() {
616            // Skip the first argument, as it will be some absolute path to the bootstrap binary.
617            let bootstrap_args =
618                std::env::args().skip(1).map(|a| a.to_string()).collect::<Vec<_>>().join(" ");
619            eprintln!("Bootstrap failed while executing `{bootstrap_args}`");
620            eprintln!("Currently active steps:");
621            StepStack::with_current(|stack| {
622                for step in stack.get_active_steps() {
623                    eprintln!("{} at {}", step.info, step.location);
624                }
625            });
626        }
627
628        // otherwise, exit with provided status code
629        std::process::exit(code);
630    }
631}
632
633pub fn fail(s: &str) -> ! {
634    eprintln!("\n\n{s}\n\n");
635    exit_process(1);
636}