bootstrap/
lib.rs

1//! Implementation of bootstrap, the Rust build system.
2//!
3//! This module, and its descendants, are the implementation of the Rust build
4//! system. Most of this build system is backed by Cargo but the outer layer
5//! here serves as the ability to orchestrate calling Cargo, sequencing Cargo
6//! builds, building artifacts like LLVM, etc. The goals of bootstrap are:
7//!
8//! * To be an easily understandable, easily extensible, and maintainable build
9//!   system.
10//! * Leverage standard tools in the Rust ecosystem to build the compiler, aka
11//!   crates.io and Cargo.
12//! * A standard interface to build across all platforms, including MSVC
13//!
14//! ## Further information
15//!
16//! More documentation can be found in each respective module below, and you can
17//! also check out the `src/bootstrap/README.md` file for more information.
18
19use std::cell::{Cell, RefCell};
20use std::collections::{BTreeSet, HashMap, HashSet};
21use std::fmt::Display;
22use std::path::{Path, PathBuf};
23use std::process::Command;
24use std::sync::OnceLock;
25use std::time::SystemTime;
26use std::{env, fs, io, str};
27
28use build_helper::ci::gha;
29use build_helper::exit;
30use termcolor::{ColorChoice, StandardStream, WriteColor};
31use utils::build_stamp::BuildStamp;
32use utils::channel::GitInfo;
33
34use crate::core::builder;
35use crate::core::builder::Kind;
36use crate::core::config::{DryRun, LldMode, LlvmLibunwind, Target, TargetSelection, flags};
37use crate::utils::exec::{BehaviorOnFailure, BootstrapCommand, CommandOutput, OutputMode, command};
38use crate::utils::helpers::{self, dir_is_empty, exe, libdir, output, set_file_times, symlink_dir};
39
40mod core;
41mod utils;
42
43pub use core::builder::PathSet;
44pub use core::config::Config;
45pub use core::config::flags::{Flags, Subcommand};
46
47#[cfg(feature = "tracing")]
48use tracing::{instrument, span};
49pub use utils::change_tracker::{
50    CONFIG_CHANGE_HISTORY, find_recent_config_change_ids, human_readable_changes,
51};
52
53const LLVM_TOOLS: &[&str] = &[
54    "llvm-cov",      // used to generate coverage report
55    "llvm-nm",       // used to inspect binaries; it shows symbol names, their sizes and visibility
56    "llvm-objcopy",  // used to transform ELFs into binary format which flashing tools consume
57    "llvm-objdump",  // used to disassemble programs
58    "llvm-profdata", // used to inspect and merge files generated by profiles
59    "llvm-readobj",  // used to get information from ELFs/objects that the other tools don't provide
60    "llvm-size",     // used to prints the size of the linker sections of a program
61    "llvm-strip",    // used to discard symbols from binary files to reduce their size
62    "llvm-ar",       // used for creating and modifying archive files
63    "llvm-as",       // used to convert LLVM assembly to LLVM bitcode
64    "llvm-dis",      // used to disassemble LLVM bitcode
65    "llvm-link",     // Used to link LLVM bitcode
66    "llc",           // used to compile LLVM bytecode
67    "opt",           // used to optimize LLVM bytecode
68];
69
70/// LLD file names for all flavors.
71const LLD_FILE_NAMES: &[&str] = &["ld.lld", "ld64.lld", "lld-link", "wasm-ld"];
72
73/// Extra `--check-cfg` to add when building the compiler or tools
74/// (Mode restriction, config name, config values (if any))
75#[allow(clippy::type_complexity)] // It's fine for hard-coded list and type is explained above.
76const EXTRA_CHECK_CFGS: &[(Option<Mode>, &str, Option<&[&'static str]>)] = &[
77    (None, "bootstrap", None),
78    (Some(Mode::Rustc), "llvm_enzyme", None),
79    (Some(Mode::Codegen), "llvm_enzyme", None),
80    (Some(Mode::ToolRustc), "llvm_enzyme", None),
81    (Some(Mode::ToolRustc), "rust_analyzer", None),
82    (Some(Mode::ToolStd), "rust_analyzer", None),
83    // Any library specific cfgs like `target_os`, `target_arch` should be put in
84    // priority the `[lints.rust.unexpected_cfgs.check-cfg]` table
85    // in the appropriate `library/{std,alloc,core}/Cargo.toml`
86];
87
88/// A structure representing a Rust compiler.
89///
90/// Each compiler has a `stage` that it is associated with and a `host` that
91/// corresponds to the platform the compiler runs on. This structure is used as
92/// a parameter to many methods below.
93#[derive(Eq, PartialOrd, Ord, PartialEq, Clone, Copy, Hash, Debug)]
94pub struct Compiler {
95    stage: u32,
96    host: TargetSelection,
97}
98
99#[derive(PartialEq, Eq, Copy, Clone, Debug)]
100pub enum DocTests {
101    /// Run normal tests and doc tests (default).
102    Yes,
103    /// Do not run any doc tests.
104    No,
105    /// Only run doc tests.
106    Only,
107}
108
109pub enum GitRepo {
110    Rustc,
111    Llvm,
112}
113
114/// Global configuration for the build system.
115///
116/// This structure transitively contains all configuration for the build system.
117/// All filesystem-encoded configuration is in `config`, all flags are in
118/// `flags`, and then parsed or probed information is listed in the keys below.
119///
120/// This structure is a parameter of almost all methods in the build system,
121/// although most functions are implemented as free functions rather than
122/// methods specifically on this structure itself (to make it easier to
123/// organize).
124#[derive(Clone)]
125pub struct Build {
126    /// User-specified configuration from `config.toml`.
127    config: Config,
128
129    // Version information
130    version: String,
131
132    // Properties derived from the above configuration
133    src: PathBuf,
134    out: PathBuf,
135    bootstrap_out: PathBuf,
136    cargo_info: GitInfo,
137    rust_analyzer_info: GitInfo,
138    clippy_info: GitInfo,
139    miri_info: GitInfo,
140    rustfmt_info: GitInfo,
141    enzyme_info: GitInfo,
142    in_tree_llvm_info: GitInfo,
143    in_tree_gcc_info: GitInfo,
144    local_rebuild: bool,
145    fail_fast: bool,
146    doc_tests: DocTests,
147    verbosity: usize,
148
149    /// Build triple for the pre-compiled snapshot compiler.
150    build: TargetSelection,
151    /// Which triples to produce a compiler toolchain for.
152    hosts: Vec<TargetSelection>,
153    /// Which triples to build libraries (core/alloc/std/test/proc_macro) for.
154    targets: Vec<TargetSelection>,
155
156    initial_rustc: PathBuf,
157    initial_rustdoc: PathBuf,
158    initial_cargo: PathBuf,
159    initial_lld: PathBuf,
160    initial_relative_libdir: PathBuf,
161    initial_sysroot: PathBuf,
162
163    // Runtime state filled in later on
164    // C/C++ compilers and archiver for all targets
165    cc: RefCell<HashMap<TargetSelection, cc::Tool>>,
166    cxx: RefCell<HashMap<TargetSelection, cc::Tool>>,
167    ar: RefCell<HashMap<TargetSelection, PathBuf>>,
168    ranlib: RefCell<HashMap<TargetSelection, PathBuf>>,
169    // Miscellaneous
170    // allow bidirectional lookups: both name -> path and path -> name
171    crates: HashMap<String, Crate>,
172    crate_paths: HashMap<PathBuf, String>,
173    is_sudo: bool,
174    delayed_failures: RefCell<Vec<String>>,
175    prerelease_version: Cell<Option<u32>>,
176
177    #[cfg(feature = "build-metrics")]
178    metrics: crate::utils::metrics::BuildMetrics,
179}
180
181#[derive(Debug, Clone)]
182struct Crate {
183    name: String,
184    deps: HashSet<String>,
185    path: PathBuf,
186    has_lib: bool,
187    features: Vec<String>,
188}
189
190impl Crate {
191    fn local_path(&self, build: &Build) -> PathBuf {
192        self.path.strip_prefix(&build.config.src).unwrap().into()
193    }
194}
195
196/// When building Rust various objects are handled differently.
197#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
198pub enum DependencyType {
199    /// Libraries originating from proc-macros.
200    Host,
201    /// Typical Rust libraries.
202    Target,
203    /// Non Rust libraries and objects shipped to ease usage of certain targets.
204    TargetSelfContained,
205}
206
207/// The various "modes" of invoking Cargo.
208///
209/// These entries currently correspond to the various output directories of the
210/// build system, with each mod generating output in a different directory.
211#[derive(Debug, Hash, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
212pub enum Mode {
213    /// Build the standard library, placing output in the "stageN-std" directory.
214    Std,
215
216    /// Build librustc, and compiler libraries, placing output in the "stageN-rustc" directory.
217    Rustc,
218
219    /// Build a codegen backend for rustc, placing the output in the "stageN-codegen" directory.
220    Codegen,
221
222    /// Build a tool, placing output in the "stage0-bootstrap-tools"
223    /// directory. This is for miscellaneous sets of tools that are built
224    /// using the bootstrap stage0 compiler in its entirety (target libraries
225    /// and all). Typically these tools compile with stable Rust.
226    ///
227    /// Only works for stage 0.
228    ToolBootstrap,
229
230    /// Build a tool which uses the locally built std, placing output in the
231    /// "stageN-tools" directory. Its usage is quite rare, mainly used by
232    /// compiletest which needs libtest.
233    ToolStd,
234
235    /// Build a tool which uses the locally built rustc and the target std,
236    /// placing the output in the "stageN-tools" directory. This is used for
237    /// anything that needs a fully functional rustc, such as rustdoc, clippy,
238    /// cargo, rls, rustfmt, miri, etc.
239    ToolRustc,
240}
241
242impl Mode {
243    pub fn is_tool(&self) -> bool {
244        matches!(self, Mode::ToolBootstrap | Mode::ToolRustc | Mode::ToolStd)
245    }
246
247    pub fn must_support_dlopen(&self) -> bool {
248        matches!(self, Mode::Std | Mode::Codegen)
249    }
250}
251
252#[derive(Debug, Hash, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
253pub enum CLang {
254    C,
255    Cxx,
256}
257
258macro_rules! forward {
259    ( $( $fn:ident( $($param:ident: $ty:ty),* ) $( -> $ret:ty)? ),+ $(,)? ) => {
260        impl Build {
261            $( fn $fn(&self, $($param: $ty),* ) $( -> $ret)? {
262                self.config.$fn( $($param),* )
263            } )+
264        }
265    }
266}
267
268forward! {
269    verbose(f: impl Fn()),
270    is_verbose() -> bool,
271    create(path: &Path, s: &str),
272    remove(f: &Path),
273    tempdir() -> PathBuf,
274    llvm_link_shared() -> bool,
275    download_rustc() -> bool,
276    initial_rustfmt() -> Option<PathBuf>,
277}
278
279impl Build {
280    /// Creates a new set of build configuration from the `flags` on the command
281    /// line and the filesystem `config`.
282    ///
283    /// By default all build output will be placed in the current directory.
284    pub fn new(mut config: Config) -> Build {
285        let src = config.src.clone();
286        let out = config.out.clone();
287
288        #[cfg(unix)]
289        // keep this consistent with the equivalent check in x.py:
290        // https://github.com/rust-lang/rust/blob/a8a33cf27166d3eabaffc58ed3799e054af3b0c6/src/bootstrap/bootstrap.py#L796-L797
291        let is_sudo = match env::var_os("SUDO_USER") {
292            Some(_sudo_user) => {
293                // SAFETY: getuid() system call is always successful and no return value is reserved
294                // to indicate an error.
295                //
296                // For more context, see https://man7.org/linux/man-pages/man2/geteuid.2.html
297                let uid = unsafe { libc::getuid() };
298                uid == 0
299            }
300            None => false,
301        };
302        #[cfg(not(unix))]
303        let is_sudo = false;
304
305        let rust_info = config.rust_info.clone();
306        let cargo_info = config.cargo_info.clone();
307        let rust_analyzer_info = config.rust_analyzer_info.clone();
308        let clippy_info = config.clippy_info.clone();
309        let miri_info = config.miri_info.clone();
310        let rustfmt_info = config.rustfmt_info.clone();
311        let enzyme_info = config.enzyme_info.clone();
312        let in_tree_llvm_info = config.in_tree_llvm_info.clone();
313        let in_tree_gcc_info = config.in_tree_gcc_info.clone();
314
315        let initial_target_libdir_str =
316            config.initial_sysroot.join("lib/rustlib").join(config.build).join("lib");
317
318        let initial_target_dir = Path::new(&initial_target_libdir_str).parent().unwrap();
319        let initial_lld = initial_target_dir.join("bin").join("rust-lld");
320
321        let initial_relative_libdir = initial_target_dir
322            .ancestors()
323            .nth(2)
324            .unwrap()
325            .strip_prefix(&config.initial_sysroot)
326            .expect("Couldn’t determine initial relative libdir.")
327            .to_path_buf();
328
329        let version = std::fs::read_to_string(src.join("src").join("version"))
330            .expect("failed to read src/version");
331        let version = version.trim();
332
333        let mut bootstrap_out = std::env::current_exe()
334            .expect("could not determine path to running process")
335            .parent()
336            .unwrap()
337            .to_path_buf();
338        // Since bootstrap is hardlink to deps/bootstrap-*, Solaris can sometimes give
339        // path with deps/ which is bad and needs to be avoided.
340        if bootstrap_out.ends_with("deps") {
341            bootstrap_out.pop();
342        }
343        if !bootstrap_out.join(exe("rustc", config.build)).exists() && !cfg!(test) {
344            // this restriction can be lifted whenever https://github.com/rust-lang/rfcs/pull/3028 is implemented
345            panic!(
346                "`rustc` not found in {}, run `cargo build --bins` before `cargo run`",
347                bootstrap_out.display()
348            )
349        }
350
351        if rust_info.is_from_tarball() && config.description.is_none() {
352            config.description = Some("built from a source tarball".to_owned());
353        }
354
355        let mut build = Build {
356            initial_lld,
357            initial_relative_libdir,
358            initial_rustc: config.initial_rustc.clone(),
359            initial_rustdoc: config.initial_rustc.with_file_name(exe("rustdoc", config.build)),
360            initial_cargo: config.initial_cargo.clone(),
361            initial_sysroot: config.initial_sysroot.clone(),
362            local_rebuild: config.local_rebuild,
363            fail_fast: config.cmd.fail_fast(),
364            doc_tests: config.cmd.doc_tests(),
365            verbosity: config.verbose,
366
367            build: config.build,
368            hosts: config.hosts.clone(),
369            targets: config.targets.clone(),
370
371            config,
372            version: version.to_string(),
373            src,
374            out,
375            bootstrap_out,
376
377            cargo_info,
378            rust_analyzer_info,
379            clippy_info,
380            miri_info,
381            rustfmt_info,
382            enzyme_info,
383            in_tree_llvm_info,
384            in_tree_gcc_info,
385            cc: RefCell::new(HashMap::new()),
386            cxx: RefCell::new(HashMap::new()),
387            ar: RefCell::new(HashMap::new()),
388            ranlib: RefCell::new(HashMap::new()),
389            crates: HashMap::new(),
390            crate_paths: HashMap::new(),
391            is_sudo,
392            delayed_failures: RefCell::new(Vec::new()),
393            prerelease_version: Cell::new(None),
394
395            #[cfg(feature = "build-metrics")]
396            metrics: crate::utils::metrics::BuildMetrics::init(),
397        };
398
399        // If local-rust is the same major.minor as the current version, then force a
400        // local-rebuild
401        let local_version_verbose =
402            output(Command::new(&build.initial_rustc).arg("--version").arg("--verbose"));
403        let local_release = local_version_verbose
404            .lines()
405            .filter_map(|x| x.strip_prefix("release:"))
406            .next()
407            .unwrap()
408            .trim();
409        if local_release.split('.').take(2).eq(version.split('.').take(2)) {
410            build.verbose(|| println!("auto-detected local-rebuild {local_release}"));
411            build.local_rebuild = true;
412        }
413
414        build.verbose(|| println!("finding compilers"));
415        utils::cc_detect::find(&build);
416        // When running `setup`, the profile is about to change, so any requirements we have now may
417        // be different on the next invocation. Don't check for them until the next time x.py is
418        // run. This is ok because `setup` never runs any build commands, so it won't fail if commands are missing.
419        //
420        // Similarly, for `setup` we don't actually need submodules or cargo metadata.
421        if !matches!(build.config.cmd, Subcommand::Setup { .. }) {
422            build.verbose(|| println!("running sanity check"));
423            crate::core::sanity::check(&mut build);
424
425            // Make sure we update these before gathering metadata so we don't get an error about missing
426            // Cargo.toml files.
427            let rust_submodules = ["library/backtrace", "library/stdarch"];
428            for s in rust_submodules {
429                build.require_submodule(
430                    s,
431                    Some(
432                        "The submodule is required for the standard library \
433                         and the main Cargo workspace.",
434                    ),
435                );
436            }
437            // Now, update all existing submodules.
438            build.update_existing_submodules();
439
440            build.verbose(|| println!("learning about cargo"));
441            crate::core::metadata::build(&mut build);
442        }
443
444        // Create symbolic link to use host sysroot from a consistent path (e.g., in the rust-analyzer config file).
445        let build_triple = build.out.join(build.build);
446        t!(fs::create_dir_all(&build_triple));
447        let host = build.out.join("host");
448        if host.is_symlink() {
449            // Left over from a previous build; overwrite it.
450            // This matters if `build.build` has changed between invocations.
451            #[cfg(windows)]
452            t!(fs::remove_dir(&host));
453            #[cfg(not(windows))]
454            t!(fs::remove_file(&host));
455        }
456        t!(
457            symlink_dir(&build.config, &build_triple, &host),
458            format!("symlink_dir({} => {}) failed", host.display(), build_triple.display())
459        );
460
461        build
462    }
463
464    /// Updates a submodule, and exits with a failure if submodule management
465    /// is disabled and the submodule does not exist.
466    ///
467    /// The given submodule name should be its path relative to the root of
468    /// the main repository.
469    ///
470    /// The given `err_hint` will be shown to the user if the submodule is not
471    /// checked out and submodule management is disabled.
472    pub fn require_submodule(&self, submodule: &str, err_hint: Option<&str>) {
473        // When testing bootstrap itself, it is much faster to ignore
474        // submodules. Almost all Steps work fine without their submodules.
475        if cfg!(test) && !self.config.submodules() {
476            return;
477        }
478        self.config.update_submodule(submodule);
479        let absolute_path = self.config.src.join(submodule);
480        if dir_is_empty(&absolute_path) {
481            let maybe_enable = if !self.config.submodules()
482                && self.config.rust_info.is_managed_git_subrepository()
483            {
484                "\nConsider setting `build.submodules = true` or manually initializing the submodules."
485            } else {
486                ""
487            };
488            let err_hint = err_hint.map_or_else(String::new, |e| format!("\n{e}"));
489            eprintln!(
490                "submodule {submodule} does not appear to be checked out, \
491                 but it is required for this step{maybe_enable}{err_hint}"
492            );
493            exit!(1);
494        }
495    }
496
497    /// Updates all submodules, and exits with an error if submodule
498    /// management is disabled and the submodule does not exist.
499    pub fn require_and_update_all_submodules(&self) {
500        for submodule in build_helper::util::parse_gitmodules(&self.src) {
501            self.require_submodule(submodule, None);
502        }
503    }
504
505    /// If any submodule has been initialized already, sync it unconditionally.
506    /// This avoids contributors checking in a submodule change by accident.
507    fn update_existing_submodules(&self) {
508        // Avoid running git when there isn't a git checkout, or the user has
509        // explicitly disabled submodules in `config.toml`.
510        if !self.config.submodules() {
511            return;
512        }
513        let output = helpers::git(Some(&self.src))
514            .args(["config", "--file"])
515            .arg(".gitmodules")
516            .args(["--get-regexp", "path"])
517            .run_capture(self)
518            .stdout();
519        std::thread::scope(|s| {
520            // Look for `submodule.$name.path = $path`
521            // Sample output: `submodule.src/rust-installer.path src/tools/rust-installer`
522            for line in output.lines() {
523                let submodule = line.split_once(' ').unwrap().1;
524                let config = self.config.clone();
525                s.spawn(move || {
526                    Self::update_existing_submodule(&config, submodule);
527                });
528            }
529        });
530    }
531
532    /// Updates the given submodule only if it's initialized already; nothing happens otherwise.
533    pub fn update_existing_submodule(config: &Config, submodule: &str) {
534        // Avoid running git when there isn't a git checkout.
535        if !config.submodules() {
536            return;
537        }
538
539        if GitInfo::new(false, Path::new(submodule)).is_managed_git_subrepository() {
540            config.update_submodule(submodule);
541        }
542    }
543
544    /// Executes the entire build, as configured by the flags and configuration.
545    #[cfg_attr(feature = "tracing", instrument(level = "debug", name = "Build::build", skip_all))]
546    pub fn build(&mut self) {
547        trace!("setting up job management");
548        unsafe {
549            crate::utils::job::setup(self);
550        }
551
552        // Download rustfmt early so that it can be used in rust-analyzer configs.
553        trace!("downloading rustfmt early");
554        let _ = &builder::Builder::new(self).initial_rustfmt();
555
556        // Handle hard-coded subcommands.
557        {
558            #[cfg(feature = "tracing")]
559            let _hardcoded_span = span!(
560                tracing::Level::DEBUG,
561                "handling hardcoded subcommands (Format, Suggest, Perf)"
562            )
563            .entered();
564
565            match &self.config.cmd {
566                Subcommand::Format { check, all } => {
567                    return core::build_steps::format::format(
568                        &builder::Builder::new(self),
569                        *check,
570                        *all,
571                        &self.config.paths,
572                    );
573                }
574                Subcommand::Suggest { run } => {
575                    return core::build_steps::suggest::suggest(&builder::Builder::new(self), *run);
576                }
577                Subcommand::Perf(args) => {
578                    return core::build_steps::perf::perf(&builder::Builder::new(self), args);
579                }
580                _cmd => {
581                    debug!(cmd = ?_cmd, "not a hardcoded subcommand; returning to normal handling");
582                }
583            }
584
585            debug!("handling subcommand normally");
586        }
587
588        if !self.config.dry_run() {
589            #[cfg(feature = "tracing")]
590            let _real_run_span = span!(tracing::Level::DEBUG, "executing real run").entered();
591
592            // We first do a dry-run. This is a sanity-check to ensure that
593            // steps don't do anything expensive in the dry-run.
594            {
595                #[cfg(feature = "tracing")]
596                let _sanity_check_span =
597                    span!(tracing::Level::DEBUG, "(1) executing dry-run sanity-check").entered();
598                self.config.dry_run = DryRun::SelfCheck;
599                let builder = builder::Builder::new(self);
600                builder.execute_cli();
601            }
602
603            // Actual run.
604            {
605                #[cfg(feature = "tracing")]
606                let _actual_run_span =
607                    span!(tracing::Level::DEBUG, "(2) executing actual run").entered();
608                self.config.dry_run = DryRun::Disabled;
609                let builder = builder::Builder::new(self);
610                builder.execute_cli();
611            }
612        } else {
613            #[cfg(feature = "tracing")]
614            let _dry_run_span = span!(tracing::Level::DEBUG, "executing dry run").entered();
615
616            let builder = builder::Builder::new(self);
617            builder.execute_cli();
618        }
619
620        #[cfg(feature = "tracing")]
621        debug!("checking for postponed test failures from `test  --no-fail-fast`");
622
623        // Check for postponed failures from `test --no-fail-fast`.
624        let failures = self.delayed_failures.borrow();
625        if failures.len() > 0 {
626            eprintln!("\n{} command(s) did not execute successfully:\n", failures.len());
627            for failure in failures.iter() {
628                eprintln!("  - {failure}\n");
629            }
630            exit!(1);
631        }
632
633        #[cfg(feature = "build-metrics")]
634        self.metrics.persist(self);
635    }
636
637    fn rust_info(&self) -> &GitInfo {
638        &self.config.rust_info
639    }
640
641    /// Gets the space-separated set of activated features for the standard library.
642    /// This can be configured with the `std-features` key in config.toml.
643    fn std_features(&self, target: TargetSelection) -> String {
644        let mut features: BTreeSet<&str> =
645            self.config.rust_std_features.iter().map(|s| s.as_str()).collect();
646
647        match self.config.llvm_libunwind(target) {
648            LlvmLibunwind::InTree => features.insert("llvm-libunwind"),
649            LlvmLibunwind::System => features.insert("system-llvm-libunwind"),
650            LlvmLibunwind::No => false,
651        };
652
653        if self.config.backtrace {
654            features.insert("backtrace");
655        }
656
657        if self.config.profiler_enabled(target) {
658            features.insert("profiler");
659        }
660
661        // If zkvm target, generate memcpy, etc.
662        if target.contains("zkvm") {
663            features.insert("compiler-builtins-mem");
664        }
665
666        features.into_iter().collect::<Vec<_>>().join(" ")
667    }
668
669    /// Gets the space-separated set of activated features for the compiler.
670    fn rustc_features(&self, kind: Kind, target: TargetSelection, crates: &[String]) -> String {
671        let possible_features_by_crates: HashSet<_> = crates
672            .iter()
673            .flat_map(|krate| &self.crates[krate].features)
674            .map(std::ops::Deref::deref)
675            .collect();
676        let check = |feature: &str| -> bool {
677            crates.is_empty() || possible_features_by_crates.contains(feature)
678        };
679        let mut features = vec![];
680        if self.config.jemalloc && check("jemalloc") {
681            features.push("jemalloc");
682        }
683        if (self.config.llvm_enabled(target) || kind == Kind::Check) && check("llvm") {
684            features.push("llvm");
685        }
686        // keep in sync with `bootstrap/compile.rs:rustc_cargo_env`
687        if self.config.rust_randomize_layout {
688            features.push("rustc_randomized_layouts");
689        }
690
691        // If debug logging is on, then we want the default for tracing:
692        // https://github.com/tokio-rs/tracing/blob/3dd5c03d907afdf2c39444a29931833335171554/tracing/src/level_filters.rs#L26
693        // which is everything (including debug/trace/etc.)
694        // if its unset, if debug_assertions is on, then debug_logging will also be on
695        // as well as tracing *ignoring* this feature when debug_assertions is on
696        if !self.config.rust_debug_logging && check("max_level_info") {
697            features.push("max_level_info");
698        }
699
700        features.join(" ")
701    }
702
703    /// Component directory that Cargo will produce output into (e.g.
704    /// release/debug)
705    fn cargo_dir(&self) -> &'static str {
706        if self.config.rust_optimize.is_release() { "release" } else { "debug" }
707    }
708
709    fn tools_dir(&self, compiler: Compiler) -> PathBuf {
710        let out = self.out.join(compiler.host).join(format!("stage{}-tools-bin", compiler.stage));
711        t!(fs::create_dir_all(&out));
712        out
713    }
714
715    /// Returns the root directory for all output generated in a particular
716    /// stage when running with a particular host compiler.
717    ///
718    /// The mode indicates what the root directory is for.
719    fn stage_out(&self, compiler: Compiler, mode: Mode) -> PathBuf {
720        let suffix = match mode {
721            Mode::Std => "-std",
722            Mode::Rustc => "-rustc",
723            Mode::Codegen => "-codegen",
724            Mode::ToolBootstrap => "-bootstrap-tools",
725            Mode::ToolStd | Mode::ToolRustc => "-tools",
726        };
727        self.out.join(compiler.host).join(format!("stage{}{}", compiler.stage, suffix))
728    }
729
730    /// Returns the root output directory for all Cargo output in a given stage,
731    /// running a particular compiler, whether or not we're building the
732    /// standard library, and targeting the specified architecture.
733    fn cargo_out(&self, compiler: Compiler, mode: Mode, target: TargetSelection) -> PathBuf {
734        self.stage_out(compiler, mode).join(target).join(self.cargo_dir())
735    }
736
737    /// Root output directory of LLVM for `target`
738    ///
739    /// Note that if LLVM is configured externally then the directory returned
740    /// will likely be empty.
741    fn llvm_out(&self, target: TargetSelection) -> PathBuf {
742        if self.config.llvm_from_ci && self.is_builder_target(&target) {
743            self.config.ci_llvm_root()
744        } else {
745            self.out.join(target).join("llvm")
746        }
747    }
748
749    fn enzyme_out(&self, target: TargetSelection) -> PathBuf {
750        self.out.join(&*target.triple).join("enzyme")
751    }
752
753    fn gcc_out(&self, target: TargetSelection) -> PathBuf {
754        self.out.join(&*target.triple).join("gcc")
755    }
756
757    fn lld_out(&self, target: TargetSelection) -> PathBuf {
758        self.out.join(target).join("lld")
759    }
760
761    /// Output directory for all documentation for a target
762    fn doc_out(&self, target: TargetSelection) -> PathBuf {
763        self.out.join(target).join("doc")
764    }
765
766    /// Output directory for all JSON-formatted documentation for a target
767    fn json_doc_out(&self, target: TargetSelection) -> PathBuf {
768        self.out.join(target).join("json-doc")
769    }
770
771    fn test_out(&self, target: TargetSelection) -> PathBuf {
772        self.out.join(target).join("test")
773    }
774
775    /// Output directory for all documentation for a target
776    fn compiler_doc_out(&self, target: TargetSelection) -> PathBuf {
777        self.out.join(target).join("compiler-doc")
778    }
779
780    /// Output directory for some generated md crate documentation for a target (temporary)
781    fn md_doc_out(&self, target: TargetSelection) -> PathBuf {
782        self.out.join(target).join("md-doc")
783    }
784
785    /// Returns `true` if this is an external version of LLVM not managed by bootstrap.
786    /// In particular, we expect llvm sources to be available when this is false.
787    ///
788    /// NOTE: this is not the same as `!is_rust_llvm` when `llvm_has_patches` is set.
789    fn is_system_llvm(&self, target: TargetSelection) -> bool {
790        match self.config.target_config.get(&target) {
791            Some(Target { llvm_config: Some(_), .. }) => {
792                let ci_llvm = self.config.llvm_from_ci && self.is_builder_target(&target);
793                !ci_llvm
794            }
795            // We're building from the in-tree src/llvm-project sources.
796            Some(Target { llvm_config: None, .. }) => false,
797            None => false,
798        }
799    }
800
801    /// Returns `true` if this is our custom, patched, version of LLVM.
802    ///
803    /// This does not necessarily imply that we're managing the `llvm-project` submodule.
804    fn is_rust_llvm(&self, target: TargetSelection) -> bool {
805        match self.config.target_config.get(&target) {
806            // We're using a user-controlled version of LLVM. The user has explicitly told us whether the version has our patches.
807            // (They might be wrong, but that's not a supported use-case.)
808            // In particular, this tries to support `submodules = false` and `patches = false`, for using a newer version of LLVM that's not through `rust-lang/llvm-project`.
809            Some(Target { llvm_has_rust_patches: Some(patched), .. }) => *patched,
810            // The user hasn't promised the patches match.
811            // This only has our patches if it's downloaded from CI or built from source.
812            _ => !self.is_system_llvm(target),
813        }
814    }
815
816    /// Returns the path to `FileCheck` binary for the specified target
817    fn llvm_filecheck(&self, target: TargetSelection) -> PathBuf {
818        let target_config = self.config.target_config.get(&target);
819        if let Some(s) = target_config.and_then(|c| c.llvm_filecheck.as_ref()) {
820            s.to_path_buf()
821        } else if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
822            let llvm_bindir = command(s).arg("--bindir").run_capture_stdout(self).stdout();
823            let filecheck = Path::new(llvm_bindir.trim()).join(exe("FileCheck", target));
824            if filecheck.exists() {
825                filecheck
826            } else {
827                // On Fedora the system LLVM installs FileCheck in the
828                // llvm subdirectory of the libdir.
829                let llvm_libdir = command(s).arg("--libdir").run_capture_stdout(self).stdout();
830                let lib_filecheck =
831                    Path::new(llvm_libdir.trim()).join("llvm").join(exe("FileCheck", target));
832                if lib_filecheck.exists() {
833                    lib_filecheck
834                } else {
835                    // Return the most normal file name, even though
836                    // it doesn't exist, so that any error message
837                    // refers to that.
838                    filecheck
839                }
840            }
841        } else {
842            let base = self.llvm_out(target).join("build");
843            let base = if !self.ninja() && target.is_msvc() {
844                if self.config.llvm_optimize {
845                    if self.config.llvm_release_debuginfo {
846                        base.join("RelWithDebInfo")
847                    } else {
848                        base.join("Release")
849                    }
850                } else {
851                    base.join("Debug")
852                }
853            } else {
854                base
855            };
856            base.join("bin").join(exe("FileCheck", target))
857        }
858    }
859
860    /// Directory for libraries built from C/C++ code and shared between stages.
861    fn native_dir(&self, target: TargetSelection) -> PathBuf {
862        self.out.join(target).join("native")
863    }
864
865    /// Root output directory for rust_test_helpers library compiled for
866    /// `target`
867    fn test_helpers_out(&self, target: TargetSelection) -> PathBuf {
868        self.native_dir(target).join("rust-test-helpers")
869    }
870
871    /// Adds the `RUST_TEST_THREADS` env var if necessary
872    fn add_rust_test_threads(&self, cmd: &mut BootstrapCommand) {
873        if env::var_os("RUST_TEST_THREADS").is_none() {
874            cmd.env("RUST_TEST_THREADS", self.jobs().to_string());
875        }
876    }
877
878    /// Returns the libdir of the snapshot compiler.
879    fn rustc_snapshot_libdir(&self) -> PathBuf {
880        self.rustc_snapshot_sysroot().join(libdir(self.config.build))
881    }
882
883    /// Returns the sysroot of the snapshot compiler.
884    fn rustc_snapshot_sysroot(&self) -> &Path {
885        static SYSROOT_CACHE: OnceLock<PathBuf> = OnceLock::new();
886        SYSROOT_CACHE.get_or_init(|| {
887            let mut rustc = Command::new(&self.initial_rustc);
888            rustc.args(["--print", "sysroot"]);
889            output(&mut rustc).trim().into()
890        })
891    }
892
893    /// Execute a command and return its output.
894    /// Note: Ideally, you should use one of the BootstrapCommand::run* functions to
895    /// execute commands. They internally call this method.
896    #[track_caller]
897    fn run(
898        &self,
899        command: &mut BootstrapCommand,
900        stdout: OutputMode,
901        stderr: OutputMode,
902    ) -> CommandOutput {
903        command.mark_as_executed();
904        if self.config.dry_run() && !command.run_always {
905            return CommandOutput::default();
906        }
907
908        #[cfg(feature = "tracing")]
909        let _run_span = trace_cmd!(command);
910
911        let created_at = command.get_created_location();
912        let executed_at = std::panic::Location::caller();
913
914        self.verbose(|| {
915            println!("running: {command:?} (created at {created_at}, executed at {executed_at})")
916        });
917
918        let cmd = command.as_command_mut();
919        cmd.stdout(stdout.stdio());
920        cmd.stderr(stderr.stdio());
921
922        let output = cmd.output();
923
924        use std::fmt::Write;
925
926        let mut message = String::new();
927        let output: CommandOutput = match output {
928            // Command has succeeded
929            Ok(output) if output.status.success() => {
930                CommandOutput::from_output(output, stdout, stderr)
931            }
932            // Command has started, but then it failed
933            Ok(output) => {
934                writeln!(
935                    message,
936                    r#"
937Command {command:?} did not execute successfully.
938Expected success, got {}
939Created at: {created_at}
940Executed at: {executed_at}"#,
941                    output.status,
942                )
943                .unwrap();
944
945                let output: CommandOutput = CommandOutput::from_output(output, stdout, stderr);
946
947                // If the output mode is OutputMode::Capture, we can now print the output.
948                // If it is OutputMode::Print, then the output has already been printed to
949                // stdout/stderr, and we thus don't have anything captured to print anyway.
950                if stdout.captures() {
951                    writeln!(message, "\nSTDOUT ----\n{}", output.stdout().trim()).unwrap();
952                }
953                if stderr.captures() {
954                    writeln!(message, "\nSTDERR ----\n{}", output.stderr().trim()).unwrap();
955                }
956                output
957            }
958            // The command did not even start
959            Err(e) => {
960                writeln!(
961                    message,
962                    "\n\nCommand {command:?} did not execute successfully.\
963            \nIt was not possible to execute the command: {e:?}"
964                )
965                .unwrap();
966                CommandOutput::did_not_start(stdout, stderr)
967            }
968        };
969
970        let fail = |message: &str, output: CommandOutput| -> ! {
971            if self.is_verbose() {
972                println!("{message}");
973            } else {
974                let (stdout, stderr) = (output.stdout_if_present(), output.stderr_if_present());
975                // If the command captures output, the user would not see any indication that
976                // it has failed. In this case, print a more verbose error, since to provide more
977                // context.
978                if stdout.is_some() || stderr.is_some() {
979                    if let Some(stdout) =
980                        output.stdout_if_present().take_if(|s| !s.trim().is_empty())
981                    {
982                        println!("STDOUT:\n{stdout}\n");
983                    }
984                    if let Some(stderr) =
985                        output.stderr_if_present().take_if(|s| !s.trim().is_empty())
986                    {
987                        println!("STDERR:\n{stderr}\n");
988                    }
989                    println!("Command {command:?} has failed. Rerun with -v to see more details.");
990                } else {
991                    println!("Command has failed. Rerun with -v to see more details.");
992                }
993            }
994            exit!(1);
995        };
996
997        if !output.is_success() {
998            match command.failure_behavior {
999                BehaviorOnFailure::DelayFail => {
1000                    if self.fail_fast {
1001                        fail(&message, output);
1002                    }
1003
1004                    let mut failures = self.delayed_failures.borrow_mut();
1005                    failures.push(message);
1006                }
1007                BehaviorOnFailure::Exit => {
1008                    fail(&message, output);
1009                }
1010                BehaviorOnFailure::Ignore => {
1011                    // If failures are allowed, either the error has been printed already
1012                    // (OutputMode::Print) or the user used a capture output mode and wants to
1013                    // handle the error output on their own.
1014                }
1015            }
1016        }
1017        output
1018    }
1019
1020    /// Check if verbosity is greater than the `level`
1021    pub fn is_verbose_than(&self, level: usize) -> bool {
1022        self.verbosity > level
1023    }
1024
1025    /// Runs a function if verbosity is greater than `level`.
1026    fn verbose_than(&self, level: usize, f: impl Fn()) {
1027        if self.is_verbose_than(level) {
1028            f()
1029        }
1030    }
1031
1032    fn info(&self, msg: &str) {
1033        match self.config.dry_run {
1034            DryRun::SelfCheck => (),
1035            DryRun::Disabled | DryRun::UserSelected => {
1036                println!("{msg}");
1037            }
1038        }
1039    }
1040
1041    #[must_use = "Groups should not be dropped until the Step finishes running"]
1042    #[track_caller]
1043    fn msg_clippy(
1044        &self,
1045        what: impl Display,
1046        target: impl Into<Option<TargetSelection>>,
1047    ) -> Option<gha::Group> {
1048        self.msg(Kind::Clippy, self.config.stage, what, self.config.build, target)
1049    }
1050
1051    #[must_use = "Groups should not be dropped until the Step finishes running"]
1052    #[track_caller]
1053    fn msg_check(
1054        &self,
1055        what: impl Display,
1056        target: impl Into<Option<TargetSelection>>,
1057    ) -> Option<gha::Group> {
1058        self.msg(Kind::Check, self.config.stage, what, self.config.build, target)
1059    }
1060
1061    #[must_use = "Groups should not be dropped until the Step finishes running"]
1062    #[track_caller]
1063    fn msg_doc(
1064        &self,
1065        compiler: Compiler,
1066        what: impl Display,
1067        target: impl Into<Option<TargetSelection>> + Copy,
1068    ) -> Option<gha::Group> {
1069        self.msg(Kind::Doc, compiler.stage, what, compiler.host, target.into())
1070    }
1071
1072    #[must_use = "Groups should not be dropped until the Step finishes running"]
1073    #[track_caller]
1074    fn msg_build(
1075        &self,
1076        compiler: Compiler,
1077        what: impl Display,
1078        target: impl Into<Option<TargetSelection>>,
1079    ) -> Option<gha::Group> {
1080        self.msg(Kind::Build, compiler.stage, what, compiler.host, target)
1081    }
1082
1083    /// Return a `Group` guard for a [`Step`] that is built for each `--stage`.
1084    ///
1085    /// [`Step`]: crate::core::builder::Step
1086    #[must_use = "Groups should not be dropped until the Step finishes running"]
1087    #[track_caller]
1088    fn msg(
1089        &self,
1090        action: impl Into<Kind>,
1091        stage: u32,
1092        what: impl Display,
1093        host: impl Into<Option<TargetSelection>>,
1094        target: impl Into<Option<TargetSelection>>,
1095    ) -> Option<gha::Group> {
1096        let action = action.into().description();
1097        let msg = |fmt| format!("{action} stage{stage} {what}{fmt}");
1098        let msg = if let Some(target) = target.into() {
1099            let host = host.into().unwrap();
1100            if host == target {
1101                msg(format_args!(" ({target})"))
1102            } else {
1103                msg(format_args!(" ({host} -> {target})"))
1104            }
1105        } else {
1106            msg(format_args!(""))
1107        };
1108        self.group(&msg)
1109    }
1110
1111    /// Return a `Group` guard for a [`Step`] that is only built once and isn't affected by `--stage`.
1112    ///
1113    /// [`Step`]: crate::core::builder::Step
1114    #[must_use = "Groups should not be dropped until the Step finishes running"]
1115    #[track_caller]
1116    fn msg_unstaged(
1117        &self,
1118        action: impl Into<Kind>,
1119        what: impl Display,
1120        target: TargetSelection,
1121    ) -> Option<gha::Group> {
1122        let action = action.into().description();
1123        let msg = format!("{action} {what} for {target}");
1124        self.group(&msg)
1125    }
1126
1127    #[must_use = "Groups should not be dropped until the Step finishes running"]
1128    #[track_caller]
1129    fn msg_sysroot_tool(
1130        &self,
1131        action: impl Into<Kind>,
1132        stage: u32,
1133        what: impl Display,
1134        host: TargetSelection,
1135        target: TargetSelection,
1136    ) -> Option<gha::Group> {
1137        let action = action.into().description();
1138        let msg = |fmt| format!("{action} {what} {fmt}");
1139        let msg = if host == target {
1140            msg(format_args!("(stage{stage} -> stage{}, {target})", stage + 1))
1141        } else {
1142            msg(format_args!("(stage{stage}:{host} -> stage{}:{target})", stage + 1))
1143        };
1144        self.group(&msg)
1145    }
1146
1147    #[track_caller]
1148    fn group(&self, msg: &str) -> Option<gha::Group> {
1149        match self.config.dry_run {
1150            DryRun::SelfCheck => None,
1151            DryRun::Disabled | DryRun::UserSelected => Some(gha::group(msg)),
1152        }
1153    }
1154
1155    /// Returns the number of parallel jobs that have been configured for this
1156    /// build.
1157    fn jobs(&self) -> u32 {
1158        self.config.jobs.unwrap_or_else(|| {
1159            std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get) as u32
1160        })
1161    }
1162
1163    fn debuginfo_map_to(&self, which: GitRepo) -> Option<String> {
1164        if !self.config.rust_remap_debuginfo {
1165            return None;
1166        }
1167
1168        match which {
1169            GitRepo::Rustc => {
1170                let sha = self.rust_sha().unwrap_or(&self.version);
1171                Some(format!("/rustc/{sha}"))
1172            }
1173            GitRepo::Llvm => Some(String::from("/rustc/llvm")),
1174        }
1175    }
1176
1177    /// Returns the path to the C compiler for the target specified.
1178    fn cc(&self, target: TargetSelection) -> PathBuf {
1179        if self.config.dry_run() {
1180            return PathBuf::new();
1181        }
1182        self.cc.borrow()[&target].path().into()
1183    }
1184
1185    /// Returns C flags that `cc-rs` thinks should be enabled for the
1186    /// specified target by default.
1187    fn cc_handled_clags(&self, target: TargetSelection, c: CLang) -> Vec<String> {
1188        if self.config.dry_run() {
1189            return Vec::new();
1190        }
1191        let base = match c {
1192            CLang::C => self.cc.borrow()[&target].clone(),
1193            CLang::Cxx => self.cxx.borrow()[&target].clone(),
1194        };
1195
1196        // Filter out -O and /O (the optimization flags) that we picked up
1197        // from cc-rs, that's up to the caller to figure out.
1198        base.args()
1199            .iter()
1200            .map(|s| s.to_string_lossy().into_owned())
1201            .filter(|s| !s.starts_with("-O") && !s.starts_with("/O"))
1202            .collect::<Vec<String>>()
1203    }
1204
1205    /// Returns extra C flags that `cc-rs` doesn't handle.
1206    fn cc_unhandled_cflags(
1207        &self,
1208        target: TargetSelection,
1209        which: GitRepo,
1210        c: CLang,
1211    ) -> Vec<String> {
1212        let mut base = Vec::new();
1213
1214        // If we're compiling C++ on macOS then we add a flag indicating that
1215        // we want libc++ (more filled out than libstdc++), ensuring that
1216        // LLVM/etc are all properly compiled.
1217        if matches!(c, CLang::Cxx) && target.contains("apple-darwin") {
1218            base.push("-stdlib=libc++".into());
1219        }
1220
1221        // Work around an apparently bad MinGW / GCC optimization,
1222        // See: https://lists.llvm.org/pipermail/cfe-dev/2016-December/051980.html
1223        // See: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=78936
1224        if &*target.triple == "i686-pc-windows-gnu" {
1225            base.push("-fno-omit-frame-pointer".into());
1226        }
1227
1228        if let Some(map_to) = self.debuginfo_map_to(which) {
1229            let map = format!("{}={}", self.src.display(), map_to);
1230            let cc = self.cc(target);
1231            if cc.ends_with("clang") || cc.ends_with("gcc") {
1232                base.push(format!("-fdebug-prefix-map={map}"));
1233            } else if cc.ends_with("clang-cl.exe") {
1234                base.push("-Xclang".into());
1235                base.push(format!("-fdebug-prefix-map={map}"));
1236            }
1237        }
1238        base
1239    }
1240
1241    /// Returns the path to the `ar` archive utility for the target specified.
1242    fn ar(&self, target: TargetSelection) -> Option<PathBuf> {
1243        if self.config.dry_run() {
1244            return None;
1245        }
1246        self.ar.borrow().get(&target).cloned()
1247    }
1248
1249    /// Returns the path to the `ranlib` utility for the target specified.
1250    fn ranlib(&self, target: TargetSelection) -> Option<PathBuf> {
1251        if self.config.dry_run() {
1252            return None;
1253        }
1254        self.ranlib.borrow().get(&target).cloned()
1255    }
1256
1257    /// Returns the path to the C++ compiler for the target specified.
1258    fn cxx(&self, target: TargetSelection) -> Result<PathBuf, String> {
1259        if self.config.dry_run() {
1260            return Ok(PathBuf::new());
1261        }
1262        match self.cxx.borrow().get(&target) {
1263            Some(p) => Ok(p.path().into()),
1264            None => Err(format!("target `{target}` is not configured as a host, only as a target")),
1265        }
1266    }
1267
1268    /// Returns the path to the linker for the given target if it needs to be overridden.
1269    fn linker(&self, target: TargetSelection) -> Option<PathBuf> {
1270        if self.config.dry_run() {
1271            return Some(PathBuf::new());
1272        }
1273        if let Some(linker) = self.config.target_config.get(&target).and_then(|c| c.linker.clone())
1274        {
1275            Some(linker)
1276        } else if target.contains("vxworks") {
1277            // need to use CXX compiler as linker to resolve the exception functions
1278            // that are only existed in CXX libraries
1279            Some(self.cxx.borrow()[&target].path().into())
1280        } else if !self.is_builder_target(&target)
1281            && helpers::use_host_linker(target)
1282            && !target.is_msvc()
1283        {
1284            Some(self.cc(target))
1285        } else if self.config.lld_mode.is_used()
1286            && self.is_lld_direct_linker(target)
1287            && self.build == target
1288        {
1289            match self.config.lld_mode {
1290                LldMode::SelfContained => Some(self.initial_lld.clone()),
1291                LldMode::External => Some("lld".into()),
1292                LldMode::Unused => None,
1293            }
1294        } else {
1295            None
1296        }
1297    }
1298
1299    // Is LLD configured directly through `-Clinker`?
1300    // Only MSVC targets use LLD directly at the moment.
1301    fn is_lld_direct_linker(&self, target: TargetSelection) -> bool {
1302        target.is_msvc()
1303    }
1304
1305    /// Returns if this target should statically link the C runtime, if specified
1306    fn crt_static(&self, target: TargetSelection) -> Option<bool> {
1307        if target.contains("pc-windows-msvc") {
1308            Some(true)
1309        } else {
1310            self.config.target_config.get(&target).and_then(|t| t.crt_static)
1311        }
1312    }
1313
1314    /// Returns the "musl root" for this `target`, if defined
1315    fn musl_root(&self, target: TargetSelection) -> Option<&Path> {
1316        self.config
1317            .target_config
1318            .get(&target)
1319            .and_then(|t| t.musl_root.as_ref())
1320            .or(self.config.musl_root.as_ref())
1321            .map(|p| &**p)
1322    }
1323
1324    /// Returns the "musl libdir" for this `target`.
1325    fn musl_libdir(&self, target: TargetSelection) -> Option<PathBuf> {
1326        let t = self.config.target_config.get(&target)?;
1327        if let libdir @ Some(_) = &t.musl_libdir {
1328            return libdir.clone();
1329        }
1330        self.musl_root(target).map(|root| root.join("lib"))
1331    }
1332
1333    /// Returns the `lib` directory for the WASI target specified, if
1334    /// configured.
1335    ///
1336    /// This first consults `wasi-root` as configured in per-target
1337    /// configuration, and failing that it assumes that `$WASI_SDK_PATH` is
1338    /// set in the environment, and failing that `None` is returned.
1339    fn wasi_libdir(&self, target: TargetSelection) -> Option<PathBuf> {
1340        let configured =
1341            self.config.target_config.get(&target).and_then(|t| t.wasi_root.as_ref()).map(|p| &**p);
1342        if let Some(path) = configured {
1343            return Some(path.join("lib").join(target.to_string()));
1344        }
1345        let mut env_root = PathBuf::from(std::env::var_os("WASI_SDK_PATH")?);
1346        env_root.push("share");
1347        env_root.push("wasi-sysroot");
1348        env_root.push("lib");
1349        env_root.push(target.to_string());
1350        Some(env_root)
1351    }
1352
1353    /// Returns `true` if this is a no-std `target`, if defined
1354    fn no_std(&self, target: TargetSelection) -> Option<bool> {
1355        self.config.target_config.get(&target).map(|t| t.no_std)
1356    }
1357
1358    /// Returns `true` if the target will be tested using the `remote-test-client`
1359    /// and `remote-test-server` binaries.
1360    fn remote_tested(&self, target: TargetSelection) -> bool {
1361        self.qemu_rootfs(target).is_some()
1362            || target.contains("android")
1363            || env::var_os("TEST_DEVICE_ADDR").is_some()
1364    }
1365
1366    /// Returns an optional "runner" to pass to `compiletest` when executing
1367    /// test binaries.
1368    ///
1369    /// An example of this would be a WebAssembly runtime when testing the wasm
1370    /// targets.
1371    fn runner(&self, target: TargetSelection) -> Option<String> {
1372        let configured_runner =
1373            self.config.target_config.get(&target).and_then(|t| t.runner.as_ref()).map(|p| &**p);
1374        if let Some(runner) = configured_runner {
1375            return Some(runner.to_owned());
1376        }
1377
1378        if target.starts_with("wasm") && target.contains("wasi") {
1379            self.default_wasi_runner(target)
1380        } else {
1381            None
1382        }
1383    }
1384
1385    /// When a `runner` configuration is not provided and a WASI-looking target
1386    /// is being tested this is consulted to prove the environment to see if
1387    /// there's a runtime already lying around that seems reasonable to use.
1388    fn default_wasi_runner(&self, target: TargetSelection) -> Option<String> {
1389        let mut finder = crate::core::sanity::Finder::new();
1390
1391        // Look for Wasmtime, and for its default options be sure to disable
1392        // its caching system since we're executing quite a lot of tests and
1393        // ideally shouldn't pollute the cache too much.
1394        if let Some(path) = finder.maybe_have("wasmtime") {
1395            if let Ok(mut path) = path.into_os_string().into_string() {
1396                path.push_str(" run -C cache=n --dir .");
1397                // Make sure that tests have access to RUSTC_BOOTSTRAP. This (for example) is
1398                // required for libtest to work on beta/stable channels.
1399                //
1400                // NB: with Wasmtime 20 this can change to `-S inherit-env` to
1401                // inherit the entire environment rather than just this single
1402                // environment variable.
1403                path.push_str(" --env RUSTC_BOOTSTRAP");
1404
1405                if target.contains("wasip2") {
1406                    path.push_str(" --wasi inherit-network --wasi allow-ip-name-lookup");
1407                }
1408
1409                return Some(path);
1410            }
1411        }
1412
1413        None
1414    }
1415
1416    /// Returns whether the specified tool is configured as part of this build.
1417    ///
1418    /// This requires that both the `extended` key is set and the `tools` key is
1419    /// either unset or specifically contains the specified tool.
1420    fn tool_enabled(&self, tool: &str) -> bool {
1421        if !self.config.extended {
1422            return false;
1423        }
1424        match &self.config.tools {
1425            Some(set) => set.contains(tool),
1426            None => true,
1427        }
1428    }
1429
1430    /// Returns the root of the "rootfs" image that this target will be using,
1431    /// if one was configured.
1432    ///
1433    /// If `Some` is returned then that means that tests for this target are
1434    /// emulated with QEMU and binaries will need to be shipped to the emulator.
1435    fn qemu_rootfs(&self, target: TargetSelection) -> Option<&Path> {
1436        self.config.target_config.get(&target).and_then(|t| t.qemu_rootfs.as_ref()).map(|p| &**p)
1437    }
1438
1439    /// Path to the python interpreter to use
1440    fn python(&self) -> &Path {
1441        if self.config.build.ends_with("apple-darwin") {
1442            // Force /usr/bin/python3 on macOS for LLDB tests because we're loading the
1443            // LLDB plugin's compiled module which only works with the system python
1444            // (namely not Homebrew-installed python)
1445            Path::new("/usr/bin/python3")
1446        } else {
1447            self.config
1448                .python
1449                .as_ref()
1450                .expect("python is required for running LLDB or rustdoc tests")
1451        }
1452    }
1453
1454    /// Temporary directory that extended error information is emitted to.
1455    fn extended_error_dir(&self) -> PathBuf {
1456        self.out.join("tmp/extended-error-metadata")
1457    }
1458
1459    /// Tests whether the `compiler` compiling for `target` should be forced to
1460    /// use a stage1 compiler instead.
1461    ///
1462    /// Currently, by default, the build system does not perform a "full
1463    /// bootstrap" by default where we compile the compiler three times.
1464    /// Instead, we compile the compiler two times. The final stage (stage2)
1465    /// just copies the libraries from the previous stage, which is what this
1466    /// method detects.
1467    ///
1468    /// Here we return `true` if:
1469    ///
1470    /// * The build isn't performing a full bootstrap
1471    /// * The `compiler` is in the final stage, 2
1472    /// * We're not cross-compiling, so the artifacts are already available in
1473    ///   stage1
1474    ///
1475    /// When all of these conditions are met the build will lift artifacts from
1476    /// the previous stage forward.
1477    fn force_use_stage1(&self, stage: u32, target: TargetSelection) -> bool {
1478        !self.config.full_bootstrap
1479            && !self.config.download_rustc()
1480            && stage >= 2
1481            && (self.hosts.iter().any(|h| *h == target) || target == self.build)
1482    }
1483
1484    /// Checks whether the `compiler` compiling for `target` should be forced to
1485    /// use a stage2 compiler instead.
1486    ///
1487    /// When we download the pre-compiled version of rustc and compiler stage is >= 2,
1488    /// it should be forced to use a stage2 compiler.
1489    fn force_use_stage2(&self, stage: u32) -> bool {
1490        self.config.download_rustc() && stage >= 2
1491    }
1492
1493    /// Given `num` in the form "a.b.c" return a "release string" which
1494    /// describes the release version number.
1495    ///
1496    /// For example on nightly this returns "a.b.c-nightly", on beta it returns
1497    /// "a.b.c-beta.1" and on stable it just returns "a.b.c".
1498    fn release(&self, num: &str) -> String {
1499        match &self.config.channel[..] {
1500            "stable" => num.to_string(),
1501            "beta" => {
1502                if !self.config.omit_git_hash {
1503                    format!("{}-beta.{}", num, self.beta_prerelease_version())
1504                } else {
1505                    format!("{num}-beta")
1506                }
1507            }
1508            "nightly" => format!("{num}-nightly"),
1509            _ => format!("{num}-dev"),
1510        }
1511    }
1512
1513    fn beta_prerelease_version(&self) -> u32 {
1514        fn extract_beta_rev_from_file<P: AsRef<Path>>(version_file: P) -> Option<String> {
1515            let version = fs::read_to_string(version_file).ok()?;
1516
1517            helpers::extract_beta_rev(&version)
1518        }
1519
1520        if let Some(s) = self.prerelease_version.get() {
1521            return s;
1522        }
1523
1524        // First check if there is a version file available.
1525        // If available, we read the beta revision from that file.
1526        // This only happens when building from a source tarball when Git should not be used.
1527        let count = extract_beta_rev_from_file(self.src.join("version")).unwrap_or_else(|| {
1528            // Figure out how many merge commits happened since we branched off master.
1529            // That's our beta number!
1530            // (Note that we use a `..` range, not the `...` symmetric difference.)
1531            helpers::git(Some(&self.src))
1532                .arg("rev-list")
1533                .arg("--count")
1534                .arg("--merges")
1535                .arg(format!(
1536                    "refs/remotes/origin/{}..HEAD",
1537                    self.config.stage0_metadata.config.nightly_branch
1538                ))
1539                .run_always()
1540                .run_capture(self)
1541                .stdout()
1542        });
1543        let n = count.trim().parse().unwrap();
1544        self.prerelease_version.set(Some(n));
1545        n
1546    }
1547
1548    /// Returns the value of `release` above for Rust itself.
1549    fn rust_release(&self) -> String {
1550        self.release(&self.version)
1551    }
1552
1553    /// Returns the "package version" for a component given the `num` release
1554    /// number.
1555    ///
1556    /// The package version is typically what shows up in the names of tarballs.
1557    /// For channels like beta/nightly it's just the channel name, otherwise
1558    /// it's the `num` provided.
1559    fn package_vers(&self, num: &str) -> String {
1560        match &self.config.channel[..] {
1561            "stable" => num.to_string(),
1562            "beta" => "beta".to_string(),
1563            "nightly" => "nightly".to_string(),
1564            _ => format!("{num}-dev"),
1565        }
1566    }
1567
1568    /// Returns the value of `package_vers` above for Rust itself.
1569    fn rust_package_vers(&self) -> String {
1570        self.package_vers(&self.version)
1571    }
1572
1573    /// Returns the `version` string associated with this compiler for Rust
1574    /// itself.
1575    ///
1576    /// Note that this is a descriptive string which includes the commit date,
1577    /// sha, version, etc.
1578    fn rust_version(&self) -> String {
1579        let mut version = self.rust_info().version(self, &self.version);
1580        if let Some(ref s) = self.config.description {
1581            if !s.is_empty() {
1582                version.push_str(" (");
1583                version.push_str(s);
1584                version.push(')');
1585            }
1586        }
1587        version
1588    }
1589
1590    /// Returns the full commit hash.
1591    fn rust_sha(&self) -> Option<&str> {
1592        self.rust_info().sha()
1593    }
1594
1595    /// Returns the `a.b.c` version that the given package is at.
1596    fn release_num(&self, package: &str) -> String {
1597        let toml_file_name = self.src.join(format!("src/tools/{package}/Cargo.toml"));
1598        let toml = t!(fs::read_to_string(toml_file_name));
1599        for line in toml.lines() {
1600            if let Some(stripped) =
1601                line.strip_prefix("version = \"").and_then(|s| s.strip_suffix('"'))
1602            {
1603                return stripped.to_owned();
1604            }
1605        }
1606
1607        panic!("failed to find version in {package}'s Cargo.toml")
1608    }
1609
1610    /// Returns `true` if unstable features should be enabled for the compiler
1611    /// we're building.
1612    fn unstable_features(&self) -> bool {
1613        !matches!(&self.config.channel[..], "stable" | "beta")
1614    }
1615
1616    /// Returns a Vec of all the dependencies of the given root crate,
1617    /// including transitive dependencies and the root itself. Only includes
1618    /// "local" crates (those in the local source tree, not from a registry).
1619    fn in_tree_crates(&self, root: &str, target: Option<TargetSelection>) -> Vec<&Crate> {
1620        let mut ret = Vec::new();
1621        let mut list = vec![root.to_owned()];
1622        let mut visited = HashSet::new();
1623        while let Some(krate) = list.pop() {
1624            let krate = self
1625                .crates
1626                .get(&krate)
1627                .unwrap_or_else(|| panic!("metadata missing for {krate}: {:?}", self.crates));
1628            ret.push(krate);
1629            for dep in &krate.deps {
1630                if !self.crates.contains_key(dep) {
1631                    // Ignore non-workspace members.
1632                    continue;
1633                }
1634                // Don't include optional deps if their features are not
1635                // enabled. Ideally this would be computed from `cargo
1636                // metadata --features …`, but that is somewhat slow. In
1637                // the future, we may want to consider just filtering all
1638                // build and dev dependencies in metadata::build.
1639                if visited.insert(dep)
1640                    && (dep != "profiler_builtins"
1641                        || target
1642                            .map(|t| self.config.profiler_enabled(t))
1643                            .unwrap_or_else(|| self.config.any_profiler_enabled()))
1644                    && (dep != "rustc_codegen_llvm"
1645                        || self.config.hosts.iter().any(|host| self.config.llvm_enabled(*host)))
1646                {
1647                    list.push(dep.clone());
1648                }
1649            }
1650        }
1651        ret.sort_unstable_by_key(|krate| krate.name.clone()); // reproducible order needed for tests
1652        ret
1653    }
1654
1655    fn read_stamp_file(&self, stamp: &BuildStamp) -> Vec<(PathBuf, DependencyType)> {
1656        if self.config.dry_run() {
1657            return Vec::new();
1658        }
1659
1660        if !stamp.path().exists() {
1661            eprintln!(
1662                "ERROR: Unable to find the stamp file {}, did you try to keep a nonexistent build stage?",
1663                stamp.path().display()
1664            );
1665            crate::exit!(1);
1666        }
1667
1668        let mut paths = Vec::new();
1669        let contents = t!(fs::read(stamp.path()), stamp.path());
1670        // This is the method we use for extracting paths from the stamp file passed to us. See
1671        // run_cargo for more information (in compile.rs).
1672        for part in contents.split(|b| *b == 0) {
1673            if part.is_empty() {
1674                continue;
1675            }
1676            let dependency_type = match part[0] as char {
1677                'h' => DependencyType::Host,
1678                's' => DependencyType::TargetSelfContained,
1679                't' => DependencyType::Target,
1680                _ => unreachable!(),
1681            };
1682            let path = PathBuf::from(t!(str::from_utf8(&part[1..])));
1683            paths.push((path, dependency_type));
1684        }
1685        paths
1686    }
1687
1688    /// Copies a file from `src` to `dst`.
1689    ///
1690    /// If `src` is a symlink, `src` will be resolved to the actual path
1691    /// and copied to `dst` instead of the symlink itself.
1692    pub fn resolve_symlink_and_copy(&self, src: &Path, dst: &Path) {
1693        self.copy_link_internal(src, dst, true);
1694    }
1695
1696    /// Links a file from `src` to `dst`.
1697    /// Attempts to use hard links if possible, falling back to copying.
1698    /// You can neither rely on this being a copy nor it being a link,
1699    /// so do not write to dst.
1700    pub fn copy_link(&self, src: &Path, dst: &Path) {
1701        self.copy_link_internal(src, dst, false);
1702    }
1703
1704    fn copy_link_internal(&self, src: &Path, dst: &Path, dereference_symlinks: bool) {
1705        if self.config.dry_run() {
1706            return;
1707        }
1708        self.verbose_than(1, || println!("Copy/Link {src:?} to {dst:?}"));
1709        if src == dst {
1710            return;
1711        }
1712        if let Err(e) = fs::remove_file(dst) {
1713            if cfg!(windows) && e.kind() != io::ErrorKind::NotFound {
1714                // workaround for https://github.com/rust-lang/rust/issues/127126
1715                // if removing the file fails, attempt to rename it instead.
1716                let now = t!(SystemTime::now().duration_since(SystemTime::UNIX_EPOCH));
1717                let _ = fs::rename(dst, format!("{}-{}", dst.display(), now.as_nanos()));
1718            }
1719        }
1720        let metadata = t!(src.symlink_metadata(), format!("src = {}", src.display()));
1721        let mut src = src.to_path_buf();
1722        if metadata.file_type().is_symlink() {
1723            if dereference_symlinks {
1724                src = t!(fs::canonicalize(src));
1725            } else {
1726                let link = t!(fs::read_link(src));
1727                t!(self.symlink_file(link, dst));
1728                return;
1729            }
1730        }
1731        if let Ok(()) = fs::hard_link(&src, dst) {
1732            // Attempt to "easy copy" by creating a hard link (symlinks are privileged on windows),
1733            // but if that fails just fall back to a slow `copy` operation.
1734        } else {
1735            if let Err(e) = fs::copy(&src, dst) {
1736                panic!("failed to copy `{}` to `{}`: {}", src.display(), dst.display(), e)
1737            }
1738            t!(fs::set_permissions(dst, metadata.permissions()));
1739
1740            // Restore file times because changing permissions on e.g. Linux using `chmod` can cause
1741            // file access time to change.
1742            let file_times = fs::FileTimes::new()
1743                .set_accessed(t!(metadata.accessed()))
1744                .set_modified(t!(metadata.modified()));
1745            t!(set_file_times(dst, file_times));
1746        }
1747    }
1748
1749    /// Links the `src` directory recursively to `dst`. Both are assumed to exist
1750    /// when this function is called.
1751    /// Will attempt to use hard links if possible and fall back to copying.
1752    pub fn cp_link_r(&self, src: &Path, dst: &Path) {
1753        if self.config.dry_run() {
1754            return;
1755        }
1756        for f in self.read_dir(src) {
1757            let path = f.path();
1758            let name = path.file_name().unwrap();
1759            let dst = dst.join(name);
1760            if t!(f.file_type()).is_dir() {
1761                t!(fs::create_dir_all(&dst));
1762                self.cp_link_r(&path, &dst);
1763            } else {
1764                self.copy_link(&path, &dst);
1765            }
1766        }
1767    }
1768
1769    /// Copies the `src` directory recursively to `dst`. Both are assumed to exist
1770    /// when this function is called.
1771    /// Will attempt to use hard links if possible and fall back to copying.
1772    /// Unwanted files or directories can be skipped
1773    /// by returning `false` from the filter function.
1774    pub fn cp_link_filtered(&self, src: &Path, dst: &Path, filter: &dyn Fn(&Path) -> bool) {
1775        // Immediately recurse with an empty relative path
1776        self.cp_link_filtered_recurse(src, dst, Path::new(""), filter)
1777    }
1778
1779    // Inner function does the actual work
1780    fn cp_link_filtered_recurse(
1781        &self,
1782        src: &Path,
1783        dst: &Path,
1784        relative: &Path,
1785        filter: &dyn Fn(&Path) -> bool,
1786    ) {
1787        for f in self.read_dir(src) {
1788            let path = f.path();
1789            let name = path.file_name().unwrap();
1790            let dst = dst.join(name);
1791            let relative = relative.join(name);
1792            // Only copy file or directory if the filter function returns true
1793            if filter(&relative) {
1794                if t!(f.file_type()).is_dir() {
1795                    let _ = fs::remove_dir_all(&dst);
1796                    self.create_dir(&dst);
1797                    self.cp_link_filtered_recurse(&path, &dst, &relative, filter);
1798                } else {
1799                    let _ = fs::remove_file(&dst);
1800                    self.copy_link(&path, &dst);
1801                }
1802            }
1803        }
1804    }
1805
1806    fn copy_link_to_folder(&self, src: &Path, dest_folder: &Path) {
1807        let file_name = src.file_name().unwrap();
1808        let dest = dest_folder.join(file_name);
1809        self.copy_link(src, &dest);
1810    }
1811
1812    fn install(&self, src: &Path, dstdir: &Path, perms: u32) {
1813        if self.config.dry_run() {
1814            return;
1815        }
1816        let dst = dstdir.join(src.file_name().unwrap());
1817        self.verbose_than(1, || println!("Install {src:?} to {dst:?}"));
1818        t!(fs::create_dir_all(dstdir));
1819        if !src.exists() {
1820            panic!("ERROR: File \"{}\" not found!", src.display());
1821        }
1822        self.copy_link_internal(src, &dst, true);
1823        chmod(&dst, perms);
1824    }
1825
1826    fn read(&self, path: &Path) -> String {
1827        if self.config.dry_run() {
1828            return String::new();
1829        }
1830        t!(fs::read_to_string(path))
1831    }
1832
1833    fn create_dir(&self, dir: &Path) {
1834        if self.config.dry_run() {
1835            return;
1836        }
1837        t!(fs::create_dir_all(dir))
1838    }
1839
1840    fn remove_dir(&self, dir: &Path) {
1841        if self.config.dry_run() {
1842            return;
1843        }
1844        t!(fs::remove_dir_all(dir))
1845    }
1846
1847    fn read_dir(&self, dir: &Path) -> impl Iterator<Item = fs::DirEntry> {
1848        let iter = match fs::read_dir(dir) {
1849            Ok(v) => v,
1850            Err(_) if self.config.dry_run() => return vec![].into_iter(),
1851            Err(err) => panic!("could not read dir {dir:?}: {err:?}"),
1852        };
1853        iter.map(|e| t!(e)).collect::<Vec<_>>().into_iter()
1854    }
1855
1856    fn symlink_file<P: AsRef<Path>, Q: AsRef<Path>>(&self, src: P, link: Q) -> io::Result<()> {
1857        #[cfg(unix)]
1858        use std::os::unix::fs::symlink as symlink_file;
1859        #[cfg(windows)]
1860        use std::os::windows::fs::symlink_file;
1861        if !self.config.dry_run() { symlink_file(src.as_ref(), link.as_ref()) } else { Ok(()) }
1862    }
1863
1864    /// Returns if config.ninja is enabled, and checks for ninja existence,
1865    /// exiting with a nicer error message if not.
1866    fn ninja(&self) -> bool {
1867        let mut cmd_finder = crate::core::sanity::Finder::new();
1868
1869        if self.config.ninja_in_file {
1870            // Some Linux distros rename `ninja` to `ninja-build`.
1871            // CMake can work with either binary name.
1872            if cmd_finder.maybe_have("ninja-build").is_none()
1873                && cmd_finder.maybe_have("ninja").is_none()
1874            {
1875                eprintln!(
1876                    "
1877Couldn't find required command: ninja (or ninja-build)
1878
1879You should install ninja as described at
1880<https://github.com/ninja-build/ninja/wiki/Pre-built-Ninja-packages>,
1881or set `ninja = false` in the `[llvm]` section of `config.toml`.
1882Alternatively, set `download-ci-llvm = true` in that `[llvm]` section
1883to download LLVM rather than building it.
1884"
1885                );
1886                exit!(1);
1887            }
1888        }
1889
1890        // If ninja isn't enabled but we're building for MSVC then we try
1891        // doubly hard to enable it. It was realized in #43767 that the msbuild
1892        // CMake generator for MSVC doesn't respect configuration options like
1893        // disabling LLVM assertions, which can often be quite important!
1894        //
1895        // In these cases we automatically enable Ninja if we find it in the
1896        // environment.
1897        if !self.config.ninja_in_file
1898            && self.config.build.is_msvc()
1899            && cmd_finder.maybe_have("ninja").is_some()
1900        {
1901            return true;
1902        }
1903
1904        self.config.ninja_in_file
1905    }
1906
1907    pub fn colored_stdout<R, F: FnOnce(&mut dyn WriteColor) -> R>(&self, f: F) -> R {
1908        self.colored_stream_inner(StandardStream::stdout, self.config.stdout_is_tty, f)
1909    }
1910
1911    pub fn colored_stderr<R, F: FnOnce(&mut dyn WriteColor) -> R>(&self, f: F) -> R {
1912        self.colored_stream_inner(StandardStream::stderr, self.config.stderr_is_tty, f)
1913    }
1914
1915    fn colored_stream_inner<R, F, C>(&self, constructor: C, is_tty: bool, f: F) -> R
1916    where
1917        C: Fn(ColorChoice) -> StandardStream,
1918        F: FnOnce(&mut dyn WriteColor) -> R,
1919    {
1920        let choice = match self.config.color {
1921            flags::Color::Always => ColorChoice::Always,
1922            flags::Color::Never => ColorChoice::Never,
1923            flags::Color::Auto if !is_tty => ColorChoice::Never,
1924            flags::Color::Auto => ColorChoice::Auto,
1925        };
1926        let mut stream = constructor(choice);
1927        let result = f(&mut stream);
1928        stream.reset().unwrap();
1929        result
1930    }
1931
1932    /// Checks if the given target is the same as the builder target.
1933    fn is_builder_target(&self, target: &TargetSelection) -> bool {
1934        &self.config.build == target
1935    }
1936}
1937
1938#[cfg(unix)]
1939fn chmod(path: &Path, perms: u32) {
1940    use std::os::unix::fs::*;
1941    t!(fs::set_permissions(path, fs::Permissions::from_mode(perms)));
1942}
1943#[cfg(windows)]
1944fn chmod(_path: &Path, _perms: u32) {}
1945
1946impl Compiler {
1947    pub fn with_stage(mut self, stage: u32) -> Compiler {
1948        self.stage = stage;
1949        self
1950    }
1951
1952    /// Returns `true` if this is a snapshot compiler for `build`'s configuration
1953    pub fn is_snapshot(&self, build: &Build) -> bool {
1954        self.stage == 0 && self.host == build.build
1955    }
1956}
1957
1958fn envify(s: &str) -> String {
1959    s.chars()
1960        .map(|c| match c {
1961            '-' => '_',
1962            c => c,
1963        })
1964        .flat_map(|c| c.to_uppercase())
1965        .collect()
1966}
1967
1968/// Ensures that the behavior dump directory is properly initialized.
1969pub fn prepare_behaviour_dump_dir(build: &Build) {
1970    static INITIALIZED: OnceLock<bool> = OnceLock::new();
1971
1972    let dump_path = build.out.join("bootstrap-shims-dump");
1973
1974    let initialized = INITIALIZED.get().unwrap_or(&false);
1975    if !initialized {
1976        // clear old dumps
1977        if dump_path.exists() {
1978            t!(fs::remove_dir_all(&dump_path));
1979        }
1980
1981        t!(fs::create_dir_all(&dump_path));
1982
1983        t!(INITIALIZED.set(true));
1984    }
1985}