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