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