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