Skip to main content

bootstrap/core/build_steps/
tool.rs

1//! This module handles building and managing various tools in bootstrap
2//! build system.
3//!
4//! **What It Does**
5//! - Defines how tools are built, configured and installed.
6//! - Manages tool dependencies and build steps.
7//! - Copies built tool binaries to the correct locations.
8//!
9//! Each Rust tool **MUST** utilize `ToolBuild` inside their `Step` logic,
10//! return `ToolBuildResult` and should never prepare `cargo` invocations manually.
11
12use std::ffi::OsStr;
13use std::path::{Path, PathBuf};
14use std::{env, fs};
15
16use crate::core::build_steps::compile::is_lto_stage;
17use crate::core::build_steps::toolstate::ToolState;
18use crate::core::build_steps::{compile, llvm};
19use crate::core::builder;
20use crate::core::builder::{
21    Builder, Cargo as CargoCommand, RunConfig, ShouldRun, Step, StepMetadata, apply_pgo,
22    cargo_profile_var,
23};
24use crate::core::config::{DebuginfoLevel, RustcLto, TargetSelection};
25use crate::utils::exec::{BootstrapCommand, command};
26use crate::utils::helpers::{add_dylib_path, exe, t};
27use crate::{Compiler, FileType, Kind, Mode};
28
29#[derive(Debug, Clone, Hash, PartialEq, Eq)]
30pub enum SourceType {
31    InTree,
32    Submodule,
33}
34
35#[derive(Debug, Clone, Hash, PartialEq, Eq)]
36pub enum ToolArtifactKind {
37    Binary,
38    Library,
39}
40
41#[derive(Debug, Clone, Hash, PartialEq, Eq)]
42struct ToolBuild {
43    /// Compiler that will build this tool.
44    build_compiler: Compiler,
45    target: TargetSelection,
46    tool: &'static str,
47    path: &'static str,
48    mode: Mode,
49    source_type: SourceType,
50    extra_features: Vec<String>,
51    /// Nightly-only features that are allowed (comma-separated list).
52    allow_features: &'static str,
53    /// Additional arguments to pass to the `cargo` invocation.
54    cargo_args: Vec<String>,
55    /// Whether the tool builds a binary or a library.
56    artifact_kind: ToolArtifactKind,
57}
58
59/// Result of the tool build process. Each `Step` in this module is responsible
60/// for using this type as `type Output = ToolBuildResult;`
61#[derive(Clone)]
62pub struct ToolBuildResult {
63    /// Artifact path of the corresponding tool that was built.
64    pub tool_path: PathBuf,
65    /// Compiler used to build the tool.
66    pub build_compiler: Compiler,
67}
68
69impl Step for ToolBuild {
70    type Output = ToolBuildResult;
71
72    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
73        run.never()
74    }
75
76    /// Builds a tool in `src/tools`
77    ///
78    /// This will build the specified tool with the specified `host` compiler in
79    /// `stage` into the normal cargo output directory.
80    fn run(self, builder: &Builder<'_>) -> ToolBuildResult {
81        let target = self.target;
82        let mut tool = self.tool;
83        let path = self.path;
84
85        match self.mode {
86            Mode::ToolRustcPrivate => {
87                // FIXME: remove this, it's only needed for download-rustc...
88                if !self.build_compiler.is_forced_compiler() && builder.download_rustc() {
89                    builder.std(self.build_compiler, self.build_compiler.host);
90                    builder.ensure(compile::Rustc::new(self.build_compiler, target));
91                }
92            }
93            Mode::ToolStd => {
94                // If compiler was forced, its artifacts should have been prepared earlier.
95                if !self.build_compiler.is_forced_compiler() {
96                    builder.std(self.build_compiler, target);
97                }
98            }
99            Mode::ToolBootstrap | Mode::ToolTarget => {} // uses downloaded stage0 compiler libs
100            _ => panic!("unexpected Mode for tool build"),
101        }
102
103        let mut cargo = prepare_tool_cargo(
104            builder,
105            self.build_compiler,
106            self.mode,
107            target,
108            Kind::Build,
109            path,
110            self.source_type,
111            &self.extra_features,
112        );
113
114        // The stage0 compiler changes infrequently and does not directly depend on code
115        // in the current working directory. Therefore, caching it with sccache should be
116        // useful.
117        // This is only performed for non-incremental builds, as ccache cannot deal with these.
118        if let Some(ref ccache) = builder.config.ccache
119            && matches!(self.mode, Mode::ToolBootstrap)
120            && !builder.config.incremental
121        {
122            cargo.env("RUSTC_WRAPPER", ccache);
123        }
124
125        // RustcPrivate tools (miri, clippy, rustfmt, rust-analyzer) and cargo
126        // could use the additional optimizations.
127        if is_lto_stage(&self.build_compiler)
128            && (self.mode == Mode::ToolRustcPrivate || self.path == "src/tools/cargo")
129        {
130            let lto = match builder.config.rust_lto {
131                RustcLto::Off => Some("off"),
132                RustcLto::Thin => Some("thin"),
133                RustcLto::Fat => Some("fat"),
134                RustcLto::ThinLocal => None,
135            };
136            if let Some(lto) = lto {
137                cargo.env(cargo_profile_var("LTO", &builder.config, self.mode), lto);
138            }
139        }
140
141        if self.path == "src/tools/rustdoc" {
142            apply_pgo(builder, &mut cargo, self.build_compiler, &builder.config.rustdoc_pgo);
143        }
144
145        if !self.allow_features.is_empty() {
146            cargo.allow_features(self.allow_features);
147        }
148
149        cargo.args(self.cargo_args);
150
151        let _guard =
152            builder.msg(Kind::Build, self.tool, self.mode, self.build_compiler, self.target);
153
154        // we check this below
155        let build_success = compile::stream_cargo(builder, cargo, vec![], &mut |_| {});
156
157        builder.save_toolstate(
158            tool,
159            if build_success { ToolState::TestFail } else { ToolState::BuildFail },
160        );
161
162        if !build_success {
163            crate::exit!(1);
164        } else {
165            // HACK(#82501): on Windows, the tools directory gets added to PATH when running tests, and
166            // compiletest confuses HTML tidy with the in-tree tidy. Name the in-tree tidy something
167            // different so the problem doesn't come up.
168            if tool == "tidy" {
169                tool = "rust-tidy";
170            }
171            let tool_path = match self.artifact_kind {
172                ToolArtifactKind::Binary => {
173                    copy_link_tool_bin(builder, self.build_compiler, self.target, self.mode, tool)
174                }
175                ToolArtifactKind::Library => builder
176                    .cargo_out(self.build_compiler, self.mode, self.target)
177                    .join(format!("lib{tool}.rlib")),
178            };
179
180            ToolBuildResult { tool_path, build_compiler: self.build_compiler }
181        }
182    }
183}
184
185#[expect(clippy::too_many_arguments)] // FIXME: reduce the number of args and remove this.
186pub fn prepare_tool_cargo(
187    builder: &Builder<'_>,
188    compiler: Compiler,
189    mode: Mode,
190    target: TargetSelection,
191    cmd_kind: Kind,
192    path: &str,
193    source_type: SourceType,
194    extra_features: &[String],
195) -> CargoCommand {
196    let mut cargo = builder::Cargo::new(builder, compiler, mode, source_type, target, cmd_kind);
197
198    let path = PathBuf::from(path);
199    let dir = builder.src.join(&path);
200    cargo.arg("--manifest-path").arg(dir.join("Cargo.toml"));
201
202    let mut features = extra_features.to_vec();
203    if builder.build.config.cargo_native_static {
204        if path.ends_with("cargo")
205            || path.ends_with("clippy")
206            || path.ends_with("miri")
207            || path.ends_with("rustfmt")
208        {
209            cargo.env("LIBZ_SYS_STATIC", "1");
210        }
211        if path.ends_with("cargo") {
212            features.push("all-static".to_string());
213        }
214    }
215
216    // build.tool.TOOL_NAME.features in bootstrap.toml allows specifying which features to enable
217    // for a specific tool. `extra_features` instead is not controlled by the toml and provides
218    // features that are always enabled for a specific tool (e.g. "in-rust-tree" for rust-analyzer).
219    // Finally, `prepare_tool_cargo` above here might add more features to adapt the build
220    // to the chosen flags (e.g. "all-static" for cargo if `cargo_native_static` is true).
221    builder
222        .config
223        .tool
224        .iter()
225        .filter(|(tool_name, _)| path.file_name().and_then(OsStr::to_str) == Some(tool_name))
226        .for_each(|(_, tool)| features.extend(tool.features.clone().unwrap_or_default()));
227
228    // clippy tests need to know about the stage sysroot. Set them consistently while building to
229    // avoid rebuilding when running tests.
230    cargo.env("SYSROOT", builder.sysroot(compiler));
231
232    // Make sure we explicitly add rustc_private libs to path centrally here so that
233    // RustcPrivate tools can pick them up.
234    if mode == Mode::ToolRustcPrivate {
235        cargo.add_rustc_lib_path(builder);
236    }
237
238    // if tools are using lzma we want to force the build script to build its
239    // own copy
240    cargo.env("LZMA_API_STATIC", "1");
241
242    // See also the "JEMALLOC_SYS_WITH_LG_PAGE" setting in the compile build step.
243    if builder.config.jemalloc(target) && env::var_os("JEMALLOC_SYS_WITH_LG_PAGE").is_none() {
244        // Build jemalloc on AArch64 with support for page sizes up to 64K
245        // See: https://github.com/rust-lang/rust/pull/135081
246        if target.starts_with("aarch64") {
247            cargo.env("JEMALLOC_SYS_WITH_LG_PAGE", "16");
248        }
249        // Build jemalloc on LoongArch with support for page sizes up to 16K
250        else if target.starts_with("loongarch") {
251            cargo.env("JEMALLOC_SYS_WITH_LG_PAGE", "14");
252        }
253    }
254
255    // CFG_RELEASE is needed by rustfmt (and possibly other tools) which
256    // import rustc-ap-rustc_attr which requires this to be set for the
257    // `#[cfg(version(...))]` attribute.
258    cargo.env("CFG_RELEASE", builder.rust_release());
259    cargo.env("CFG_RELEASE_CHANNEL", &builder.config.channel);
260    cargo.env("CFG_VERSION", builder.rust_version());
261    cargo.env("CFG_RELEASE_NUM", &builder.version);
262    cargo.env("DOC_RUST_LANG_ORG_CHANNEL", builder.doc_rust_lang_org_channel());
263
264    if let Some(ref ver_date) = builder.rust_info().commit_date() {
265        cargo.env("CFG_VER_DATE", ver_date);
266    }
267
268    if let Some(ref ver_hash) = builder.rust_info().sha() {
269        cargo.env("CFG_VER_HASH", ver_hash);
270    }
271
272    if let Some(description) = &builder.config.description {
273        cargo.env("CFG_VER_DESCRIPTION", description);
274    }
275
276    let info = builder.config.git_info(builder.config.omit_git_hash, &dir);
277    if let Some(sha) = info.sha() {
278        cargo.env("CFG_COMMIT_HASH", sha);
279    }
280
281    if let Some(sha_short) = info.sha_short() {
282        cargo.env("CFG_SHORT_COMMIT_HASH", sha_short);
283    }
284
285    if let Some(date) = info.commit_date() {
286        cargo.env("CFG_COMMIT_DATE", date);
287    }
288
289    if !features.is_empty() {
290        cargo.arg("--features").arg(features.join(", "));
291    }
292
293    // Enable internal lints for clippy and rustdoc
294    // NOTE: this doesn't enable lints for any other tools unless they explicitly add `#![warn(rustc::internal)]`
295    // See https://github.com/rust-lang/rust/pull/80573#issuecomment-754010776
296    //
297    // NOTE: We unconditionally set this here to avoid recompiling tools between `x check $tool`
298    // and `x test $tool` executions.
299    // See https://github.com/rust-lang/rust/issues/116538
300    cargo.rustflag("-Zunstable-options");
301
302    // NOTE: The root cause of needing `-Zon-broken-pipe=kill` in the first place is because `rustc`
303    // and `rustdoc` doesn't gracefully handle I/O errors due to usages of raw std `println!` macros
304    // which panics upon encountering broken pipes. `-Zon-broken-pipe=kill` just papers over that
305    // and stops rustc/rustdoc ICEing on e.g. `rustc --print=sysroot | false`.
306    //
307    // cargo explicitly does not want the `-Zon-broken-pipe=kill` paper because it does actually use
308    // variants of `println!` that handles I/O errors gracefully. It's also a breaking change for a
309    // spawn process not written in Rust, especially if the language default handler is not
310    // `SIG_IGN`. Thankfully cargo tests will break if we do set the flag.
311    //
312    // For the cargo discussion, see
313    // <https://rust-lang.zulipchat.com/#narrow/stream/246057-t-cargo/topic/Applying.20.60-Zon-broken-pipe.3Dkill.60.20flags.20in.20bootstrap.3F>.
314    //
315    // For the rustc discussion, see
316    // <https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/Internal.20lint.20for.20raw.20.60print!.60.20and.20.60println!.60.3F>
317    // for proper solutions.
318    if !path.ends_with("cargo") {
319        // Use an untracked env var `FORCE_ON_BROKEN_PIPE_KILL` here instead of `RUSTFLAGS`.
320        // `RUSTFLAGS` is tracked by cargo. Conditionally omitting `-Zon-broken-pipe=kill` from
321        // `RUSTFLAGS` causes unnecessary tool rebuilds due to cache invalidation from building e.g.
322        // cargo *without* `-Zon-broken-pipe=kill` but then rustdoc *with* `-Zon-broken-pipe=kill`.
323        cargo.env("FORCE_ON_BROKEN_PIPE_KILL", "-Zon-broken-pipe=kill");
324    }
325
326    cargo
327}
328
329/// Determines how to build a `ToolTarget`, i.e. which compiler should be used to compile it.
330/// The compiler stage is automatically bumped if we need to cross-compile a stage 1 tool.
331pub enum ToolTargetBuildMode {
332    /// Build the tool for the given `target` using rustc that corresponds to the top CLI
333    /// stage.
334    Build(TargetSelection),
335    /// Build the tool so that it can be attached to the sysroot of the passed compiler.
336    /// Since we always dist stage 2+, the compiler that builds the tool in this case has to be
337    /// stage 1+.
338    Dist(Compiler),
339}
340
341/// Returns compiler that is able to compile a `ToolTarget` tool with the given `mode`.
342pub(crate) fn get_tool_target_compiler(
343    builder: &Builder<'_>,
344    mode: ToolTargetBuildMode,
345) -> Compiler {
346    let (target, build_compiler_stage) = match mode {
347        ToolTargetBuildMode::Build(target) => {
348            assert!(builder.top_stage > 0);
349            // If we want to build a stage N tool, we need to compile it with stage N-1 rustc
350            (target, builder.top_stage - 1)
351        }
352        ToolTargetBuildMode::Dist(target_compiler) => {
353            assert!(target_compiler.stage > 0);
354            // If we want to dist a stage N rustc, we want to attach stage N tool to it.
355            // And to build that tool, we need to compile it with stage N-1 rustc
356            (target_compiler.host, target_compiler.stage - 1)
357        }
358    };
359
360    let compiler = if builder.host_target == target {
361        builder.compiler(build_compiler_stage, builder.host_target)
362    } else {
363        // If we are cross-compiling a stage 1 tool, we cannot do that with a stage 0 compiler,
364        // so we auto-bump the tool's stage to 2, which means we need a stage 1 compiler.
365        let build_compiler = builder.compiler(build_compiler_stage.max(1), builder.host_target);
366        // We also need the host stdlib to compile host code (proc macros/build scripts)
367        builder.std(build_compiler, builder.host_target);
368        build_compiler
369    };
370    builder.std(compiler, target);
371    compiler
372}
373
374/// Links a built tool binary with the given `name` from the build directory to the
375/// tools directory.
376fn copy_link_tool_bin(
377    builder: &Builder<'_>,
378    build_compiler: Compiler,
379    target: TargetSelection,
380    mode: Mode,
381    name: &str,
382) -> PathBuf {
383    let cargo_out = builder.cargo_out(build_compiler, mode, target).join(exe(name, target));
384    let bin = builder.tools_dir(build_compiler).join(exe(name, target));
385    builder.copy_link(&cargo_out, &bin, FileType::Executable);
386    bin
387}
388
389macro_rules! bootstrap_tool {
390    ($(
391        $name:ident, $path:expr, $tool_name:expr
392        $(,is_external_tool = $external:expr)*
393        $(,allow_features = $allow_features:expr)?
394        $(,submodules = $submodules:expr)?
395        $(,artifact_kind = $artifact_kind:expr)?
396        ;
397    )+) => {
398        #[derive(PartialEq, Eq, Clone)]
399        pub enum Tool {
400            $(
401                $name,
402            )+
403        }
404
405        impl<'a> Builder<'a> {
406            /// Ensure a tool is built, then get the path to its executable.
407            ///
408            /// The actual building, if any, will be handled via [`ToolBuild`].
409            pub fn tool_exe(&self, tool: Tool) -> PathBuf {
410                match tool {
411                    $(Tool::$name =>
412                        self.ensure($name {
413                            compiler: self.compiler(0, self.config.host_target),
414                            target: self.config.host_target,
415                        }).tool_path,
416                    )+
417                }
418            }
419        }
420
421        $(
422            #[derive(Debug, Clone, Hash, PartialEq, Eq)]
423        pub struct $name {
424            pub compiler: Compiler,
425            pub target: TargetSelection,
426        }
427
428        impl Step for $name {
429            type Output = ToolBuildResult;
430
431            fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
432                run.path($path)
433            }
434
435            fn make_run(run: RunConfig<'_>) {
436                run.builder.ensure($name {
437                    // snapshot compiler
438                    compiler: run.builder.compiler(0, run.builder.config.host_target),
439                    target: run.target,
440                });
441            }
442
443            fn run(self, builder: &Builder<'_>) -> ToolBuildResult {
444                $(
445                    for submodule in $submodules {
446                        builder.require_submodule(submodule, None);
447                    }
448                )*
449
450                builder.ensure(ToolBuild {
451                    build_compiler: self.compiler,
452                    target: self.target,
453                    tool: $tool_name,
454                    mode: Mode::ToolBootstrap,
455                    path: $path,
456                    source_type: if false $(|| $external)* {
457                        SourceType::Submodule
458                    } else {
459                        SourceType::InTree
460                    },
461                    extra_features: vec![],
462                    allow_features: {
463                        let mut _value = "";
464                        $( _value = $allow_features; )?
465                        _value
466                    },
467                    cargo_args: vec![],
468                    artifact_kind: if false $(|| $artifact_kind == ToolArtifactKind::Library)* {
469                        ToolArtifactKind::Library
470                    } else {
471                        ToolArtifactKind::Binary
472                    }
473                })
474            }
475
476            fn metadata(&self) -> Option<StepMetadata> {
477                Some(
478                    StepMetadata::build(stringify!($name), self.target)
479                        .built_by(self.compiler)
480                )
481            }
482        }
483        )+
484    }
485}
486
487bootstrap_tool!(
488    // This is marked as an external tool because it includes dependencies
489    // from submodules. Trying to keep the lints in sync between all the repos
490    // is a bit of a pain. Unfortunately it means the rustbook source itself
491    // doesn't deny warnings, but it is a relatively small piece of code.
492    Rustbook, "src/tools/rustbook", "rustbook", is_external_tool = true, submodules = SUBMODULES_FOR_RUSTBOOK;
493    UnstableBookGen, "src/tools/unstable-book-gen", "unstable-book-gen";
494    Tidy, "src/tools/tidy", "tidy";
495    Linkchecker, "src/tools/linkchecker", "linkchecker";
496    CargoTest, "src/tools/cargotest", "cargotest";
497    Compiletest, "src/tools/compiletest", "compiletest";
498    RemoteTestClient, "src/tools/remote-test-client", "remote-test-client";
499    RustInstaller, "src/tools/rust-installer", "rust-installer";
500    RustdocTheme, "src/tools/rustdoc-themes", "rustdoc-themes";
501    LintDocs, "src/tools/lint-docs", "lint-docs";
502    JsonDocCk, "src/tools/jsondocck", "jsondocck";
503    JsonDocLint, "src/tools/jsondoclint", "jsondoclint";
504    HtmlChecker, "src/tools/html-checker", "html-checker";
505    BumpStage0, "src/tools/bump-stage0", "bump-stage0";
506    ReplaceVersionPlaceholder, "src/tools/replace-version-placeholder", "replace-version-placeholder";
507    CollectLicenseMetadata, "src/tools/collect-license-metadata", "collect-license-metadata";
508    GenerateCopyright, "src/tools/generate-copyright", "generate-copyright";
509    GenerateWindowsSys, "src/tools/generate-windows-sys", "generate-windows-sys";
510    RustdocGUITest, "src/tools/rustdoc-gui-test", "rustdoc-gui-test";
511    CoverageDump, "src/tools/coverage-dump", "coverage-dump";
512    UnicodeTableGenerator, "src/tools/unicode-table-generator", "unicode-table-generator";
513    FeaturesStatusDump, "src/tools/features-status-dump", "features-status-dump";
514    OptimizedDist, "src/tools/opt-dist", "opt-dist", submodules = &["src/tools/rustc-perf"];
515    RunMakeSupport, "src/tools/run-make-support", "run_make_support", artifact_kind = ToolArtifactKind::Library;
516    IntrinsicTest, "library/stdarch/crates/intrinsic-test", "intrinsic-test";
517);
518
519/// These are the submodules that are required for rustbook to work due to
520/// depending on mdbook plugins.
521pub static SUBMODULES_FOR_RUSTBOOK: &[&str] = &["src/doc/book", "src/doc/reference"];
522
523/// The [rustc-perf](https://github.com/rust-lang/rustc-perf) benchmark suite, which is added
524/// as a submodule at `src/tools/rustc-perf`.
525#[derive(Debug, Clone, Hash, PartialEq, Eq)]
526pub struct RustcPerf {
527    pub compiler: Compiler,
528    pub target: TargetSelection,
529}
530
531impl Step for RustcPerf {
532    /// Path to the built `collector` binary.
533    type Output = ToolBuildResult;
534
535    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
536        run.path("src/tools/rustc-perf")
537    }
538
539    fn make_run(run: RunConfig<'_>) {
540        run.builder.ensure(RustcPerf {
541            compiler: run.builder.compiler(0, run.builder.config.host_target),
542            target: run.target,
543        });
544    }
545
546    fn run(self, builder: &Builder<'_>) -> ToolBuildResult {
547        // We need to ensure the rustc-perf submodule is initialized.
548        builder.require_submodule("src/tools/rustc-perf", None);
549
550        let tool = ToolBuild {
551            build_compiler: self.compiler,
552            target: self.target,
553            tool: "collector",
554            mode: Mode::ToolBootstrap,
555            path: "src/tools/rustc-perf",
556            source_type: SourceType::Submodule,
557            extra_features: Vec::new(),
558            allow_features: "",
559            // Only build the collector package, which is used for benchmarking through
560            // a CLI.
561            cargo_args: vec!["-p".to_string(), "collector".to_string()],
562            artifact_kind: ToolArtifactKind::Binary,
563        };
564        let res = builder.ensure(tool.clone());
565        // We also need to symlink the `rustc-fake` binary to the corresponding directory,
566        // because `collector` expects it in the same directory.
567        copy_link_tool_bin(builder, tool.build_compiler, tool.target, tool.mode, "rustc-fake");
568
569        res
570    }
571}
572
573#[derive(Debug, Clone, Hash, PartialEq, Eq)]
574pub struct ErrorIndex {
575    compilers: RustcPrivateCompilers,
576}
577
578impl ErrorIndex {
579    pub fn command(builder: &Builder<'_>, compilers: RustcPrivateCompilers) -> BootstrapCommand {
580        // Error-index-generator links with the rustdoc library, so we need to add `rustc_lib_paths`
581        // for rustc_private and libLLVM.so, and `sysroot_lib` for libstd, etc.
582        let mut cmd = command(builder.ensure(ErrorIndex { compilers }).tool_path);
583
584        let target_compiler = compilers.target_compiler();
585        let mut dylib_paths = builder.rustc_lib_paths(target_compiler);
586        dylib_paths.push(builder.sysroot_target_libdir(target_compiler, target_compiler.host));
587        add_dylib_path(dylib_paths, &mut cmd);
588        cmd
589    }
590}
591
592impl Step for ErrorIndex {
593    type Output = ToolBuildResult;
594
595    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
596        run.path("src/tools/error_index_generator")
597    }
598
599    fn make_run(run: RunConfig<'_>) {
600        // NOTE: This `make_run` isn't used in normal situations, only if you
601        // manually build the tool with `x.py build
602        // src/tools/error-index-generator` which almost nobody does.
603        // Normally, `x.py test` or `x.py doc` will use the
604        // `ErrorIndex::command` function instead.
605        run.builder.ensure(ErrorIndex {
606            compilers: RustcPrivateCompilers::new(
607                run.builder,
608                run.builder.top_stage,
609                run.builder.host_target,
610            ),
611        });
612    }
613
614    fn run(self, builder: &Builder<'_>) -> ToolBuildResult {
615        builder.require_submodule(
616            "src/doc/reference",
617            Some("error_index_generator requires mdbook-spec"),
618        );
619        builder
620            .require_submodule("src/doc/book", Some("error_index_generator requires mdbook-trpl"));
621        builder.ensure(ToolBuild {
622            build_compiler: self.compilers.build_compiler,
623            target: self.compilers.target(),
624            tool: "error_index_generator",
625            mode: Mode::ToolRustcPrivate,
626            path: "src/tools/error_index_generator",
627            source_type: SourceType::InTree,
628            extra_features: Vec::new(),
629            allow_features: "",
630            cargo_args: Vec::new(),
631            artifact_kind: ToolArtifactKind::Binary,
632        })
633    }
634
635    fn metadata(&self) -> Option<StepMetadata> {
636        Some(
637            StepMetadata::build("error-index", self.compilers.target())
638                .built_by(self.compilers.build_compiler),
639        )
640    }
641}
642
643#[derive(Debug, Clone, Hash, PartialEq, Eq)]
644pub struct RemoteTestServer {
645    pub build_compiler: Compiler,
646    pub target: TargetSelection,
647}
648
649impl Step for RemoteTestServer {
650    type Output = ToolBuildResult;
651
652    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
653        run.path("src/tools/remote-test-server")
654    }
655
656    fn make_run(run: RunConfig<'_>) {
657        run.builder.ensure(RemoteTestServer {
658            build_compiler: get_tool_target_compiler(
659                run.builder,
660                ToolTargetBuildMode::Build(run.target),
661            ),
662            target: run.target,
663        });
664    }
665
666    fn run(self, builder: &Builder<'_>) -> ToolBuildResult {
667        builder.ensure(ToolBuild {
668            build_compiler: self.build_compiler,
669            target: self.target,
670            tool: "remote-test-server",
671            mode: Mode::ToolTarget,
672            path: "src/tools/remote-test-server",
673            source_type: SourceType::InTree,
674            extra_features: Vec::new(),
675            allow_features: "",
676            cargo_args: Vec::new(),
677            artifact_kind: ToolArtifactKind::Binary,
678        })
679    }
680
681    fn metadata(&self) -> Option<StepMetadata> {
682        Some(StepMetadata::build("remote-test-server", self.target).built_by(self.build_compiler))
683    }
684}
685
686/// Represents `Rustdoc` that either comes from the external stage0 sysroot or that is built
687/// locally.
688/// Rustdoc is special, because it both essentially corresponds to a `Compiler` (that can be
689/// externally provided), but also to a `ToolRustcPrivate` tool.
690#[derive(Debug, Clone, Hash, PartialEq, Eq)]
691pub struct Rustdoc {
692    /// If the stage of `target_compiler` is `0`, then rustdoc is externally provided.
693    /// Otherwise it is built locally.
694    pub target_compiler: Compiler,
695}
696
697impl Step for Rustdoc {
698    /// Path to the built rustdoc binary.
699    type Output = PathBuf;
700
701    const IS_HOST: bool = true;
702
703    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
704        run.selectors(&["src/tools/rustdoc", "src/librustdoc"])
705    }
706
707    fn is_default_step(_builder: &Builder<'_>) -> bool {
708        true
709    }
710
711    fn make_run(run: RunConfig<'_>) {
712        run.builder.ensure(Rustdoc {
713            target_compiler: run.builder.compiler(run.builder.top_stage, run.target),
714        });
715    }
716
717    fn run(self, builder: &Builder<'_>) -> Self::Output {
718        let target_compiler = self.target_compiler;
719        let target = target_compiler.host;
720
721        // If stage is 0, we use a prebuilt rustdoc from stage0
722        if target_compiler.stage == 0 {
723            if !target_compiler.is_snapshot(builder) {
724                panic!("rustdoc in stage 0 must be snapshot rustdoc");
725            }
726
727            return builder.initial_rustdoc.clone();
728        }
729
730        // If stage is higher, we build rustdoc instead
731        let bin_rustdoc = || {
732            let sysroot = builder.sysroot(target_compiler);
733            let bindir = sysroot.join("bin");
734            t!(fs::create_dir_all(&bindir));
735            let bin_rustdoc = bindir.join(exe("rustdoc", target_compiler.host));
736            let _ = fs::remove_file(&bin_rustdoc);
737            bin_rustdoc
738        };
739
740        // If CI rustc is enabled and we haven't modified the rustdoc sources,
741        // use the precompiled rustdoc from CI rustc's sysroot to speed up bootstrapping.
742        if builder.download_rustc() && builder.rust_info().is_managed_git_subrepository() {
743            let files_to_track = &["src/librustdoc", "src/tools/rustdoc", "src/rustdoc-json-types"];
744
745            // Check if unchanged
746            if !builder.config.has_changes_from_upstream(files_to_track) {
747                let precompiled_rustdoc = builder
748                    .config
749                    .ci_rustc_dir()
750                    .join("bin")
751                    .join(exe("rustdoc", target_compiler.host));
752
753                let bin_rustdoc = bin_rustdoc();
754                builder.copy_link(&precompiled_rustdoc, &bin_rustdoc, FileType::Executable);
755                return bin_rustdoc;
756            }
757        }
758
759        // The presence of `target_compiler` ensures that the necessary libraries (codegen backends,
760        // compiler libraries, ...) are built. Rustdoc does not require the presence of any
761        // libraries within sysroot_libdir (i.e., rustlib), though doctests may want it (since
762        // they'll be linked to those libraries). As such, don't explicitly `ensure` any additional
763        // libraries here. The intuition here is that If we've built a compiler, we should be able
764        // to build rustdoc.
765        //
766        let mut extra_features = Vec::new();
767        if builder.config.jemalloc(target) {
768            extra_features.push("jemalloc".to_string());
769        }
770
771        let compilers = RustcPrivateCompilers::from_target_compiler(builder, target_compiler);
772        let tool_path = builder
773            .ensure(ToolBuild {
774                build_compiler: compilers.build_compiler,
775                target,
776                // Cargo adds a number of paths to the dylib search path on windows, which results in
777                // the wrong rustdoc being executed. To avoid the conflicting rustdocs, we name the "tool"
778                // rustdoc a different name.
779                tool: "rustdoc_tool_binary",
780                mode: Mode::ToolRustcPrivate,
781                path: "src/tools/rustdoc",
782                source_type: SourceType::InTree,
783                extra_features,
784                allow_features: "",
785                cargo_args: Vec::new(),
786                artifact_kind: ToolArtifactKind::Binary,
787            })
788            .tool_path;
789
790        if builder.config.rust_debuginfo_level_tools == DebuginfoLevel::None {
791            // Due to LTO a lot of debug info from C++ dependencies such as jemalloc can make it into
792            // our final binaries
793            compile::strip_debug(builder, target, &tool_path);
794        }
795        let bin_rustdoc = bin_rustdoc();
796        builder.copy_link(&tool_path, &bin_rustdoc, FileType::Executable);
797        bin_rustdoc
798    }
799
800    fn metadata(&self) -> Option<StepMetadata> {
801        Some(
802            StepMetadata::build("rustdoc", self.target_compiler.host)
803                .stage(self.target_compiler.stage),
804        )
805    }
806}
807
808/// Builds the cargo tool.
809/// Note that it can be built using a stable compiler.
810#[derive(Debug, Clone, Hash, PartialEq, Eq)]
811pub struct Cargo {
812    build_compiler: Compiler,
813    target: TargetSelection,
814}
815
816impl Cargo {
817    /// Returns `Cargo` that will be **compiled** by the passed compiler, for the given
818    /// `target`.
819    pub fn from_build_compiler(build_compiler: Compiler, target: TargetSelection) -> Self {
820        Self { build_compiler, target }
821    }
822}
823
824impl Step for Cargo {
825    type Output = ToolBuildResult;
826    const IS_HOST: bool = true;
827
828    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
829        run.path("src/tools/cargo")
830    }
831
832    fn is_default_step(builder: &Builder<'_>) -> bool {
833        builder.tool_enabled("cargo")
834    }
835
836    fn make_run(run: RunConfig<'_>) {
837        run.builder.ensure(Cargo {
838            build_compiler: get_tool_target_compiler(
839                run.builder,
840                ToolTargetBuildMode::Build(run.target),
841            ),
842            target: run.target,
843        });
844    }
845
846    fn run(self, builder: &Builder<'_>) -> ToolBuildResult {
847        builder.build.require_submodule("src/tools/cargo", None);
848
849        builder.std(self.build_compiler, builder.host_target);
850        builder.std(self.build_compiler, self.target);
851
852        builder.ensure(ToolBuild {
853            build_compiler: self.build_compiler,
854            target: self.target,
855            tool: "cargo",
856            mode: Mode::ToolTarget,
857            path: "src/tools/cargo",
858            source_type: SourceType::Submodule,
859            extra_features: Vec::new(),
860            // Cargo is compilable with a stable compiler, but since we run in bootstrap,
861            // with RUSTC_BOOTSTRAP being set, some "clever" build scripts enable specialization
862            // based on this, which breaks stuff. We thus have to explicitly allow these features
863            // here.
864            allow_features: "min_specialization,specialization",
865            cargo_args: Vec::new(),
866            artifact_kind: ToolArtifactKind::Binary,
867        })
868    }
869
870    fn metadata(&self) -> Option<StepMetadata> {
871        Some(StepMetadata::build("cargo", self.target).built_by(self.build_compiler))
872    }
873}
874
875/// Represents a built LldWrapper, the `lld-wrapper` tool itself, and a directory
876/// containing a build of LLD.
877#[derive(Clone)]
878pub struct BuiltLldWrapper {
879    tool: ToolBuildResult,
880    lld_dir: PathBuf,
881}
882
883#[derive(Debug, Clone, Hash, PartialEq, Eq)]
884pub struct LldWrapper {
885    pub build_compiler: Compiler,
886    pub target: TargetSelection,
887}
888
889impl LldWrapper {
890    /// Returns `LldWrapper` that should be **used** by the passed compiler.
891    pub fn for_use_by_compiler(builder: &Builder<'_>, target_compiler: Compiler) -> Self {
892        Self {
893            build_compiler: get_tool_target_compiler(
894                builder,
895                ToolTargetBuildMode::Dist(target_compiler),
896            ),
897            target: target_compiler.host,
898        }
899    }
900}
901
902impl Step for LldWrapper {
903    type Output = BuiltLldWrapper;
904
905    const IS_HOST: bool = true;
906
907    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
908        run.path("src/tools/lld-wrapper")
909    }
910
911    fn make_run(run: RunConfig<'_>) {
912        run.builder.ensure(LldWrapper {
913            build_compiler: get_tool_target_compiler(
914                run.builder,
915                ToolTargetBuildMode::Build(run.target),
916            ),
917            target: run.target,
918        });
919    }
920
921    fn run(self, builder: &Builder<'_>) -> Self::Output {
922        let lld_dir = builder.ensure(llvm::Lld { target: self.target });
923        let tool = builder.ensure(ToolBuild {
924            build_compiler: self.build_compiler,
925            target: self.target,
926            tool: "lld-wrapper",
927            mode: Mode::ToolTarget,
928            path: "src/tools/lld-wrapper",
929            source_type: SourceType::InTree,
930            extra_features: Vec::new(),
931            allow_features: "",
932            cargo_args: Vec::new(),
933            artifact_kind: ToolArtifactKind::Binary,
934        });
935        BuiltLldWrapper { tool, lld_dir }
936    }
937
938    fn metadata(&self) -> Option<StepMetadata> {
939        Some(StepMetadata::build("LldWrapper", self.target).built_by(self.build_compiler))
940    }
941}
942
943pub(crate) fn copy_lld_artifacts(
944    builder: &Builder<'_>,
945    lld_wrapper: BuiltLldWrapper,
946    target_compiler: Compiler,
947) {
948    let target = target_compiler.host;
949
950    let libdir_bin = builder.sysroot_target_bindir(target_compiler, target);
951    t!(fs::create_dir_all(&libdir_bin));
952
953    let src_exe = exe("lld", target);
954    let dst_exe = exe("rust-lld", target);
955
956    builder.copy_link(
957        &lld_wrapper.lld_dir.join("bin").join(src_exe),
958        &libdir_bin.join(dst_exe),
959        FileType::Executable,
960    );
961    let self_contained_lld_dir = libdir_bin.join("gcc-ld");
962    t!(fs::create_dir_all(&self_contained_lld_dir));
963
964    for name in crate::LLD_FILE_NAMES {
965        builder.copy_link(
966            &lld_wrapper.tool.tool_path,
967            &self_contained_lld_dir.join(exe(name, target)),
968            FileType::Executable,
969        );
970    }
971}
972
973/// Builds the `wasm-component-ld` linker wrapper, which is shipped with rustc to be executed on the
974/// host platform where rustc runs.
975#[derive(Debug, Clone, Hash, PartialEq, Eq)]
976pub struct WasmComponentLd {
977    build_compiler: Compiler,
978    target: TargetSelection,
979}
980
981impl WasmComponentLd {
982    /// Returns `WasmComponentLd` that should be **used** by the passed compiler.
983    pub fn for_use_by_compiler(builder: &Builder<'_>, target_compiler: Compiler) -> Self {
984        Self {
985            build_compiler: get_tool_target_compiler(
986                builder,
987                ToolTargetBuildMode::Dist(target_compiler),
988            ),
989            target: target_compiler.host,
990        }
991    }
992}
993
994impl Step for WasmComponentLd {
995    type Output = ToolBuildResult;
996
997    const IS_HOST: bool = true;
998
999    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1000        run.path("src/tools/wasm-component-ld")
1001    }
1002
1003    fn make_run(run: RunConfig<'_>) {
1004        run.builder.ensure(WasmComponentLd {
1005            build_compiler: get_tool_target_compiler(
1006                run.builder,
1007                ToolTargetBuildMode::Build(run.target),
1008            ),
1009            target: run.target,
1010        });
1011    }
1012
1013    fn run(self, builder: &Builder<'_>) -> ToolBuildResult {
1014        builder.ensure(ToolBuild {
1015            build_compiler: self.build_compiler,
1016            target: self.target,
1017            tool: "wasm-component-ld",
1018            mode: Mode::ToolTarget,
1019            path: "src/tools/wasm-component-ld",
1020            source_type: SourceType::InTree,
1021            extra_features: vec![],
1022            allow_features: "",
1023            cargo_args: vec![],
1024            artifact_kind: ToolArtifactKind::Binary,
1025        })
1026    }
1027
1028    fn metadata(&self) -> Option<StepMetadata> {
1029        Some(StepMetadata::build("WasmComponentLd", self.target).built_by(self.build_compiler))
1030    }
1031}
1032
1033#[derive(Debug, Clone, Hash, PartialEq, Eq)]
1034pub struct RustAnalyzer {
1035    compilers: RustcPrivateCompilers,
1036}
1037
1038impl RustAnalyzer {
1039    pub fn from_compilers(compilers: RustcPrivateCompilers) -> Self {
1040        Self { compilers }
1041    }
1042}
1043
1044impl RustAnalyzer {
1045    pub const ALLOW_FEATURES: &'static str = "rustc_private,proc_macro_internals,proc_macro_diagnostic,proc_macro_span,proc_macro_span_shrink,proc_macro_def_site,new_zeroed_alloc";
1046}
1047
1048impl Step for RustAnalyzer {
1049    type Output = ToolBuildResult;
1050    const IS_HOST: bool = true;
1051
1052    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1053        run.path("src/tools/rust-analyzer")
1054    }
1055
1056    fn is_default_step(builder: &Builder<'_>) -> bool {
1057        builder.tool_enabled("rust-analyzer")
1058    }
1059
1060    fn make_run(run: RunConfig<'_>) {
1061        run.builder.ensure(RustAnalyzer {
1062            compilers: RustcPrivateCompilers::new(run.builder, run.builder.top_stage, run.target),
1063        });
1064    }
1065
1066    fn run(self, builder: &Builder<'_>) -> ToolBuildResult {
1067        let build_compiler = self.compilers.build_compiler;
1068        let target = self.compilers.target();
1069        builder.ensure(ToolBuild {
1070            build_compiler,
1071            target,
1072            tool: "rust-analyzer",
1073            mode: Mode::ToolRustcPrivate,
1074            path: "src/tools/rust-analyzer",
1075            extra_features: vec!["in-rust-tree".to_owned()],
1076            source_type: SourceType::InTree,
1077            allow_features: RustAnalyzer::ALLOW_FEATURES,
1078            cargo_args: Vec::new(),
1079            artifact_kind: ToolArtifactKind::Binary,
1080        })
1081    }
1082
1083    fn metadata(&self) -> Option<StepMetadata> {
1084        Some(
1085            StepMetadata::build("rust-analyzer", self.compilers.target())
1086                .built_by(self.compilers.build_compiler),
1087        )
1088    }
1089}
1090
1091#[derive(Debug, Clone, Hash, PartialEq, Eq)]
1092pub struct RustAnalyzerProcMacroSrv {
1093    compilers: RustcPrivateCompilers,
1094}
1095
1096impl RustAnalyzerProcMacroSrv {
1097    pub fn from_compilers(compilers: RustcPrivateCompilers) -> Self {
1098        Self { compilers }
1099    }
1100}
1101
1102impl Step for RustAnalyzerProcMacroSrv {
1103    type Output = ToolBuildResult;
1104    const IS_HOST: bool = true;
1105
1106    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1107        // Allow building `rust-analyzer-proc-macro-srv` both as part of the `rust-analyzer` and as a stand-alone tool.
1108        run.path("src/tools/rust-analyzer")
1109            .path("src/tools/rust-analyzer/crates/proc-macro-srv-cli")
1110    }
1111
1112    fn is_default_step(builder: &Builder<'_>) -> bool {
1113        builder.tool_enabled("rust-analyzer")
1114            || builder.tool_enabled("rust-analyzer-proc-macro-srv")
1115    }
1116
1117    fn make_run(run: RunConfig<'_>) {
1118        run.builder.ensure(RustAnalyzerProcMacroSrv {
1119            compilers: RustcPrivateCompilers::new(run.builder, run.builder.top_stage, run.target),
1120        });
1121    }
1122
1123    fn run(self, builder: &Builder<'_>) -> Self::Output {
1124        let tool_result = builder.ensure(ToolBuild {
1125            build_compiler: self.compilers.build_compiler,
1126            target: self.compilers.target(),
1127            tool: "rust-analyzer-proc-macro-srv",
1128            mode: Mode::ToolRustcPrivate,
1129            path: "src/tools/rust-analyzer/crates/proc-macro-srv-cli",
1130            extra_features: vec!["in-rust-tree".to_owned()],
1131            source_type: SourceType::InTree,
1132            allow_features: RustAnalyzer::ALLOW_FEATURES,
1133            cargo_args: Vec::new(),
1134            artifact_kind: ToolArtifactKind::Binary,
1135        });
1136
1137        // Copy `rust-analyzer-proc-macro-srv` to `<sysroot>/libexec/`
1138        // so that r-a can use it.
1139        let libexec_path = builder.sysroot(self.compilers.target_compiler).join("libexec");
1140        t!(fs::create_dir_all(&libexec_path));
1141        builder.copy_link(
1142            &tool_result.tool_path,
1143            &libexec_path.join("rust-analyzer-proc-macro-srv"),
1144            FileType::Executable,
1145        );
1146
1147        tool_result
1148    }
1149
1150    fn metadata(&self) -> Option<StepMetadata> {
1151        Some(
1152            StepMetadata::build("rust-analyzer-proc-macro-srv", self.compilers.target())
1153                .built_by(self.compilers.build_compiler),
1154        )
1155    }
1156}
1157
1158#[derive(Debug, Clone, Hash, PartialEq, Eq)]
1159pub struct LlvmBitcodeLinker {
1160    build_compiler: Compiler,
1161    target: TargetSelection,
1162}
1163
1164impl LlvmBitcodeLinker {
1165    /// Returns `LlvmBitcodeLinker` that will be **compiled** by the passed compiler, for the given
1166    /// `target`.
1167    pub fn from_build_compiler(build_compiler: Compiler, target: TargetSelection) -> Self {
1168        Self { build_compiler, target }
1169    }
1170
1171    /// Returns `LlvmBitcodeLinker` that should be **used** by the passed compiler.
1172    pub fn from_target_compiler(builder: &Builder<'_>, target_compiler: Compiler) -> Self {
1173        Self {
1174            build_compiler: get_tool_target_compiler(
1175                builder,
1176                ToolTargetBuildMode::Dist(target_compiler),
1177            ),
1178            target: target_compiler.host,
1179        }
1180    }
1181
1182    /// Return a compiler that is able to build this tool for the given `target`.
1183    pub fn get_build_compiler_for_target(
1184        builder: &Builder<'_>,
1185        target: TargetSelection,
1186    ) -> Compiler {
1187        get_tool_target_compiler(builder, ToolTargetBuildMode::Build(target))
1188    }
1189}
1190
1191impl Step for LlvmBitcodeLinker {
1192    type Output = ToolBuildResult;
1193    const IS_HOST: bool = true;
1194
1195    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1196        run.path("src/tools/llvm-bitcode-linker")
1197    }
1198
1199    fn is_default_step(builder: &Builder<'_>) -> bool {
1200        builder.tool_enabled("llvm-bitcode-linker")
1201    }
1202
1203    fn make_run(run: RunConfig<'_>) {
1204        run.builder.ensure(LlvmBitcodeLinker {
1205            build_compiler: Self::get_build_compiler_for_target(run.builder, run.target),
1206            target: run.target,
1207        });
1208    }
1209
1210    fn run(self, builder: &Builder<'_>) -> ToolBuildResult {
1211        builder.ensure(ToolBuild {
1212            build_compiler: self.build_compiler,
1213            target: self.target,
1214            tool: "llvm-bitcode-linker",
1215            mode: Mode::ToolTarget,
1216            path: "src/tools/llvm-bitcode-linker",
1217            source_type: SourceType::InTree,
1218            extra_features: vec![],
1219            allow_features: "",
1220            cargo_args: Vec::new(),
1221            artifact_kind: ToolArtifactKind::Binary,
1222        })
1223    }
1224
1225    fn metadata(&self) -> Option<StepMetadata> {
1226        Some(StepMetadata::build("LlvmBitcodeLinker", self.target).built_by(self.build_compiler))
1227    }
1228}
1229
1230#[derive(Debug, Clone, Hash, PartialEq, Eq)]
1231pub struct LibcxxVersionTool {
1232    pub target: TargetSelection,
1233}
1234
1235#[expect(dead_code)]
1236#[derive(Debug, Clone)]
1237pub enum LibcxxVersion {
1238    Gnu(usize),
1239    Llvm(usize),
1240}
1241
1242impl Step for LibcxxVersionTool {
1243    type Output = LibcxxVersion;
1244    const IS_HOST: bool = true;
1245
1246    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1247        run.never()
1248    }
1249
1250    fn is_default_step(_builder: &Builder<'_>) -> bool {
1251        false
1252    }
1253
1254    fn run(self, builder: &Builder<'_>) -> LibcxxVersion {
1255        let out_dir = builder.out.join(self.target.to_string()).join("libcxx-version");
1256        let executable = out_dir.join(exe("libcxx-version", self.target));
1257
1258        // This is a sanity-check specific step, which means it is frequently called (when using
1259        // CI LLVM), and compiling `src/tools/libcxx-version/main.cpp` at the beginning of the bootstrap
1260        // invocation adds a fair amount of overhead to the process (see https://github.com/rust-lang/rust/issues/126423).
1261        // Therefore, we want to avoid recompiling this file unnecessarily.
1262        if !executable.exists() {
1263            if !out_dir.exists() {
1264                t!(fs::create_dir_all(&out_dir));
1265            }
1266
1267            let compiler = builder.cxx(self.target).unwrap();
1268            let mut cmd = command(compiler);
1269
1270            cmd.arg("-o")
1271                .arg(&executable)
1272                .arg(builder.src.join("src/tools/libcxx-version/main.cpp"));
1273
1274            cmd.run(builder);
1275
1276            if !executable.exists() {
1277                panic!("Something went wrong. {} is not present", executable.display());
1278            }
1279        }
1280
1281        let version_output = command(executable).run_capture_stdout(builder).stdout();
1282
1283        let version_str = version_output.split_once("version:").unwrap().1;
1284        let version = version_str.trim().parse::<usize>().unwrap();
1285
1286        if version_output.starts_with("libstdc++") {
1287            LibcxxVersion::Gnu(version)
1288        } else if version_output.starts_with("libc++") {
1289            LibcxxVersion::Llvm(version)
1290        } else {
1291            panic!("Coudln't recognize the standard library version.");
1292        }
1293    }
1294}
1295
1296#[derive(Debug, Clone, Hash, PartialEq, Eq)]
1297pub struct BuildManifest {
1298    compiler: Compiler,
1299    target: TargetSelection,
1300}
1301
1302impl BuildManifest {
1303    pub fn new(builder: &Builder<'_>, target: TargetSelection) -> Self {
1304        BuildManifest { compiler: builder.compiler(1, builder.config.host_target), target }
1305    }
1306}
1307
1308impl Step for BuildManifest {
1309    type Output = ToolBuildResult;
1310
1311    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1312        run.path("src/tools/build-manifest")
1313    }
1314
1315    fn make_run(run: RunConfig<'_>) {
1316        run.builder.ensure(BuildManifest::new(run.builder, run.target));
1317    }
1318
1319    fn run(self, builder: &Builder<'_>) -> ToolBuildResult {
1320        // Building with the beta compiler will produce a broken build-manifest that doesn't support
1321        // recently stabilized targets/hosts.
1322        assert!(self.compiler.stage != 0);
1323        builder.ensure(ToolBuild {
1324            build_compiler: self.compiler,
1325            target: self.target,
1326            tool: "build-manifest",
1327            mode: Mode::ToolStd,
1328            path: "src/tools/build-manifest",
1329            source_type: SourceType::InTree,
1330            extra_features: vec![],
1331            allow_features: "",
1332            cargo_args: vec![],
1333            artifact_kind: ToolArtifactKind::Binary,
1334        })
1335    }
1336
1337    fn metadata(&self) -> Option<StepMetadata> {
1338        Some(StepMetadata::build("build-manifest", self.target).built_by(self.compiler))
1339    }
1340}
1341
1342/// Represents which compilers are involved in the compilation of a tool
1343/// that depends on compiler internals (`rustc_private`).
1344/// Their compilation looks like this:
1345///
1346/// - `build_compiler` (stage N-1) builds `target_compiler` (stage N) to produce .rlibs
1347///     - These .rlibs are copied into the sysroot of `build_compiler`
1348/// - `build_compiler` (stage N-1) builds `<tool>` (stage N)
1349///     - `<tool>` links to .rlibs from `target_compiler`
1350///
1351/// Eventually, this could also be used for .rmetas and check builds, but so far we only deal with
1352/// normal builds here.
1353#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
1354pub struct RustcPrivateCompilers {
1355    /// Compiler that builds the tool and that builds `target_compiler`.
1356    build_compiler: Compiler,
1357    /// Compiler to which .rlib artifacts the tool links to.
1358    /// The host target of this compiler corresponds to the target of the tool.
1359    target_compiler: Compiler,
1360}
1361
1362impl RustcPrivateCompilers {
1363    /// Create compilers for a `rustc_private` tool with the given `stage` and for the given
1364    /// `target`.
1365    pub fn new(builder: &Builder<'_>, stage: u32, target: TargetSelection) -> Self {
1366        let build_compiler = Self::build_compiler_from_stage(builder, stage);
1367
1368        // This is the compiler we'll link to
1369        // FIXME: make 100% sure that `target_compiler` was indeed built with `build_compiler`...
1370        let target_compiler = builder.compiler(build_compiler.stage + 1, target);
1371
1372        Self { build_compiler, target_compiler }
1373    }
1374
1375    pub fn from_build_and_target_compiler(
1376        build_compiler: Compiler,
1377        target_compiler: Compiler,
1378    ) -> Self {
1379        Self { build_compiler, target_compiler }
1380    }
1381
1382    /// Create rustc tool compilers from the build compiler.
1383    pub fn from_build_compiler(
1384        builder: &Builder<'_>,
1385        build_compiler: Compiler,
1386        target: TargetSelection,
1387    ) -> Self {
1388        let target_compiler = builder.compiler(build_compiler.stage + 1, target);
1389        Self { build_compiler, target_compiler }
1390    }
1391
1392    /// Create rustc tool compilers from the target compiler.
1393    pub fn from_target_compiler(builder: &Builder<'_>, target_compiler: Compiler) -> Self {
1394        Self {
1395            build_compiler: Self::build_compiler_from_stage(builder, target_compiler.stage),
1396            target_compiler,
1397        }
1398    }
1399
1400    fn build_compiler_from_stage(builder: &Builder<'_>, stage: u32) -> Compiler {
1401        assert!(stage > 0);
1402
1403        if builder.download_rustc() && stage == 1 {
1404            // We shouldn't drop to stage0 compiler when using CI rustc.
1405            builder.compiler(1, builder.config.host_target)
1406        } else {
1407            builder.compiler(stage - 1, builder.config.host_target)
1408        }
1409    }
1410
1411    pub fn build_compiler(&self) -> Compiler {
1412        self.build_compiler
1413    }
1414
1415    pub fn target_compiler(&self) -> Compiler {
1416        self.target_compiler
1417    }
1418
1419    /// Target of the tool being compiled
1420    pub fn target(&self) -> TargetSelection {
1421        self.target_compiler.host
1422    }
1423}
1424
1425/// Creates a step that builds an extended `Mode::ToolRustcPrivate` tool
1426/// and installs it into the sysroot of a corresponding compiler.
1427macro_rules! tool_rustc_extended {
1428    (
1429        $name:ident {
1430            path: $path:expr,
1431            tool_name: $tool_name:expr,
1432            stable: $stable:expr
1433            $( , add_bins_to_sysroot: $add_bins_to_sysroot:expr )?
1434            $( , add_features: $add_features:expr )?
1435            $( , cargo_args: $cargo_args:expr )?
1436            $( , )?
1437        }
1438    ) => {
1439        #[derive(Debug, Clone, Hash, PartialEq, Eq)]
1440        pub struct $name {
1441            compilers: RustcPrivateCompilers,
1442        }
1443
1444        impl $name {
1445            pub fn from_compilers(compilers: RustcPrivateCompilers) -> Self {
1446                Self {
1447                    compilers,
1448                }
1449            }
1450        }
1451
1452        impl Step for $name {
1453            type Output = ToolBuildResult;
1454            const IS_HOST: bool = true;
1455
1456            fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1457                should_run_extended_rustc_tool(
1458                    run,
1459                    $path,
1460                )
1461            }
1462
1463            fn is_default_step(builder: &Builder<'_>) -> bool {
1464                extended_rustc_tool_is_default_step(
1465                    builder,
1466                    $tool_name,
1467                    $stable,
1468                )
1469            }
1470
1471            fn make_run(run: RunConfig<'_>) {
1472                run.builder.ensure($name {
1473                    compilers: RustcPrivateCompilers::new(run.builder, run.builder.top_stage, run.target),
1474                });
1475            }
1476
1477            fn run(self, builder: &Builder<'_>) -> ToolBuildResult {
1478                let Self { compilers } = self;
1479                build_extended_rustc_tool(
1480                    builder,
1481                    compilers,
1482                    $tool_name,
1483                    $path,
1484                    None $( .or(Some(&$add_bins_to_sysroot)) )?,
1485                    None $( .or(Some($add_features)) )?,
1486                    None $( .or(Some($cargo_args)) )?,
1487                )
1488            }
1489
1490            fn metadata(&self) -> Option<StepMetadata> {
1491                Some(
1492                    StepMetadata::build($tool_name, self.compilers.target())
1493                        .built_by(self.compilers.build_compiler)
1494                )
1495            }
1496        }
1497    }
1498}
1499
1500fn should_run_extended_rustc_tool<'a>(run: ShouldRun<'a>, path: &'static str) -> ShouldRun<'a> {
1501    run.path(path)
1502}
1503
1504fn extended_rustc_tool_is_default_step(
1505    builder: &Builder<'_>,
1506    tool_name: &'static str,
1507    stable: bool,
1508) -> bool {
1509    builder.config.extended
1510        && builder.config.tools.as_ref().map_or(
1511            // By default, on nightly/dev enable all tools, else only
1512            // build stable tools.
1513            stable || builder.build.unstable_features(),
1514            // If `tools` is set, search list for this tool.
1515            |tools| {
1516                tools.iter().any(|tool| match tool.as_ref() {
1517                    "clippy" => tool_name == "clippy-driver",
1518                    x => tool_name == x,
1519                })
1520            },
1521        )
1522}
1523
1524fn build_extended_rustc_tool(
1525    builder: &Builder<'_>,
1526    compilers: RustcPrivateCompilers,
1527    tool_name: &'static str,
1528    path: &'static str,
1529    add_bins_to_sysroot: Option<&[&str]>,
1530    add_features: Option<fn(&Builder<'_>, TargetSelection, &mut Vec<String>)>,
1531    cargo_args: Option<&[&'static str]>,
1532) -> ToolBuildResult {
1533    let target = compilers.target();
1534    let mut extra_features = Vec::new();
1535    if let Some(func) = add_features {
1536        func(builder, target, &mut extra_features);
1537    }
1538
1539    let build_compiler = compilers.build_compiler;
1540    let ToolBuildResult { tool_path, .. } = builder.ensure(ToolBuild {
1541        build_compiler,
1542        target,
1543        tool: tool_name,
1544        mode: Mode::ToolRustcPrivate,
1545        path,
1546        extra_features,
1547        source_type: SourceType::InTree,
1548        allow_features: "",
1549        cargo_args: cargo_args.unwrap_or_default().iter().map(|s| String::from(*s)).collect(),
1550        artifact_kind: ToolArtifactKind::Binary,
1551    });
1552
1553    let target_compiler = compilers.target_compiler;
1554    if let Some(add_bins_to_sysroot) = add_bins_to_sysroot
1555        && !add_bins_to_sysroot.is_empty()
1556    {
1557        let bindir = builder.sysroot(target_compiler).join("bin");
1558        t!(fs::create_dir_all(&bindir));
1559
1560        for add_bin in add_bins_to_sysroot {
1561            let bin_destination = bindir.join(exe(add_bin, target_compiler.host));
1562            builder.copy_link(&tool_path, &bin_destination, FileType::Executable);
1563        }
1564
1565        // Return a path into the bin dir.
1566        let path = bindir.join(exe(tool_name, target_compiler.host));
1567        ToolBuildResult { tool_path: path, build_compiler }
1568    } else {
1569        ToolBuildResult { tool_path, build_compiler }
1570    }
1571}
1572
1573tool_rustc_extended!(Cargofmt {
1574    path: "src/tools/rustfmt",
1575    tool_name: "cargo-fmt",
1576    stable: true,
1577    add_bins_to_sysroot: ["cargo-fmt"]
1578});
1579tool_rustc_extended!(CargoClippy {
1580    path: "src/tools/clippy",
1581    tool_name: "cargo-clippy",
1582    stable: true,
1583    add_bins_to_sysroot: ["cargo-clippy"]
1584});
1585tool_rustc_extended!(Clippy {
1586    path: "src/tools/clippy",
1587    tool_name: "clippy-driver",
1588    stable: true,
1589    add_bins_to_sysroot: ["clippy-driver"],
1590    add_features: |builder, target, features| {
1591        if builder.config.jemalloc(target) {
1592            features.push("jemalloc".to_string());
1593        }
1594    }
1595});
1596tool_rustc_extended!(Miri {
1597    path: "src/tools/miri",
1598    tool_name: "miri",
1599    stable: false,
1600    add_bins_to_sysroot: ["miri"],
1601    add_features: |builder, target, features| {
1602        if builder.config.jemalloc(target) {
1603            features.push("jemalloc".to_string());
1604        }
1605    },
1606    // Always compile also tests when building miri. Otherwise feature unification can cause rebuilds between building and testing miri.
1607    cargo_args: &["--all-targets"],
1608});
1609tool_rustc_extended!(CargoMiri {
1610    path: "src/tools/miri/cargo-miri",
1611    tool_name: "cargo-miri",
1612    stable: false,
1613    add_bins_to_sysroot: ["cargo-miri"]
1614});
1615tool_rustc_extended!(Rustfmt {
1616    path: "src/tools/rustfmt",
1617    tool_name: "rustfmt",
1618    stable: true,
1619    add_bins_to_sysroot: ["rustfmt"]
1620});
1621
1622pub const TEST_FLOAT_PARSE_ALLOW_FEATURES: &str = "f16,cfg_target_has_reliable_f16_f128";
1623
1624impl Builder<'_> {
1625    /// Gets a `BootstrapCommand` which is ready to run `tool` in `stage` built for
1626    /// `host`.
1627    ///
1628    /// This also ensures that the given tool is built (using [`ToolBuild`]).
1629    pub fn tool_cmd(&self, tool: Tool) -> BootstrapCommand {
1630        let mut cmd = command(self.tool_exe(tool));
1631        let compiler = self.compiler(0, self.config.host_target);
1632        let host = &compiler.host;
1633        // Prepares the `cmd` provided to be able to run the `compiler` provided.
1634        //
1635        // Notably this munges the dynamic library lookup path to point to the
1636        // right location to run `compiler`.
1637        let mut lib_paths: Vec<PathBuf> = discover_out_dirs_with_dylibs(
1638            self.cargo_out(compiler, Mode::ToolBootstrap, *host).join("build"),
1639        );
1640
1641        // On MSVC a tool may invoke a C compiler (e.g., compiletest in run-make
1642        // mode) and that C compiler may need some extra PATH modification. Do
1643        // so here.
1644        if compiler.host.is_msvc() {
1645            let curpaths = env::var_os("PATH").unwrap_or_default();
1646            let curpaths = env::split_paths(&curpaths).collect::<Vec<_>>();
1647            for (k, v) in self.cc[&compiler.host].env() {
1648                if k != "PATH" {
1649                    continue;
1650                }
1651                for path in env::split_paths(v) {
1652                    if !curpaths.contains(&path) {
1653                        lib_paths.push(path);
1654                    }
1655                }
1656            }
1657        }
1658
1659        add_dylib_path(lib_paths, &mut cmd);
1660
1661        // Provide a RUSTC for this command to use.
1662        cmd.env("RUSTC", &self.initial_rustc);
1663
1664        cmd
1665    }
1666}
1667
1668/// Gets all of the `out` dirs in a given Cargo `build-dir/<profile>/build` dir.
1669fn discover_out_dirs_with_dylibs(dir: PathBuf) -> Vec<PathBuf> {
1670    if !dir.exists() {
1671        return Vec::new();
1672    }
1673    let read_dir = |path: &Path| path.read_dir().ok().into_iter().flatten().filter_map(Result::ok);
1674    let has_dylib = |path: &Path| {
1675        read_dir(path)
1676            .any(|e| e.path().extension().is_some_and(|ext| ext == std::env::consts::DLL_EXTENSION))
1677    };
1678    dir.read_dir()
1679        .unwrap_or_else(|e| panic!("Couldn't read {}: {}", dir.display(), e))
1680        .map(|e| e.unwrap())
1681        .flat_map(|e| read_dir(&e.path()))
1682        .flat_map(|e| read_dir(&e.path()))
1683        .map(|e| e.path())
1684        .filter(|path| path.ends_with("out") && has_dylib(path))
1685        .collect::<Vec<_>>()
1686}