bootstrap/core/builder/
mod.rs

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