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 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 self.config.jemalloc(target) && check("jemalloc") {
870            features.push("jemalloc");
871        }
872        if (self.config.llvm_enabled(target) || kind == Kind::Check) && check("llvm") {
873            features.push("llvm");
874        }
875        if self.config.llvm_enzyme {
876            features.push("llvm_enzyme");
877        }
878        if self.config.llvm_offload {
879            features.push("llvm_offload");
880        }
881        // keep in sync with `bootstrap/compile.rs:rustc_cargo_env`
882        if self.config.rust_randomize_layout && check("rustc_randomized_layouts") {
883            features.push("rustc_randomized_layouts");
884        }
885        if self.config.compile_time_deps && kind == Kind::Check {
886            features.push("check_only");
887        }
888
889        if crates.iter().any(|c| c == "rustc_transmute") {
890            // for `x test rustc_transmute`, this feature isn't enabled automatically by a
891            // dependent crate.
892            features.push("rustc");
893        }
894
895        // If debug logging is on, then we want the default for tracing:
896        // https://github.com/tokio-rs/tracing/blob/3dd5c03d907afdf2c39444a29931833335171554/tracing/src/level_filters.rs#L26
897        // which is everything (including debug/trace/etc.)
898        // if its unset, if debug_assertions is on, then debug_logging will also be on
899        // as well as tracing *ignoring* this feature when debug_assertions is on
900        if !self.config.rust_debug_logging && check("max_level_info") {
901            features.push("max_level_info");
902        }
903
904        features.join(" ")
905    }
906
907    /// Component directory that Cargo will produce output into (e.g.
908    /// release/debug)
909    fn cargo_dir(&self, mode: Mode) -> &'static str {
910        match (mode, self.config.rust_optimize.is_release()) {
911            (Mode::Std, _) => "dist",
912            (_, true) => "release",
913            (_, false) => "debug",
914        }
915    }
916
917    fn tools_dir(&self, build_compiler: Compiler) -> PathBuf {
918        let out = self
919            .out
920            .join(build_compiler.host)
921            .join(format!("stage{}-tools-bin", build_compiler.stage + 1));
922        t!(fs::create_dir_all(&out));
923        out
924    }
925
926    /// Returns the root directory for all output generated in a particular
927    /// stage when being built with a particular build compiler.
928    ///
929    /// The mode indicates what the root directory is for.
930    fn stage_out(&self, build_compiler: Compiler, mode: Mode) -> PathBuf {
931        use std::fmt::Write;
932
933        fn bootstrap_tool() -> (Option<u32>, &'static str) {
934            (None, "bootstrap-tools")
935        }
936        fn staged_tool(build_compiler: Compiler) -> (Option<u32>, &'static str) {
937            (Some(build_compiler.stage + 1), "tools")
938        }
939
940        let (stage, suffix) = match mode {
941            // Std is special, stage N std is built with stage N rustc
942            Mode::Std => (Some(build_compiler.stage), "std"),
943            // The rest of things are built with stage N-1 rustc
944            Mode::Rustc => (Some(build_compiler.stage + 1), "rustc"),
945            Mode::Codegen => (Some(build_compiler.stage + 1), "codegen"),
946            Mode::ToolBootstrap => bootstrap_tool(),
947            Mode::ToolStd | Mode::ToolRustcPrivate => (Some(build_compiler.stage + 1), "tools"),
948            Mode::ToolTarget => {
949                // If we're not cross-compiling (the common case), share the target directory with
950                // bootstrap tools to reuse the build cache.
951                if build_compiler.stage == 0 {
952                    bootstrap_tool()
953                } else {
954                    staged_tool(build_compiler)
955                }
956            }
957        };
958        let path = self.out.join(build_compiler.host);
959        let mut dir_name = String::new();
960        if let Some(stage) = stage {
961            write!(dir_name, "stage{stage}-").unwrap();
962        }
963        dir_name.push_str(suffix);
964        path.join(dir_name)
965    }
966
967    /// Returns the root output directory for all Cargo output in a given stage,
968    /// running a particular compiler, whether or not we're building the
969    /// standard library, and targeting the specified architecture.
970    fn cargo_out(&self, build_compiler: Compiler, mode: Mode, target: TargetSelection) -> PathBuf {
971        self.stage_out(build_compiler, mode).join(target).join(self.cargo_dir(mode))
972    }
973
974    /// Root output directory of LLVM for `target`
975    ///
976    /// Note that if LLVM is configured externally then the directory returned
977    /// will likely be empty.
978    fn llvm_out(&self, target: TargetSelection) -> PathBuf {
979        if self.config.llvm_from_ci && self.config.is_host_target(target) {
980            self.config.ci_llvm_root()
981        } else {
982            self.out.join(target).join("llvm")
983        }
984    }
985
986    fn enzyme_out(&self, target: TargetSelection) -> PathBuf {
987        self.out.join(&*target.triple).join("enzyme")
988    }
989
990    fn offload_out(&self, target: TargetSelection) -> PathBuf {
991        self.out.join(&*target.triple).join("offload")
992    }
993
994    fn lld_out(&self, target: TargetSelection) -> PathBuf {
995        self.out.join(target).join("lld")
996    }
997
998    /// Output directory for all documentation for a target
999    fn doc_out(&self, target: TargetSelection) -> PathBuf {
1000        self.out.join(target).join("doc")
1001    }
1002
1003    /// Output directory for all JSON-formatted documentation for a target
1004    fn json_doc_out(&self, target: TargetSelection) -> PathBuf {
1005        self.out.join(target).join("json-doc")
1006    }
1007
1008    fn test_out(&self, target: TargetSelection) -> PathBuf {
1009        self.out.join(target).join("test")
1010    }
1011
1012    /// Output directory for all documentation for a target
1013    fn compiler_doc_out(&self, target: TargetSelection) -> PathBuf {
1014        self.out.join(target).join("compiler-doc")
1015    }
1016
1017    /// Output directory for some generated md crate documentation for a target (temporary)
1018    fn md_doc_out(&self, target: TargetSelection) -> PathBuf {
1019        self.out.join(target).join("md-doc")
1020    }
1021
1022    /// Path to the vendored Rust crates.
1023    fn vendored_crates_path(&self) -> Option<PathBuf> {
1024        if self.config.vendor { Some(self.src.join(VENDOR_DIR)) } else { None }
1025    }
1026
1027    /// Returns the path to `FileCheck` binary for the specified target
1028    fn llvm_filecheck(&self, target: TargetSelection) -> PathBuf {
1029        let target_config = self.config.target_config.get(&target);
1030        if let Some(s) = target_config.and_then(|c| c.llvm_filecheck.as_ref()) {
1031            s.to_path_buf()
1032        } else if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
1033            let llvm_bindir = command(s).arg("--bindir").run_capture_stdout(self).stdout();
1034            let filecheck = Path::new(llvm_bindir.trim()).join(exe("FileCheck", target));
1035            if filecheck.exists() {
1036                filecheck
1037            } else {
1038                // On Fedora the system LLVM installs FileCheck in the
1039                // llvm subdirectory of the libdir.
1040                let llvm_libdir = command(s).arg("--libdir").run_capture_stdout(self).stdout();
1041                let lib_filecheck =
1042                    Path::new(llvm_libdir.trim()).join("llvm").join(exe("FileCheck", target));
1043                if lib_filecheck.exists() {
1044                    lib_filecheck
1045                } else {
1046                    // Return the most normal file name, even though
1047                    // it doesn't exist, so that any error message
1048                    // refers to that.
1049                    filecheck
1050                }
1051            }
1052        } else {
1053            let base = self.llvm_out(target).join("build");
1054            let base = if !self.ninja() && target.is_msvc() {
1055                if self.config.llvm_optimize {
1056                    if self.config.llvm_release_debuginfo {
1057                        base.join("RelWithDebInfo")
1058                    } else {
1059                        base.join("Release")
1060                    }
1061                } else {
1062                    base.join("Debug")
1063                }
1064            } else {
1065                base
1066            };
1067            base.join("bin").join(exe("FileCheck", target))
1068        }
1069    }
1070
1071    /// Directory for libraries built from C/C++ code and shared between stages.
1072    fn native_dir(&self, target: TargetSelection) -> PathBuf {
1073        self.out.join(target).join("native")
1074    }
1075
1076    /// Root output directory for rust_test_helpers library compiled for
1077    /// `target`
1078    fn test_helpers_out(&self, target: TargetSelection) -> PathBuf {
1079        self.native_dir(target).join("rust-test-helpers")
1080    }
1081
1082    /// Adds the `RUST_TEST_THREADS` env var if necessary
1083    fn add_rust_test_threads(&self, cmd: &mut BootstrapCommand) {
1084        if env::var_os("RUST_TEST_THREADS").is_none() {
1085            cmd.env("RUST_TEST_THREADS", self.jobs().to_string());
1086        }
1087    }
1088
1089    /// Returns the libdir of the snapshot compiler.
1090    fn rustc_snapshot_libdir(&self) -> PathBuf {
1091        self.rustc_snapshot_sysroot().join(libdir(self.config.host_target))
1092    }
1093
1094    /// Returns the sysroot of the snapshot compiler.
1095    fn rustc_snapshot_sysroot(&self) -> &Path {
1096        static SYSROOT_CACHE: OnceLock<PathBuf> = OnceLock::new();
1097        SYSROOT_CACHE.get_or_init(|| {
1098            command(&self.initial_rustc)
1099                .run_in_dry_run()
1100                .args(["--print", "sysroot"])
1101                .run_capture_stdout(self)
1102                .stdout()
1103                .trim()
1104                .to_owned()
1105                .into()
1106        })
1107    }
1108
1109    fn info(&self, msg: &str) {
1110        match self.config.get_dry_run() {
1111            DryRun::SelfCheck => (),
1112            DryRun::Disabled | DryRun::UserSelected => {
1113                println!("{msg}");
1114            }
1115        }
1116    }
1117
1118    /// Return a `Group` guard for a [`Step`] that:
1119    /// - Performs `action`
1120    ///   - If the action is `Kind::Test`, use [`Build::msg_test`] instead.
1121    /// - On `what`
1122    ///   - Where `what` possibly corresponds to a `mode`
1123    /// - `action` is performed with/on the given compiler (`target_and_stage`).
1124    ///   - Since for some steps it is not possible to pass a single compiler here, it is also
1125    ///     possible to pass the host and stage explicitly.
1126    /// - With a given `target`.
1127    ///
1128    /// [`Step`]: crate::core::builder::Step
1129    #[must_use = "Groups should not be dropped until the Step finishes running"]
1130    #[track_caller]
1131    fn msg(
1132        &self,
1133        action: impl Into<Kind>,
1134        what: impl Display,
1135        mode: impl Into<Option<Mode>>,
1136        target_and_stage: impl Into<TargetAndStage>,
1137        target: impl Into<Option<TargetSelection>>,
1138    ) -> Option<gha::Group> {
1139        let target_and_stage = target_and_stage.into();
1140        let action = action.into();
1141        assert!(
1142            action != Kind::Test,
1143            "Please use `Build::msg_test` instead of `Build::msg(Kind::Test)`"
1144        );
1145
1146        let actual_stage = match mode.into() {
1147            // Std has the same stage as the compiler that builds it
1148            Some(Mode::Std) => target_and_stage.stage,
1149            // Other things have stage corresponding to their build compiler + 1
1150            Some(
1151                Mode::Rustc
1152                | Mode::Codegen
1153                | Mode::ToolBootstrap
1154                | Mode::ToolTarget
1155                | Mode::ToolStd
1156                | Mode::ToolRustcPrivate,
1157            )
1158            | None => target_and_stage.stage + 1,
1159        };
1160
1161        let action = action.description();
1162        let what = what.to_string();
1163        let msg = |fmt| {
1164            let space = if !what.is_empty() { " " } else { "" };
1165            format!("{action} stage{actual_stage} {what}{space}{fmt}")
1166        };
1167        let msg = if let Some(target) = target.into() {
1168            let build_stage = target_and_stage.stage;
1169            let host = target_and_stage.target;
1170            if host == target {
1171                msg(format_args!("(stage{build_stage} -> stage{actual_stage}, {target})"))
1172            } else {
1173                msg(format_args!("(stage{build_stage}:{host} -> stage{actual_stage}:{target})"))
1174            }
1175        } else {
1176            msg(format_args!(""))
1177        };
1178        self.group(&msg)
1179    }
1180
1181    /// Return a `Group` guard for a [`Step`] that tests `what` with the given `stage` and `target`.
1182    /// Use this instead of [`Build::msg`] for test steps, because for them it is not always clear
1183    /// what exactly is a build compiler.
1184    ///
1185    /// [`Step`]: crate::core::builder::Step
1186    #[must_use = "Groups should not be dropped until the Step finishes running"]
1187    #[track_caller]
1188    fn msg_test(
1189        &self,
1190        what: impl Display,
1191        target: TargetSelection,
1192        stage: u32,
1193    ) -> Option<gha::Group> {
1194        let action = Kind::Test.description();
1195        let msg = format!("{action} stage{stage} {what} ({target})");
1196        self.group(&msg)
1197    }
1198
1199    /// Return a `Group` guard for a [`Step`] that is only built once and isn't affected by `--stage`.
1200    ///
1201    /// [`Step`]: crate::core::builder::Step
1202    #[must_use = "Groups should not be dropped until the Step finishes running"]
1203    #[track_caller]
1204    fn msg_unstaged(
1205        &self,
1206        action: impl Into<Kind>,
1207        what: impl Display,
1208        target: TargetSelection,
1209    ) -> Option<gha::Group> {
1210        let action = action.into().description();
1211        let msg = format!("{action} {what} for {target}");
1212        self.group(&msg)
1213    }
1214
1215    #[track_caller]
1216    fn group(&self, msg: &str) -> Option<gha::Group> {
1217        match self.config.get_dry_run() {
1218            DryRun::SelfCheck => None,
1219            DryRun::Disabled | DryRun::UserSelected => Some(gha::group(msg)),
1220        }
1221    }
1222
1223    /// Returns the number of parallel jobs that have been configured for this
1224    /// build.
1225    fn jobs(&self) -> u32 {
1226        self.config.jobs.unwrap_or_else(|| {
1227            std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get) as u32
1228        })
1229    }
1230
1231    fn debuginfo_map_to(&self, which: GitRepo, remap_scheme: RemapScheme) -> Option<String> {
1232        if !self.config.rust_remap_debuginfo {
1233            return None;
1234        }
1235
1236        match which {
1237            GitRepo::Rustc => {
1238                let sha = self.rust_sha().unwrap_or(&self.version);
1239
1240                match remap_scheme {
1241                    RemapScheme::Compiler => {
1242                        // For compiler sources, remap via `/rustc-dev/{sha}` to allow
1243                        // distinguishing between compiler sources vs library sources, since
1244                        // `rustc-dev` dist component places them under
1245                        // `$sysroot/lib/rustlib/rustc-src/rust` as opposed to `rust-src`'s
1246                        // `$sysroot/lib/rustlib/src/rust`.
1247                        //
1248                        // Keep this scheme in sync with `rustc_metadata::rmeta::decoder`'s
1249                        // `try_to_translate_virtual_to_real`.
1250                        Some(format!("/rustc-dev/{sha}"))
1251                    }
1252                    RemapScheme::NonCompiler => {
1253                        // For non-compiler sources, use `/rustc/{sha}` remapping scheme.
1254                        Some(format!("/rustc/{sha}"))
1255                    }
1256                }
1257            }
1258            GitRepo::Llvm => Some(String::from("/rustc/llvm")),
1259        }
1260    }
1261
1262    /// Returns the path to the C compiler for the target specified.
1263    fn cc(&self, target: TargetSelection) -> PathBuf {
1264        if self.config.dry_run() {
1265            return PathBuf::new();
1266        }
1267        self.cc[&target].path().into()
1268    }
1269
1270    /// Returns the internal `cc::Tool` for the C compiler.
1271    fn cc_tool(&self, target: TargetSelection) -> Tool {
1272        self.cc[&target].clone()
1273    }
1274
1275    /// Returns the internal `cc::Tool` for the C++ compiler.
1276    fn cxx_tool(&self, target: TargetSelection) -> Tool {
1277        self.cxx[&target].clone()
1278    }
1279
1280    /// Returns C flags that `cc-rs` thinks should be enabled for the
1281    /// specified target by default.
1282    fn cc_handled_cflags(&self, target: TargetSelection, c: CLang) -> Vec<String> {
1283        if self.config.dry_run() {
1284            return Vec::new();
1285        }
1286        let base = match c {
1287            CLang::C => self.cc[&target].clone(),
1288            CLang::Cxx => self.cxx[&target].clone(),
1289        };
1290
1291        // Filter out -O and /O (the optimization flags) that we picked up
1292        // from cc-rs, that's up to the caller to figure out.
1293        base.args()
1294            .iter()
1295            .map(|s| s.to_string_lossy().into_owned())
1296            .filter(|s| !s.starts_with("-O") && !s.starts_with("/O"))
1297            .collect::<Vec<String>>()
1298    }
1299
1300    /// Returns extra C flags that `cc-rs` doesn't handle.
1301    fn cc_unhandled_cflags(
1302        &self,
1303        target: TargetSelection,
1304        which: GitRepo,
1305        c: CLang,
1306    ) -> Vec<String> {
1307        let mut base = Vec::new();
1308
1309        // If we're compiling C++ on macOS then we add a flag indicating that
1310        // we want libc++ (more filled out than libstdc++), ensuring that
1311        // LLVM/etc are all properly compiled.
1312        if matches!(c, CLang::Cxx) && target.contains("apple-darwin") {
1313            base.push("-stdlib=libc++".into());
1314        }
1315
1316        // Work around an apparently bad MinGW / GCC optimization,
1317        // See: https://lists.llvm.org/pipermail/cfe-dev/2016-December/051980.html
1318        // See: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=78936
1319        if &*target.triple == "i686-pc-windows-gnu" {
1320            base.push("-fno-omit-frame-pointer".into());
1321        }
1322
1323        if let Some(map_to) = self.debuginfo_map_to(which, RemapScheme::NonCompiler) {
1324            let map = format!("{}={}", self.src.display(), map_to);
1325            let cc = self.cc(target);
1326            if cc.ends_with("clang") || cc.ends_with("gcc") {
1327                base.push(format!("-fdebug-prefix-map={map}"));
1328            } else if cc.ends_with("clang-cl.exe") {
1329                base.push("-Xclang".into());
1330                base.push(format!("-fdebug-prefix-map={map}"));
1331            }
1332        }
1333        base
1334    }
1335
1336    /// Returns the path to the `ar` archive utility for the target specified.
1337    fn ar(&self, target: TargetSelection) -> Option<PathBuf> {
1338        if self.config.dry_run() {
1339            return None;
1340        }
1341        self.ar.get(&target).cloned()
1342    }
1343
1344    /// Returns the path to the `ranlib` utility for the target specified.
1345    fn ranlib(&self, target: TargetSelection) -> Option<PathBuf> {
1346        if self.config.dry_run() {
1347            return None;
1348        }
1349        self.ranlib.get(&target).cloned()
1350    }
1351
1352    /// Returns the path to the C++ compiler for the target specified.
1353    fn cxx(&self, target: TargetSelection) -> Result<PathBuf, String> {
1354        if self.config.dry_run() {
1355            return Ok(PathBuf::new());
1356        }
1357        match self.cxx.get(&target) {
1358            Some(p) => Ok(p.path().into()),
1359            None => Err(format!("target `{target}` is not configured as a host, only as a target")),
1360        }
1361    }
1362
1363    /// Returns the path to the linker for the given target if it needs to be overridden.
1364    fn linker(&self, target: TargetSelection) -> Option<PathBuf> {
1365        if self.config.dry_run() {
1366            return Some(PathBuf::new());
1367        }
1368        if let Some(linker) = self.config.target_config.get(&target).and_then(|c| c.linker.clone())
1369        {
1370            Some(linker)
1371        } else if target.contains("vxworks") {
1372            // need to use CXX compiler as linker to resolve the exception functions
1373            // that are only existed in CXX libraries
1374            Some(self.cxx[&target].path().into())
1375        } else if !self.config.is_host_target(target)
1376            && helpers::use_host_linker(target)
1377            && !target.is_msvc()
1378        {
1379            Some(self.cc(target))
1380        } else if self.config.bootstrap_override_lld.is_used()
1381            && self.is_lld_direct_linker(target)
1382            && self.host_target == target
1383        {
1384            match self.config.bootstrap_override_lld {
1385                BootstrapOverrideLld::SelfContained => Some(self.initial_lld.clone()),
1386                BootstrapOverrideLld::External => Some("lld".into()),
1387                BootstrapOverrideLld::None => None,
1388            }
1389        } else {
1390            None
1391        }
1392    }
1393
1394    // Is LLD configured directly through `-Clinker`?
1395    // Only MSVC targets use LLD directly at the moment.
1396    fn is_lld_direct_linker(&self, target: TargetSelection) -> bool {
1397        target.is_msvc()
1398    }
1399
1400    /// Returns if this target should statically link the C runtime, if specified
1401    fn crt_static(&self, target: TargetSelection) -> Option<bool> {
1402        if target.contains("pc-windows-msvc") {
1403            Some(true)
1404        } else {
1405            self.config.target_config.get(&target).and_then(|t| t.crt_static)
1406        }
1407    }
1408
1409    /// Returns the "musl root" for this `target`, if defined.
1410    ///
1411    /// If this is a native target (host is also musl) and no musl-root is given,
1412    /// it falls back to the system toolchain in /usr.
1413    fn musl_root(&self, target: TargetSelection) -> Option<&Path> {
1414        let configured_root = self
1415            .config
1416            .target_config
1417            .get(&target)
1418            .and_then(|t| t.musl_root.as_ref())
1419            .or(self.config.musl_root.as_ref())
1420            .map(|p| &**p);
1421
1422        if self.config.is_host_target(target) && configured_root.is_none() {
1423            Some(Path::new("/usr"))
1424        } else {
1425            configured_root
1426        }
1427    }
1428
1429    /// Returns the "musl libdir" for this `target`.
1430    fn musl_libdir(&self, target: TargetSelection) -> Option<PathBuf> {
1431        self.config
1432            .target_config
1433            .get(&target)
1434            .and_then(|t| t.musl_libdir.clone())
1435            .or_else(|| self.musl_root(target).map(|root| root.join("lib")))
1436    }
1437
1438    /// Returns the `lib` directory for the WASI target specified, if
1439    /// configured.
1440    ///
1441    /// This first consults `wasi-root` as configured in per-target
1442    /// configuration, and failing that it assumes that `$WASI_SDK_PATH` is
1443    /// set in the environment, and failing that `None` is returned.
1444    fn wasi_libdir(&self, target: TargetSelection) -> Option<PathBuf> {
1445        let configured =
1446            self.config.target_config.get(&target).and_then(|t| t.wasi_root.as_ref()).map(|p| &**p);
1447        if let Some(path) = configured {
1448            return Some(path.join("lib").join(target.to_string()));
1449        }
1450        let mut env_root = self.wasi_sdk_path.clone()?;
1451        env_root.push("share");
1452        env_root.push("wasi-sysroot");
1453        env_root.push("lib");
1454        env_root.push(target.to_string());
1455        Some(env_root)
1456    }
1457
1458    /// Returns `true` if this is a no-std `target`, if defined
1459    fn no_std(&self, target: TargetSelection) -> Option<bool> {
1460        self.config.target_config.get(&target).map(|t| t.no_std)
1461    }
1462
1463    /// Returns `true` if the target will be tested using the `remote-test-client`
1464    /// and `remote-test-server` binaries.
1465    fn remote_tested(&self, target: TargetSelection) -> bool {
1466        self.qemu_rootfs(target).is_some()
1467            || target.contains("android")
1468            || env::var_os("TEST_DEVICE_ADDR").is_some()
1469    }
1470
1471    /// Returns an optional "runner" to pass to `compiletest` when executing
1472    /// test binaries.
1473    ///
1474    /// An example of this would be a WebAssembly runtime when testing the wasm
1475    /// targets.
1476    fn runner(&self, target: TargetSelection) -> Option<String> {
1477        let configured_runner =
1478            self.config.target_config.get(&target).and_then(|t| t.runner.as_ref()).map(|p| &**p);
1479        if let Some(runner) = configured_runner {
1480            return Some(runner.to_owned());
1481        }
1482
1483        if target.starts_with("wasm") && target.contains("wasi") {
1484            self.default_wasi_runner(target)
1485        } else {
1486            None
1487        }
1488    }
1489
1490    /// When a `runner` configuration is not provided and a WASI-looking target
1491    /// is being tested this is consulted to prove the environment to see if
1492    /// there's a runtime already lying around that seems reasonable to use.
1493    fn default_wasi_runner(&self, target: TargetSelection) -> Option<String> {
1494        let mut finder = crate::core::sanity::Finder::new();
1495
1496        // Look for Wasmtime, and for its default options be sure to disable
1497        // its caching system since we're executing quite a lot of tests and
1498        // ideally shouldn't pollute the cache too much.
1499        if let Some(path) = finder.maybe_have("wasmtime")
1500            && let Ok(mut path) = path.into_os_string().into_string()
1501        {
1502            path.push_str(" run -Wexceptions -C cache=n --dir .");
1503            // Make sure that tests have access to RUSTC_BOOTSTRAP. This (for example) is
1504            // required for libtest to work on beta/stable channels.
1505            //
1506            // NB: with Wasmtime 20 this can change to `-S inherit-env` to
1507            // inherit the entire environment rather than just this single
1508            // environment variable.
1509            path.push_str(" --env RUSTC_BOOTSTRAP");
1510
1511            if target.contains("wasip2") {
1512                path.push_str(" --wasi inherit-network --wasi allow-ip-name-lookup");
1513            }
1514
1515            return Some(path);
1516        }
1517
1518        None
1519    }
1520
1521    /// Returns whether the specified tool is configured as part of this build.
1522    ///
1523    /// This requires that both the `extended` key is set and the `tools` key is
1524    /// either unset or specifically contains the specified tool.
1525    fn tool_enabled(&self, tool: &str) -> bool {
1526        if !self.config.extended {
1527            return false;
1528        }
1529        match &self.config.tools {
1530            Some(set) => set.contains(tool),
1531            None => true,
1532        }
1533    }
1534
1535    /// Returns the root of the "rootfs" image that this target will be using,
1536    /// if one was configured.
1537    ///
1538    /// If `Some` is returned then that means that tests for this target are
1539    /// emulated with QEMU and binaries will need to be shipped to the emulator.
1540    fn qemu_rootfs(&self, target: TargetSelection) -> Option<&Path> {
1541        self.config.target_config.get(&target).and_then(|t| t.qemu_rootfs.as_ref()).map(|p| &**p)
1542    }
1543
1544    /// Temporary directory that extended error information is emitted to.
1545    fn extended_error_dir(&self) -> PathBuf {
1546        self.out.join("tmp/extended-error-metadata")
1547    }
1548
1549    /// Tests whether the `compiler` compiling for `target` should be forced to
1550    /// use a stage1 compiler instead.
1551    ///
1552    /// Currently, by default, the build system does not perform a "full
1553    /// bootstrap" by default where we compile the compiler three times.
1554    /// Instead, we compile the compiler two times. The final stage (stage2)
1555    /// just copies the libraries from the previous stage, which is what this
1556    /// method detects.
1557    ///
1558    /// Here we return `true` if:
1559    ///
1560    /// * The build isn't performing a full bootstrap
1561    /// * The `compiler` is in the final stage, 2
1562    /// * We're not cross-compiling, so the artifacts are already available in
1563    ///   stage1
1564    ///
1565    /// When all of these conditions are met the build will lift artifacts from
1566    /// the previous stage forward.
1567    fn force_use_stage1(&self, stage: u32, target: TargetSelection) -> bool {
1568        !self.config.full_bootstrap
1569            && !self.config.download_rustc()
1570            && stage >= 2
1571            && (self.hosts.contains(&target) || target == self.host_target)
1572    }
1573
1574    /// Checks whether the `compiler` compiling for `target` should be forced to
1575    /// use a stage2 compiler instead.
1576    ///
1577    /// When we download the pre-compiled version of rustc and compiler stage is >= 2,
1578    /// it should be forced to use a stage2 compiler.
1579    fn force_use_stage2(&self, stage: u32) -> bool {
1580        self.config.download_rustc() && stage >= 2
1581    }
1582
1583    /// Given `num` in the form "a.b.c" return a "release string" which
1584    /// describes the release version number.
1585    ///
1586    /// For example on nightly this returns "a.b.c-nightly", on beta it returns
1587    /// "a.b.c-beta.1" and on stable it just returns "a.b.c".
1588    fn release(&self, num: &str) -> String {
1589        match &self.config.channel[..] {
1590            "stable" => num.to_string(),
1591            "beta" => {
1592                if !self.config.omit_git_hash {
1593                    format!("{}-beta.{}", num, self.beta_prerelease_version())
1594                } else {
1595                    format!("{num}-beta")
1596                }
1597            }
1598            "nightly" => format!("{num}-nightly"),
1599            _ => format!("{num}-dev"),
1600        }
1601    }
1602
1603    fn beta_prerelease_version(&self) -> u32 {
1604        fn extract_beta_rev_from_file<P: AsRef<Path>>(version_file: P) -> Option<String> {
1605            let version = fs::read_to_string(version_file).ok()?;
1606
1607            helpers::extract_beta_rev(&version)
1608        }
1609
1610        if let Some(s) = self.prerelease_version.get() {
1611            return s;
1612        }
1613
1614        // First check if there is a version file available.
1615        // If available, we read the beta revision from that file.
1616        // This only happens when building from a source tarball when Git should not be used.
1617        let count = extract_beta_rev_from_file(self.src.join("version")).unwrap_or_else(|| {
1618            // Figure out how many merge commits happened since we branched off main.
1619            // That's our beta number!
1620            // (Note that we use a `..` range, not the `...` symmetric difference.)
1621            helpers::git(Some(&self.src))
1622                .arg("rev-list")
1623                .arg("--count")
1624                .arg("--merges")
1625                .arg(format!(
1626                    "refs/remotes/origin/{}..HEAD",
1627                    self.config.stage0_metadata.config.nightly_branch
1628                ))
1629                .run_in_dry_run()
1630                .run_capture(self)
1631                .stdout()
1632        });
1633        let n = count.trim().parse().unwrap();
1634        self.prerelease_version.set(Some(n));
1635        n
1636    }
1637
1638    /// Returns the value of `release` above for Rust itself.
1639    fn rust_release(&self) -> String {
1640        self.release(&self.version)
1641    }
1642
1643    /// Returns the "package version" for a component.
1644    ///
1645    /// The package version is typically what shows up in the names of tarballs.
1646    /// For channels like beta/nightly it's just the channel name, otherwise it's the release
1647    /// version.
1648    fn rust_package_vers(&self) -> String {
1649        match &self.config.channel[..] {
1650            "stable" => self.version.to_string(),
1651            "beta" => "beta".to_string(),
1652            "nightly" => "nightly".to_string(),
1653            _ => format!("{}-dev", self.version),
1654        }
1655    }
1656
1657    /// Returns the `version` string associated with this compiler for Rust
1658    /// itself.
1659    ///
1660    /// Note that this is a descriptive string which includes the commit date,
1661    /// sha, version, etc.
1662    fn rust_version(&self) -> String {
1663        let mut version = self.rust_info().version(self, &self.version);
1664        if let Some(ref s) = self.config.description
1665            && !s.is_empty()
1666        {
1667            version.push_str(" (");
1668            version.push_str(s);
1669            version.push(')');
1670        }
1671        version
1672    }
1673
1674    /// Returns the full commit hash.
1675    fn rust_sha(&self) -> Option<&str> {
1676        self.rust_info().sha()
1677    }
1678
1679    /// Returns the `a.b.c` version that the given package is at.
1680    fn release_num(&self, package: &str) -> String {
1681        if self.config.dry_run() {
1682            return "0.0.0 (dry-run)".into();
1683        }
1684        let toml_file_name = self.src.join(format!("src/tools/{package}/Cargo.toml"));
1685        let toml = t!(fs::read_to_string(toml_file_name));
1686        for line in toml.lines() {
1687            if let Some(stripped) =
1688                line.strip_prefix("version = \"").and_then(|s| s.strip_suffix('"'))
1689            {
1690                return stripped.to_owned();
1691            }
1692        }
1693
1694        panic!("failed to find version in {package}'s Cargo.toml")
1695    }
1696
1697    /// Returns `true` if unstable features should be enabled for the compiler
1698    /// we're building.
1699    fn unstable_features(&self) -> bool {
1700        !matches!(&self.config.channel[..], "stable" | "beta")
1701    }
1702
1703    /// Returns a Vec of all the dependencies of the given root crate,
1704    /// including transitive dependencies and the root itself. Only includes
1705    /// "local" crates (those in the local source tree, not from a registry).
1706    fn in_tree_crates(&self, root: &str, target: Option<TargetSelection>) -> Vec<&Crate> {
1707        let mut ret = Vec::new();
1708        let mut list = vec![root.to_owned()];
1709        let mut visited = HashSet::new();
1710        while let Some(krate) = list.pop() {
1711            let krate = self
1712                .crates
1713                .get(&krate)
1714                .unwrap_or_else(|| panic!("metadata missing for {krate}: {:?}", self.crates));
1715            ret.push(krate);
1716            for dep in &krate.deps {
1717                if !self.crates.contains_key(dep) {
1718                    // Ignore non-workspace members.
1719                    continue;
1720                }
1721                // Don't include optional deps if their features are not
1722                // enabled. Ideally this would be computed from `cargo
1723                // metadata --features …`, but that is somewhat slow. In
1724                // the future, we may want to consider just filtering all
1725                // build and dev dependencies in metadata::build.
1726                if visited.insert(dep)
1727                    && (dep != "profiler_builtins"
1728                        || target
1729                            .map(|t| self.config.profiler_enabled(t))
1730                            .unwrap_or_else(|| self.config.any_profiler_enabled()))
1731                    && (dep != "rustc_codegen_llvm"
1732                        || self.config.hosts.iter().any(|host| self.config.llvm_enabled(*host)))
1733                {
1734                    list.push(dep.clone());
1735                }
1736            }
1737        }
1738        ret.sort_unstable_by_key(|krate| krate.name.clone()); // reproducible order needed for tests
1739        ret
1740    }
1741
1742    fn read_stamp_file(&self, stamp: &BuildStamp) -> Vec<(PathBuf, DependencyType)> {
1743        if self.config.dry_run() {
1744            return Vec::new();
1745        }
1746
1747        if !stamp.path().exists() {
1748            eprintln!(
1749                "ERROR: Unable to find the stamp file {}, did you try to keep a nonexistent build stage?",
1750                stamp.path().display()
1751            );
1752            crate::exit!(1);
1753        }
1754
1755        let mut paths = Vec::new();
1756        let contents = t!(fs::read(stamp.path()), stamp.path());
1757        // This is the method we use for extracting paths from the stamp file passed to us. See
1758        // run_cargo for more information (in compile.rs).
1759        for part in contents.split(|b| *b == 0) {
1760            if part.is_empty() {
1761                continue;
1762            }
1763            let dependency_type = match part[0] as char {
1764                'h' => DependencyType::Host,
1765                's' => DependencyType::TargetSelfContained,
1766                't' => DependencyType::Target,
1767                _ => unreachable!(),
1768            };
1769            let path = PathBuf::from(t!(str::from_utf8(&part[1..])));
1770            paths.push((path, dependency_type));
1771        }
1772        paths
1773    }
1774
1775    /// Copies a file from `src` to `dst`.
1776    ///
1777    /// If `src` is a symlink, `src` will be resolved to the actual path
1778    /// and copied to `dst` instead of the symlink itself.
1779    #[track_caller]
1780    pub fn resolve_symlink_and_copy(&self, src: &Path, dst: &Path) {
1781        self.copy_link_internal(src, dst, true);
1782    }
1783
1784    /// Links a file from `src` to `dst`.
1785    /// Attempts to use hard links if possible, falling back to copying.
1786    /// You can neither rely on this being a copy nor it being a link,
1787    /// so do not write to dst.
1788    #[track_caller]
1789    pub fn copy_link(&self, src: &Path, dst: &Path, file_type: FileType) {
1790        self.copy_link_internal(src, dst, false);
1791
1792        if file_type.could_have_split_debuginfo()
1793            && let Some(dbg_file) = split_debuginfo(src)
1794        {
1795            self.copy_link_internal(
1796                &dbg_file,
1797                &dst.with_extension(dbg_file.extension().unwrap()),
1798                false,
1799            );
1800        }
1801    }
1802
1803    #[track_caller]
1804    fn copy_link_internal(&self, src: &Path, dst: &Path, dereference_symlinks: bool) {
1805        if self.config.dry_run() {
1806            return;
1807        }
1808        if src == dst {
1809            return;
1810        }
1811
1812        #[cfg(feature = "tracing")]
1813        let _span = trace_io!("file-copy-link", ?src, ?dst);
1814
1815        if let Err(e) = fs::remove_file(dst)
1816            && cfg!(windows)
1817            && e.kind() != io::ErrorKind::NotFound
1818        {
1819            // workaround for https://github.com/rust-lang/rust/issues/127126
1820            // if removing the file fails, attempt to rename it instead.
1821            let now = t!(SystemTime::now().duration_since(SystemTime::UNIX_EPOCH));
1822            let _ = fs::rename(dst, format!("{}-{}", dst.display(), now.as_nanos()));
1823        }
1824        let mut metadata = t!(src.symlink_metadata(), format!("src = {}", src.display()));
1825        let mut src = src.to_path_buf();
1826        if metadata.file_type().is_symlink() {
1827            if dereference_symlinks {
1828                src = t!(fs::canonicalize(src));
1829                metadata = t!(fs::metadata(&src), format!("target = {}", src.display()));
1830            } else {
1831                let link = t!(fs::read_link(src));
1832                t!(self.symlink_file(link, dst));
1833                return;
1834            }
1835        }
1836        if let Ok(()) = fs::hard_link(&src, dst) {
1837            // Attempt to "easy copy" by creating a hard link (symlinks are privileged on windows),
1838            // but if that fails just fall back to a slow `copy` operation.
1839        } else {
1840            if let Err(e) = fs::copy(&src, dst) {
1841                panic!("failed to copy `{}` to `{}`: {}", src.display(), dst.display(), e)
1842            }
1843            t!(fs::set_permissions(dst, metadata.permissions()));
1844
1845            // Restore file times because changing permissions on e.g. Linux using `chmod` can cause
1846            // file access time to change.
1847            let file_times = fs::FileTimes::new()
1848                .set_accessed(t!(metadata.accessed()))
1849                .set_modified(t!(metadata.modified()));
1850            t!(set_file_times(dst, file_times));
1851        }
1852    }
1853
1854    /// Links the `src` directory recursively to `dst`. Both are assumed to exist
1855    /// when this function is called.
1856    /// Will attempt to use hard links if possible and fall back to copying.
1857    #[track_caller]
1858    pub fn cp_link_r(&self, src: &Path, dst: &Path) {
1859        if self.config.dry_run() {
1860            return;
1861        }
1862        for f in self.read_dir(src) {
1863            let path = f.path();
1864            let name = path.file_name().unwrap();
1865            let dst = dst.join(name);
1866            if t!(f.file_type()).is_dir() {
1867                t!(fs::create_dir_all(&dst));
1868                self.cp_link_r(&path, &dst);
1869            } else {
1870                self.copy_link(&path, &dst, FileType::Regular);
1871            }
1872        }
1873    }
1874
1875    /// Copies the `src` directory recursively to `dst`. Both are assumed to exist
1876    /// when this function is called.
1877    /// Will attempt to use hard links if possible and fall back to copying.
1878    /// Unwanted files or directories can be skipped
1879    /// by returning `false` from the filter function.
1880    #[track_caller]
1881    pub fn cp_link_filtered(&self, src: &Path, dst: &Path, filter: &dyn Fn(&Path) -> bool) {
1882        // Immediately recurse with an empty relative path
1883        self.cp_link_filtered_recurse(src, dst, Path::new(""), filter)
1884    }
1885
1886    // Inner function does the actual work
1887    #[track_caller]
1888    fn cp_link_filtered_recurse(
1889        &self,
1890        src: &Path,
1891        dst: &Path,
1892        relative: &Path,
1893        filter: &dyn Fn(&Path) -> bool,
1894    ) {
1895        for f in self.read_dir(src) {
1896            let path = f.path();
1897            let name = path.file_name().unwrap();
1898            let dst = dst.join(name);
1899            let relative = relative.join(name);
1900            // Only copy file or directory if the filter function returns true
1901            if filter(&relative) {
1902                if t!(f.file_type()).is_dir() {
1903                    let _ = fs::remove_dir_all(&dst);
1904                    self.create_dir(&dst);
1905                    self.cp_link_filtered_recurse(&path, &dst, &relative, filter);
1906                } else {
1907                    self.copy_link(&path, &dst, FileType::Regular);
1908                }
1909            }
1910        }
1911    }
1912
1913    fn copy_link_to_folder(&self, src: &Path, dest_folder: &Path) {
1914        let file_name = src.file_name().unwrap();
1915        let dest = dest_folder.join(file_name);
1916        self.copy_link(src, &dest, FileType::Regular);
1917    }
1918
1919    fn install(&self, src: &Path, dstdir: &Path, file_type: FileType) {
1920        if self.config.dry_run() {
1921            return;
1922        }
1923        let dst = dstdir.join(src.file_name().unwrap());
1924
1925        #[cfg(feature = "tracing")]
1926        let _span = trace_io!("install", ?src, ?dst);
1927
1928        t!(fs::create_dir_all(dstdir));
1929        if !src.exists() {
1930            panic!("ERROR: File \"{}\" not found!", src.display());
1931        }
1932
1933        self.copy_link_internal(src, &dst, true);
1934        chmod(&dst, file_type.perms());
1935
1936        // If this file can have debuginfo, look for split debuginfo and install it too.
1937        if file_type.could_have_split_debuginfo()
1938            && let Some(dbg_file) = split_debuginfo(src)
1939        {
1940            self.install(&dbg_file, dstdir, FileType::Regular);
1941        }
1942    }
1943
1944    fn read(&self, path: &Path) -> String {
1945        if self.config.dry_run() {
1946            return String::new();
1947        }
1948        t!(fs::read_to_string(path))
1949    }
1950
1951    #[track_caller]
1952    fn create_dir(&self, dir: &Path) {
1953        if self.config.dry_run() {
1954            return;
1955        }
1956
1957        #[cfg(feature = "tracing")]
1958        let _span = trace_io!("dir-create", ?dir);
1959
1960        t!(fs::create_dir_all(dir))
1961    }
1962
1963    fn remove_dir(&self, dir: &Path) {
1964        if self.config.dry_run() {
1965            return;
1966        }
1967
1968        #[cfg(feature = "tracing")]
1969        let _span = trace_io!("dir-remove", ?dir);
1970
1971        t!(fs::remove_dir_all(dir))
1972    }
1973
1974    /// Make sure that `dir` will be an empty existing directory after this function ends.
1975    /// If it existed before, it will be first deleted.
1976    fn clear_dir(&self, dir: &Path) {
1977        if self.config.dry_run() {
1978            return;
1979        }
1980
1981        #[cfg(feature = "tracing")]
1982        let _span = trace_io!("dir-clear", ?dir);
1983
1984        let _ = std::fs::remove_dir_all(dir);
1985        self.create_dir(dir);
1986    }
1987
1988    fn read_dir(&self, dir: &Path) -> impl Iterator<Item = fs::DirEntry> {
1989        let iter = match fs::read_dir(dir) {
1990            Ok(v) => v,
1991            Err(_) if self.config.dry_run() => return vec![].into_iter(),
1992            Err(err) => panic!("could not read dir {dir:?}: {err:?}"),
1993        };
1994        iter.map(|e| t!(e)).collect::<Vec<_>>().into_iter()
1995    }
1996
1997    fn symlink_file<P: AsRef<Path>, Q: AsRef<Path>>(&self, src: P, link: Q) -> io::Result<()> {
1998        #[cfg(unix)]
1999        use std::os::unix::fs::symlink as symlink_file;
2000        #[cfg(windows)]
2001        use std::os::windows::fs::symlink_file;
2002        if !self.config.dry_run() { symlink_file(src.as_ref(), link.as_ref()) } else { Ok(()) }
2003    }
2004
2005    /// Returns if config.ninja is enabled, and checks for ninja existence,
2006    /// exiting with a nicer error message if not.
2007    fn ninja(&self) -> bool {
2008        let mut cmd_finder = crate::core::sanity::Finder::new();
2009
2010        if self.config.ninja_in_file {
2011            // Some Linux distros rename `ninja` to `ninja-build`.
2012            // CMake can work with either binary name.
2013            if cmd_finder.maybe_have("ninja-build").is_none()
2014                && cmd_finder.maybe_have("ninja").is_none()
2015            {
2016                eprintln!(
2017                    "
2018Couldn't find required command: ninja (or ninja-build)
2019
2020You should install ninja as described at
2021<https://github.com/ninja-build/ninja/wiki/Pre-built-Ninja-packages>,
2022or set `ninja = false` in the `[llvm]` section of `bootstrap.toml`.
2023Alternatively, set `download-ci-llvm = true` in that `[llvm]` section
2024to download LLVM rather than building it.
2025"
2026                );
2027                exit!(1);
2028            }
2029        }
2030
2031        // If ninja isn't enabled but we're building for MSVC then we try
2032        // doubly hard to enable it. It was realized in #43767 that the msbuild
2033        // CMake generator for MSVC doesn't respect configuration options like
2034        // disabling LLVM assertions, which can often be quite important!
2035        //
2036        // In these cases we automatically enable Ninja if we find it in the
2037        // environment.
2038        if !self.config.ninja_in_file
2039            && self.config.host_target.is_msvc()
2040            && cmd_finder.maybe_have("ninja").is_some()
2041        {
2042            return true;
2043        }
2044
2045        self.config.ninja_in_file
2046    }
2047
2048    pub fn colored_stdout<R, F: FnOnce(&mut dyn WriteColor) -> R>(&self, f: F) -> R {
2049        self.colored_stream_inner(StandardStream::stdout, self.config.stdout_is_tty, f)
2050    }
2051
2052    pub fn colored_stderr<R, F: FnOnce(&mut dyn WriteColor) -> R>(&self, f: F) -> R {
2053        self.colored_stream_inner(StandardStream::stderr, self.config.stderr_is_tty, f)
2054    }
2055
2056    fn colored_stream_inner<R, F, C>(&self, constructor: C, is_tty: bool, f: F) -> R
2057    where
2058        C: Fn(ColorChoice) -> StandardStream,
2059        F: FnOnce(&mut dyn WriteColor) -> R,
2060    {
2061        let choice = match self.config.color {
2062            flags::Color::Always => ColorChoice::Always,
2063            flags::Color::Never => ColorChoice::Never,
2064            flags::Color::Auto if !is_tty => ColorChoice::Never,
2065            flags::Color::Auto => ColorChoice::Auto,
2066        };
2067        let mut stream = constructor(choice);
2068        let result = f(&mut stream);
2069        stream.reset().unwrap();
2070        result
2071    }
2072
2073    pub fn exec_ctx(&self) -> &ExecutionContext {
2074        &self.config.exec_ctx
2075    }
2076
2077    pub fn report_summary(&self, path: &Path, start_time: Instant) {
2078        self.config.exec_ctx.profiler().report_summary(path, start_time);
2079    }
2080
2081    #[cfg(feature = "tracing")]
2082    pub fn report_step_graph(self, directory: &Path) {
2083        self.step_graph.into_inner().store_to_dot_files(directory);
2084    }
2085}
2086
2087impl AsRef<ExecutionContext> for Build {
2088    fn as_ref(&self) -> &ExecutionContext {
2089        &self.config.exec_ctx
2090    }
2091}
2092
2093#[cfg(unix)]
2094fn chmod(path: &Path, perms: u32) {
2095    use std::os::unix::fs::*;
2096    t!(fs::set_permissions(path, fs::Permissions::from_mode(perms)));
2097}
2098#[cfg(windows)]
2099fn chmod(_path: &Path, _perms: u32) {}
2100
2101impl Compiler {
2102    pub fn new(stage: u32, host: TargetSelection) -> Self {
2103        Self { stage, host, forced_compiler: false }
2104    }
2105
2106    pub fn forced_compiler(&mut self, forced_compiler: bool) {
2107        self.forced_compiler = forced_compiler;
2108    }
2109
2110    /// Returns `true` if this is a snapshot compiler for `build`'s configuration
2111    pub fn is_snapshot(&self, build: &Build) -> bool {
2112        self.stage == 0 && self.host == build.host_target
2113    }
2114
2115    /// Indicates whether the compiler was forced to use a specific stage.
2116    pub fn is_forced_compiler(&self) -> bool {
2117        self.forced_compiler
2118    }
2119}
2120
2121fn envify(s: &str) -> String {
2122    // Converting foo-bar to FOO_BAR is a fairly idomatic mapping to an environment variable name.
2123    // We also convert '.' to '_' to fix https://github.com/rust-lang/rust/issues/158090
2124    s.chars()
2125        .map(|c| match c {
2126            '-' | '.' => '_',
2127            c => c,
2128        })
2129        .flat_map(|c| c.to_uppercase())
2130        .collect()
2131}
2132
2133/// Ensures that the behavior dump directory is properly initialized.
2134pub fn prepare_behaviour_dump_dir(build: &Build) {
2135    static INITIALIZED: OnceLock<bool> = OnceLock::new();
2136
2137    let dump_path = build.out.join("bootstrap-shims-dump");
2138
2139    let initialized = INITIALIZED.get().unwrap_or(&false);
2140    if !initialized {
2141        // clear old dumps
2142        if dump_path.exists() {
2143            t!(fs::remove_dir_all(&dump_path));
2144        }
2145
2146        t!(fs::create_dir_all(&dump_path));
2147
2148        t!(INITIALIZED.set(true));
2149    }
2150}
2151
2152#[macro_export]
2153macro_rules! exit {
2154    ($code:expr) => {
2155        $crate::utils::helpers::detail_exit($code, cfg!(test));
2156    };
2157}