Skip to main content

bootstrap/core/
session.rs

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