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 is 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: {p}"
698                        );
699                    }
700
701                    TaskPath { path: p.into(), kind: Some(self.kind) }
702                })
703                .collect(),
704        ));
705        self
706    }
707
708    /// Handles individual files (not directories) within a test suite.
709    fn is_suite_path(&self, requested_path: &Path) -> Option<&PathSet> {
710        self.paths.iter().find(|pathset| match pathset {
711            PathSet::Suite(suite) => requested_path.starts_with(&suite.path),
712            PathSet::Set(_) => false,
713        })
714    }
715
716    pub fn suite_path(mut self, suite: &str) -> Self {
717        self.paths.insert(PathSet::Suite(TaskPath { path: suite.into(), kind: Some(self.kind) }));
718        self
719    }
720
721    // allows being more explicit about why should_run in Step returns the value passed to it
722    pub fn never(mut self) -> ShouldRun<'a> {
723        self.paths.insert(PathSet::empty());
724        self
725    }
726
727    /// Given a set of requested paths, return the subset which match the Step for this `ShouldRun`,
728    /// removing the matches from `paths`.
729    ///
730    /// NOTE: this returns multiple PathSets to allow for the possibility of multiple units of work
731    /// within the same step. For example, `test::Crate` allows testing multiple crates in the same
732    /// cargo invocation, which are put into separate sets because they aren't aliases.
733    ///
734    /// The reason we return PathSet instead of PathBuf is to allow for aliases that mean the same thing
735    /// (for now, just `all_krates` and `paths`, but we may want to add an `aliases` function in the future?)
736    fn pathset_for_paths_removing_matches(
737        &self,
738        paths: &mut [CLIStepPath],
739        kind: Kind,
740    ) -> Vec<PathSet> {
741        let mut sets = vec![];
742        for pathset in &self.paths {
743            let subset = pathset.intersection_removing_matches(paths, kind);
744            if subset != PathSet::empty() {
745                sets.push(subset);
746            }
747        }
748        sets
749    }
750}
751
752#[derive(Debug, Copy, Clone, Eq, Hash, PartialEq, PartialOrd, Ord, ValueEnum)]
753pub enum Kind {
754    #[value(alias = "b")]
755    Build,
756    #[value(alias = "c")]
757    Check,
758    Clippy,
759    Fix,
760    Format,
761    #[value(alias = "t")]
762    Test,
763    Miri,
764    MiriSetup,
765    MiriTest,
766    Bench,
767    #[value(alias = "d")]
768    Doc,
769    Clean,
770    Dist,
771    Install,
772    #[value(alias = "r")]
773    Run,
774    Setup,
775    Suggest,
776    Vendor,
777    Perf,
778}
779
780impl Kind {
781    pub fn as_str(&self) -> &'static str {
782        match self {
783            Kind::Build => "build",
784            Kind::Check => "check",
785            Kind::Clippy => "clippy",
786            Kind::Fix => "fix",
787            Kind::Format => "fmt",
788            Kind::Test => "test",
789            Kind::Miri => "miri",
790            Kind::MiriSetup => panic!("`as_str` is not supported for `Kind::MiriSetup`."),
791            Kind::MiriTest => panic!("`as_str` is not supported for `Kind::MiriTest`."),
792            Kind::Bench => "bench",
793            Kind::Doc => "doc",
794            Kind::Clean => "clean",
795            Kind::Dist => "dist",
796            Kind::Install => "install",
797            Kind::Run => "run",
798            Kind::Setup => "setup",
799            Kind::Suggest => "suggest",
800            Kind::Vendor => "vendor",
801            Kind::Perf => "perf",
802        }
803    }
804
805    pub fn description(&self) -> String {
806        match self {
807            Kind::Test => "Testing",
808            Kind::Bench => "Benchmarking",
809            Kind::Doc => "Documenting",
810            Kind::Run => "Running",
811            Kind::Suggest => "Suggesting",
812            Kind::Clippy => "Linting",
813            Kind::Perf => "Profiling & benchmarking",
814            _ => {
815                let title_letter = self.as_str()[0..1].to_ascii_uppercase();
816                return format!("{title_letter}{}ing", &self.as_str()[1..]);
817            }
818        }
819        .to_owned()
820    }
821}
822
823#[derive(Debug, Clone, Hash, PartialEq, Eq)]
824struct Libdir {
825    compiler: Compiler,
826    target: TargetSelection,
827}
828
829impl Step for Libdir {
830    type Output = PathBuf;
831
832    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
833        run.never()
834    }
835
836    fn run(self, builder: &Builder<'_>) -> PathBuf {
837        let relative_sysroot_libdir = builder.sysroot_libdir_relative(self.compiler);
838        let sysroot = builder.sysroot(self.compiler).join(relative_sysroot_libdir).join("rustlib");
839
840        if !builder.config.dry_run() {
841            // Avoid deleting the `rustlib/` directory we just copied (in `impl Step for
842            // Sysroot`).
843            if !builder.download_rustc() {
844                let sysroot_target_libdir = sysroot.join(self.target).join("lib");
845                builder.verbose(|| {
846                    eprintln!(
847                        "Removing sysroot {} to avoid caching bugs",
848                        sysroot_target_libdir.display()
849                    )
850                });
851                let _ = fs::remove_dir_all(&sysroot_target_libdir);
852                t!(fs::create_dir_all(&sysroot_target_libdir));
853            }
854
855            if self.compiler.stage == 0 {
856                // The stage 0 compiler for the build triple is always pre-built. Ensure that
857                // `libLLVM.so` ends up in the target libdir, so that ui-fulldeps tests can use
858                // it when run.
859                dist::maybe_install_llvm_target(
860                    builder,
861                    self.compiler.host,
862                    &builder.sysroot(self.compiler),
863                );
864            }
865        }
866
867        sysroot
868    }
869}
870
871impl<'a> Builder<'a> {
872    fn get_step_descriptions(kind: Kind) -> Vec<StepDescription> {
873        macro_rules! describe {
874            ($($rule:ty),+ $(,)?) => {{
875                vec![$(StepDescription::from::<$rule>(kind)),+]
876            }};
877        }
878        match kind {
879            Kind::Build => describe!(
880                compile::Std,
881                compile::Rustc,
882                compile::Assemble,
883                compile::CodegenBackend,
884                compile::StartupObjects,
885                tool::BuildManifest,
886                tool::Rustbook,
887                tool::ErrorIndex,
888                tool::UnstableBookGen,
889                tool::Tidy,
890                tool::Linkchecker,
891                tool::CargoTest,
892                tool::Compiletest,
893                tool::RemoteTestServer,
894                tool::RemoteTestClient,
895                tool::RustInstaller,
896                tool::Cargo,
897                tool::RustAnalyzer,
898                tool::RustAnalyzerProcMacroSrv,
899                tool::Rustdoc,
900                tool::Clippy,
901                tool::CargoClippy,
902                llvm::Llvm,
903                gcc::Gcc,
904                llvm::Sanitizers,
905                tool::Rustfmt,
906                tool::Cargofmt,
907                tool::Miri,
908                tool::CargoMiri,
909                llvm::Lld,
910                llvm::Enzyme,
911                llvm::CrtBeginEnd,
912                tool::RustdocGUITest,
913                tool::OptimizedDist,
914                tool::CoverageDump,
915                tool::LlvmBitcodeLinker,
916                tool::RustcPerf,
917            ),
918            Kind::Clippy => describe!(
919                clippy::Std,
920                clippy::Rustc,
921                clippy::Bootstrap,
922                clippy::BuildHelper,
923                clippy::BuildManifest,
924                clippy::CargoMiri,
925                clippy::Clippy,
926                clippy::CodegenGcc,
927                clippy::CollectLicenseMetadata,
928                clippy::Compiletest,
929                clippy::CoverageDump,
930                clippy::Jsondocck,
931                clippy::Jsondoclint,
932                clippy::LintDocs,
933                clippy::LlvmBitcodeLinker,
934                clippy::Miri,
935                clippy::MiroptTestTools,
936                clippy::OptDist,
937                clippy::RemoteTestClient,
938                clippy::RemoteTestServer,
939                clippy::RustAnalyzer,
940                clippy::Rustdoc,
941                clippy::Rustfmt,
942                clippy::RustInstaller,
943                clippy::TestFloatParse,
944                clippy::Tidy,
945                clippy::CI,
946            ),
947            Kind::Check | Kind::Fix => describe!(
948                check::Rustc,
949                check::Rustdoc,
950                check::CodegenBackend,
951                check::Clippy,
952                check::Miri,
953                check::CargoMiri,
954                check::MiroptTestTools,
955                check::Rustfmt,
956                check::RustAnalyzer,
957                check::TestFloatParse,
958                check::Bootstrap,
959                check::RunMakeSupport,
960                check::Compiletest,
961                check::FeaturesStatusDump,
962                check::CoverageDump,
963                // This has special staging logic, it may run on stage 1 while others run on stage 0.
964                // It takes quite some time to build stage 1, so put this at the end.
965                //
966                // FIXME: This also helps bootstrap to not interfere with stage 0 builds. We should probably fix
967                // that issue somewhere else, but we still want to keep `check::Std` at the end so that the
968                // quicker steps run before this.
969                check::Std,
970            ),
971            Kind::Test => describe!(
972                crate::core::build_steps::toolstate::ToolStateCheck,
973                test::Tidy,
974                test::Ui,
975                test::Crashes,
976                test::Coverage,
977                test::MirOpt,
978                test::Codegen,
979                test::CodegenUnits,
980                test::Assembly,
981                test::Incremental,
982                test::Debuginfo,
983                test::UiFullDeps,
984                test::Rustdoc,
985                test::CoverageRunRustdoc,
986                test::Pretty,
987                test::CodegenCranelift,
988                test::CodegenGCC,
989                test::Crate,
990                test::CrateLibrustc,
991                test::CrateRustdoc,
992                test::CrateRustdocJsonTypes,
993                test::CrateBootstrap,
994                test::Linkcheck,
995                test::TierCheck,
996                test::Cargotest,
997                test::Cargo,
998                test::RustAnalyzer,
999                test::ErrorIndex,
1000                test::Distcheck,
1001                test::Nomicon,
1002                test::Reference,
1003                test::RustdocBook,
1004                test::RustByExample,
1005                test::TheBook,
1006                test::UnstableBook,
1007                test::RustcBook,
1008                test::LintDocs,
1009                test::EmbeddedBook,
1010                test::EditionGuide,
1011                test::Rustfmt,
1012                test::Miri,
1013                test::CargoMiri,
1014                test::Clippy,
1015                test::CompiletestTest,
1016                test::CrateRunMakeSupport,
1017                test::CrateBuildHelper,
1018                test::RustdocJSStd,
1019                test::RustdocJSNotStd,
1020                test::RustdocGUI,
1021                test::RustdocTheme,
1022                test::RustdocUi,
1023                test::RustdocJson,
1024                test::HtmlCheck,
1025                test::RustInstaller,
1026                test::TestFloatParse,
1027                test::CollectLicenseMetadata,
1028                // Run bootstrap close to the end as it's unlikely to fail
1029                test::Bootstrap,
1030                // Run run-make last, since these won't pass without make on Windows
1031                test::RunMake,
1032            ),
1033            Kind::Miri => describe!(test::Crate),
1034            Kind::Bench => describe!(test::Crate, test::CrateLibrustc),
1035            Kind::Doc => describe!(
1036                doc::UnstableBook,
1037                doc::UnstableBookGen,
1038                doc::TheBook,
1039                doc::Standalone,
1040                doc::Std,
1041                doc::Rustc,
1042                doc::Rustdoc,
1043                doc::Rustfmt,
1044                doc::ErrorIndex,
1045                doc::Nomicon,
1046                doc::Reference,
1047                doc::RustdocBook,
1048                doc::RustByExample,
1049                doc::RustcBook,
1050                doc::Cargo,
1051                doc::CargoBook,
1052                doc::Clippy,
1053                doc::ClippyBook,
1054                doc::Miri,
1055                doc::EmbeddedBook,
1056                doc::EditionGuide,
1057                doc::StyleGuide,
1058                doc::Tidy,
1059                doc::Bootstrap,
1060                doc::Releases,
1061                doc::RunMakeSupport,
1062                doc::BuildHelper,
1063                doc::Compiletest,
1064            ),
1065            Kind::Dist => describe!(
1066                dist::Docs,
1067                dist::RustcDocs,
1068                dist::JsonDocs,
1069                dist::Mingw,
1070                dist::Rustc,
1071                dist::CodegenBackend,
1072                dist::Std,
1073                dist::RustcDev,
1074                dist::Analysis,
1075                dist::Src,
1076                dist::Cargo,
1077                dist::RustAnalyzer,
1078                dist::Rustfmt,
1079                dist::Clippy,
1080                dist::Miri,
1081                dist::LlvmTools,
1082                dist::LlvmBitcodeLinker,
1083                dist::RustDev,
1084                dist::Bootstrap,
1085                dist::Extended,
1086                // It seems that PlainSourceTarball somehow changes how some of the tools
1087                // perceive their dependencies (see #93033) which would invalidate fingerprints
1088                // and force us to rebuild tools after vendoring dependencies.
1089                // To work around this, create the Tarball after building all the tools.
1090                dist::PlainSourceTarball,
1091                dist::BuildManifest,
1092                dist::ReproducibleArtifacts,
1093                dist::Gcc
1094            ),
1095            Kind::Install => describe!(
1096                install::Docs,
1097                install::Std,
1098                // During the Rust compiler (rustc) installation process, we copy the entire sysroot binary
1099                // path (build/host/stage2/bin). Since the building tools also make their copy in the sysroot
1100                // binary path, we must install rustc before the tools. Otherwise, the rust-installer will
1101                // install the same binaries twice for each tool, leaving backup files (*.old) as a result.
1102                install::Rustc,
1103                install::Cargo,
1104                install::RustAnalyzer,
1105                install::Rustfmt,
1106                install::Clippy,
1107                install::Miri,
1108                install::LlvmTools,
1109                install::Src,
1110            ),
1111            Kind::Run => describe!(
1112                run::BuildManifest,
1113                run::BumpStage0,
1114                run::ReplaceVersionPlaceholder,
1115                run::Miri,
1116                run::CollectLicenseMetadata,
1117                run::GenerateCopyright,
1118                run::GenerateWindowsSys,
1119                run::GenerateCompletions,
1120                run::UnicodeTableGenerator,
1121                run::FeaturesStatusDump,
1122                run::CyclicStep,
1123                run::CoverageDump,
1124                run::Rustfmt,
1125            ),
1126            Kind::Setup => {
1127                describe!(setup::Profile, setup::Hook, setup::Link, setup::Editor)
1128            }
1129            Kind::Clean => describe!(clean::CleanAll, clean::Rustc, clean::Std),
1130            Kind::Vendor => describe!(vendor::Vendor),
1131            // special-cased in Build::build()
1132            Kind::Format | Kind::Suggest | Kind::Perf => vec![],
1133            Kind::MiriTest | Kind::MiriSetup => unreachable!(),
1134        }
1135    }
1136
1137    pub fn get_help(build: &Build, kind: Kind) -> Option<String> {
1138        let step_descriptions = Builder::get_step_descriptions(kind);
1139        if step_descriptions.is_empty() {
1140            return None;
1141        }
1142
1143        let builder = Self::new_internal(build, kind, vec![]);
1144        let builder = &builder;
1145        // The "build" kind here is just a placeholder, it will be replaced with something else in
1146        // the following statement.
1147        let mut should_run = ShouldRun::new(builder, Kind::Build);
1148        for desc in step_descriptions {
1149            should_run.kind = desc.kind;
1150            should_run = (desc.should_run)(should_run);
1151        }
1152        let mut help = String::from("Available paths:\n");
1153        let mut add_path = |path: &Path| {
1154            t!(write!(help, "    ./x.py {} {}\n", kind.as_str(), path.display()));
1155        };
1156        for pathset in should_run.paths {
1157            match pathset {
1158                PathSet::Set(set) => {
1159                    for path in set {
1160                        add_path(&path.path);
1161                    }
1162                }
1163                PathSet::Suite(path) => {
1164                    add_path(&path.path.join("..."));
1165                }
1166            }
1167        }
1168        Some(help)
1169    }
1170
1171    fn new_internal(build: &Build, kind: Kind, paths: Vec<PathBuf>) -> Builder<'_> {
1172        Builder {
1173            build,
1174            top_stage: build.config.stage,
1175            kind,
1176            cache: Cache::new(),
1177            stack: RefCell::new(Vec::new()),
1178            time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
1179            paths,
1180        }
1181    }
1182
1183    pub fn new(build: &Build) -> Builder<'_> {
1184        let paths = &build.config.paths;
1185        let (kind, paths) = match build.config.cmd {
1186            Subcommand::Build => (Kind::Build, &paths[..]),
1187            Subcommand::Check { .. } => (Kind::Check, &paths[..]),
1188            Subcommand::Clippy { .. } => (Kind::Clippy, &paths[..]),
1189            Subcommand::Fix => (Kind::Fix, &paths[..]),
1190            Subcommand::Doc { .. } => (Kind::Doc, &paths[..]),
1191            Subcommand::Test { .. } => (Kind::Test, &paths[..]),
1192            Subcommand::Miri { .. } => (Kind::Miri, &paths[..]),
1193            Subcommand::Bench { .. } => (Kind::Bench, &paths[..]),
1194            Subcommand::Dist => (Kind::Dist, &paths[..]),
1195            Subcommand::Install => (Kind::Install, &paths[..]),
1196            Subcommand::Run { .. } => (Kind::Run, &paths[..]),
1197            Subcommand::Clean { .. } => (Kind::Clean, &paths[..]),
1198            Subcommand::Format { .. } => (Kind::Format, &[][..]),
1199            Subcommand::Suggest { .. } => (Kind::Suggest, &[][..]),
1200            Subcommand::Setup { profile: ref path } => (
1201                Kind::Setup,
1202                path.as_ref().map_or([].as_slice(), |path| std::slice::from_ref(path)),
1203            ),
1204            Subcommand::Vendor { .. } => (Kind::Vendor, &paths[..]),
1205            Subcommand::Perf { .. } => (Kind::Perf, &paths[..]),
1206        };
1207
1208        Self::new_internal(build, kind, paths.to_owned())
1209    }
1210
1211    pub fn execute_cli(&self) {
1212        self.run_step_descriptions(&Builder::get_step_descriptions(self.kind), &self.paths);
1213    }
1214
1215    pub fn default_doc(&self, paths: &[PathBuf]) {
1216        self.run_step_descriptions(&Builder::get_step_descriptions(Kind::Doc), paths);
1217    }
1218
1219    pub fn doc_rust_lang_org_channel(&self) -> String {
1220        let channel = match &*self.config.channel {
1221            "stable" => &self.version,
1222            "beta" => "beta",
1223            "nightly" | "dev" => "nightly",
1224            // custom build of rustdoc maybe? link to the latest stable docs just in case
1225            _ => "stable",
1226        };
1227
1228        format!("https://doc.rust-lang.org/{channel}")
1229    }
1230
1231    fn run_step_descriptions(&self, v: &[StepDescription], paths: &[PathBuf]) {
1232        StepDescription::run(v, self, paths);
1233    }
1234
1235    /// Returns if `std` should be statically linked into `rustc_driver`.
1236    /// It's currently not done on `windows-gnu` due to linker bugs.
1237    pub fn link_std_into_rustc_driver(&self, target: TargetSelection) -> bool {
1238        !target.triple.ends_with("-windows-gnu")
1239    }
1240
1241    /// Obtain a compiler at a given stage and for a given host (i.e., this is the target that the
1242    /// compiler will run on, *not* the target it will build code for). Explicitly does not take
1243    /// `Compiler` since all `Compiler` instances are meant to be obtained through this function,
1244    /// since it ensures that they are valid (i.e., built and assembled).
1245    #[cfg_attr(
1246        feature = "tracing",
1247        instrument(
1248            level = "trace",
1249            name = "Builder::compiler",
1250            target = "COMPILER",
1251            skip_all,
1252            fields(
1253                stage = stage,
1254                host = ?host,
1255            ),
1256        ),
1257    )]
1258    pub fn compiler(&self, stage: u32, host: TargetSelection) -> Compiler {
1259        self.ensure(compile::Assemble { target_compiler: Compiler::new(stage, host) })
1260    }
1261
1262    /// Similar to `compiler`, except handles the full-bootstrap option to
1263    /// silently use the stage1 compiler instead of a stage2 compiler if one is
1264    /// requested.
1265    ///
1266    /// Note that this does *not* have the side effect of creating
1267    /// `compiler(stage, host)`, unlike `compiler` above which does have such
1268    /// a side effect. The returned compiler here can only be used to compile
1269    /// new artifacts, it can't be used to rely on the presence of a particular
1270    /// sysroot.
1271    ///
1272    /// See `force_use_stage1` and `force_use_stage2` for documentation on what each argument is.
1273    #[cfg_attr(
1274        feature = "tracing",
1275        instrument(
1276            level = "trace",
1277            name = "Builder::compiler_for",
1278            target = "COMPILER_FOR",
1279            skip_all,
1280            fields(
1281                stage = stage,
1282                host = ?host,
1283                target = ?target,
1284            ),
1285        ),
1286    )]
1287    /// FIXME: This function is unnecessary (and dangerous, see <https://github.com/rust-lang/rust/issues/137469>).
1288    /// We already have uplifting logic for the compiler, so remove this.
1289    pub fn compiler_for(
1290        &self,
1291        stage: u32,
1292        host: TargetSelection,
1293        target: TargetSelection,
1294    ) -> Compiler {
1295        let mut resolved_compiler = if self.build.force_use_stage2(stage) {
1296            trace!(target: "COMPILER_FOR", ?stage, "force_use_stage2");
1297            self.compiler(2, self.config.build)
1298        } else if self.build.force_use_stage1(stage, target) {
1299            trace!(target: "COMPILER_FOR", ?stage, "force_use_stage1");
1300            self.compiler(1, self.config.build)
1301        } else {
1302            trace!(target: "COMPILER_FOR", ?stage, ?host, "no force, fallback to `compiler()`");
1303            self.compiler(stage, host)
1304        };
1305
1306        if stage != resolved_compiler.stage {
1307            resolved_compiler.forced_compiler(true);
1308        }
1309
1310        trace!(target: "COMPILER_FOR", ?resolved_compiler);
1311        resolved_compiler
1312    }
1313
1314    pub fn sysroot(&self, compiler: Compiler) -> PathBuf {
1315        self.ensure(compile::Sysroot::new(compiler))
1316    }
1317
1318    /// Returns the bindir for a compiler's sysroot.
1319    pub fn sysroot_target_bindir(&self, compiler: Compiler, target: TargetSelection) -> PathBuf {
1320        self.ensure(Libdir { compiler, target }).join(target).join("bin")
1321    }
1322
1323    /// Returns the libdir where the standard library and other artifacts are
1324    /// found for a compiler's sysroot.
1325    pub fn sysroot_target_libdir(&self, compiler: Compiler, target: TargetSelection) -> PathBuf {
1326        self.ensure(Libdir { compiler, target }).join(target).join("lib")
1327    }
1328
1329    pub fn sysroot_codegen_backends(&self, compiler: Compiler) -> PathBuf {
1330        self.sysroot_target_libdir(compiler, compiler.host).with_file_name("codegen-backends")
1331    }
1332
1333    /// Returns the compiler's libdir where it stores the dynamic libraries that
1334    /// it itself links against.
1335    ///
1336    /// For example this returns `<sysroot>/lib` on Unix and `<sysroot>/bin` on
1337    /// Windows.
1338    pub fn rustc_libdir(&self, compiler: Compiler) -> PathBuf {
1339        if compiler.is_snapshot(self) {
1340            self.rustc_snapshot_libdir()
1341        } else {
1342            match self.config.libdir_relative() {
1343                Some(relative_libdir) if compiler.stage >= 1 => {
1344                    self.sysroot(compiler).join(relative_libdir)
1345                }
1346                _ => self.sysroot(compiler).join(libdir(compiler.host)),
1347            }
1348        }
1349    }
1350
1351    /// Returns the compiler's relative libdir where it stores the dynamic libraries that
1352    /// it itself links against.
1353    ///
1354    /// For example this returns `lib` on Unix and `bin` on
1355    /// Windows.
1356    pub fn libdir_relative(&self, compiler: Compiler) -> &Path {
1357        if compiler.is_snapshot(self) {
1358            libdir(self.config.build).as_ref()
1359        } else {
1360            match self.config.libdir_relative() {
1361                Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
1362                _ => libdir(compiler.host).as_ref(),
1363            }
1364        }
1365    }
1366
1367    /// Returns the compiler's relative libdir where the standard library and other artifacts are
1368    /// found for a compiler's sysroot.
1369    ///
1370    /// For example this returns `lib` on Unix and Windows.
1371    pub fn sysroot_libdir_relative(&self, compiler: Compiler) -> &Path {
1372        match self.config.libdir_relative() {
1373            Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
1374            _ if compiler.stage == 0 => &self.build.initial_relative_libdir,
1375            _ => Path::new("lib"),
1376        }
1377    }
1378
1379    pub fn rustc_lib_paths(&self, compiler: Compiler) -> Vec<PathBuf> {
1380        let mut dylib_dirs = vec![self.rustc_libdir(compiler)];
1381
1382        // Ensure that the downloaded LLVM libraries can be found.
1383        if self.config.llvm_from_ci {
1384            let ci_llvm_lib = self.out.join(compiler.host).join("ci-llvm").join("lib");
1385            dylib_dirs.push(ci_llvm_lib);
1386        }
1387
1388        dylib_dirs
1389    }
1390
1391    /// Adds the compiler's directory of dynamic libraries to `cmd`'s dynamic
1392    /// library lookup path.
1393    pub fn add_rustc_lib_path(&self, compiler: Compiler, cmd: &mut BootstrapCommand) {
1394        // Windows doesn't need dylib path munging because the dlls for the
1395        // compiler live next to the compiler and the system will find them
1396        // automatically.
1397        if cfg!(any(windows, target_os = "cygwin")) {
1398            return;
1399        }
1400
1401        add_dylib_path(self.rustc_lib_paths(compiler), cmd);
1402    }
1403
1404    /// Gets a path to the compiler specified.
1405    pub fn rustc(&self, compiler: Compiler) -> PathBuf {
1406        if compiler.is_snapshot(self) {
1407            self.initial_rustc.clone()
1408        } else {
1409            self.sysroot(compiler).join("bin").join(exe("rustc", compiler.host))
1410        }
1411    }
1412
1413    /// Gets the paths to all of the compiler's codegen backends.
1414    fn codegen_backends(&self, compiler: Compiler) -> impl Iterator<Item = PathBuf> {
1415        fs::read_dir(self.sysroot_codegen_backends(compiler))
1416            .into_iter()
1417            .flatten()
1418            .filter_map(Result::ok)
1419            .map(|entry| entry.path())
1420    }
1421
1422    pub fn rustdoc(&self, compiler: Compiler) -> PathBuf {
1423        self.ensure(tool::Rustdoc { compiler }).tool_path
1424    }
1425
1426    pub fn cargo_clippy_cmd(&self, run_compiler: Compiler) -> BootstrapCommand {
1427        if run_compiler.stage == 0 {
1428            let cargo_clippy = self
1429                .config
1430                .initial_cargo_clippy
1431                .clone()
1432                .unwrap_or_else(|| self.build.config.download_clippy());
1433
1434            let mut cmd = command(cargo_clippy);
1435            cmd.env("CARGO", &self.initial_cargo);
1436            return cmd;
1437        }
1438
1439        let _ = self.ensure(tool::Clippy { compiler: run_compiler, target: self.build.build });
1440        let cargo_clippy =
1441            self.ensure(tool::CargoClippy { compiler: run_compiler, target: self.build.build });
1442        let mut dylib_path = helpers::dylib_path();
1443        dylib_path.insert(0, self.sysroot(run_compiler).join("lib"));
1444
1445        let mut cmd = command(cargo_clippy.tool_path);
1446        cmd.env(helpers::dylib_path_var(), env::join_paths(&dylib_path).unwrap());
1447        cmd.env("CARGO", &self.initial_cargo);
1448        cmd
1449    }
1450
1451    pub fn cargo_miri_cmd(&self, run_compiler: Compiler) -> BootstrapCommand {
1452        assert!(run_compiler.stage > 0, "miri can not be invoked at stage 0");
1453        // Prepare the tools
1454        let miri = self.ensure(tool::Miri { compiler: run_compiler, target: self.build.build });
1455        let cargo_miri =
1456            self.ensure(tool::CargoMiri { compiler: run_compiler, target: self.build.build });
1457        // Invoke cargo-miri, make sure it can find miri and cargo.
1458        let mut cmd = command(cargo_miri.tool_path);
1459        cmd.env("MIRI", &miri.tool_path);
1460        cmd.env("CARGO", &self.initial_cargo);
1461        // Need to add the `run_compiler` libs. Those are the libs produces *by* `build_compiler`
1462        // in `tool::ToolBuild` step, so they match the Miri we just built. However this means they
1463        // are actually living one stage up, i.e. we are running `stage0-tools-bin/miri` with the
1464        // libraries in `stage1/lib`. This is an unfortunate off-by-1 caused (possibly) by the fact
1465        // that Miri doesn't have an "assemble" step like rustc does that would cross the stage boundary.
1466        // We can't use `add_rustc_lib_path` as that's a NOP on Windows but we do need these libraries
1467        // added to the PATH due to the stage mismatch.
1468        // Also see https://github.com/rust-lang/rust/pull/123192#issuecomment-2028901503.
1469        add_dylib_path(self.rustc_lib_paths(run_compiler), &mut cmd);
1470        cmd
1471    }
1472
1473    pub fn rustdoc_cmd(&self, compiler: Compiler) -> BootstrapCommand {
1474        let mut cmd = command(self.bootstrap_out.join("rustdoc"));
1475        cmd.env("RUSTC_STAGE", compiler.stage.to_string())
1476            .env("RUSTC_SYSROOT", self.sysroot(compiler))
1477            // Note that this is *not* the sysroot_libdir because rustdoc must be linked
1478            // equivalently to rustc.
1479            .env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler))
1480            .env("CFG_RELEASE_CHANNEL", &self.config.channel)
1481            .env("RUSTDOC_REAL", self.rustdoc(compiler))
1482            .env("RUSTC_BOOTSTRAP", "1");
1483
1484        cmd.arg("-Wrustdoc::invalid_codeblock_attributes");
1485
1486        if self.config.deny_warnings {
1487            cmd.arg("-Dwarnings");
1488        }
1489        cmd.arg("-Znormalize-docs");
1490        cmd.args(linker_args(self, compiler.host, LldThreads::Yes));
1491        cmd
1492    }
1493
1494    /// Return the path to `llvm-config` for the target, if it exists.
1495    ///
1496    /// Note that this returns `None` if LLVM is disabled, or if we're in a
1497    /// check build or dry-run, where there's no need to build all of LLVM.
1498    pub fn llvm_config(&self, target: TargetSelection) -> Option<PathBuf> {
1499        if self.config.llvm_enabled(target) && self.kind != Kind::Check && !self.config.dry_run() {
1500            let llvm::LlvmResult { llvm_config, .. } = self.ensure(llvm::Llvm { target });
1501            if llvm_config.is_file() {
1502                return Some(llvm_config);
1503            }
1504        }
1505        None
1506    }
1507
1508    /// Ensure that a given step is built, returning its output. This will
1509    /// cache the step, so it is safe (and good!) to call this as often as
1510    /// needed to ensure that all dependencies are built.
1511    pub fn ensure<S: Step>(&'a self, step: S) -> S::Output {
1512        {
1513            let mut stack = self.stack.borrow_mut();
1514            for stack_step in stack.iter() {
1515                // should skip
1516                if stack_step.downcast_ref::<S>().is_none_or(|stack_step| *stack_step != step) {
1517                    continue;
1518                }
1519                let mut out = String::new();
1520                out += &format!("\n\nCycle in build detected when adding {step:?}\n");
1521                for el in stack.iter().rev() {
1522                    out += &format!("\t{el:?}\n");
1523                }
1524                panic!("{}", out);
1525            }
1526            if let Some(out) = self.cache.get(&step) {
1527                self.verbose_than(1, || println!("{}c {:?}", "  ".repeat(stack.len()), step));
1528
1529                return out;
1530            }
1531            self.verbose_than(1, || println!("{}> {:?}", "  ".repeat(stack.len()), step));
1532            stack.push(Box::new(step.clone()));
1533        }
1534
1535        #[cfg(feature = "build-metrics")]
1536        self.metrics.enter_step(&step, self);
1537
1538        let (out, dur) = {
1539            let start = Instant::now();
1540            let zero = Duration::new(0, 0);
1541            let parent = self.time_spent_on_dependencies.replace(zero);
1542            let out = step.clone().run(self);
1543            let dur = start.elapsed();
1544            let deps = self.time_spent_on_dependencies.replace(parent + dur);
1545            (out, dur.saturating_sub(deps))
1546        };
1547
1548        if self.config.print_step_timings && !self.config.dry_run() {
1549            let step_string = format!("{step:?}");
1550            let brace_index = step_string.find('{').unwrap_or(0);
1551            let type_string = type_name::<S>();
1552            println!(
1553                "[TIMING] {} {} -- {}.{:03}",
1554                &type_string.strip_prefix("bootstrap::").unwrap_or(type_string),
1555                &step_string[brace_index..],
1556                dur.as_secs(),
1557                dur.subsec_millis()
1558            );
1559        }
1560
1561        #[cfg(feature = "build-metrics")]
1562        self.metrics.exit_step(self);
1563
1564        {
1565            let mut stack = self.stack.borrow_mut();
1566            let cur_step = stack.pop().expect("step stack empty");
1567            assert_eq!(cur_step.downcast_ref(), Some(&step));
1568        }
1569        self.verbose_than(1, || println!("{}< {:?}", "  ".repeat(self.stack.borrow().len()), step));
1570        self.cache.put(step, out.clone());
1571        out
1572    }
1573
1574    /// Ensure that a given step is built *only if it's supposed to be built by default*, returning
1575    /// its output. This will cache the step, so it's safe (and good!) to call this as often as
1576    /// needed to ensure that all dependencies are build.
1577    pub(crate) fn ensure_if_default<T, S: Step<Output = Option<T>>>(
1578        &'a self,
1579        step: S,
1580        kind: Kind,
1581    ) -> S::Output {
1582        let desc = StepDescription::from::<S>(kind);
1583        let should_run = (desc.should_run)(ShouldRun::new(self, desc.kind));
1584
1585        // Avoid running steps contained in --skip
1586        for pathset in &should_run.paths {
1587            if desc.is_excluded(self, pathset) {
1588                return None;
1589            }
1590        }
1591
1592        // Only execute if it's supposed to run as default
1593        if desc.default && should_run.is_really_default() { self.ensure(step) } else { None }
1594    }
1595
1596    /// Checks if any of the "should_run" paths is in the `Builder` paths.
1597    pub(crate) fn was_invoked_explicitly<S: Step>(&'a self, kind: Kind) -> bool {
1598        let desc = StepDescription::from::<S>(kind);
1599        let should_run = (desc.should_run)(ShouldRun::new(self, desc.kind));
1600
1601        for path in &self.paths {
1602            if should_run.paths.iter().any(|s| s.has(path, desc.kind))
1603                && !desc.is_excluded(
1604                    self,
1605                    &PathSet::Suite(TaskPath { path: path.clone(), kind: Some(desc.kind) }),
1606                )
1607            {
1608                return true;
1609            }
1610        }
1611
1612        false
1613    }
1614
1615    pub(crate) fn maybe_open_in_browser<S: Step>(&self, path: impl AsRef<Path>) {
1616        if self.was_invoked_explicitly::<S>(Kind::Doc) {
1617            self.open_in_browser(path);
1618        } else {
1619            self.info(&format!("Doc path: {}", path.as_ref().display()));
1620        }
1621    }
1622
1623    pub(crate) fn open_in_browser(&self, path: impl AsRef<Path>) {
1624        let path = path.as_ref();
1625
1626        if self.config.dry_run() || !self.config.cmd.open() {
1627            self.info(&format!("Doc path: {}", path.display()));
1628            return;
1629        }
1630
1631        self.info(&format!("Opening doc {}", path.display()));
1632        if let Err(err) = opener::open(path) {
1633            self.info(&format!("{err}\n"));
1634        }
1635    }
1636}