bootstrap/
lib.rs

1//! Implementation of bootstrap, the Rust build system.
2//!
3//! This module, and its descendants, are the implementation of the Rust build
4//! system. Most of this build system is backed by Cargo but the outer layer
5//! here serves as the ability to orchestrate calling Cargo, sequencing Cargo
6//! builds, building artifacts like LLVM, etc. The goals of bootstrap are:
7//!
8//! * To be an easily understandable, easily extensible, and maintainable build
9//!   system.
10//! * Leverage standard tools in the Rust ecosystem to build the compiler, aka
11//!   crates.io and Cargo.
12//! * A standard interface to build across all platforms, including MSVC
13//!
14//! ## Further information
15//!
16//! More documentation can be found in each respective module below, and you can
17//! also check out the `src/bootstrap/README.md` file for more information.
18#![cfg_attr(test, allow(unused))]
19
20use std::cell::Cell;
21use std::collections::{BTreeSet, HashMap, HashSet};
22use std::fmt::Display;
23use std::path::{Path, PathBuf};
24use std::sync::OnceLock;
25use std::time::{Instant, SystemTime};
26use std::{env, fs, io, str};
27
28use build_helper::ci::gha;
29use build_helper::exit;
30use cc::Tool;
31use termcolor::{ColorChoice, StandardStream, WriteColor};
32use utils::build_stamp::BuildStamp;
33use utils::channel::GitInfo;
34use utils::exec::ExecutionContext;
35
36use crate::core::builder;
37use crate::core::builder::Kind;
38use crate::core::config::{DryRun, LldMode, LlvmLibunwind, TargetSelection, flags};
39use crate::utils::exec::{BootstrapCommand, command};
40use crate::utils::helpers::{
41    self, dir_is_empty, exe, libdir, set_file_times, split_debuginfo, symlink_dir,
42};
43
44mod core;
45mod utils;
46
47pub use core::builder::PathSet;
48pub use core::config::flags::{Flags, Subcommand};
49pub use core::config::{ChangeId, Config};
50
51#[cfg(feature = "tracing")]
52use tracing::{instrument, span};
53pub use utils::change_tracker::{
54    CONFIG_CHANGE_HISTORY, find_recent_config_change_ids, human_readable_changes,
55};
56pub use utils::helpers::PanicTracker;
57
58use crate::core::build_steps::vendor::VENDOR_DIR;
59
60const LLVM_TOOLS: &[&str] = &[
61    "llvm-cov",      // used to generate coverage report
62    "llvm-nm",       // used to inspect binaries; it shows symbol names, their sizes and visibility
63    "llvm-objcopy",  // used to transform ELFs into binary format which flashing tools consume
64    "llvm-objdump",  // used to disassemble programs
65    "llvm-profdata", // used to inspect and merge files generated by profiles
66    "llvm-readobj",  // used to get information from ELFs/objects that the other tools don't provide
67    "llvm-size",     // used to prints the size of the linker sections of a program
68    "llvm-strip",    // used to discard symbols from binary files to reduce their size
69    "llvm-ar",       // used for creating and modifying archive files
70    "llvm-as",       // used to convert LLVM assembly to LLVM bitcode
71    "llvm-dis",      // used to disassemble LLVM bitcode
72    "llvm-link",     // Used to link LLVM bitcode
73    "llc",           // used to compile LLVM bytecode
74    "opt",           // used to optimize LLVM bytecode
75];
76
77/// LLD file names for all flavors.
78const LLD_FILE_NAMES: &[&str] = &["ld.lld", "ld64.lld", "lld-link", "wasm-ld"];
79
80/// Extra `--check-cfg` to add when building the compiler or tools
81/// (Mode restriction, config name, config values (if any))
82#[expect(clippy::type_complexity)] // It's fine for hard-coded list and type is explained above.
83const EXTRA_CHECK_CFGS: &[(Option<Mode>, &str, Option<&[&'static str]>)] = &[
84    (Some(Mode::Rustc), "bootstrap", None),
85    (Some(Mode::Codegen), "bootstrap", None),
86    (Some(Mode::ToolRustc), "bootstrap", None),
87    (Some(Mode::ToolStd), "bootstrap", None),
88    (Some(Mode::Rustc), "llvm_enzyme", None),
89    (Some(Mode::Codegen), "llvm_enzyme", None),
90    (Some(Mode::ToolRustc), "llvm_enzyme", None),
91    (Some(Mode::ToolRustc), "rust_analyzer", None),
92    (Some(Mode::ToolStd), "rust_analyzer", None),
93    // Any library specific cfgs like `target_os`, `target_arch` should be put in
94    // priority the `[lints.rust.unexpected_cfgs.check-cfg]` table
95    // in the appropriate `library/{std,alloc,core}/Cargo.toml`
96];
97
98/// A structure representing a Rust compiler.
99///
100/// Each compiler has a `stage` that it is associated with and a `host` that
101/// corresponds to the platform the compiler runs on. This structure is used as
102/// a parameter to many methods below.
103#[derive(Eq, PartialOrd, Ord, Clone, Copy, Debug)]
104pub struct Compiler {
105    stage: u32,
106    host: TargetSelection,
107    /// Indicates whether the compiler was forced to use a specific stage.
108    /// This field is ignored in `Hash` and `PartialEq` implementations as only the `stage`
109    /// and `host` fields are relevant for those.
110    forced_compiler: bool,
111}
112
113impl std::hash::Hash for Compiler {
114    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
115        self.stage.hash(state);
116        self.host.hash(state);
117    }
118}
119
120impl PartialEq for Compiler {
121    fn eq(&self, other: &Self) -> bool {
122        self.stage == other.stage && self.host == other.host
123    }
124}
125
126/// Represents a codegen backend.
127#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
128pub enum CodegenBackendKind {
129    #[default]
130    Llvm,
131    Cranelift,
132    Gcc,
133    Custom(String),
134}
135
136impl CodegenBackendKind {
137    /// Name of the codegen backend, as identified in the `compiler` directory
138    /// (`rustc_codegen_<name>`).
139    pub fn name(&self) -> &str {
140        match self {
141            CodegenBackendKind::Llvm => "llvm",
142            CodegenBackendKind::Cranelift => "cranelift",
143            CodegenBackendKind::Gcc => "gcc",
144            CodegenBackendKind::Custom(name) => name,
145        }
146    }
147
148    /// Name of the codegen backend's crate, e.g. `rustc_codegen_cranelift`.
149    pub fn crate_name(&self) -> String {
150        format!("rustc_codegen_{}", self.name())
151    }
152
153    pub fn is_llvm(&self) -> bool {
154        matches!(self, Self::Llvm)
155    }
156
157    pub fn is_cranelift(&self) -> bool {
158        matches!(self, Self::Cranelift)
159    }
160
161    pub fn is_gcc(&self) -> bool {
162        matches!(self, Self::Gcc)
163    }
164}
165
166#[derive(PartialEq, Eq, Copy, Clone, Debug)]
167pub enum DocTests {
168    /// Run normal tests and doc tests (default).
169    Yes,
170    /// Do not run any doc tests.
171    No,
172    /// Only run doc tests.
173    Only,
174}
175
176pub enum GitRepo {
177    Rustc,
178    Llvm,
179}
180
181/// Global configuration for the build system.
182///
183/// This structure transitively contains all configuration for the build system.
184/// All filesystem-encoded configuration is in `config`, all flags are in
185/// `flags`, and then parsed or probed information is listed in the keys below.
186///
187/// This structure is a parameter of almost all methods in the build system,
188/// although most functions are implemented as free functions rather than
189/// methods specifically on this structure itself (to make it easier to
190/// organize).
191#[derive(Clone)]
192pub struct Build {
193    /// User-specified configuration from `bootstrap.toml`.
194    config: Config,
195
196    // Version information
197    version: String,
198
199    // Properties derived from the above configuration
200    src: PathBuf,
201    out: PathBuf,
202    bootstrap_out: PathBuf,
203    cargo_info: GitInfo,
204    rust_analyzer_info: GitInfo,
205    clippy_info: GitInfo,
206    miri_info: GitInfo,
207    rustfmt_info: GitInfo,
208    enzyme_info: GitInfo,
209    in_tree_llvm_info: GitInfo,
210    in_tree_gcc_info: GitInfo,
211    local_rebuild: bool,
212    fail_fast: bool,
213    doc_tests: DocTests,
214    verbosity: usize,
215
216    /// Build triple for the pre-compiled snapshot compiler.
217    host_target: TargetSelection,
218    /// Which triples to produce a compiler toolchain for.
219    hosts: Vec<TargetSelection>,
220    /// Which triples to build libraries (core/alloc/std/test/proc_macro) for.
221    targets: Vec<TargetSelection>,
222
223    initial_rustc: PathBuf,
224    initial_rustdoc: PathBuf,
225    initial_cargo: PathBuf,
226    initial_lld: PathBuf,
227    initial_relative_libdir: PathBuf,
228    initial_sysroot: PathBuf,
229
230    // Runtime state filled in later on
231    // C/C++ compilers and archiver for all targets
232    cc: HashMap<TargetSelection, cc::Tool>,
233    cxx: HashMap<TargetSelection, cc::Tool>,
234    ar: HashMap<TargetSelection, PathBuf>,
235    ranlib: HashMap<TargetSelection, PathBuf>,
236    wasi_sdk_path: Option<PathBuf>,
237
238    // Miscellaneous
239    // allow bidirectional lookups: both name -> path and path -> name
240    crates: HashMap<String, Crate>,
241    crate_paths: HashMap<PathBuf, String>,
242    is_sudo: bool,
243    prerelease_version: Cell<Option<u32>>,
244
245    #[cfg(feature = "build-metrics")]
246    metrics: crate::utils::metrics::BuildMetrics,
247}
248
249#[derive(Debug, Clone)]
250struct Crate {
251    name: String,
252    deps: HashSet<String>,
253    path: PathBuf,
254    features: Vec<String>,
255}
256
257impl Crate {
258    fn local_path(&self, build: &Build) -> PathBuf {
259        self.path.strip_prefix(&build.config.src).unwrap().into()
260    }
261}
262
263/// When building Rust various objects are handled differently.
264#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
265pub enum DependencyType {
266    /// Libraries originating from proc-macros.
267    Host,
268    /// Typical Rust libraries.
269    Target,
270    /// Non Rust libraries and objects shipped to ease usage of certain targets.
271    TargetSelfContained,
272}
273
274/// The various "modes" of invoking Cargo.
275///
276/// These entries currently correspond to the various output directories of the
277/// build system, with each mod generating output in a different directory.
278#[derive(Debug, Hash, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
279pub enum Mode {
280    /// Build the standard library, placing output in the "stageN-std" directory.
281    Std,
282
283    /// Build librustc, and compiler libraries, placing output in the "stageN-rustc" directory.
284    Rustc,
285
286    /// Build a codegen backend for rustc, placing the output in the "stageN-codegen" directory.
287    Codegen,
288
289    /// Build a tool, placing output in the "bootstrap-tools"
290    /// directory. This is for miscellaneous sets of tools that extend
291    /// bootstrap.
292    ///
293    /// These tools are intended to be only executed on the host system that
294    /// invokes bootstrap, and they thus cannot be cross-compiled.
295    ///
296    /// They are always built using the stage0 compiler, and they
297    /// can be compiled with stable Rust.
298    ///
299    /// These tools also essentially do not participate in staging.
300    ToolBootstrap,
301
302    /// Build a cross-compilable helper tool. These tools do not depend on unstable features or
303    /// compiler internals, but they might be cross-compilable (so we cannot build them using the
304    /// stage0 compiler, unlike `ToolBootstrap`).
305    ///
306    /// Some of these tools are also shipped in our `dist` archives.
307    /// While we could compile them using the stage0 compiler when not cross-compiling, we instead
308    /// use the in-tree compiler (and std) to build them, so that we can ship e.g. std security
309    /// fixes and avoid depending fully on stage0 for the artifacts that we ship.
310    ///
311    /// This mode is used e.g. for linkers and linker tools invoked by rustc on its host target.
312    ToolTarget,
313
314    /// Build a tool which uses the locally built std, placing output in the
315    /// "stageN-tools" directory. Its usage is quite rare, mainly used by
316    /// compiletest which needs libtest.
317    ToolStd,
318
319    /// Build a tool which uses the locally built rustc and the target std,
320    /// placing the output in the "stageN-tools" directory. This is used for
321    /// anything that needs a fully functional rustc, such as rustdoc, clippy,
322    /// cargo, rustfmt, miri, etc.
323    ToolRustc,
324}
325
326impl Mode {
327    pub fn is_tool(&self) -> bool {
328        match self {
329            Mode::ToolBootstrap | Mode::ToolRustc | Mode::ToolStd | Mode::ToolTarget => true,
330            Mode::Std | Mode::Codegen | Mode::Rustc => false,
331        }
332    }
333
334    pub fn must_support_dlopen(&self) -> bool {
335        match self {
336            Mode::Std | Mode::Codegen => true,
337            Mode::ToolBootstrap
338            | Mode::ToolRustc
339            | Mode::ToolStd
340            | Mode::ToolTarget
341            | Mode::Rustc => false,
342        }
343    }
344}
345
346/// When `rust.rust_remap_debuginfo` is requested, the compiler needs to know how to
347/// opportunistically unremap compiler vs non-compiler sources. We use two schemes,
348/// [`RemapScheme::Compiler`] and [`RemapScheme::NonCompiler`].
349pub enum RemapScheme {
350    /// The [`RemapScheme::Compiler`] scheme will remap to `/rustc-dev/{hash}`.
351    Compiler,
352    /// The [`RemapScheme::NonCompiler`] scheme will remap to `/rustc/{hash}`.
353    NonCompiler,
354}
355
356#[derive(Debug, Hash, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
357pub enum CLang {
358    C,
359    Cxx,
360}
361
362#[derive(Debug, Clone, Copy, PartialEq, Eq)]
363pub enum FileType {
364    /// An executable binary file (like a `.exe`).
365    Executable,
366    /// A native, binary library file (like a `.so`, `.dll`, `.a`, `.lib` or `.o`).
367    NativeLibrary,
368    /// An executable (non-binary) script file (like a `.py` or `.sh`).
369    Script,
370    /// Any other regular file that is non-executable.
371    Regular,
372}
373
374impl FileType {
375    /// Get Unix permissions appropriate for this file type.
376    pub fn perms(self) -> u32 {
377        match self {
378            FileType::Executable | FileType::Script => 0o755,
379            FileType::Regular | FileType::NativeLibrary => 0o644,
380        }
381    }
382
383    pub fn could_have_split_debuginfo(self) -> bool {
384        match self {
385            FileType::Executable | FileType::NativeLibrary => true,
386            FileType::Script | FileType::Regular => false,
387        }
388    }
389}
390
391macro_rules! forward {
392    ( $( $fn:ident( $($param:ident: $ty:ty),* ) $( -> $ret:ty)? ),+ $(,)? ) => {
393        impl Build {
394            $( fn $fn(&self, $($param: $ty),* ) $( -> $ret)? {
395                self.config.$fn( $($param),* )
396            } )+
397        }
398    }
399}
400
401forward! {
402    verbose(f: impl Fn()),
403    is_verbose() -> bool,
404    create(path: &Path, s: &str),
405    remove(f: &Path),
406    tempdir() -> PathBuf,
407    llvm_link_shared() -> bool,
408    download_rustc() -> bool,
409}
410
411impl Build {
412    /// Creates a new set of build configuration from the `flags` on the command
413    /// line and the filesystem `config`.
414    ///
415    /// By default all build output will be placed in the current directory.
416    pub fn new(mut config: Config) -> Build {
417        let src = config.src.clone();
418        let out = config.out.clone();
419
420        #[cfg(unix)]
421        // keep this consistent with the equivalent check in x.py:
422        // https://github.com/rust-lang/rust/blob/a8a33cf27166d3eabaffc58ed3799e054af3b0c6/src/bootstrap/bootstrap.py#L796-L797
423        let is_sudo = match env::var_os("SUDO_USER") {
424            Some(_sudo_user) => {
425                // SAFETY: getuid() system call is always successful and no return value is reserved
426                // to indicate an error.
427                //
428                // For more context, see https://man7.org/linux/man-pages/man2/geteuid.2.html
429                let uid = unsafe { libc::getuid() };
430                uid == 0
431            }
432            None => false,
433        };
434        #[cfg(not(unix))]
435        let is_sudo = false;
436
437        let rust_info = config.rust_info.clone();
438        let cargo_info = config.cargo_info.clone();
439        let rust_analyzer_info = config.rust_analyzer_info.clone();
440        let clippy_info = config.clippy_info.clone();
441        let miri_info = config.miri_info.clone();
442        let rustfmt_info = config.rustfmt_info.clone();
443        let enzyme_info = config.enzyme_info.clone();
444        let in_tree_llvm_info = config.in_tree_llvm_info.clone();
445        let in_tree_gcc_info = config.in_tree_gcc_info.clone();
446
447        let initial_target_libdir = command(&config.initial_rustc)
448            .run_in_dry_run()
449            .args(["--print", "target-libdir"])
450            .run_capture_stdout(&config)
451            .stdout()
452            .trim()
453            .to_owned();
454
455        let initial_target_dir = Path::new(&initial_target_libdir)
456            .parent()
457            .unwrap_or_else(|| panic!("{initial_target_libdir} has no parent"));
458
459        let initial_lld = initial_target_dir.join("bin").join("rust-lld");
460
461        let initial_relative_libdir = if cfg!(test) {
462            // On tests, bootstrap uses the shim rustc, not the one from the stage0 toolchain.
463            PathBuf::default()
464        } else {
465            let ancestor = initial_target_dir.ancestors().nth(2).unwrap_or_else(|| {
466                panic!("Not enough ancestors for {}", initial_target_dir.display())
467            });
468
469            ancestor
470                .strip_prefix(&config.initial_sysroot)
471                .unwrap_or_else(|_| {
472                    panic!(
473                        "Couldn’t resolve the initial relative libdir from {}",
474                        initial_target_dir.display()
475                    )
476                })
477                .to_path_buf()
478        };
479
480        let version = std::fs::read_to_string(src.join("src").join("version"))
481            .expect("failed to read src/version");
482        let version = version.trim();
483
484        let mut bootstrap_out = std::env::current_exe()
485            .expect("could not determine path to running process")
486            .parent()
487            .unwrap()
488            .to_path_buf();
489        // Since bootstrap is hardlink to deps/bootstrap-*, Solaris can sometimes give
490        // path with deps/ which is bad and needs to be avoided.
491        if bootstrap_out.ends_with("deps") {
492            bootstrap_out.pop();
493        }
494        if !bootstrap_out.join(exe("rustc", config.host_target)).exists() && !cfg!(test) {
495            // this restriction can be lifted whenever https://github.com/rust-lang/rfcs/pull/3028 is implemented
496            panic!(
497                "`rustc` not found in {}, run `cargo build --bins` before `cargo run`",
498                bootstrap_out.display()
499            )
500        }
501
502        if rust_info.is_from_tarball() && config.description.is_none() {
503            config.description = Some("built from a source tarball".to_owned());
504        }
505
506        let mut build = Build {
507            initial_lld,
508            initial_relative_libdir,
509            initial_rustc: config.initial_rustc.clone(),
510            initial_rustdoc: config
511                .initial_rustc
512                .with_file_name(exe("rustdoc", config.host_target)),
513            initial_cargo: config.initial_cargo.clone(),
514            initial_sysroot: config.initial_sysroot.clone(),
515            local_rebuild: config.local_rebuild,
516            fail_fast: config.cmd.fail_fast(),
517            doc_tests: config.cmd.doc_tests(),
518            verbosity: config.verbose,
519
520            host_target: config.host_target,
521            hosts: config.hosts.clone(),
522            targets: config.targets.clone(),
523
524            config,
525            version: version.to_string(),
526            src,
527            out,
528            bootstrap_out,
529
530            cargo_info,
531            rust_analyzer_info,
532            clippy_info,
533            miri_info,
534            rustfmt_info,
535            enzyme_info,
536            in_tree_llvm_info,
537            in_tree_gcc_info,
538            cc: HashMap::new(),
539            cxx: HashMap::new(),
540            ar: HashMap::new(),
541            ranlib: HashMap::new(),
542            wasi_sdk_path: env::var_os("WASI_SDK_PATH").map(PathBuf::from),
543            crates: HashMap::new(),
544            crate_paths: HashMap::new(),
545            is_sudo,
546            prerelease_version: Cell::new(None),
547
548            #[cfg(feature = "build-metrics")]
549            metrics: crate::utils::metrics::BuildMetrics::init(),
550        };
551
552        // If local-rust is the same major.minor as the current version, then force a
553        // local-rebuild
554        let local_version_verbose = command(&build.initial_rustc)
555            .run_in_dry_run()
556            .args(["--version", "--verbose"])
557            .run_capture_stdout(&build)
558            .stdout();
559        let local_release = local_version_verbose
560            .lines()
561            .filter_map(|x| x.strip_prefix("release:"))
562            .next()
563            .unwrap()
564            .trim();
565        if local_release.split('.').take(2).eq(version.split('.').take(2)) {
566            build.verbose(|| println!("auto-detected local-rebuild {local_release}"));
567            build.local_rebuild = true;
568        }
569
570        build.verbose(|| println!("finding compilers"));
571        utils::cc_detect::fill_compilers(&mut build);
572        // When running `setup`, the profile is about to change, so any requirements we have now may
573        // be different on the next invocation. Don't check for them until the next time x.py is
574        // run. This is ok because `setup` never runs any build commands, so it won't fail if commands are missing.
575        //
576        // Similarly, for `setup` we don't actually need submodules or cargo metadata.
577        if !matches!(build.config.cmd, Subcommand::Setup { .. }) {
578            build.verbose(|| println!("running sanity check"));
579            crate::core::sanity::check(&mut build);
580
581            // Make sure we update these before gathering metadata so we don't get an error about missing
582            // Cargo.toml files.
583            let rust_submodules = ["library/backtrace"];
584            for s in rust_submodules {
585                build.require_submodule(
586                    s,
587                    Some(
588                        "The submodule is required for the standard library \
589                         and the main Cargo workspace.",
590                    ),
591                );
592            }
593            // Now, update all existing submodules.
594            build.update_existing_submodules();
595
596            build.verbose(|| println!("learning about cargo"));
597            crate::core::metadata::build(&mut build);
598        }
599
600        // Create symbolic link to use host sysroot from a consistent path (e.g., in the rust-analyzer config file).
601        let build_triple = build.out.join(build.host_target);
602        t!(fs::create_dir_all(&build_triple));
603        let host = build.out.join("host");
604        if host.is_symlink() {
605            // Left over from a previous build; overwrite it.
606            // This matters if `build.build` has changed between invocations.
607            #[cfg(windows)]
608            t!(fs::remove_dir(&host));
609            #[cfg(not(windows))]
610            t!(fs::remove_file(&host));
611        }
612        t!(
613            symlink_dir(&build.config, &build_triple, &host),
614            format!("symlink_dir({} => {}) failed", host.display(), build_triple.display())
615        );
616
617        build
618    }
619
620    /// Updates a submodule, and exits with a failure if submodule management
621    /// is disabled and the submodule does not exist.
622    ///
623    /// The given submodule name should be its path relative to the root of
624    /// the main repository.
625    ///
626    /// The given `err_hint` will be shown to the user if the submodule is not
627    /// checked out and submodule management is disabled.
628    #[cfg_attr(
629        feature = "tracing",
630        instrument(
631            level = "trace",
632            name = "Build::require_submodule",
633            skip_all,
634            fields(submodule = submodule),
635        ),
636    )]
637    pub fn require_submodule(&self, submodule: &str, err_hint: Option<&str>) {
638        if self.rust_info().is_from_tarball() {
639            return;
640        }
641
642        // When testing bootstrap itself, it is much faster to ignore
643        // submodules. Almost all Steps work fine without their submodules.
644        if cfg!(test) && !self.config.submodules() {
645            return;
646        }
647        self.config.update_submodule(submodule);
648        let absolute_path = self.config.src.join(submodule);
649        if !absolute_path.exists() || dir_is_empty(&absolute_path) {
650            let maybe_enable = if !self.config.submodules()
651                && self.config.rust_info.is_managed_git_subrepository()
652            {
653                "\nConsider setting `build.submodules = true` or manually initializing the submodules."
654            } else {
655                ""
656            };
657            let err_hint = err_hint.map_or_else(String::new, |e| format!("\n{e}"));
658            eprintln!(
659                "submodule {submodule} does not appear to be checked out, \
660                 but it is required for this step{maybe_enable}{err_hint}"
661            );
662            exit!(1);
663        }
664    }
665
666    /// If any submodule has been initialized already, sync it unconditionally.
667    /// This avoids contributors checking in a submodule change by accident.
668    fn update_existing_submodules(&self) {
669        // Avoid running git when there isn't a git checkout, or the user has
670        // explicitly disabled submodules in `bootstrap.toml`.
671        if !self.config.submodules() {
672            return;
673        }
674        let output = helpers::git(Some(&self.src))
675            .args(["config", "--file"])
676            .arg(".gitmodules")
677            .args(["--get-regexp", "path"])
678            .run_capture(self)
679            .stdout();
680        std::thread::scope(|s| {
681            // Look for `submodule.$name.path = $path`
682            // Sample output: `submodule.src/rust-installer.path src/tools/rust-installer`
683            for line in output.lines() {
684                let submodule = line.split_once(' ').unwrap().1;
685                let config = self.config.clone();
686                s.spawn(move || {
687                    Self::update_existing_submodule(&config, submodule);
688                });
689            }
690        });
691    }
692
693    /// Updates the given submodule only if it's initialized already; nothing happens otherwise.
694    pub fn update_existing_submodule(config: &Config, submodule: &str) {
695        // Avoid running git when there isn't a git checkout.
696        if !config.submodules() {
697            return;
698        }
699
700        if config.git_info(false, Path::new(submodule)).is_managed_git_subrepository() {
701            config.update_submodule(submodule);
702        }
703    }
704
705    /// Executes the entire build, as configured by the flags and configuration.
706    #[cfg_attr(feature = "tracing", instrument(level = "debug", name = "Build::build", skip_all))]
707    pub fn build(&mut self) {
708        trace!("setting up job management");
709        unsafe {
710            crate::utils::job::setup(self);
711        }
712
713        // Handle hard-coded subcommands.
714        {
715            #[cfg(feature = "tracing")]
716            let _hardcoded_span =
717                span!(tracing::Level::DEBUG, "handling hardcoded subcommands (Format, Perf)")
718                    .entered();
719
720            match &self.config.cmd {
721                Subcommand::Format { check, all } => {
722                    return core::build_steps::format::format(
723                        &builder::Builder::new(self),
724                        *check,
725                        *all,
726                        &self.config.paths,
727                    );
728                }
729                Subcommand::Perf(args) => {
730                    return core::build_steps::perf::perf(&builder::Builder::new(self), args);
731                }
732                _cmd => {
733                    debug!(cmd = ?_cmd, "not a hardcoded subcommand; returning to normal handling");
734                }
735            }
736
737            debug!("handling subcommand normally");
738        }
739
740        if !self.config.dry_run() {
741            #[cfg(feature = "tracing")]
742            let _real_run_span = span!(tracing::Level::DEBUG, "executing real run").entered();
743
744            // We first do a dry-run. This is a sanity-check to ensure that
745            // steps don't do anything expensive in the dry-run.
746            {
747                #[cfg(feature = "tracing")]
748                let _sanity_check_span =
749                    span!(tracing::Level::DEBUG, "(1) executing dry-run sanity-check").entered();
750                self.config.set_dry_run(DryRun::SelfCheck);
751                let builder = builder::Builder::new(self);
752                builder.execute_cli();
753            }
754
755            // Actual run.
756            {
757                #[cfg(feature = "tracing")]
758                let _actual_run_span =
759                    span!(tracing::Level::DEBUG, "(2) executing actual run").entered();
760                self.config.set_dry_run(DryRun::Disabled);
761                let builder = builder::Builder::new(self);
762                builder.execute_cli();
763            }
764        } else {
765            #[cfg(feature = "tracing")]
766            let _dry_run_span = span!(tracing::Level::DEBUG, "executing dry run").entered();
767
768            let builder = builder::Builder::new(self);
769            builder.execute_cli();
770        }
771
772        #[cfg(feature = "tracing")]
773        debug!("checking for postponed test failures from `test  --no-fail-fast`");
774
775        // Check for postponed failures from `test --no-fail-fast`.
776        self.config.exec_ctx().report_failures_and_exit();
777
778        #[cfg(feature = "build-metrics")]
779        self.metrics.persist(self);
780    }
781
782    fn rust_info(&self) -> &GitInfo {
783        &self.config.rust_info
784    }
785
786    /// Gets the space-separated set of activated features for the standard library.
787    /// This can be configured with the `std-features` key in bootstrap.toml.
788    fn std_features(&self, target: TargetSelection) -> String {
789        let mut features: BTreeSet<&str> =
790            self.config.rust_std_features.iter().map(|s| s.as_str()).collect();
791
792        match self.config.llvm_libunwind(target) {
793            LlvmLibunwind::InTree => features.insert("llvm-libunwind"),
794            LlvmLibunwind::System => features.insert("system-llvm-libunwind"),
795            LlvmLibunwind::No => false,
796        };
797
798        if self.config.backtrace {
799            features.insert("backtrace");
800        }
801
802        if self.config.profiler_enabled(target) {
803            features.insert("profiler");
804        }
805
806        // If zkvm target, generate memcpy, etc.
807        if target.contains("zkvm") {
808            features.insert("compiler-builtins-mem");
809        }
810
811        features.into_iter().collect::<Vec<_>>().join(" ")
812    }
813
814    /// Gets the space-separated set of activated features for the compiler.
815    fn rustc_features(&self, kind: Kind, target: TargetSelection, crates: &[String]) -> String {
816        let possible_features_by_crates: HashSet<_> = crates
817            .iter()
818            .flat_map(|krate| &self.crates[krate].features)
819            .map(std::ops::Deref::deref)
820            .collect();
821        let check = |feature: &str| -> bool {
822            crates.is_empty() || possible_features_by_crates.contains(feature)
823        };
824        let mut features = vec![];
825        if self.config.jemalloc(target) && check("jemalloc") {
826            features.push("jemalloc");
827        }
828        if (self.config.llvm_enabled(target) || kind == Kind::Check) && check("llvm") {
829            features.push("llvm");
830        }
831        // keep in sync with `bootstrap/compile.rs:rustc_cargo_env`
832        if self.config.rust_randomize_layout && check("rustc_randomized_layouts") {
833            features.push("rustc_randomized_layouts");
834        }
835        if self.config.compile_time_deps && kind == Kind::Check {
836            features.push("check_only");
837        }
838
839        // If debug logging is on, then we want the default for tracing:
840        // https://github.com/tokio-rs/tracing/blob/3dd5c03d907afdf2c39444a29931833335171554/tracing/src/level_filters.rs#L26
841        // which is everything (including debug/trace/etc.)
842        // if its unset, if debug_assertions is on, then debug_logging will also be on
843        // as well as tracing *ignoring* this feature when debug_assertions is on
844        if !self.config.rust_debug_logging && check("max_level_info") {
845            features.push("max_level_info");
846        }
847
848        features.join(" ")
849    }
850
851    /// Component directory that Cargo will produce output into (e.g.
852    /// release/debug)
853    fn cargo_dir(&self) -> &'static str {
854        if self.config.rust_optimize.is_release() { "release" } else { "debug" }
855    }
856
857    fn tools_dir(&self, compiler: Compiler) -> PathBuf {
858        let out = self.out.join(compiler.host).join(format!("stage{}-tools-bin", compiler.stage));
859        t!(fs::create_dir_all(&out));
860        out
861    }
862
863    /// Returns the root directory for all output generated in a particular
864    /// stage when running with a particular host compiler.
865    ///
866    /// The mode indicates what the root directory is for.
867    fn stage_out(&self, build_compiler: Compiler, mode: Mode) -> PathBuf {
868        use std::fmt::Write;
869
870        fn bootstrap_tool() -> (Option<u32>, &'static str) {
871            (None, "bootstrap-tools")
872        }
873        fn staged_tool(build_compiler: Compiler) -> (Option<u32>, &'static str) {
874            (Some(build_compiler.stage), "tools")
875        }
876
877        let (stage, suffix) = match mode {
878            Mode::Std => (Some(build_compiler.stage), "std"),
879            Mode::Rustc => (Some(build_compiler.stage), "rustc"),
880            Mode::Codegen => (Some(build_compiler.stage), "codegen"),
881            Mode::ToolBootstrap => bootstrap_tool(),
882            Mode::ToolStd | Mode::ToolRustc => (Some(build_compiler.stage), "tools"),
883            Mode::ToolTarget => {
884                // If we're not cross-compiling (the common case), share the target directory with
885                // bootstrap tools to reuse the build cache.
886                if build_compiler.stage == 0 {
887                    bootstrap_tool()
888                } else {
889                    staged_tool(build_compiler)
890                }
891            }
892        };
893        let path = self.out.join(build_compiler.host);
894        let mut dir_name = String::new();
895        if let Some(stage) = stage {
896            write!(dir_name, "stage{stage}-").unwrap();
897        }
898        dir_name.push_str(suffix);
899        path.join(dir_name)
900    }
901
902    /// Returns the root output directory for all Cargo output in a given stage,
903    /// running a particular compiler, whether or not we're building the
904    /// standard library, and targeting the specified architecture.
905    fn cargo_out(&self, compiler: Compiler, mode: Mode, target: TargetSelection) -> PathBuf {
906        self.stage_out(compiler, mode).join(target).join(self.cargo_dir())
907    }
908
909    /// Root output directory of LLVM for `target`
910    ///
911    /// Note that if LLVM is configured externally then the directory returned
912    /// will likely be empty.
913    fn llvm_out(&self, target: TargetSelection) -> PathBuf {
914        if self.config.llvm_from_ci && self.config.is_host_target(target) {
915            self.config.ci_llvm_root()
916        } else {
917            self.out.join(target).join("llvm")
918        }
919    }
920
921    fn enzyme_out(&self, target: TargetSelection) -> PathBuf {
922        self.out.join(&*target.triple).join("enzyme")
923    }
924
925    fn gcc_out(&self, target: TargetSelection) -> PathBuf {
926        self.out.join(&*target.triple).join("gcc")
927    }
928
929    fn lld_out(&self, target: TargetSelection) -> PathBuf {
930        self.out.join(target).join("lld")
931    }
932
933    /// Output directory for all documentation for a target
934    fn doc_out(&self, target: TargetSelection) -> PathBuf {
935        self.out.join(target).join("doc")
936    }
937
938    /// Output directory for all JSON-formatted documentation for a target
939    fn json_doc_out(&self, target: TargetSelection) -> PathBuf {
940        self.out.join(target).join("json-doc")
941    }
942
943    fn test_out(&self, target: TargetSelection) -> PathBuf {
944        self.out.join(target).join("test")
945    }
946
947    /// Output directory for all documentation for a target
948    fn compiler_doc_out(&self, target: TargetSelection) -> PathBuf {
949        self.out.join(target).join("compiler-doc")
950    }
951
952    /// Output directory for some generated md crate documentation for a target (temporary)
953    fn md_doc_out(&self, target: TargetSelection) -> PathBuf {
954        self.out.join(target).join("md-doc")
955    }
956
957    /// Path to the vendored Rust crates.
958    fn vendored_crates_path(&self) -> Option<PathBuf> {
959        if self.config.vendor { Some(self.src.join(VENDOR_DIR)) } else { None }
960    }
961
962    /// Returns the path to `FileCheck` binary for the specified target
963    fn llvm_filecheck(&self, target: TargetSelection) -> PathBuf {
964        let target_config = self.config.target_config.get(&target);
965        if let Some(s) = target_config.and_then(|c| c.llvm_filecheck.as_ref()) {
966            s.to_path_buf()
967        } else if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
968            let llvm_bindir = command(s).arg("--bindir").run_capture_stdout(self).stdout();
969            let filecheck = Path::new(llvm_bindir.trim()).join(exe("FileCheck", target));
970            if filecheck.exists() {
971                filecheck
972            } else {
973                // On Fedora the system LLVM installs FileCheck in the
974                // llvm subdirectory of the libdir.
975                let llvm_libdir = command(s).arg("--libdir").run_capture_stdout(self).stdout();
976                let lib_filecheck =
977                    Path::new(llvm_libdir.trim()).join("llvm").join(exe("FileCheck", target));
978                if lib_filecheck.exists() {
979                    lib_filecheck
980                } else {
981                    // Return the most normal file name, even though
982                    // it doesn't exist, so that any error message
983                    // refers to that.
984                    filecheck
985                }
986            }
987        } else {
988            let base = self.llvm_out(target).join("build");
989            let base = if !self.ninja() && target.is_msvc() {
990                if self.config.llvm_optimize {
991                    if self.config.llvm_release_debuginfo {
992                        base.join("RelWithDebInfo")
993                    } else {
994                        base.join("Release")
995                    }
996                } else {
997                    base.join("Debug")
998                }
999            } else {
1000                base
1001            };
1002            base.join("bin").join(exe("FileCheck", target))
1003        }
1004    }
1005
1006    /// Directory for libraries built from C/C++ code and shared between stages.
1007    fn native_dir(&self, target: TargetSelection) -> PathBuf {
1008        self.out.join(target).join("native")
1009    }
1010
1011    /// Root output directory for rust_test_helpers library compiled for
1012    /// `target`
1013    fn test_helpers_out(&self, target: TargetSelection) -> PathBuf {
1014        self.native_dir(target).join("rust-test-helpers")
1015    }
1016
1017    /// Adds the `RUST_TEST_THREADS` env var if necessary
1018    fn add_rust_test_threads(&self, cmd: &mut BootstrapCommand) {
1019        if env::var_os("RUST_TEST_THREADS").is_none() {
1020            cmd.env("RUST_TEST_THREADS", self.jobs().to_string());
1021        }
1022    }
1023
1024    /// Returns the libdir of the snapshot compiler.
1025    fn rustc_snapshot_libdir(&self) -> PathBuf {
1026        self.rustc_snapshot_sysroot().join(libdir(self.config.host_target))
1027    }
1028
1029    /// Returns the sysroot of the snapshot compiler.
1030    fn rustc_snapshot_sysroot(&self) -> &Path {
1031        static SYSROOT_CACHE: OnceLock<PathBuf> = OnceLock::new();
1032        SYSROOT_CACHE.get_or_init(|| {
1033            command(&self.initial_rustc)
1034                .run_in_dry_run()
1035                .args(["--print", "sysroot"])
1036                .run_capture_stdout(self)
1037                .stdout()
1038                .trim()
1039                .to_owned()
1040                .into()
1041        })
1042    }
1043
1044    /// Check if verbosity is greater than the `level`
1045    pub fn is_verbose_than(&self, level: usize) -> bool {
1046        self.verbosity > level
1047    }
1048
1049    /// Runs a function if verbosity is greater than `level`.
1050    fn verbose_than(&self, level: usize, f: impl Fn()) {
1051        if self.is_verbose_than(level) {
1052            f()
1053        }
1054    }
1055
1056    fn info(&self, msg: &str) {
1057        match self.config.get_dry_run() {
1058            DryRun::SelfCheck => (),
1059            DryRun::Disabled | DryRun::UserSelected => {
1060                println!("{msg}");
1061            }
1062        }
1063    }
1064
1065    #[must_use = "Groups should not be dropped until the Step finishes running"]
1066    #[track_caller]
1067    fn msg_clippy(
1068        &self,
1069        what: impl Display,
1070        target: impl Into<Option<TargetSelection>>,
1071    ) -> Option<gha::Group> {
1072        self.msg(Kind::Clippy, self.config.stage, what, self.config.host_target, target)
1073    }
1074
1075    #[must_use = "Groups should not be dropped until the Step finishes running"]
1076    #[track_caller]
1077    fn msg_check(
1078        &self,
1079        what: impl Display,
1080        target: impl Into<Option<TargetSelection>>,
1081        custom_stage: Option<u32>,
1082    ) -> Option<gha::Group> {
1083        self.msg(
1084            Kind::Check,
1085            custom_stage.unwrap_or(self.config.stage),
1086            what,
1087            self.config.host_target,
1088            target,
1089        )
1090    }
1091
1092    #[must_use = "Groups should not be dropped until the Step finishes running"]
1093    #[track_caller]
1094    fn msg_doc(
1095        &self,
1096        compiler: Compiler,
1097        what: impl Display,
1098        target: impl Into<Option<TargetSelection>> + Copy,
1099    ) -> Option<gha::Group> {
1100        self.msg(Kind::Doc, compiler.stage, what, compiler.host, target.into())
1101    }
1102
1103    #[must_use = "Groups should not be dropped until the Step finishes running"]
1104    #[track_caller]
1105    fn msg_build(
1106        &self,
1107        compiler: Compiler,
1108        what: impl Display,
1109        target: impl Into<Option<TargetSelection>>,
1110    ) -> Option<gha::Group> {
1111        self.msg(Kind::Build, compiler.stage, what, compiler.host, target)
1112    }
1113
1114    /// Return a `Group` guard for a [`Step`] that is built for each `--stage`.
1115    ///
1116    /// [`Step`]: crate::core::builder::Step
1117    #[must_use = "Groups should not be dropped until the Step finishes running"]
1118    #[track_caller]
1119    fn msg(
1120        &self,
1121        action: impl Into<Kind>,
1122        stage: u32,
1123        what: impl Display,
1124        host: impl Into<Option<TargetSelection>>,
1125        target: impl Into<Option<TargetSelection>>,
1126    ) -> Option<gha::Group> {
1127        let action = action.into().description();
1128        let msg = |fmt| format!("{action} stage{stage} {what}{fmt}");
1129        let msg = if let Some(target) = target.into() {
1130            let host = host.into().unwrap();
1131            if host == target {
1132                msg(format_args!(" ({target})"))
1133            } else {
1134                msg(format_args!(" ({host} -> {target})"))
1135            }
1136        } else {
1137            msg(format_args!(""))
1138        };
1139        self.group(&msg)
1140    }
1141
1142    /// Return a `Group` guard for a [`Step`] that is only built once and isn't affected by `--stage`.
1143    ///
1144    /// [`Step`]: crate::core::builder::Step
1145    #[must_use = "Groups should not be dropped until the Step finishes running"]
1146    #[track_caller]
1147    fn msg_unstaged(
1148        &self,
1149        action: impl Into<Kind>,
1150        what: impl Display,
1151        target: TargetSelection,
1152    ) -> Option<gha::Group> {
1153        let action = action.into().description();
1154        let msg = format!("{action} {what} for {target}");
1155        self.group(&msg)
1156    }
1157
1158    #[must_use = "Groups should not be dropped until the Step finishes running"]
1159    #[track_caller]
1160    fn msg_sysroot_tool(
1161        &self,
1162        action: impl Into<Kind>,
1163        stage: u32,
1164        what: impl Display,
1165        host: TargetSelection,
1166        target: TargetSelection,
1167    ) -> Option<gha::Group> {
1168        let action = action.into().description();
1169        let msg = |fmt| format!("{action} {what} {fmt}");
1170        let msg = if host == target {
1171            msg(format_args!("(stage{stage} -> stage{}, {target})", stage + 1))
1172        } else {
1173            msg(format_args!("(stage{stage}:{host} -> stage{}:{target})", stage + 1))
1174        };
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    pub fn resolve_symlink_and_copy(&self, src: &Path, dst: &Path) {
1761        self.copy_link_internal(src, dst, true);
1762    }
1763
1764    /// Links a file from `src` to `dst`.
1765    /// Attempts to use hard links if possible, falling back to copying.
1766    /// You can neither rely on this being a copy nor it being a link,
1767    /// so do not write to dst.
1768    pub fn copy_link(&self, src: &Path, dst: &Path, file_type: FileType) {
1769        self.copy_link_internal(src, dst, false);
1770
1771        if file_type.could_have_split_debuginfo()
1772            && let Some(dbg_file) = split_debuginfo(src)
1773        {
1774            self.copy_link_internal(
1775                &dbg_file,
1776                &dst.with_extension(dbg_file.extension().unwrap()),
1777                false,
1778            );
1779        }
1780    }
1781
1782    fn copy_link_internal(&self, src: &Path, dst: &Path, dereference_symlinks: bool) {
1783        if self.config.dry_run() {
1784            return;
1785        }
1786        self.verbose_than(1, || println!("Copy/Link {src:?} to {dst:?}"));
1787        if src == dst {
1788            return;
1789        }
1790        if let Err(e) = fs::remove_file(dst)
1791            && cfg!(windows)
1792            && e.kind() != io::ErrorKind::NotFound
1793        {
1794            // workaround for https://github.com/rust-lang/rust/issues/127126
1795            // if removing the file fails, attempt to rename it instead.
1796            let now = t!(SystemTime::now().duration_since(SystemTime::UNIX_EPOCH));
1797            let _ = fs::rename(dst, format!("{}-{}", dst.display(), now.as_nanos()));
1798        }
1799        let mut metadata = t!(src.symlink_metadata(), format!("src = {}", src.display()));
1800        let mut src = src.to_path_buf();
1801        if metadata.file_type().is_symlink() {
1802            if dereference_symlinks {
1803                src = t!(fs::canonicalize(src));
1804                metadata = t!(fs::metadata(&src), format!("target = {}", src.display()));
1805            } else {
1806                let link = t!(fs::read_link(src));
1807                t!(self.symlink_file(link, dst));
1808                return;
1809            }
1810        }
1811        if let Ok(()) = fs::hard_link(&src, dst) {
1812            // Attempt to "easy copy" by creating a hard link (symlinks are privileged on windows),
1813            // but if that fails just fall back to a slow `copy` operation.
1814        } else {
1815            if let Err(e) = fs::copy(&src, dst) {
1816                panic!("failed to copy `{}` to `{}`: {}", src.display(), dst.display(), e)
1817            }
1818            t!(fs::set_permissions(dst, metadata.permissions()));
1819
1820            // Restore file times because changing permissions on e.g. Linux using `chmod` can cause
1821            // file access time to change.
1822            let file_times = fs::FileTimes::new()
1823                .set_accessed(t!(metadata.accessed()))
1824                .set_modified(t!(metadata.modified()));
1825            t!(set_file_times(dst, file_times));
1826        }
1827    }
1828
1829    /// Links the `src` directory recursively to `dst`. Both are assumed to exist
1830    /// when this function is called.
1831    /// Will attempt to use hard links if possible and fall back to copying.
1832    pub fn cp_link_r(&self, src: &Path, dst: &Path) {
1833        if self.config.dry_run() {
1834            return;
1835        }
1836        for f in self.read_dir(src) {
1837            let path = f.path();
1838            let name = path.file_name().unwrap();
1839            let dst = dst.join(name);
1840            if t!(f.file_type()).is_dir() {
1841                t!(fs::create_dir_all(&dst));
1842                self.cp_link_r(&path, &dst);
1843            } else {
1844                self.copy_link(&path, &dst, FileType::Regular);
1845            }
1846        }
1847    }
1848
1849    /// Copies the `src` directory recursively to `dst`. Both are assumed to exist
1850    /// when this function is called.
1851    /// Will attempt to use hard links if possible and fall back to copying.
1852    /// Unwanted files or directories can be skipped
1853    /// by returning `false` from the filter function.
1854    pub fn cp_link_filtered(&self, src: &Path, dst: &Path, filter: &dyn Fn(&Path) -> bool) {
1855        // Immediately recurse with an empty relative path
1856        self.cp_link_filtered_recurse(src, dst, Path::new(""), filter)
1857    }
1858
1859    // Inner function does the actual work
1860    fn cp_link_filtered_recurse(
1861        &self,
1862        src: &Path,
1863        dst: &Path,
1864        relative: &Path,
1865        filter: &dyn Fn(&Path) -> bool,
1866    ) {
1867        for f in self.read_dir(src) {
1868            let path = f.path();
1869            let name = path.file_name().unwrap();
1870            let dst = dst.join(name);
1871            let relative = relative.join(name);
1872            // Only copy file or directory if the filter function returns true
1873            if filter(&relative) {
1874                if t!(f.file_type()).is_dir() {
1875                    let _ = fs::remove_dir_all(&dst);
1876                    self.create_dir(&dst);
1877                    self.cp_link_filtered_recurse(&path, &dst, &relative, filter);
1878                } else {
1879                    let _ = fs::remove_file(&dst);
1880                    self.copy_link(&path, &dst, FileType::Regular);
1881                }
1882            }
1883        }
1884    }
1885
1886    fn copy_link_to_folder(&self, src: &Path, dest_folder: &Path) {
1887        let file_name = src.file_name().unwrap();
1888        let dest = dest_folder.join(file_name);
1889        self.copy_link(src, &dest, FileType::Regular);
1890    }
1891
1892    fn install(&self, src: &Path, dstdir: &Path, file_type: FileType) {
1893        if self.config.dry_run() {
1894            return;
1895        }
1896        let dst = dstdir.join(src.file_name().unwrap());
1897        self.verbose_than(1, || println!("Install {src:?} to {dst:?}"));
1898        t!(fs::create_dir_all(dstdir));
1899        if !src.exists() {
1900            panic!("ERROR: File \"{}\" not found!", src.display());
1901        }
1902
1903        self.copy_link_internal(src, &dst, true);
1904        chmod(&dst, file_type.perms());
1905
1906        // If this file can have debuginfo, look for split debuginfo and install it too.
1907        if file_type.could_have_split_debuginfo()
1908            && let Some(dbg_file) = split_debuginfo(src)
1909        {
1910            self.install(&dbg_file, dstdir, FileType::Regular);
1911        }
1912    }
1913
1914    fn read(&self, path: &Path) -> String {
1915        if self.config.dry_run() {
1916            return String::new();
1917        }
1918        t!(fs::read_to_string(path))
1919    }
1920
1921    fn create_dir(&self, dir: &Path) {
1922        if self.config.dry_run() {
1923            return;
1924        }
1925        t!(fs::create_dir_all(dir))
1926    }
1927
1928    fn remove_dir(&self, dir: &Path) {
1929        if self.config.dry_run() {
1930            return;
1931        }
1932        t!(fs::remove_dir_all(dir))
1933    }
1934
1935    fn read_dir(&self, dir: &Path) -> impl Iterator<Item = fs::DirEntry> {
1936        let iter = match fs::read_dir(dir) {
1937            Ok(v) => v,
1938            Err(_) if self.config.dry_run() => return vec![].into_iter(),
1939            Err(err) => panic!("could not read dir {dir:?}: {err:?}"),
1940        };
1941        iter.map(|e| t!(e)).collect::<Vec<_>>().into_iter()
1942    }
1943
1944    fn symlink_file<P: AsRef<Path>, Q: AsRef<Path>>(&self, src: P, link: Q) -> io::Result<()> {
1945        #[cfg(unix)]
1946        use std::os::unix::fs::symlink as symlink_file;
1947        #[cfg(windows)]
1948        use std::os::windows::fs::symlink_file;
1949        if !self.config.dry_run() { symlink_file(src.as_ref(), link.as_ref()) } else { Ok(()) }
1950    }
1951
1952    /// Returns if config.ninja is enabled, and checks for ninja existence,
1953    /// exiting with a nicer error message if not.
1954    fn ninja(&self) -> bool {
1955        let mut cmd_finder = crate::core::sanity::Finder::new();
1956
1957        if self.config.ninja_in_file {
1958            // Some Linux distros rename `ninja` to `ninja-build`.
1959            // CMake can work with either binary name.
1960            if cmd_finder.maybe_have("ninja-build").is_none()
1961                && cmd_finder.maybe_have("ninja").is_none()
1962            {
1963                eprintln!(
1964                    "
1965Couldn't find required command: ninja (or ninja-build)
1966
1967You should install ninja as described at
1968<https://github.com/ninja-build/ninja/wiki/Pre-built-Ninja-packages>,
1969or set `ninja = false` in the `[llvm]` section of `bootstrap.toml`.
1970Alternatively, set `download-ci-llvm = true` in that `[llvm]` section
1971to download LLVM rather than building it.
1972"
1973                );
1974                exit!(1);
1975            }
1976        }
1977
1978        // If ninja isn't enabled but we're building for MSVC then we try
1979        // doubly hard to enable it. It was realized in #43767 that the msbuild
1980        // CMake generator for MSVC doesn't respect configuration options like
1981        // disabling LLVM assertions, which can often be quite important!
1982        //
1983        // In these cases we automatically enable Ninja if we find it in the
1984        // environment.
1985        if !self.config.ninja_in_file
1986            && self.config.host_target.is_msvc()
1987            && cmd_finder.maybe_have("ninja").is_some()
1988        {
1989            return true;
1990        }
1991
1992        self.config.ninja_in_file
1993    }
1994
1995    pub fn colored_stdout<R, F: FnOnce(&mut dyn WriteColor) -> R>(&self, f: F) -> R {
1996        self.colored_stream_inner(StandardStream::stdout, self.config.stdout_is_tty, f)
1997    }
1998
1999    pub fn colored_stderr<R, F: FnOnce(&mut dyn WriteColor) -> R>(&self, f: F) -> R {
2000        self.colored_stream_inner(StandardStream::stderr, self.config.stderr_is_tty, f)
2001    }
2002
2003    fn colored_stream_inner<R, F, C>(&self, constructor: C, is_tty: bool, f: F) -> R
2004    where
2005        C: Fn(ColorChoice) -> StandardStream,
2006        F: FnOnce(&mut dyn WriteColor) -> R,
2007    {
2008        let choice = match self.config.color {
2009            flags::Color::Always => ColorChoice::Always,
2010            flags::Color::Never => ColorChoice::Never,
2011            flags::Color::Auto if !is_tty => ColorChoice::Never,
2012            flags::Color::Auto => ColorChoice::Auto,
2013        };
2014        let mut stream = constructor(choice);
2015        let result = f(&mut stream);
2016        stream.reset().unwrap();
2017        result
2018    }
2019
2020    pub fn exec_ctx(&self) -> &ExecutionContext {
2021        &self.config.exec_ctx
2022    }
2023
2024    pub fn report_summary(&self, start_time: Instant) {
2025        self.config.exec_ctx.profiler().report_summary(start_time);
2026    }
2027}
2028
2029impl AsRef<ExecutionContext> for Build {
2030    fn as_ref(&self) -> &ExecutionContext {
2031        &self.config.exec_ctx
2032    }
2033}
2034
2035#[cfg(unix)]
2036fn chmod(path: &Path, perms: u32) {
2037    use std::os::unix::fs::*;
2038    t!(fs::set_permissions(path, fs::Permissions::from_mode(perms)));
2039}
2040#[cfg(windows)]
2041fn chmod(_path: &Path, _perms: u32) {}
2042
2043impl Compiler {
2044    pub fn new(stage: u32, host: TargetSelection) -> Self {
2045        Self { stage, host, forced_compiler: false }
2046    }
2047
2048    pub fn forced_compiler(&mut self, forced_compiler: bool) {
2049        self.forced_compiler = forced_compiler;
2050    }
2051
2052    pub fn with_stage(mut self, stage: u32) -> Compiler {
2053        self.stage = stage;
2054        self
2055    }
2056
2057    /// Returns `true` if this is a snapshot compiler for `build`'s configuration
2058    pub fn is_snapshot(&self, build: &Build) -> bool {
2059        self.stage == 0 && self.host == build.host_target
2060    }
2061
2062    /// Indicates whether the compiler was forced to use a specific stage.
2063    pub fn is_forced_compiler(&self) -> bool {
2064        self.forced_compiler
2065    }
2066}
2067
2068fn envify(s: &str) -> String {
2069    s.chars()
2070        .map(|c| match c {
2071            '-' => '_',
2072            c => c,
2073        })
2074        .flat_map(|c| c.to_uppercase())
2075        .collect()
2076}
2077
2078/// Ensures that the behavior dump directory is properly initialized.
2079pub fn prepare_behaviour_dump_dir(build: &Build) {
2080    static INITIALIZED: OnceLock<bool> = OnceLock::new();
2081
2082    let dump_path = build.out.join("bootstrap-shims-dump");
2083
2084    let initialized = INITIALIZED.get().unwrap_or(&false);
2085    if !initialized {
2086        // clear old dumps
2087        if dump_path.exists() {
2088            t!(fs::remove_dir_all(&dump_path));
2089        }
2090
2091        t!(fs::create_dir_all(&dump_path));
2092
2093        t!(INITIALIZED.set(true));
2094    }
2095}