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