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