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