Skip to main content

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