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