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