Skip to main content

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