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