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