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