Skip to main content

bootstrap/
lib.rs

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