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