bootstrap/core/builder/
mod.rs

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