Skip to main content

bootstrap/core/builder/
mod.rs

1use std::any::{Any, type_name};
2use std::cell::{Cell, RefCell};
3use std::collections::BTreeSet;
4use std::fmt::{Debug, Write};
5use std::hash::Hash;
6use std::ops::Deref;
7use std::path::{Path, PathBuf};
8use std::sync::OnceLock;
9use std::time::{Duration, Instant};
10use std::{env, fs, iter};
11
12use clap::ValueEnum;
13#[cfg(feature = "tracing")]
14use tracing::instrument;
15
16pub(crate) use self::cargo::{Cargo, apply_pgo, cargo_profile_var};
17use crate::core::build_steps::compile::{Std, StdLink, looks_like_codegen_backend};
18use crate::core::build_steps::llvm::{LlvmKind, get_llvm_build_status};
19use crate::core::build_steps::tool::RustcPrivateCompilers;
20use crate::core::build_steps::{
21    check, clean, clippy, compile, dist, doc, gcc, install, llvm, run, setup, test, tool, vendor,
22};
23use crate::core::builder::step_stack::StepRecord;
24pub use crate::core::builder::step_stack::StepStack;
25use crate::core::compiler::Compiler;
26use crate::core::config::flags::Subcommand;
27use crate::core::config::{DryRun, TargetSelection};
28use crate::core::metadata::Crate;
29use crate::core::session::Session;
30use crate::trace;
31use crate::utils::build_stamp::BuildStamp;
32use crate::utils::cache::Cache;
33use crate::utils::exec::{BootstrapCommand, ExecutionContext, command};
34use crate::utils::helpers::{self, LldThreads, add_dylib_path, exe, libdir, linker_args, t};
35use crate::utils::tracing::format_location;
36
37mod cargo;
38mod cli_paths;
39mod step_stack;
40#[cfg(test)]
41mod tests;
42
43/// Builds and performs different [`Self::kind`]s of stuff and actions, taking
44/// into account build configuration from e.g. bootstrap.toml.
45pub(crate) struct Builder<'a> {
46    /// Build configuration from e.g. bootstrap.toml.
47    pub sess: &'a Session,
48
49    /// The stage to use. Either implicitly determined based on subcommand, or
50    /// explicitly specified with `--stage N`. Normally this is the stage we
51    /// use, but sometimes we want to run steps with a lower stage than this.
52    pub top_stage: u32,
53
54    /// What to build or what action to perform.
55    pub kind: Kind,
56
57    /// A cache of outputs of [`Step`]s so we can avoid running steps we already
58    /// ran.
59    cache: Cache,
60
61    /// A stack of [`Step`]s to run before we can run this builder. The output
62    /// of steps is cached in [`Self::cache`].
63    stack: RefCell<Vec<Box<dyn AnyDebug>>>,
64
65    /// The total amount of time we spent running [`Step`]s in [`Self::stack`].
66    time_spent_on_dependencies: Cell<Duration>,
67
68    /// The paths passed on the command line. Used by steps to figure out what
69    /// to do. For example: with `./x check foo bar` we get `paths=["foo",
70    /// "bar"]`.
71    pub paths: Vec<PathBuf>,
72
73    /// Cached list of submodules from self.sess.src.
74    submodule_paths_cache: OnceLock<Vec<String>>,
75
76    /// When enabled by tests, this causes the top-level steps that _would_ be
77    /// executed to be logged instead. Used by snapshot tests of command-line
78    /// paths-to-steps handling.
79    #[expect(clippy::type_complexity)]
80    log_cli_step_for_tests:
81        Option<Box<dyn Fn(&CommandLineStepDescription, &[PathSet], &[TargetSelection])>>,
82}
83
84impl Deref for Builder<'_> {
85    type Target = Session;
86
87    fn deref(&self) -> &Self::Target {
88        self.sess
89    }
90}
91
92/// This trait is similar to `Any`, except that it also exposes the underlying
93/// type's [`Debug`] implementation.
94///
95/// (Trying to debug-print `dyn Any` results in the unhelpful `"Any { .. }"`.)
96pub trait AnyDebug: Any + Debug {}
97impl<T: Any + Debug> AnyDebug for T {}
98impl dyn AnyDebug {
99    /// Equivalent to `<dyn Any>::downcast_ref`.
100    fn downcast_ref<T: Any>(&self) -> Option<&T> {
101        (self as &dyn Any).downcast_ref()
102    }
103
104    // Feel free to add other `dyn Any` methods as necessary.
105}
106
107/// A unit of work within bootstrap that is cached to avoid redundant execution.
108/// Steps can be performed via [`Builder::ensure`].
109///
110/// Historically, steps also participated in command-line processing.
111/// That responsibility has been split off into the larger [`CommandLineStep`] trait,
112/// which helper steps don't need to implement.
113pub(crate) trait Step: 'static + Clone + Debug + PartialEq + Eq + Hash {
114    /// Result type of [`Step::run`]. Stored in the step cache for later lookup.
115    type Output: Clone;
116
117    /// Executes this step.
118    ///
119    /// Called by [`Builder::ensure`] if no cached result was found for this step.
120    fn run(self, builder: &Builder<'_>) -> Self::Output;
121
122    /// Returns metadata of the step, for tests.
123    #[cfg_attr(not(any(test, feature = "tracing")), expect(dead_code))]
124    fn metadata(&self) -> Option<StepMetadata> {
125        None
126    }
127}
128
129/// Every [`CommandLineStep`] is also a [`Step`].
130impl<S: CommandLineStep> Step for S {
131    type Output = <S as CommandLineStep>::Output;
132
133    fn run(self, builder: &Builder<'_>) -> Self::Output {
134        <S as CommandLineStep>::run(self, builder)
135    }
136
137    fn metadata(&self) -> Option<StepMetadata> {
138        <S as CommandLineStep>::metadata(self)
139    }
140}
141
142/// A [`Step`] that can be selected by command-line arguments.
143///
144/// A blanket impl allows every [`CommandLineStep`] to be used as a [`Step`].
145/// This is arguably nicer than having it be a subtrait, because it avoids the
146/// need for two separate `impl` blocks per command-line-step type.
147pub(crate) trait CommandLineStep: 'static + Clone + Debug + PartialEq + Eq + Hash {
148    /// Result type of [`Step::run`].
149    type Output: Clone;
150
151    /// If this value is true, then the values of `run.target` passed to the `make_run` function of
152    /// this Step will be determined based on the `--host` flag.
153    /// If this value is false, then they will be determined based on the `--target` flag.
154    ///
155    /// A corollary of the above is that if this is set to true, then the step will be skipped if
156    /// `--target` was specified, but `--host` was explicitly set to '' (empty string).
157    const IS_HOST: bool = false;
158
159    /// Called to allow steps to register the command-line paths that should
160    /// cause them to run.
161    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_>;
162
163    /// Should this step run when the user invokes bootstrap with a subcommand
164    /// but no paths/aliases?
165    ///
166    /// For example, `./x test` runs all default test steps, and `./x dist`
167    /// runs all default dist steps.
168    ///
169    /// Most steps are always default or always non-default, and just return
170    /// true or false. But some steps are conditionally default, based on
171    /// bootstrap config or the availability of ambient tools.
172    ///
173    /// If the underlying check should not be performed repeatedly
174    /// (e.g. because it probes command-line tools),
175    /// consider memoizing its outcome via a field in the builder.
176    fn is_default_step(_builder: &Builder<'_>) -> bool {
177        false
178    }
179
180    /// Called directly by the bootstrap `Step` handler when not triggered indirectly by other `Step`s using [`Builder::ensure`].
181    /// For example, `./x.py test bootstrap` runs this for `test::Bootstrap`. Similarly, `./x.py test` runs it for every step
182    /// that is listed by the `describe` macro in [`Builder::get_step_descriptions`].
183    fn make_run(_run: RunConfig<'_>);
184
185    /// Used as the implementation of [`Step::run`].
186    fn run(self, builder: &Builder<'_>) -> Self::Output;
187
188    /// Used as the implementation of [`Step::metadata`].
189    fn metadata(&self) -> Option<StepMetadata> {
190        None
191    }
192}
193
194/// Metadata that describes an executed step, mostly for testing and tracing.
195#[derive(Clone, Debug, PartialEq, Eq)]
196pub(crate) struct StepMetadata {
197    name: String,
198    kind: Kind,
199    target: TargetSelection,
200    built_by: Option<Compiler>,
201    stage: Option<u32>,
202    /// Additional opaque string printed in the metadata
203    metadata: Option<String>,
204}
205
206impl StepMetadata {
207    pub fn build(name: &str, target: TargetSelection) -> Self {
208        Self::new(name, target, Kind::Build)
209    }
210
211    pub fn check(name: &str, target: TargetSelection) -> Self {
212        Self::new(name, target, Kind::Check)
213    }
214
215    pub fn clippy(name: &str, target: TargetSelection) -> Self {
216        Self::new(name, target, Kind::Clippy)
217    }
218
219    pub fn doc(name: &str, target: TargetSelection) -> Self {
220        Self::new(name, target, Kind::Doc)
221    }
222
223    pub fn dist(name: &str, target: TargetSelection) -> Self {
224        Self::new(name, target, Kind::Dist)
225    }
226
227    pub fn test(name: &str, target: TargetSelection) -> Self {
228        Self::new(name, target, Kind::Test)
229    }
230
231    pub fn run(name: &str, target: TargetSelection) -> Self {
232        Self::new(name, target, Kind::Run)
233    }
234
235    pub fn new(name: &str, target: TargetSelection, kind: Kind) -> Self {
236        Self { name: name.to_string(), kind, target, built_by: None, stage: None, metadata: None }
237    }
238
239    pub fn built_by(mut self, compiler: Compiler) -> Self {
240        self.built_by = Some(compiler);
241        self
242    }
243
244    pub fn stage(mut self, stage: u32) -> Self {
245        self.stage = Some(stage);
246        self
247    }
248
249    pub fn with_metadata(mut self, metadata: String) -> Self {
250        self.metadata = Some(metadata);
251        self
252    }
253
254    #[cfg_attr(not(any(test, feature = "tracing")), expect(dead_code))]
255    pub(crate) fn get_stage(&self) -> Option<u32> {
256        self.stage.or(self
257            .built_by
258            // For std, its stage corresponds to the stage of the compiler that builds it.
259            // For everything else, a stage N things gets built by a stage N-1 compiler.
260            .map(|compiler| if self.name == "std" { compiler.stage } else { compiler.stage + 1 }))
261    }
262
263    #[cfg_attr(not(feature = "tracing"), expect(dead_code))]
264    pub(crate) fn get_name(&self) -> &str {
265        &self.name
266    }
267
268    #[cfg_attr(not(feature = "tracing"), expect(dead_code))]
269    pub(crate) fn get_target(&self) -> TargetSelection {
270        self.target
271    }
272}
273
274pub struct RunConfig<'a> {
275    pub builder: &'a Builder<'a>,
276    pub target: TargetSelection,
277    pub paths: Vec<PathSet>,
278}
279
280impl RunConfig<'_> {
281    pub fn build_triple(&self) -> TargetSelection {
282        self.builder.sess.host_target
283    }
284
285    /// Return a list of crate names selected by `run.paths`.
286    #[track_caller]
287    pub fn cargo_crates_in_set(&self) -> Vec<String> {
288        let mut crates = Vec::new();
289        for krate in &self.paths {
290            let path = &krate.assert_single_path().path;
291
292            let crate_name = self
293                .builder
294                .crate_paths
295                .get(path)
296                .unwrap_or_else(|| panic!("missing crate for path {}", path.display()));
297
298            crates.push(crate_name.to_string());
299        }
300        crates
301    }
302
303    /// Given an `alias` selected by the `Step` and the paths passed on the command line,
304    /// return a list of the crates that should be built.
305    ///
306    /// Normally, people will pass *just* `library` if they pass it.
307    /// But it's possible (although strange) to pass something like `library std core`.
308    /// Build all crates anyway, as if they hadn't passed the other args.
309    pub fn make_run_crates(&self, alias: Alias) -> Vec<String> {
310        let has_alias =
311            self.paths.iter().any(|set| set.assert_single_path().path.ends_with(alias.as_str()));
312        if !has_alias {
313            return self.cargo_crates_in_set();
314        }
315
316        let crates = match alias {
317            Alias::Library => self.builder.in_tree_crates("sysroot", Some(self.target)),
318            Alias::Compiler => self.builder.in_tree_crates("rustc-main", Some(self.target)),
319        };
320
321        crates.into_iter().map(|krate| krate.name.to_string()).collect()
322    }
323}
324
325#[derive(Debug, Copy, Clone)]
326pub enum Alias {
327    Library,
328    Compiler,
329}
330
331impl Alias {
332    fn as_str(self) -> &'static str {
333        match self {
334            Alias::Library => "library",
335            Alias::Compiler => "compiler",
336        }
337    }
338}
339
340/// A description of the crates in this set, suitable for passing to `builder.info`.
341///
342/// `crates` should be generated by [`RunConfig::cargo_crates_in_set`].
343pub fn crate_description(crates: &[impl AsRef<str>]) -> String {
344    if crates.is_empty() {
345        return "".into();
346    }
347    if crates.len() == 1 {
348        return crates[0].as_ref().into();
349    }
350
351    let mut descr = String::from("{");
352    descr.push_str(crates[0].as_ref());
353    for krate in &crates[1..] {
354        descr.push_str(", ");
355        descr.push_str(krate.as_ref());
356    }
357    descr.push('}');
358    descr
359}
360
361struct CommandLineStepDescription {
362    is_host: bool,
363    should_run: fn(ShouldRun<'_>) -> ShouldRun<'_>,
364    is_default_step_fn: fn(&Builder<'_>) -> bool,
365    make_run: fn(RunConfig<'_>),
366    name: &'static str,
367
368    /// Kind that was passed to [`CommandLineStepDescription::from`].
369    #[cfg_attr(not(test), expect(dead_code, reason = "currently only needed by tests"))]
370    kind: Kind,
371}
372
373#[derive(Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
374pub struct TaskPath {
375    pub path: PathBuf,
376}
377
378impl Debug for TaskPath {
379    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
380        write!(f, "{}", self.path.display())
381    }
382}
383
384/// Collection of paths used to match a task rule.
385#[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
386pub enum PathSet {
387    /// A collection of individual paths or aliases.
388    ///
389    /// These are generally matched as a path suffix. For example, a
390    /// command-line value of `std` will match if `library/std` is in the
391    /// set.
392    ///
393    /// NOTE: the paths within a set should all select the same unit of work.
394    /// For example, `src/librustdoc` and `src/tools/rustdoc` should be in the same set,
395    /// but `library/core` and `library/std` generally should not, unless there's no way (for that Step)
396    /// to build them separately.
397    Set(BTreeSet<TaskPath>),
398    /// A "suite" of paths.
399    ///
400    /// These can match as a path suffix (like `Set`), or as a prefix. For
401    /// example, a command-line value of `tests/ui/abi/variadic-ffi.rs`
402    /// will match `tests/ui`. A command-line value of `ui` would also
403    /// match `tests/ui`.
404    Suite(TaskPath),
405}
406
407impl PathSet {
408    fn one<P: Into<PathBuf>>(path: P) -> PathSet {
409        let mut set = BTreeSet::new();
410        set.insert(TaskPath { path: path.into() });
411        PathSet::Set(set)
412    }
413
414    fn has(&self, needle: &Path) -> bool {
415        match self {
416            PathSet::Set(set) => set.iter().any(|p| Self::check(p, needle)),
417            PathSet::Suite(suite) => Self::check(suite, needle),
418        }
419    }
420
421    // internal use only
422    fn check(p: &TaskPath, needle: &Path) -> bool {
423        // This order is important for retro-compatibility, as `starts_with` was introduced later.
424        p.path.ends_with(needle) || p.path.starts_with(needle)
425    }
426
427    /// A convenience wrapper for Steps which know they have no aliases and all their sets contain only a single path.
428    ///
429    /// This can be used with [`ShouldRun::crate_or_deps`], [`ShouldRun::path`], or [`ShouldRun::alias`].
430    #[track_caller]
431    pub fn assert_single_path(&self) -> &TaskPath {
432        match self {
433            PathSet::Set(set) => {
434                assert_eq!(set.len(), 1, "called assert_single_path on multiple paths");
435                set.iter().next().unwrap()
436            }
437            PathSet::Suite(_) => unreachable!("called assert_single_path on a Suite path"),
438        }
439    }
440}
441
442impl CommandLineStepDescription {
443    fn from<S: CommandLineStep>(kind: Kind) -> CommandLineStepDescription {
444        CommandLineStepDescription {
445            is_host: S::IS_HOST,
446            should_run: S::should_run,
447            is_default_step_fn: S::is_default_step,
448            make_run: S::make_run,
449            name: std::any::type_name::<S>(),
450            kind,
451        }
452    }
453
454    fn maybe_run(&self, builder: &Builder<'_>, mut pathsets: Vec<PathSet>) {
455        pathsets.retain(|set| !self.is_excluded(builder, set));
456
457        if pathsets.is_empty() {
458            return;
459        }
460
461        // Determine the targets participating in this rule.
462        let targets = if self.is_host { &builder.hosts } else { &builder.targets };
463
464        // Log the step that's about to run, for snapshot tests.
465        if let Some(ref log_cli_step) = builder.log_cli_step_for_tests {
466            log_cli_step(self, &pathsets, targets);
467            // Return so that the step won't actually run in snapshot tests.
468            return;
469        }
470
471        for target in targets {
472            let run = RunConfig { builder, paths: pathsets.clone(), target: *target };
473            (self.make_run)(run);
474        }
475    }
476
477    fn is_excluded(&self, builder: &Builder<'_>, pathset: &PathSet) -> bool {
478        if builder.config.skip.iter().any(|e| pathset.has(e)) {
479            if !matches!(builder.config.get_dry_run(), DryRun::SelfCheck) {
480                println!("Skipping {pathset:?} because it is excluded");
481            }
482            return true;
483        }
484
485        if !builder.config.skip.is_empty()
486            && !matches!(builder.config.get_dry_run(), DryRun::SelfCheck)
487        {
488            builder.do_if_verbose(|| {
489                println!(
490                    "{:?} not skipped for {:?} -- not in {:?}",
491                    pathset, self.name, builder.config.skip
492                )
493            });
494        }
495        false
496    }
497}
498
499/// Builder that allows steps to register command-line paths/aliases that
500/// should cause those steps to be run.
501///
502/// For example, if the user invokes `./x test compiler` or `./x doc unstable-book`,
503/// this allows bootstrap to determine what steps "compiler" or "unstable-book"
504/// correspond to.
505pub struct ShouldRun<'a> {
506    pub builder: &'a Builder<'a>,
507
508    // use a BTreeSet to maintain sort order
509    paths: BTreeSet<PathSet>,
510}
511
512impl<'a> ShouldRun<'a> {
513    fn new(builder: &'a Builder<'_>) -> ShouldRun<'a> {
514        ShouldRun { builder, paths: BTreeSet::new() }
515    }
516
517    /// The corresponding step should run if the bootstrap command-line selects
518    /// the given crate or any of its (local) dependencies.
519    ///
520    /// Delegates to [`Self::crate_or_deps_filtered`] with a filter that accepts all crates.
521    pub(crate) fn crate_or_deps(self, root_crate_name: &str) -> Self {
522        self.crate_or_deps_filtered(root_crate_name, |_: &Crate| true)
523    }
524
525    /// The corresponding step should run if the bootstrap command-line selects
526    /// the given crate or any of its (local) dependencies, not counting any
527    /// crates rejected by the given filter function.
528    ///
529    /// `make_run` will be called a single time with all matching command-line paths.
530    pub(crate) fn crate_or_deps_filtered(
531        mut self,
532        root_crate_name: &str,
533        crate_filter_fn: impl Fn(&Crate) -> bool,
534    ) -> Self {
535        let crates = self.builder.in_tree_crates(root_crate_name, None);
536        for krate in crates {
537            if !crate_filter_fn(krate) {
538                continue;
539            }
540
541            let path = krate.local_path(self.builder);
542            self.paths.insert(PathSet::one(path));
543        }
544        self
545    }
546
547    // single alias, which does not correspond to any on-disk path
548    pub fn alias(self, alias: &str) -> Self {
549        self.assert_valid_alias(alias);
550        self.alias_without_assert(alias)
551    }
552
553    /// Like [`Self::alias`], but does not assert the absence of a path with the same name.
554    ///
555    /// Needed by [`setup::Profile`], which registers aliases named `compiler` and `library`
556    /// that happen to coincide with directory names.
557    pub fn alias_without_assert(mut self, alias: &str) -> Self {
558        self.paths.insert(PathSet::Set(iter::once(TaskPath { path: alias.into() }).collect()));
559        self
560    }
561
562    fn assert_valid_alias(&self, alias: &str) {
563        assert!(
564            !self.builder.src.join(alias).exists(),
565            "use `builder.path()` for real paths: {alias}"
566        );
567    }
568
569    fn assert_valid_path(&self, path: &str) {
570        let submodules_paths = self.builder.submodule_paths();
571
572        // assert only if `p` isn't submodule
573        if !submodules_paths.iter().any(|sm_p| path.contains(sm_p)) {
574            assert!(
575                self.builder.src.join(path).exists(),
576                "`should_run.path` should correspond to a real on-disk path - use `alias` if there is no relevant path: {path}"
577            );
578        }
579    }
580
581    /// A single path
582    ///
583    /// Must be an on-disk path; use [`alias`][Self::alias] for names that do not
584    /// correspond to on-disk paths.
585    pub fn path(mut self, path: &str) -> Self {
586        self.assert_valid_path(path);
587
588        let task = TaskPath { path: path.into() };
589        self.paths.insert(PathSet::Set(BTreeSet::from_iter([task])));
590        self
591    }
592
593    /// Registers a path, and an alias that is treated as equivalent to that path.
594    pub fn path_with_alias(mut self, path: &str, alias: &str) -> Self {
595        self.assert_valid_path(path);
596        self.assert_valid_alias(alias);
597
598        let set = [path, alias]
599            .into_iter()
600            .map(|p| TaskPath { path: PathBuf::from(p) })
601            .collect::<BTreeSet<_>>();
602        self.paths.insert(PathSet::Set(set));
603        self
604    }
605
606    /// Multiple on-disk paths that should select the same unit of work.
607    pub fn multi_path(mut self, paths: &[&str]) -> Self {
608        let mut set = BTreeSet::new();
609        for path in paths {
610            self.assert_valid_path(path);
611            set.insert(TaskPath { path: (*path).into() });
612        }
613        self.paths.insert(PathSet::Set(set));
614        self
615    }
616
617    pub fn suite_path(mut self, suite: &str) -> Self {
618        self.paths.insert(PathSet::Suite(TaskPath { path: suite.into() }));
619        self
620    }
621
622    /// When the corresponding step is run "by default" (without explicit command-line paths),
623    /// act as though the user had explicitly specified these paths.
624    fn default_pathsets(&self) -> Vec<PathSet> {
625        self.paths.iter().cloned().collect::<Vec<_>>()
626    }
627}
628
629#[derive(Debug, Copy, Clone, Eq, Hash, PartialEq, PartialOrd, Ord, ValueEnum)]
630pub enum Kind {
631    #[value(alias = "b")]
632    Build,
633    #[value(alias = "c")]
634    Check,
635    Clippy,
636    Fix,
637    Format,
638    #[value(alias = "t")]
639    Test,
640    Miri,
641    MiriSetup,
642    MiriTest,
643    Bench,
644    #[value(alias = "d")]
645    Doc,
646    Clean,
647    Dist,
648    Install,
649    #[value(alias = "r")]
650    Run,
651    Setup,
652    Vendor,
653    Perf,
654}
655
656impl Kind {
657    pub fn as_str(&self) -> &'static str {
658        match self {
659            Kind::Build => "build",
660            Kind::Check => "check",
661            Kind::Clippy => "clippy",
662            Kind::Fix => "fix",
663            Kind::Format => "fmt",
664            Kind::Test => "test",
665            Kind::Miri => "miri",
666            Kind::MiriSetup => panic!("`as_str` is not supported for `Kind::MiriSetup`."),
667            Kind::MiriTest => panic!("`as_str` is not supported for `Kind::MiriTest`."),
668            Kind::Bench => "bench",
669            Kind::Doc => "doc",
670            Kind::Clean => "clean",
671            Kind::Dist => "dist",
672            Kind::Install => "install",
673            Kind::Run => "run",
674            Kind::Setup => "setup",
675            Kind::Vendor => "vendor",
676            Kind::Perf => "perf",
677        }
678    }
679
680    pub fn description(&self) -> String {
681        match self {
682            Kind::Test => "Testing",
683            Kind::Bench => "Benchmarking",
684            Kind::Doc => "Documenting",
685            Kind::Run => "Running",
686            Kind::Clippy => "Linting",
687            Kind::Perf => "Profiling & benchmarking",
688            _ => {
689                let title_letter = self.as_str()[0..1].to_ascii_uppercase();
690                return format!("{title_letter}{}ing", &self.as_str()[1..]);
691            }
692        }
693        .to_owned()
694    }
695
696    /// Is this a command similar to check, which only runs the compiler frontend and doesn't
697    /// build code for the target? (it can still build code for the host, i.e. proc macros).
698    pub fn is_check_like(&self) -> bool {
699        match self {
700            Kind::Check | Kind::Clippy | Kind::Fix | Kind::Doc => true,
701            Kind::Build
702            | Kind::Format
703            | Kind::Test
704            | Kind::Miri
705            | Kind::MiriSetup
706            | Kind::MiriTest
707            | Kind::Bench
708            | Kind::Clean
709            | Kind::Dist
710            | Kind::Install
711            | Kind::Run
712            | Kind::Setup
713            | Kind::Vendor
714            | Kind::Perf => false,
715        }
716    }
717}
718
719#[derive(Debug, Clone, Hash, PartialEq, Eq)]
720struct Libdir {
721    compiler: Compiler,
722    target: TargetSelection,
723}
724
725impl Step for Libdir {
726    type Output = PathBuf;
727
728    fn run(self, builder: &Builder<'_>) -> PathBuf {
729        let relative_sysroot_libdir = builder.sysroot_libdir_relative(self.compiler);
730        let sysroot = builder.sysroot(self.compiler).join(relative_sysroot_libdir).join("rustlib");
731
732        if !builder.config.dry_run() {
733            // Avoid deleting the `rustlib/` directory we just copied (in `impl CommandLineStep for
734            // Sysroot`).
735            if !builder.download_rustc() {
736                let sysroot_target_libdir = sysroot.join(self.target).join("lib");
737                builder.do_if_verbose(|| {
738                    eprintln!(
739                        "Removing sysroot {} to avoid caching bugs",
740                        sysroot_target_libdir.display()
741                    )
742                });
743                let _ = fs::remove_dir_all(&sysroot_target_libdir);
744                t!(fs::create_dir_all(&sysroot_target_libdir));
745            }
746
747            if self.compiler.stage == 0 {
748                // The stage 0 compiler for the build triple is always pre-built. Ensure that
749                // `libLLVM.so` ends up in the target libdir, so that ui-fulldeps tests can use
750                // it when run.
751                dist::maybe_install_llvm_target(
752                    builder,
753                    self.compiler.host,
754                    &builder.sysroot(self.compiler),
755                );
756            }
757        }
758
759        sysroot
760    }
761}
762
763#[cfg(feature = "tracing")]
764pub const STEP_SPAN_TARGET: &str = "STEP";
765
766impl<'a> Builder<'a> {
767    fn get_step_descriptions(kind: Kind) -> Vec<CommandLineStepDescription> {
768        macro_rules! describe {
769            ($($rule:ty),+ $(,)?) => {{
770                vec![$(CommandLineStepDescription::from::<$rule>(kind)),+]
771            }};
772        }
773        match kind {
774            Kind::Build => describe!(
775                compile::Std,
776                compile::Rustc,
777                compile::Assemble,
778                compile::CraneliftCodegenBackend,
779                compile::GccCodegenBackend,
780                compile::StartupObjects,
781                tool::BuildManifest,
782                tool::Rustbook,
783                tool::ErrorIndex,
784                tool::UnstableBookGen,
785                tool::Tidy,
786                tool::Linkchecker,
787                tool::CargoTest,
788                tool::Compiletest,
789                tool::RemoteTestServer,
790                tool::RemoteTestClient,
791                tool::RustInstaller,
792                tool::FeaturesStatusDump,
793                tool::Cargo,
794                tool::RustAnalyzer,
795                tool::RustAnalyzerProcMacroSrv,
796                tool::Rustdoc,
797                tool::Clippy,
798                tool::CargoClippy,
799                llvm::Llvm,
800                gcc::Gcc,
801                llvm::Sanitizers,
802                tool::Rustfmt,
803                tool::Cargofmt,
804                tool::Miri,
805                tool::CargoMiri,
806                llvm::Lld,
807                llvm::Enzyme,
808                llvm::RustOffload,
809                llvm::CrtBeginEnd,
810                llvm::Tpde,
811                tool::RustdocGUITest,
812                tool::OptimizedDist,
813                tool::CoverageDump,
814                tool::LlvmBitcodeLinker,
815                tool::RustcPerf,
816                tool::WasmComponentLd,
817                tool::LldWrapper,
818            ),
819            Kind::Clippy => describe!(
820                clippy::Std,
821                clippy::Rustc,
822                clippy::Bootstrap,
823                clippy::BuildHelper,
824                clippy::BuildManifest,
825                clippy::CargoMiri,
826                clippy::Clippy,
827                clippy::CodegenGcc,
828                clippy::CollectLicenseMetadata,
829                clippy::Compiletest,
830                clippy::CoverageDump,
831                clippy::Jsondocck,
832                clippy::Jsondoclint,
833                clippy::LintDocs,
834                clippy::LlvmBitcodeLinker,
835                clippy::Miri,
836                clippy::MiroptTestTools,
837                clippy::OptDist,
838                clippy::RemoteTestClient,
839                clippy::RemoteTestServer,
840                clippy::RustAnalyzer,
841                clippy::Rustdoc,
842                clippy::Rustfmt,
843                clippy::RustInstaller,
844                clippy::TestFloatParse,
845                clippy::Tidy,
846                clippy::CI,
847            ),
848            Kind::Check | Kind::Fix => describe!(
849                check::Rustc,
850                check::Rustdoc,
851                check::CraneliftCodegenBackend,
852                check::GccCodegenBackend,
853                check::Clippy,
854                check::Miri,
855                check::CargoMiri,
856                check::MiroptTestTools,
857                check::Rustfmt,
858                check::RustAnalyzer,
859                check::TestFloatParse,
860                check::Bootstrap,
861                check::RunMakeSupport,
862                check::Compiletest,
863                check::RustdocGuiTest,
864                check::FeaturesStatusDump,
865                check::CoverageDump,
866                check::Linkchecker,
867                check::BumpStage0,
868                check::Tidy,
869                // This has special staging logic, it may run on stage 1 while others run on stage 0.
870                // It takes quite some time to build stage 1, so put this at the end.
871                //
872                // FIXME: This also helps bootstrap to not interfere with stage 0 builds. We should probably fix
873                // that issue somewhere else, but we still want to keep `check::Std` at the end so that the
874                // quicker steps run before this.
875                check::Std,
876            ),
877            Kind::Test => describe!(
878                crate::core::build_steps::toolstate::ToolStateCheck,
879                test::Tidy,
880                test::BootstrapPy,
881                test::Bootstrap,
882                test::Ui,
883                test::Crashes,
884                test::Coverage,
885                test::CoverageModeAlias,
886                test::MirOpt,
887                test::CodegenLlvm,
888                test::CodegenUnits,
889                test::AssemblyGcc,
890                test::AssemblyLlvm,
891                test::Incremental,
892                test::Debuginfo,
893                test::UiFullDeps,
894                test::RustdocHtml,
895                test::CoverageRunRustdoc,
896                test::Pretty,
897                test::CodegenCranelift,
898                test::CodegenGCC,
899                test::Crate,
900                test::CrateLibrustc,
901                test::CrateRustdoc,
902                test::CrateRustdocJsonTypes,
903                test::CrateBootstrap,
904                test::RemoteTestClientTests,
905                test::Linkcheck,
906                test::TierCheck,
907                test::Cargotest,
908                test::Cargo,
909                test::RustAnalyzer,
910                test::ErrorIndex,
911                test::Distcheck,
912                test::Nomicon,
913                test::Reference,
914                test::RustdocBook,
915                test::RustByExample,
916                test::TheBook,
917                test::UnstableBook,
918                test::RustcBook,
919                test::LintDocs,
920                test::EmbeddedBook,
921                test::EditionGuide,
922                test::Rustfmt,
923                test::Miri,
924                test::CargoMiri,
925                test::Priroda,
926                test::Clippy,
927                test::CompiletestTest,
928                test::StdarchVerify,
929                test::StdarchGenCheck,
930                test::CrateRunMakeSupport,
931                test::CrateBuildHelper,
932                test::RustdocJSStd,
933                test::RustdocJSNotStd,
934                test::RustdocGUI,
935                test::RustdocTheme,
936                test::RustdocUi,
937                test::RustdocJson,
938                test::HtmlCheck,
939                test::RustInstaller,
940                test::TestFloatParse,
941                test::CompilerBuiltins,
942                test::CollectLicenseMetadata,
943                test::RunMake,
944                test::RunMakeCargo,
945                test::BuildStd,
946                test::StdSemverCheck,
947                test::IntrinsicTest,
948            ),
949            Kind::Miri => describe!(test::Crate),
950            Kind::Bench => describe!(test::Crate, test::CrateLibrustc, test::CrateRustdoc),
951            Kind::Doc => describe!(
952                doc::UnstableBook,
953                doc::UnstableBookGen,
954                doc::TheBook,
955                doc::Standalone,
956                doc::Std,
957                doc::Rustc,
958                doc::Rustdoc,
959                doc::Rustfmt,
960                doc::ErrorIndex,
961                doc::Nomicon,
962                doc::Reference,
963                doc::RustdocBook,
964                doc::RustByExample,
965                doc::RustcBook,
966                doc::Cargo,
967                doc::CargoBook,
968                doc::Clippy,
969                doc::ClippyBook,
970                doc::CompilerWithTools,
971                doc::Miri,
972                doc::EmbeddedBook,
973                doc::EditionGuide,
974                doc::StyleGuide,
975                doc::Tidy,
976                doc::Bootstrap,
977                doc::Releases,
978                doc::RunMakeSupport,
979                doc::BuildHelper,
980                doc::Compiletest,
981            ),
982            Kind::Dist => describe!(
983                dist::Docs,
984                dist::RustcDocs,
985                dist::JsonDocs,
986                dist::Mingw,
987                dist::Rustc,
988                dist::CraneliftCodegenBackend,
989                dist::GccCodegenBackend,
990                dist::Std,
991                dist::RustcDev,
992                dist::Analysis,
993                dist::Src,
994                dist::Cargo,
995                dist::RustAnalyzer,
996                dist::Rustfmt,
997                dist::Clippy,
998                dist::Miri,
999                dist::LlvmTools,
1000                dist::LlvmBitcodeLinker,
1001                dist::RustDev,
1002                dist::Enzyme,
1003                dist::Offload,
1004                dist::Bootstrap,
1005                dist::Extended,
1006                // It seems that PlainSourceTarball somehow changes how some of the tools
1007                // perceive their dependencies (see #93033) which would invalidate fingerprints
1008                // and force us to rebuild tools after vendoring dependencies.
1009                // To work around this, create the Tarball after building all the tools.
1010                dist::PlainSourceTarball,
1011                dist::PlainSourceTarballGpl,
1012                dist::BuildManifest,
1013                dist::ReproducibleArtifacts,
1014                dist::GccDev,
1015                dist::Gcc,
1016            ),
1017            Kind::Install => describe!(
1018                install::Docs,
1019                install::Std,
1020                // During the Rust compiler (rustc) installation process, we copy the entire sysroot binary
1021                // path (build/host/stage2/bin). Since the building tools also make their copy in the sysroot
1022                // binary path, we must install rustc before the tools. Otherwise, the rust-installer will
1023                // install the same binaries twice for each tool, leaving backup files (*.old) as a result.
1024                install::Rustc,
1025                install::RustcDev,
1026                install::Cargo,
1027                install::RustAnalyzer,
1028                install::Rustfmt,
1029                install::Clippy,
1030                install::Miri,
1031                install::LlvmTools,
1032                install::Src,
1033                install::RustcCodegenCranelift,
1034                install::LlvmBitcodeLinker
1035            ),
1036            Kind::Run => describe!(
1037                run::BuildManifest,
1038                run::BumpStage0,
1039                run::ReplaceVersionPlaceholder,
1040                run::Miri,
1041                run::CollectLicenseMetadata,
1042                run::GenerateCopyright,
1043                run::GenerateWindowsSys,
1044                run::GenerateCompletions,
1045                run::UnicodeTableGenerator,
1046                run::FeaturesStatusDump,
1047                run::CyclicStep,
1048                run::CoverageDump,
1049                run::Rustfmt,
1050                run::GenerateHelp,
1051            ),
1052            Kind::Setup => {
1053                describe!(setup::Profile, setup::Hook, setup::Link, setup::Editor)
1054            }
1055            Kind::Clean => describe!(clean::CleanAll, clean::Rustc, clean::Std),
1056            Kind::Vendor => describe!(vendor::Vendor),
1057            // special-cased in Session::build()
1058            Kind::Format | Kind::Perf => vec![],
1059            Kind::MiriTest | Kind::MiriSetup => unreachable!(),
1060        }
1061    }
1062
1063    pub fn get_help(sess: &Session, kind: Kind) -> Option<String> {
1064        let step_descriptions = Builder::get_step_descriptions(kind);
1065        if step_descriptions.is_empty() {
1066            return None;
1067        }
1068
1069        let builder = Self::new_internal(sess, kind, vec![]);
1070        let builder = &builder;
1071
1072        let mut should_run = ShouldRun::new(builder);
1073        for desc in step_descriptions {
1074            should_run = (desc.should_run)(should_run);
1075        }
1076        let mut help = String::from("Available paths:\n");
1077        let mut add_path = |path: &Path| {
1078            t!(write!(help, "    ./x.py {} {}\n", kind.as_str(), path.display()));
1079        };
1080        for pathset in should_run.paths {
1081            match pathset {
1082                PathSet::Set(set) => {
1083                    for path in set {
1084                        add_path(&path.path);
1085                    }
1086                }
1087                PathSet::Suite(path) => {
1088                    add_path(&path.path.join("..."));
1089                }
1090            }
1091        }
1092        Some(help)
1093    }
1094
1095    fn new_internal(sess: &Session, kind: Kind, paths: Vec<PathBuf>) -> Builder<'_> {
1096        Builder {
1097            sess,
1098            top_stage: sess.config.stage,
1099            kind,
1100            cache: Cache::new(),
1101            stack: RefCell::new(Vec::new()),
1102            time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
1103            paths,
1104            submodule_paths_cache: Default::default(),
1105            log_cli_step_for_tests: None,
1106        }
1107    }
1108
1109    pub fn new(sess: &Session) -> Builder<'_> {
1110        let paths = &sess.config.paths;
1111        let (kind, paths) = match sess.config.cmd {
1112            Subcommand::Build { .. } => (Kind::Build, &paths[..]),
1113            Subcommand::Check { .. } => (Kind::Check, &paths[..]),
1114            Subcommand::Clippy { .. } => (Kind::Clippy, &paths[..]),
1115            Subcommand::Fix { .. } => (Kind::Fix, &paths[..]),
1116            Subcommand::Doc { .. } => (Kind::Doc, &paths[..]),
1117            Subcommand::Test { .. } => (Kind::Test, &paths[..]),
1118            Subcommand::Miri { .. } => (Kind::Miri, &paths[..]),
1119            Subcommand::Bench { .. } => (Kind::Bench, &paths[..]),
1120            Subcommand::Dist => (Kind::Dist, &paths[..]),
1121            Subcommand::Install => (Kind::Install, &paths[..]),
1122            Subcommand::Run { .. } => (Kind::Run, &paths[..]),
1123            Subcommand::Clean { .. } => (Kind::Clean, &paths[..]),
1124            Subcommand::Format { .. } => (Kind::Format, &[][..]),
1125            Subcommand::Setup { profile: ref path } => {
1126                (Kind::Setup, path.as_ref().map_or([].as_slice(), std::slice::from_ref))
1127            }
1128            Subcommand::Vendor { .. } => (Kind::Vendor, &paths[..]),
1129            Subcommand::Perf { .. } => (Kind::Perf, &paths[..]),
1130        };
1131
1132        StepStack::with_current(|stack| stack.clear());
1133        Self::new_internal(sess, kind, paths.to_owned())
1134    }
1135
1136    pub fn execute_cli(&self) {
1137        self.run_step_descriptions(&Builder::get_step_descriptions(self.kind), &self.paths);
1138    }
1139
1140    /// Run all default documentation steps to build documentation.
1141    pub fn run_default_doc_steps(&self) {
1142        // It's important that we don't just call `run_step_descriptions` here,
1143        // because that would cause `--skip` handling for actual command-line
1144        // arguments to inappropriately skip these steps.
1145        //
1146        // This function is nevertheless a bit of a hack, to work around the
1147        // fact that we don't have a good way to simulate `./x doc` without
1148        // also simulating parts of command-line selector handling.
1149
1150        for desc in &Builder::get_step_descriptions(Kind::Doc) {
1151            if !(desc.is_default_step_fn)(self) {
1152                continue;
1153            }
1154
1155            let should_run = (desc.should_run)(ShouldRun::new(self));
1156            let default_pathsets = should_run.default_pathsets();
1157
1158            let targets = if desc.is_host { &self.hosts } else { &self.targets };
1159            for &target in targets {
1160                let run = RunConfig { builder: self, target, paths: default_pathsets.clone() };
1161                (desc.make_run)(run);
1162            }
1163        }
1164    }
1165
1166    pub fn doc_rust_lang_org_channel(&self) -> String {
1167        let channel = match &*self.config.channel {
1168            "stable" => &self.version,
1169            "beta" => "beta",
1170            "nightly" | "dev" => "nightly",
1171            // custom build of rustdoc maybe? link to the latest stable docs just in case
1172            _ => "stable",
1173        };
1174
1175        format!("https://doc.rust-lang.org/{channel}")
1176    }
1177
1178    fn run_step_descriptions(&self, v: &[CommandLineStepDescription], paths: &[PathBuf]) {
1179        cli_paths::match_paths_to_steps_and_run(self, v, paths);
1180    }
1181
1182    /// Obtain a compiler at a given stage and for a given host (i.e., this is the target that the
1183    /// compiler will run on, *not* the target it will build code for). Explicitly does not take
1184    /// `Compiler` since all `Compiler` instances are meant to be obtained through this function,
1185    /// since it ensures that they are valid (i.e., built and assembled).
1186    #[track_caller]
1187    #[cfg_attr(
1188        feature = "tracing",
1189        instrument(
1190            level = "trace",
1191            name = "Builder::compiler",
1192            target = "COMPILER",
1193            skip_all,
1194            fields(
1195                stage = stage,
1196                host = ?host,
1197            ),
1198        ),
1199    )]
1200    pub fn compiler(&self, stage: u32, host: TargetSelection) -> Compiler {
1201        self.ensure(compile::Assemble { target_compiler: Compiler::new(stage, host) })
1202    }
1203
1204    /// This function can be used to provide a build compiler for building
1205    /// the standard library, in order to avoid unnecessary rustc builds in case where std uplifting
1206    /// would happen anyway.
1207    ///
1208    /// This is an important optimization mainly for CI.
1209    ///
1210    /// Normally, to build stage N libstd, we need stage N rustc.
1211    /// However, if we know that we will uplift libstd from stage 1 anyway, building the stage N
1212    /// rustc can be wasteful.
1213    /// In particular, if we do a cross-compiling dist stage 2 build from target1 to target2,
1214    /// we need:
1215    /// - stage 2 libstd for target2 (uplifted from stage 1, where it was built by target1 rustc)
1216    /// - stage 2 rustc for target2
1217    ///
1218    /// However, without this optimization, we would also build stage 2 rustc for **target1**,
1219    /// which is completely wasteful.
1220    #[track_caller]
1221    pub fn compiler_for_std(&self, stage: u32) -> Compiler {
1222        if compile::Std::should_be_uplifted_from_stage_1(self, stage) {
1223            self.compiler(1, self.host_target)
1224        } else {
1225            self.compiler(stage, self.host_target)
1226        }
1227    }
1228
1229    /// Similar to `compiler`, except handles the full-bootstrap option to
1230    /// silently use the stage1 compiler instead of a stage2 compiler if one is
1231    /// requested.
1232    ///
1233    /// Note that this does *not* have the side effect of creating
1234    /// `compiler(stage, host)`, unlike `compiler` above which does have such
1235    /// a side effect. The returned compiler here can only be used to compile
1236    /// new artifacts, it can't be used to rely on the presence of a particular
1237    /// sysroot.
1238    ///
1239    /// See `force_use_stage1` and `force_use_stage2` for documentation on what each argument is.
1240    #[track_caller]
1241    #[cfg_attr(
1242        feature = "tracing",
1243        instrument(
1244            level = "trace",
1245            name = "Builder::compiler_for",
1246            target = "COMPILER_FOR",
1247            skip_all,
1248            fields(
1249                stage = stage,
1250                host = ?host,
1251                target = ?target,
1252            ),
1253        ),
1254    )]
1255    /// FIXME: This function is unnecessary (and dangerous, see <https://github.com/rust-lang/rust/issues/137469>).
1256    /// We already have uplifting logic for the compiler, so remove this.
1257    pub fn compiler_for(
1258        &self,
1259        stage: u32,
1260        host: TargetSelection,
1261        target: TargetSelection,
1262    ) -> Compiler {
1263        let mut resolved_compiler = if self.sess.force_use_stage2(stage) {
1264            trace!(target: "COMPILER_FOR", ?stage, "force_use_stage2");
1265            self.compiler(2, self.config.host_target)
1266        } else if self.sess.force_use_stage1(stage, target) {
1267            trace!(target: "COMPILER_FOR", ?stage, "force_use_stage1");
1268            self.compiler(1, self.config.host_target)
1269        } else {
1270            trace!(target: "COMPILER_FOR", ?stage, ?host, "no force, fallback to `compiler()`");
1271            self.compiler(stage, host)
1272        };
1273
1274        if stage != resolved_compiler.stage {
1275            resolved_compiler.forced_compiler(true);
1276        }
1277
1278        trace!(target: "COMPILER_FOR", ?resolved_compiler);
1279        resolved_compiler
1280    }
1281
1282    /// Obtain a standard library for the given target that will be built by the passed compiler.
1283    /// The standard library will be linked to the sysroot of the passed compiler.
1284    ///
1285    /// Prefer using this method rather than manually invoking `Std::new`.
1286    ///
1287    /// Returns an optional build stamp, if libstd was indeed built.
1288    #[track_caller]
1289    #[cfg_attr(
1290        feature = "tracing",
1291        instrument(
1292            level = "trace",
1293            name = "Builder::std",
1294            target = "STD",
1295            skip_all,
1296            fields(
1297                compiler = ?compiler,
1298                target = ?target,
1299            ),
1300        ),
1301    )]
1302    pub fn std(&self, compiler: Compiler, target: TargetSelection) -> Option<BuildStamp> {
1303        // FIXME: make the `Std` step return some type-level "proof" that std was indeed built,
1304        // and then require passing that to all Cargo invocations that we do.
1305
1306        // The "stage 0" std is almost always precompiled and comes with the stage0 compiler, so we
1307        // have special logic for it, to avoid creating needless and confusing Std steps that don't
1308        // actually build anything.
1309        // We only allow building the stage0 stdlib if we do a local rebuild, so the stage0 compiler
1310        // actually comes from in-tree sources, and we're cross-compiling, so the stage0 for the
1311        // given `target` is not available.
1312        if compiler.stage == 0 {
1313            if target != compiler.host {
1314                if self.local_rebuild {
1315                    self.ensure(Std::new(compiler, target))
1316                } else {
1317                    panic!(
1318                        r"It is not possible to build the standard library for `{target}` using the stage0 compiler.
1319You have to build a stage1 compiler for `{}` first, and then use it to build a standard library for `{target}`.
1320Alternatively, you can set `build.local-rebuild=true` and use a stage0 compiler built from in-tree sources.
1321",
1322                        compiler.host
1323                    )
1324                }
1325            } else {
1326                // We still need to link the prebuilt standard library into the ephemeral stage0 sysroot
1327                self.ensure(StdLink::from_std(Std::new(compiler, target), compiler));
1328                None
1329            }
1330        } else {
1331            // This step both compiles the std and links it into the compiler's sysroot.
1332            // Yes, it's quite magical and side-effecty.. would be nice to refactor later.
1333            self.ensure(Std::new(compiler, target))
1334        }
1335    }
1336
1337    #[track_caller]
1338    pub fn sysroot(&self, compiler: Compiler) -> PathBuf {
1339        self.ensure(compile::Sysroot::new(compiler))
1340    }
1341
1342    /// Returns the bindir for a compiler's sysroot.
1343    #[track_caller]
1344    pub fn sysroot_target_bindir(&self, compiler: Compiler, target: TargetSelection) -> PathBuf {
1345        self.ensure(Libdir { compiler, target }).join(target).join("bin")
1346    }
1347
1348    /// Returns the libdir where the standard library and other artifacts are
1349    /// found for a compiler's sysroot.
1350    #[track_caller]
1351    pub fn sysroot_target_libdir(&self, compiler: Compiler, target: TargetSelection) -> PathBuf {
1352        self.ensure(Libdir { compiler, target }).join(target).join("lib")
1353    }
1354
1355    pub fn sysroot_codegen_backends(&self, compiler: Compiler) -> PathBuf {
1356        self.sysroot_target_libdir(compiler, compiler.host).with_file_name("codegen-backends")
1357    }
1358
1359    /// Returns the compiler's libdir where it stores the dynamic libraries that
1360    /// it itself links against.
1361    ///
1362    /// For example this returns `<sysroot>/lib` on Unix and `<sysroot>/bin` on
1363    /// Windows.
1364    pub fn rustc_libdir(&self, compiler: Compiler) -> PathBuf {
1365        if compiler.is_snapshot(self) {
1366            self.rustc_snapshot_libdir()
1367        } else {
1368            match self.config.libdir_relative() {
1369                Some(relative_libdir) if compiler.stage >= 1 => {
1370                    self.sysroot(compiler).join(relative_libdir)
1371                }
1372                _ => self.sysroot(compiler).join(libdir(compiler.host)),
1373            }
1374        }
1375    }
1376
1377    /// Returns the compiler's relative libdir where it stores the dynamic libraries that
1378    /// it itself links against.
1379    ///
1380    /// For example this returns `lib` on Unix and `bin` on
1381    /// Windows.
1382    pub fn libdir_relative(&self, compiler: Compiler) -> &Path {
1383        if compiler.is_snapshot(self) {
1384            libdir(self.config.host_target).as_ref()
1385        } else {
1386            match self.config.libdir_relative() {
1387                Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
1388                _ => libdir(compiler.host).as_ref(),
1389            }
1390        }
1391    }
1392
1393    /// Returns the compiler's relative libdir where the standard library and other artifacts are
1394    /// found for a compiler's sysroot.
1395    ///
1396    /// For example this returns `lib` on Unix and Windows.
1397    pub fn sysroot_libdir_relative(&self, compiler: Compiler) -> &Path {
1398        match self.config.libdir_relative() {
1399            Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
1400            _ if compiler.stage == 0 => &self.sess.initial_relative_libdir,
1401            _ => Path::new("lib"),
1402        }
1403    }
1404
1405    pub fn rustc_lib_paths(&self, compiler: Compiler) -> Vec<PathBuf> {
1406        let mut dylib_dirs = vec![self.rustc_libdir(compiler)];
1407
1408        // Ensure that the downloaded LLVM libraries can be found.
1409        // FIXME: the libraries should be added elsewhere, not in this function...
1410        if get_llvm_build_status(self, compiler.host).llvm_output().kind()
1411            == LlvmKind::DownloadedFromCi
1412        {
1413            let ci_llvm_lib = self.out.join(compiler.host).join("ci-llvm").join("lib");
1414            dylib_dirs.push(ci_llvm_lib);
1415        }
1416
1417        dylib_dirs
1418    }
1419
1420    /// Adds the compiler's directory of dynamic libraries to `cmd`'s dynamic
1421    /// library lookup path.
1422    pub fn add_rustc_lib_path(&self, compiler: Compiler, cmd: &mut BootstrapCommand) {
1423        // Windows doesn't need dylib path munging because the dlls for the
1424        // compiler live next to the compiler and the system will find them
1425        // automatically.
1426        if cfg!(any(windows, target_os = "cygwin")) {
1427            return;
1428        }
1429
1430        add_dylib_path(self.rustc_lib_paths(compiler), cmd);
1431    }
1432
1433    /// Gets a path to the compiler specified.
1434    pub fn rustc(&self, compiler: Compiler) -> PathBuf {
1435        if compiler.is_snapshot(self) {
1436            self.initial_rustc.clone()
1437        } else {
1438            self.sysroot(compiler).join("bin").join(exe("rustc", compiler.host))
1439        }
1440    }
1441
1442    /// Gets a command to run the compiler specified, including the dynamic library
1443    /// path in case the executable has not been build with `rpath` enabled.
1444    pub fn rustc_cmd(&self, compiler: Compiler) -> BootstrapCommand {
1445        let mut cmd = command(self.rustc(compiler));
1446        self.add_rustc_lib_path(compiler, &mut cmd);
1447        cmd
1448    }
1449
1450    /// Gets the paths to all of the compiler's codegen backends.
1451    fn codegen_backends(&self, compiler: Compiler) -> impl Iterator<Item = PathBuf> {
1452        fs::read_dir(self.sysroot_codegen_backends(compiler))
1453            .into_iter()
1454            .flatten()
1455            .filter_map(Result::ok)
1456            .filter(|path| looks_like_codegen_backend(&path.path()))
1457            .map(|entry| entry.path())
1458    }
1459
1460    /// Returns a path to `Rustdoc` that "belongs" to the `target_compiler`.
1461    /// It can be either a stage0 rustdoc or a locally built rustdoc that *links* to
1462    /// `target_compiler`.
1463    #[track_caller]
1464    pub fn rustdoc_for_compiler(&self, target_compiler: Compiler) -> PathBuf {
1465        self.ensure(tool::Rustdoc { target_compiler })
1466    }
1467
1468    pub fn cargo_miri_cmd(&self, run_compiler: Compiler) -> BootstrapCommand {
1469        assert!(run_compiler.stage > 0, "miri can not be invoked at stage 0");
1470
1471        let compilers = RustcPrivateCompilers::new(self, run_compiler.stage, self.sess.host_target);
1472        assert_eq!(run_compiler, compilers.target_compiler());
1473
1474        // Prepare the tools
1475        let miri = self.ensure(tool::Miri::from_compilers(compilers));
1476        let cargo_miri = self.ensure(tool::CargoMiri::from_compilers(compilers));
1477        // Invoke cargo-miri, make sure it can find miri and cargo.
1478        let mut cmd = command(cargo_miri.tool_path);
1479        cmd.env("MIRI", &miri.tool_path);
1480        cmd.env("CARGO", &self.initial_cargo);
1481        // Need to add the `run_compiler` libs. Those are the libs produces *by* `build_compiler`
1482        // in `tool::ToolBuild` step, so they match the Miri we just built. However this means they
1483        // are actually living one stage up, i.e. we are running `stage1-tools-bin/miri` with the
1484        // libraries in `stage1/lib`. This is an unfortunate off-by-1 caused (possibly) by the fact
1485        // that Miri doesn't have an "assemble" step like rustc does that would cross the stage boundary.
1486        // We can't use `add_rustc_lib_path` as that's a NOP on Windows but we do need these libraries
1487        // added to the PATH due to the stage mismatch.
1488        // Also see https://github.com/rust-lang/rust/pull/123192#issuecomment-2028901503.
1489        add_dylib_path(self.rustc_lib_paths(run_compiler), &mut cmd);
1490        cmd
1491    }
1492
1493    /// Create a Cargo command for running Clippy.
1494    /// The used Clippy is (or in the case of stage 0, already was) built using `build_compiler`.
1495    pub fn cargo_clippy_cmd(&self, build_compiler: Compiler) -> BootstrapCommand {
1496        if build_compiler.stage == 0 {
1497            let cargo_clippy =
1498                self.config.external_cargo_clippy.clone().unwrap_or_else(|| {
1499                    self.sess.config.download_clippy(&self.sess.initial_sysroot)
1500                });
1501
1502            let mut cmd = command(cargo_clippy);
1503            cmd.env("CARGO", &self.initial_cargo);
1504            return cmd;
1505        }
1506
1507        // If we're linting something with build_compiler stage N, we want to build Clippy stage N
1508        // and use that to lint it. That is why we use the `build_compiler` as the target compiler
1509        // for RustcPrivateCompilers. We will use build compiler stage N-1 to build Clippy stage N.
1510        let compilers = RustcPrivateCompilers::from_target_compiler(self, build_compiler);
1511
1512        let _ = self.ensure(tool::Clippy::from_compilers(compilers));
1513        let cargo_clippy = self.ensure(tool::CargoClippy::from_compilers(compilers));
1514        let mut dylib_path = helpers::dylib_path();
1515        dylib_path.insert(0, self.sysroot(build_compiler).join("lib"));
1516
1517        let mut cmd = command(cargo_clippy.tool_path);
1518        cmd.env(helpers::dylib_path_var(), env::join_paths(&dylib_path).unwrap());
1519        cmd.env("CARGO", &self.initial_cargo);
1520        cmd
1521    }
1522
1523    pub fn rustdoc_cmd(&self, compiler: Compiler) -> BootstrapCommand {
1524        let mut cmd = command(self.bootstrap_out.join("rustdoc"));
1525        cmd.env("RUSTC_STAGE", compiler.stage.to_string())
1526            .env("RUSTC_SYSROOT", self.sysroot(compiler))
1527            // Note that this is *not* the sysroot_libdir because rustdoc must be linked
1528            // equivalently to rustc.
1529            .env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler))
1530            .env("CFG_RELEASE_CHANNEL", &self.config.channel)
1531            .env("RUSTDOC_REAL", self.rustdoc_for_compiler(compiler))
1532            .env("RUSTC_BOOTSTRAP", "1");
1533
1534        cmd.arg("-Wrustdoc::invalid_codeblock_attributes");
1535
1536        if self.config.deny_warnings {
1537            cmd.arg("-Dwarnings");
1538        }
1539        cmd.arg("-Znormalize-docs");
1540        cmd.args(linker_args(self, compiler.host, LldThreads::Yes));
1541        cmd
1542    }
1543
1544    /// Returns true is LLVM is enabled for the given target and we are supposed to build it.
1545    ///
1546    /// Note that this returns false if LLVM is disabled, or if we're in a
1547    /// check build or dry-run, where there's no need to build all of LLVM.
1548    pub fn is_llvm_enabled_for(&self, target: TargetSelection) -> bool {
1549        self.config.llvm_enabled(target) && self.kind != Kind::Check && !self.config.dry_run()
1550    }
1551
1552    /// Return the `llvm-config` for the host target, so that it is executable.
1553    pub fn host_llvm_config(&self) -> PathBuf {
1554        self.ensure(llvm::Llvm { target: self.host_target }).llvm_config().to_owned()
1555    }
1556
1557    /// Updates all submodules, and exits with an error if submodule
1558    /// management is disabled and the submodule does not exist.
1559    pub fn require_and_update_all_submodules(&self) {
1560        for submodule in self.submodule_paths() {
1561            self.require_submodule(submodule, None);
1562        }
1563    }
1564
1565    /// Get all submodules from the src directory.
1566    pub fn submodule_paths(&self) -> &[String] {
1567        self.submodule_paths_cache.get_or_init(|| build_helper::util::parse_gitmodules(&self.src))
1568    }
1569
1570    /// Ensure that a given step is built, returning its output. This will
1571    /// cache the step, so it is safe (and good!) to call this as often as
1572    /// needed to ensure that all dependencies are built.
1573    #[track_caller]
1574    pub(crate) fn ensure<S: Step>(&'a self, step: S) -> S::Output {
1575        {
1576            let mut stack = self.stack.borrow_mut();
1577            for stack_step in stack.iter() {
1578                // should skip
1579                if stack_step.downcast_ref::<S>().is_none_or(|stack_step| *stack_step != step) {
1580                    continue;
1581                }
1582                let mut out = String::new();
1583                out += &format!("\n\nCycle in build detected when adding {step:?}\n");
1584                for el in stack.iter().rev() {
1585                    out += &format!("\t{el:?}\n");
1586                }
1587                panic!("{}", out);
1588            }
1589            if let Some(out) = self.cache.get(&step) {
1590                #[cfg(feature = "tracing")]
1591                {
1592                    if let Some(parent) = stack.last() {
1593                        let mut graph = self.sess.step_graph.borrow_mut();
1594                        graph.register_cached_step(&step, parent, self.config.dry_run());
1595                    }
1596                }
1597                return out;
1598            }
1599
1600            #[cfg(feature = "tracing")]
1601            {
1602                let parent = stack.last();
1603                let mut graph = self.sess.step_graph.borrow_mut();
1604                graph.register_step_execution(&step, parent, self.config.dry_run());
1605            }
1606
1607            // The location has to be gathered in this function, to be correctly propagated with
1608            // #[track_caller].
1609            let location = format_location(*std::panic::Location::caller());
1610            StepStack::with_current(|stack| {
1611                stack.push(StepRecord { info: pretty_print_step(&step), location });
1612            });
1613            stack.push(Box::new(step.clone()));
1614        }
1615
1616        #[cfg(feature = "build-metrics")]
1617        self.metrics.enter_step(&step, self);
1618
1619        if self.config.print_step_timings && !self.config.dry_run() {
1620            println!("[TIMING:start] {}", pretty_print_step(&step));
1621        }
1622
1623        let (out, dur) = {
1624            let start = Instant::now();
1625            let zero = Duration::new(0, 0);
1626            let parent = self.time_spent_on_dependencies.replace(zero);
1627
1628            #[cfg(feature = "tracing")]
1629            let _span = {
1630                // Keep the target and field names synchronized with `setup_tracing`.
1631                let span = tracing::info_span!(
1632                    target: STEP_SPAN_TARGET,
1633                    // We cannot use a dynamic name here, so instead we record the actual step name
1634                    // in the step_name field.
1635                    "step",
1636                    step_name = pretty_step_name::<S>(),
1637                    args = step_debug_args(&step),
1638                    location = format_location(*std::panic::Location::caller())
1639                );
1640                span.entered()
1641            };
1642
1643            let out = step.clone().run(self);
1644            let dur = start.elapsed();
1645            let deps = self.time_spent_on_dependencies.replace(parent + dur);
1646            (out, dur.saturating_sub(deps))
1647        };
1648
1649        if self.config.print_step_timings && !self.config.dry_run() {
1650            println!(
1651                "[TIMING:end] {} -- {}.{:03}",
1652                pretty_print_step(&step),
1653                dur.as_secs(),
1654                dur.subsec_millis()
1655            );
1656        }
1657
1658        #[cfg(feature = "build-metrics")]
1659        self.metrics.exit_step(self);
1660
1661        {
1662            let mut stack = self.stack.borrow_mut();
1663            let cur_step = stack.pop().expect("step stack empty");
1664            assert_eq!(cur_step.downcast_ref(), Some(&step));
1665
1666            StepStack::with_current(|stack| {
1667                stack.pop();
1668            });
1669        }
1670        self.cache.put(step, out.clone());
1671        out
1672    }
1673
1674    /// Ensure that a given step is built *only if it's supposed to be built by default*, returning
1675    /// its output. This will cache the step, so it's safe (and good!) to call this as often as
1676    /// needed to ensure that all dependencies are build.
1677    pub(crate) fn ensure_if_default<T, S: CommandLineStep<Output = T>>(
1678        &'a self,
1679        step: S,
1680        kind: Kind,
1681    ) -> Option<S::Output> {
1682        let desc = CommandLineStepDescription::from::<S>(kind);
1683        let should_run = (desc.should_run)(ShouldRun::new(self));
1684
1685        // Avoid running steps contained in --skip
1686        for pathset in &should_run.paths {
1687            if desc.is_excluded(self, pathset) {
1688                return None;
1689            }
1690        }
1691
1692        // Only execute if it's supposed to run as default
1693        if (desc.is_default_step_fn)(self) { Some(self.ensure(step)) } else { None }
1694    }
1695
1696    /// Checks if any of the "should_run" paths is in the `Builder` paths.
1697    pub(crate) fn was_invoked_explicitly<S: CommandLineStep>(&'a self, kind: Kind) -> bool {
1698        let desc = CommandLineStepDescription::from::<S>(kind);
1699        let should_run = (desc.should_run)(ShouldRun::new(self));
1700
1701        for path in &self.paths {
1702            if should_run.paths.iter().any(|s| s.has(path))
1703                && !desc.is_excluded(self, &PathSet::Suite(TaskPath { path: path.clone() }))
1704            {
1705                return true;
1706            }
1707        }
1708
1709        false
1710    }
1711
1712    pub(crate) fn maybe_open_in_browser<S: CommandLineStep>(&self, path: impl AsRef<Path>) {
1713        if self.was_invoked_explicitly::<S>(Kind::Doc) {
1714            self.open_in_browser(path);
1715        } else {
1716            self.info(&format!("Doc path: {}", path.as_ref().display()));
1717        }
1718    }
1719
1720    pub(crate) fn open_in_browser(&self, path: impl AsRef<Path>) {
1721        let path = path.as_ref();
1722
1723        if self.config.dry_run() || !self.config.cmd.open() {
1724            self.info(&format!("Doc path: {}", path.display()));
1725            return;
1726        }
1727
1728        self.info(&format!("Opening doc {}", path.display()));
1729        if let Err(err) = opener::open(path) {
1730            self.info(&format!("{err}\n"));
1731        }
1732    }
1733
1734    pub fn exec_ctx(&self) -> &ExecutionContext {
1735        &self.config.exec_ctx
1736    }
1737}
1738
1739/// Return qualified step name, e.g. `compile::Rustc`.
1740pub fn pretty_step_name<S: Step>() -> String {
1741    // Normalize step type path to only keep the module and the type name
1742    let path = type_name::<S>().rsplit("::").take(2).collect::<Vec<_>>();
1743    path.into_iter().rev().collect::<Vec<_>>().join("::")
1744}
1745
1746/// Renders `step` using its `Debug` implementation and extract the field arguments out of it.
1747fn step_debug_args<S: Step>(step: &S) -> String {
1748    let step_dbg_repr = format!("{step:?}");
1749
1750    // Some steps do not have any arguments, so they do not have the braces
1751    match (step_dbg_repr.find('{'), step_dbg_repr.rfind('}')) {
1752        (Some(brace_start), Some(brace_end)) => {
1753            step_dbg_repr[brace_start + 1..brace_end - 1].trim().to_string()
1754        }
1755        _ => String::new(),
1756    }
1757}
1758
1759fn pretty_print_step<S: Step>(step: &S) -> String {
1760    format!("{} {{ {} }}", pretty_step_name::<S>(), step_debug_args(step))
1761}
1762
1763impl<'a> AsRef<ExecutionContext> for Builder<'a> {
1764    fn as_ref(&self) -> &ExecutionContext {
1765        self.exec_ctx()
1766    }
1767}