Skip to main content

bootstrap/
lib.rs

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