bootstrap/core/builder/
mod.rs

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