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