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