bootstrap/
lib.rs

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