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