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