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::path::PathBuf;
13use std::{env, fs};
14
15#[cfg(feature = "tracing")]
16use tracing::instrument;
17
18use crate::core::build_steps::compile::is_lto_stage;
19use crate::core::build_steps::toolstate::ToolState;
20use crate::core::build_steps::{compile, llvm};
21use crate::core::builder;
22use crate::core::builder::{
23    Builder, Cargo as CargoCommand, RunConfig, ShouldRun, Step, cargo_profile_var,
24};
25use crate::core::config::{DebuginfoLevel, RustcLto, TargetSelection};
26use crate::utils::channel::GitInfo;
27use crate::utils::exec::{BootstrapCommand, command};
28use crate::utils::helpers::{add_dylib_path, exe, t};
29use crate::{Compiler, Kind, Mode, gha};
30
31#[derive(Debug, Clone, Hash, PartialEq, Eq)]
32pub enum SourceType {
33    InTree,
34    Submodule,
35}
36
37#[derive(Debug, Clone, Hash, PartialEq, Eq)]
38pub enum ToolArtifactKind {
39    Binary,
40    Library,
41}
42
43#[derive(Debug, Clone, Hash, PartialEq, Eq)]
44struct ToolBuild {
45    compiler: Compiler,
46    target: TargetSelection,
47    tool: &'static str,
48    path: &'static str,
49    mode: Mode,
50    source_type: SourceType,
51    extra_features: Vec<String>,
52    /// Nightly-only features that are allowed (comma-separated list).
53    allow_features: &'static str,
54    /// Additional arguments to pass to the `cargo` invocation.
55    cargo_args: Vec<String>,
56    /// Whether the tool builds a binary or a library.
57    artifact_kind: ToolArtifactKind,
58}
59
60impl Builder<'_> {
61    #[track_caller]
62    pub(crate) fn msg_tool(
63        &self,
64        kind: Kind,
65        mode: Mode,
66        tool: &str,
67        build_stage: u32,
68        host: &TargetSelection,
69        target: &TargetSelection,
70    ) -> Option<gha::Group> {
71        match mode {
72            // depends on compiler stage, different to host compiler
73            Mode::ToolRustc => self.msg_sysroot_tool(
74                kind,
75                build_stage,
76                format_args!("tool {tool}"),
77                *host,
78                *target,
79            ),
80            // doesn't depend on compiler, same as host compiler
81            _ => self.msg(Kind::Build, build_stage, format_args!("tool {tool}"), *host, *target),
82        }
83    }
84}
85
86/// Result of the tool build process. Each `Step` in this module is responsible
87/// for using this type as `type Output = ToolBuildResult;`
88#[derive(Clone)]
89pub struct ToolBuildResult {
90    /// Artifact path of the corresponding tool that was built.
91    pub tool_path: PathBuf,
92    /// Compiler used to build the tool. For non-`ToolRustc` tools this is equal to `target_compiler`.
93    /// For `ToolRustc` this is one stage before of the `target_compiler`.
94    pub build_compiler: Compiler,
95    /// Target compiler passed to `Step`.
96    pub target_compiler: Compiler,
97}
98
99impl Step for ToolBuild {
100    type Output = ToolBuildResult;
101
102    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
103        run.never()
104    }
105
106    /// Builds a tool in `src/tools`
107    ///
108    /// This will build the specified tool with the specified `host` compiler in
109    /// `stage` into the normal cargo output directory.
110    fn run(mut self, builder: &Builder<'_>) -> ToolBuildResult {
111        let target = self.target;
112        let mut tool = self.tool;
113        let path = self.path;
114
115        let target_compiler = self.compiler;
116        self.compiler = if self.mode == Mode::ToolRustc {
117            get_tool_rustc_compiler(builder, self.compiler)
118        } else {
119            self.compiler
120        };
121
122        match self.mode {
123            Mode::ToolRustc => {
124                // If compiler was forced, its artifacts should be prepared earlier.
125                if !self.compiler.is_forced_compiler() {
126                    builder.ensure(compile::Std::new(self.compiler, self.compiler.host));
127                    builder.ensure(compile::Rustc::new(self.compiler, target));
128                }
129            }
130            Mode::ToolStd => {
131                // If compiler was forced, its artifacts should be prepared earlier.
132                if !self.compiler.is_forced_compiler() {
133                    builder.ensure(compile::Std::new(self.compiler, target))
134                }
135            }
136            Mode::ToolBootstrap => {} // uses downloaded stage0 compiler libs
137            _ => panic!("unexpected Mode for tool build"),
138        }
139
140        let mut cargo = prepare_tool_cargo(
141            builder,
142            self.compiler,
143            self.mode,
144            target,
145            Kind::Build,
146            path,
147            self.source_type,
148            &self.extra_features,
149        );
150
151        if path.ends_with("/rustdoc") &&
152            // rustdoc is performance sensitive, so apply LTO to it.
153            is_lto_stage(&self.compiler)
154        {
155            let lto = match builder.config.rust_lto {
156                RustcLto::Off => Some("off"),
157                RustcLto::Thin => Some("thin"),
158                RustcLto::Fat => Some("fat"),
159                RustcLto::ThinLocal => None,
160            };
161            if let Some(lto) = lto {
162                cargo.env(cargo_profile_var("LTO", &builder.config), lto);
163            }
164        }
165
166        if !self.allow_features.is_empty() {
167            cargo.allow_features(self.allow_features);
168        }
169
170        cargo.args(self.cargo_args);
171
172        let _guard = builder.msg_tool(
173            Kind::Build,
174            self.mode,
175            self.tool,
176            self.compiler.stage,
177            &self.compiler.host,
178            &self.target,
179        );
180
181        // we check this below
182        let build_success = compile::stream_cargo(builder, cargo, vec![], &mut |_| {});
183
184        builder.save_toolstate(
185            tool,
186            if build_success { ToolState::TestFail } else { ToolState::BuildFail },
187        );
188
189        if !build_success {
190            crate::exit!(1);
191        } else {
192            // HACK(#82501): on Windows, the tools directory gets added to PATH when running tests, and
193            // compiletest confuses HTML tidy with the in-tree tidy. Name the in-tree tidy something
194            // different so the problem doesn't come up.
195            if tool == "tidy" {
196                tool = "rust-tidy";
197            }
198            let tool_path = match self.artifact_kind {
199                ToolArtifactKind::Binary => {
200                    copy_link_tool_bin(builder, self.compiler, self.target, self.mode, tool)
201                }
202                ToolArtifactKind::Library => builder
203                    .cargo_out(self.compiler, self.mode, self.target)
204                    .join(format!("lib{tool}.rlib")),
205            };
206
207            ToolBuildResult { tool_path, build_compiler: self.compiler, target_compiler }
208        }
209    }
210}
211
212#[expect(clippy::too_many_arguments)] // FIXME: reduce the number of args and remove this.
213pub fn prepare_tool_cargo(
214    builder: &Builder<'_>,
215    compiler: Compiler,
216    mode: Mode,
217    target: TargetSelection,
218    cmd_kind: Kind,
219    path: &str,
220    source_type: SourceType,
221    extra_features: &[String],
222) -> CargoCommand {
223    let mut cargo = builder::Cargo::new(builder, compiler, mode, source_type, target, cmd_kind);
224
225    let dir = builder.src.join(path);
226    cargo.arg("--manifest-path").arg(dir.join("Cargo.toml"));
227
228    let mut features = extra_features.to_vec();
229    if builder.build.config.cargo_native_static {
230        if path.ends_with("cargo")
231            || path.ends_with("clippy")
232            || path.ends_with("miri")
233            || path.ends_with("rustfmt")
234        {
235            cargo.env("LIBZ_SYS_STATIC", "1");
236        }
237        if path.ends_with("cargo") {
238            features.push("all-static".to_string());
239        }
240    }
241
242    // clippy tests need to know about the stage sysroot. Set them consistently while building to
243    // avoid rebuilding when running tests.
244    cargo.env("SYSROOT", builder.sysroot(compiler));
245
246    // if tools are using lzma we want to force the build script to build its
247    // own copy
248    cargo.env("LZMA_API_STATIC", "1");
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 = GitInfo::new(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/// Handle stage-off logic for `ToolRustc` tools when necessary.
325pub(crate) fn get_tool_rustc_compiler(
326    builder: &Builder<'_>,
327    target_compiler: Compiler,
328) -> Compiler {
329    if target_compiler.is_forced_compiler() {
330        return target_compiler;
331    }
332
333    if builder.download_rustc() && target_compiler.stage > 0 {
334        // We already have the stage N compiler, we don't need to cut the stage.
335        return builder.compiler(target_compiler.stage, builder.config.build);
336    }
337
338    // Similar to `compile::Assemble`, build with the previous stage's compiler. Otherwise
339    // we'd have stageN/bin/rustc and stageN/bin/$rustc_tool be effectively different stage
340    // compilers, which isn't what we want. Rustc tools should be linked in the same way as the
341    // compiler it's paired with, so it must be built with the previous stage compiler.
342    builder.compiler(target_compiler.stage.saturating_sub(1), builder.config.build)
343}
344
345/// Links a built tool binary with the given `name` from the build directory to the
346/// tools directory.
347fn copy_link_tool_bin(
348    builder: &Builder<'_>,
349    compiler: Compiler,
350    target: TargetSelection,
351    mode: Mode,
352    name: &str,
353) -> PathBuf {
354    let cargo_out = builder.cargo_out(compiler, mode, target).join(exe(name, target));
355    let bin = builder.tools_dir(compiler).join(exe(name, target));
356    builder.copy_link(&cargo_out, &bin);
357    bin
358}
359
360macro_rules! bootstrap_tool {
361    ($(
362        $name:ident, $path:expr, $tool_name:expr
363        $(,is_external_tool = $external:expr)*
364        $(,is_unstable_tool = $unstable:expr)*
365        $(,allow_features = $allow_features:expr)?
366        $(,submodules = $submodules:expr)?
367        $(,artifact_kind = $artifact_kind:expr)?
368        ;
369    )+) => {
370        #[derive(PartialEq, Eq, Clone)]
371        #[allow(dead_code)]
372        pub enum Tool {
373            $(
374                $name,
375            )+
376        }
377
378        impl<'a> Builder<'a> {
379            pub fn tool_exe(&self, tool: Tool) -> PathBuf {
380                match tool {
381                    $(Tool::$name =>
382                        self.ensure($name {
383                            compiler: self.compiler(0, self.config.build),
384                            target: self.config.build,
385                        }).tool_path,
386                    )+
387                }
388            }
389        }
390
391        $(
392            #[derive(Debug, Clone, Hash, PartialEq, Eq)]
393        pub struct $name {
394            pub compiler: Compiler,
395            pub target: TargetSelection,
396        }
397
398        impl Step for $name {
399            type Output = ToolBuildResult;
400
401            fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
402                run.path($path)
403            }
404
405            fn make_run(run: RunConfig<'_>) {
406                run.builder.ensure($name {
407                    // snapshot compiler
408                    compiler: run.builder.compiler(0, run.builder.config.build),
409                    target: run.target,
410                });
411            }
412
413            #[cfg_attr(
414                feature = "tracing",
415                instrument(
416                    level = "debug",
417                    name = $tool_name,
418                    skip_all,
419                ),
420            )]
421            fn run(self, builder: &Builder<'_>) -> ToolBuildResult {
422                $(
423                    for submodule in $submodules {
424                        builder.require_submodule(submodule, None);
425                    }
426                )*
427
428                builder.ensure(ToolBuild {
429                    compiler: self.compiler,
430                    target: self.target,
431                    tool: $tool_name,
432                    mode: if false $(|| $unstable)* {
433                        // use in-tree libraries for unstable features
434                        Mode::ToolStd
435                    } else {
436                        Mode::ToolBootstrap
437                    },
438                    path: $path,
439                    source_type: if false $(|| $external)* {
440                        SourceType::Submodule
441                    } else {
442                        SourceType::InTree
443                    },
444                    extra_features: vec![],
445                    allow_features: concat!($($allow_features)*),
446                    cargo_args: vec![],
447                    artifact_kind: if false $(|| $artifact_kind == ToolArtifactKind::Library)* {
448                        ToolArtifactKind::Library
449                    } else {
450                        ToolArtifactKind::Binary
451                    }
452                })
453            }
454        }
455        )+
456    }
457}
458
459bootstrap_tool!(
460    // This is marked as an external tool because it includes dependencies
461    // from submodules. Trying to keep the lints in sync between all the repos
462    // is a bit of a pain. Unfortunately it means the rustbook source itself
463    // doesn't deny warnings, but it is a relatively small piece of code.
464    Rustbook, "src/tools/rustbook", "rustbook", is_external_tool = true, submodules = SUBMODULES_FOR_RUSTBOOK;
465    UnstableBookGen, "src/tools/unstable-book-gen", "unstable-book-gen";
466    Tidy, "src/tools/tidy", "tidy";
467    Linkchecker, "src/tools/linkchecker", "linkchecker";
468    CargoTest, "src/tools/cargotest", "cargotest";
469    Compiletest, "src/tools/compiletest", "compiletest", is_unstable_tool = true, allow_features = "test";
470    BuildManifest, "src/tools/build-manifest", "build-manifest";
471    RemoteTestClient, "src/tools/remote-test-client", "remote-test-client";
472    RustInstaller, "src/tools/rust-installer", "rust-installer";
473    RustdocTheme, "src/tools/rustdoc-themes", "rustdoc-themes";
474    LintDocs, "src/tools/lint-docs", "lint-docs";
475    JsonDocCk, "src/tools/jsondocck", "jsondocck";
476    JsonDocLint, "src/tools/jsondoclint", "jsondoclint";
477    HtmlChecker, "src/tools/html-checker", "html-checker";
478    BumpStage0, "src/tools/bump-stage0", "bump-stage0";
479    ReplaceVersionPlaceholder, "src/tools/replace-version-placeholder", "replace-version-placeholder";
480    CollectLicenseMetadata, "src/tools/collect-license-metadata", "collect-license-metadata";
481    GenerateCopyright, "src/tools/generate-copyright", "generate-copyright";
482    SuggestTests, "src/tools/suggest-tests", "suggest-tests";
483    GenerateWindowsSys, "src/tools/generate-windows-sys", "generate-windows-sys";
484    RustdocGUITest, "src/tools/rustdoc-gui-test", "rustdoc-gui-test", is_unstable_tool = true, allow_features = "test";
485    CoverageDump, "src/tools/coverage-dump", "coverage-dump";
486    WasmComponentLd, "src/tools/wasm-component-ld", "wasm-component-ld", is_unstable_tool = true, allow_features = "min_specialization";
487    UnicodeTableGenerator, "src/tools/unicode-table-generator", "unicode-table-generator";
488    FeaturesStatusDump, "src/tools/features-status-dump", "features-status-dump";
489    OptimizedDist, "src/tools/opt-dist", "opt-dist", submodules = &["src/tools/rustc-perf"];
490    RunMakeSupport, "src/tools/run-make-support", "run_make_support", artifact_kind = ToolArtifactKind::Library;
491);
492
493/// These are the submodules that are required for rustbook to work due to
494/// depending on mdbook plugins.
495pub static SUBMODULES_FOR_RUSTBOOK: &[&str] = &["src/doc/book", "src/doc/reference"];
496
497/// The [rustc-perf](https://github.com/rust-lang/rustc-perf) benchmark suite, which is added
498/// as a submodule at `src/tools/rustc-perf`.
499#[derive(Debug, Clone, Hash, PartialEq, Eq)]
500pub struct RustcPerf {
501    pub compiler: Compiler,
502    pub target: TargetSelection,
503}
504
505impl Step for RustcPerf {
506    /// Path to the built `collector` binary.
507    type Output = ToolBuildResult;
508
509    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
510        run.path("src/tools/rustc-perf")
511    }
512
513    fn make_run(run: RunConfig<'_>) {
514        run.builder.ensure(RustcPerf {
515            compiler: run.builder.compiler(0, run.builder.config.build),
516            target: run.target,
517        });
518    }
519
520    fn run(self, builder: &Builder<'_>) -> ToolBuildResult {
521        // We need to ensure the rustc-perf submodule is initialized.
522        builder.require_submodule("src/tools/rustc-perf", None);
523
524        let tool = ToolBuild {
525            compiler: self.compiler,
526            target: self.target,
527            tool: "collector",
528            mode: Mode::ToolBootstrap,
529            path: "src/tools/rustc-perf",
530            source_type: SourceType::Submodule,
531            extra_features: Vec::new(),
532            allow_features: "",
533            // Only build the collector package, which is used for benchmarking through
534            // a CLI.
535            cargo_args: vec!["-p".to_string(), "collector".to_string()],
536            artifact_kind: ToolArtifactKind::Binary,
537        };
538        let res = builder.ensure(tool.clone());
539        // We also need to symlink the `rustc-fake` binary to the corresponding directory,
540        // because `collector` expects it in the same directory.
541        copy_link_tool_bin(builder, tool.compiler, tool.target, tool.mode, "rustc-fake");
542
543        res
544    }
545}
546
547#[derive(Debug, Clone, Hash, PartialEq, Eq, Ord, PartialOrd)]
548pub struct ErrorIndex {
549    pub compiler: Compiler,
550}
551
552impl ErrorIndex {
553    pub fn command(builder: &Builder<'_>) -> BootstrapCommand {
554        // Error-index-generator links with the rustdoc library, so we need to add `rustc_lib_paths`
555        // for rustc_private and libLLVM.so, and `sysroot_lib` for libstd, etc.
556        let host = builder.config.build;
557        let compiler = builder.compiler_for(builder.top_stage, host, host);
558        let mut cmd = command(builder.ensure(ErrorIndex { compiler }).tool_path);
559        let mut dylib_paths = builder.rustc_lib_paths(compiler);
560        dylib_paths.push(PathBuf::from(&builder.sysroot_target_libdir(compiler, compiler.host)));
561        add_dylib_path(dylib_paths, &mut cmd);
562        cmd
563    }
564}
565
566impl Step for ErrorIndex {
567    type Output = ToolBuildResult;
568
569    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
570        run.path("src/tools/error_index_generator")
571    }
572
573    fn make_run(run: RunConfig<'_>) {
574        // NOTE: This `make_run` isn't used in normal situations, only if you
575        // manually build the tool with `x.py build
576        // src/tools/error-index-generator` which almost nobody does.
577        // Normally, `x.py test` or `x.py doc` will use the
578        // `ErrorIndex::command` function instead.
579        let compiler = run.builder.compiler(run.builder.top_stage, run.builder.config.build);
580        run.builder.ensure(ErrorIndex { compiler });
581    }
582
583    fn run(self, builder: &Builder<'_>) -> ToolBuildResult {
584        builder.ensure(ToolBuild {
585            compiler: self.compiler,
586            target: self.compiler.host,
587            tool: "error_index_generator",
588            mode: Mode::ToolRustc,
589            path: "src/tools/error_index_generator",
590            source_type: SourceType::InTree,
591            extra_features: Vec::new(),
592            allow_features: "",
593            cargo_args: Vec::new(),
594            artifact_kind: ToolArtifactKind::Binary,
595        })
596    }
597}
598
599#[derive(Debug, Clone, Hash, PartialEq, Eq)]
600pub struct RemoteTestServer {
601    pub compiler: Compiler,
602    pub target: TargetSelection,
603}
604
605impl Step for RemoteTestServer {
606    type Output = ToolBuildResult;
607
608    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
609        run.path("src/tools/remote-test-server")
610    }
611
612    fn make_run(run: RunConfig<'_>) {
613        run.builder.ensure(RemoteTestServer {
614            compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
615            target: run.target,
616        });
617    }
618
619    fn run(self, builder: &Builder<'_>) -> ToolBuildResult {
620        builder.ensure(ToolBuild {
621            compiler: self.compiler,
622            target: self.target,
623            tool: "remote-test-server",
624            mode: Mode::ToolStd,
625            path: "src/tools/remote-test-server",
626            source_type: SourceType::InTree,
627            extra_features: Vec::new(),
628            allow_features: "",
629            cargo_args: Vec::new(),
630            artifact_kind: ToolArtifactKind::Binary,
631        })
632    }
633}
634
635#[derive(Debug, Clone, Hash, PartialEq, Eq, Ord, PartialOrd)]
636pub struct Rustdoc {
637    /// This should only ever be 0 or 2.
638    /// We sometimes want to reference the "bootstrap" rustdoc, which is why this option is here.
639    pub compiler: Compiler,
640}
641
642impl Step for Rustdoc {
643    type Output = ToolBuildResult;
644    const DEFAULT: bool = true;
645    const ONLY_HOSTS: bool = true;
646
647    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
648        run.path("src/tools/rustdoc").path("src/librustdoc")
649    }
650
651    fn make_run(run: RunConfig<'_>) {
652        run.builder
653            .ensure(Rustdoc { compiler: run.builder.compiler(run.builder.top_stage, run.target) });
654    }
655
656    fn run(self, builder: &Builder<'_>) -> ToolBuildResult {
657        let target_compiler = self.compiler;
658        let target = target_compiler.host;
659
660        if target_compiler.stage == 0 {
661            if !target_compiler.is_snapshot(builder) {
662                panic!("rustdoc in stage 0 must be snapshot rustdoc");
663            }
664
665            return ToolBuildResult {
666                tool_path: builder.initial_rustdoc.clone(),
667                build_compiler: target_compiler,
668                target_compiler,
669            };
670        }
671
672        let bin_rustdoc = || {
673            let sysroot = builder.sysroot(target_compiler);
674            let bindir = sysroot.join("bin");
675            t!(fs::create_dir_all(&bindir));
676            let bin_rustdoc = bindir.join(exe("rustdoc", target_compiler.host));
677            let _ = fs::remove_file(&bin_rustdoc);
678            bin_rustdoc
679        };
680
681        // If CI rustc is enabled and we haven't modified the rustdoc sources,
682        // use the precompiled rustdoc from CI rustc's sysroot to speed up bootstrapping.
683        if builder.download_rustc()
684            && target_compiler.stage > 0
685            && builder.rust_info().is_managed_git_subrepository()
686        {
687            let files_to_track = &["src/librustdoc", "src/tools/rustdoc"];
688
689            // Check if unchanged
690            if builder.config.last_modified_commit(files_to_track, "download-rustc", true).is_some()
691            {
692                let precompiled_rustdoc = builder
693                    .config
694                    .ci_rustc_dir()
695                    .join("bin")
696                    .join(exe("rustdoc", target_compiler.host));
697
698                let bin_rustdoc = bin_rustdoc();
699                builder.copy_link(&precompiled_rustdoc, &bin_rustdoc);
700
701                return ToolBuildResult {
702                    tool_path: bin_rustdoc,
703                    build_compiler: target_compiler,
704                    target_compiler,
705                };
706            }
707        }
708
709        // The presence of `target_compiler` ensures that the necessary libraries (codegen backends,
710        // compiler libraries, ...) are built. Rustdoc does not require the presence of any
711        // libraries within sysroot_libdir (i.e., rustlib), though doctests may want it (since
712        // they'll be linked to those libraries). As such, don't explicitly `ensure` any additional
713        // libraries here. The intuition here is that If we've built a compiler, we should be able
714        // to build rustdoc.
715        //
716        let mut extra_features = Vec::new();
717        if builder.config.jemalloc(target) {
718            extra_features.push("jemalloc".to_string());
719        }
720
721        let ToolBuildResult { tool_path, build_compiler, target_compiler } =
722            builder.ensure(ToolBuild {
723                compiler: target_compiler,
724                target,
725                // Cargo adds a number of paths to the dylib search path on windows, which results in
726                // the wrong rustdoc being executed. To avoid the conflicting rustdocs, we name the "tool"
727                // rustdoc a different name.
728                tool: "rustdoc_tool_binary",
729                mode: Mode::ToolRustc,
730                path: "src/tools/rustdoc",
731                source_type: SourceType::InTree,
732                extra_features,
733                allow_features: "",
734                cargo_args: Vec::new(),
735                artifact_kind: ToolArtifactKind::Binary,
736            });
737
738        // don't create a stage0-sysroot/bin directory.
739        if target_compiler.stage > 0 {
740            if builder.config.rust_debuginfo_level_tools == DebuginfoLevel::None {
741                // Due to LTO a lot of debug info from C++ dependencies such as jemalloc can make it into
742                // our final binaries
743                compile::strip_debug(builder, target, &tool_path);
744            }
745            let bin_rustdoc = bin_rustdoc();
746            builder.copy_link(&tool_path, &bin_rustdoc);
747            ToolBuildResult { tool_path: bin_rustdoc, build_compiler, target_compiler }
748        } else {
749            ToolBuildResult { tool_path, build_compiler, target_compiler }
750        }
751    }
752}
753
754#[derive(Debug, Clone, Hash, PartialEq, Eq)]
755pub struct Cargo {
756    pub compiler: Compiler,
757    pub target: TargetSelection,
758}
759
760impl Step for Cargo {
761    type Output = ToolBuildResult;
762    const DEFAULT: bool = true;
763    const ONLY_HOSTS: bool = true;
764
765    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
766        let builder = run.builder;
767        run.path("src/tools/cargo").default_condition(builder.tool_enabled("cargo"))
768    }
769
770    fn make_run(run: RunConfig<'_>) {
771        run.builder.ensure(Cargo {
772            compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
773            target: run.target,
774        });
775    }
776
777    fn run(self, builder: &Builder<'_>) -> ToolBuildResult {
778        builder.build.require_submodule("src/tools/cargo", None);
779
780        builder.ensure(ToolBuild {
781            compiler: self.compiler,
782            target: self.target,
783            tool: "cargo",
784            mode: Mode::ToolRustc,
785            path: "src/tools/cargo",
786            source_type: SourceType::Submodule,
787            extra_features: Vec::new(),
788            allow_features: "",
789            cargo_args: Vec::new(),
790            artifact_kind: ToolArtifactKind::Binary,
791        })
792    }
793}
794
795#[derive(Debug, Clone, Hash, PartialEq, Eq)]
796pub struct LldWrapper {
797    pub build_compiler: Compiler,
798    pub target_compiler: Compiler,
799}
800
801impl Step for LldWrapper {
802    type Output = ToolBuildResult;
803
804    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
805        run.never()
806    }
807
808    #[cfg_attr(
809        feature = "tracing",
810        instrument(
811            level = "debug",
812            name = "LldWrapper::run",
813            skip_all,
814            fields(build_compiler = ?self.build_compiler, target_compiler = ?self.target_compiler),
815        ),
816    )]
817
818    fn run(self, builder: &Builder<'_>) -> ToolBuildResult {
819        if builder.config.dry_run() {
820            return ToolBuildResult {
821                tool_path: Default::default(),
822                build_compiler: self.build_compiler,
823                target_compiler: self.target_compiler,
824            };
825        }
826
827        let target = self.target_compiler.host;
828
829        let tool_result = builder.ensure(ToolBuild {
830            compiler: self.build_compiler,
831            target,
832            tool: "lld-wrapper",
833            mode: Mode::ToolStd,
834            path: "src/tools/lld-wrapper",
835            source_type: SourceType::InTree,
836            extra_features: Vec::new(),
837            allow_features: "",
838            cargo_args: Vec::new(),
839            artifact_kind: ToolArtifactKind::Binary,
840        });
841
842        let libdir_bin = builder.sysroot_target_bindir(self.target_compiler, target);
843        t!(fs::create_dir_all(&libdir_bin));
844
845        let lld_install = builder.ensure(llvm::Lld { target });
846        let src_exe = exe("lld", target);
847        let dst_exe = exe("rust-lld", target);
848
849        builder.copy_link(&lld_install.join("bin").join(src_exe), &libdir_bin.join(dst_exe));
850        let self_contained_lld_dir = libdir_bin.join("gcc-ld");
851        t!(fs::create_dir_all(&self_contained_lld_dir));
852
853        for name in crate::LLD_FILE_NAMES {
854            builder
855                .copy_link(&tool_result.tool_path, &self_contained_lld_dir.join(exe(name, target)));
856        }
857
858        tool_result
859    }
860}
861
862#[derive(Debug, Clone, Hash, PartialEq, Eq)]
863pub struct RustAnalyzer {
864    pub compiler: Compiler,
865    pub target: TargetSelection,
866}
867
868impl RustAnalyzer {
869    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";
870}
871
872impl Step for RustAnalyzer {
873    type Output = ToolBuildResult;
874    const DEFAULT: bool = true;
875    const ONLY_HOSTS: bool = true;
876
877    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
878        let builder = run.builder;
879        run.path("src/tools/rust-analyzer").default_condition(builder.tool_enabled("rust-analyzer"))
880    }
881
882    fn make_run(run: RunConfig<'_>) {
883        run.builder.ensure(RustAnalyzer {
884            compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
885            target: run.target,
886        });
887    }
888
889    fn run(self, builder: &Builder<'_>) -> ToolBuildResult {
890        builder.ensure(ToolBuild {
891            compiler: self.compiler,
892            target: self.target,
893            tool: "rust-analyzer",
894            mode: Mode::ToolRustc,
895            path: "src/tools/rust-analyzer",
896            extra_features: vec!["in-rust-tree".to_owned()],
897            source_type: SourceType::InTree,
898            allow_features: RustAnalyzer::ALLOW_FEATURES,
899            cargo_args: Vec::new(),
900            artifact_kind: ToolArtifactKind::Binary,
901        })
902    }
903}
904
905#[derive(Debug, Clone, Hash, PartialEq, Eq)]
906pub struct RustAnalyzerProcMacroSrv {
907    pub compiler: Compiler,
908    pub target: TargetSelection,
909}
910
911impl Step for RustAnalyzerProcMacroSrv {
912    type Output = Option<ToolBuildResult>;
913    const DEFAULT: bool = true;
914    const ONLY_HOSTS: bool = true;
915
916    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
917        let builder = run.builder;
918        // Allow building `rust-analyzer-proc-macro-srv` both as part of the `rust-analyzer` and as a stand-alone tool.
919        run.path("src/tools/rust-analyzer")
920            .path("src/tools/rust-analyzer/crates/proc-macro-srv-cli")
921            .default_condition(
922                builder.tool_enabled("rust-analyzer")
923                    || builder.tool_enabled("rust-analyzer-proc-macro-srv"),
924            )
925    }
926
927    fn make_run(run: RunConfig<'_>) {
928        run.builder.ensure(RustAnalyzerProcMacroSrv {
929            compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
930            target: run.target,
931        });
932    }
933
934    fn run(self, builder: &Builder<'_>) -> Option<ToolBuildResult> {
935        let tool_result = builder.ensure(ToolBuild {
936            compiler: self.compiler,
937            target: self.target,
938            tool: "rust-analyzer-proc-macro-srv",
939            mode: Mode::ToolRustc,
940            path: "src/tools/rust-analyzer/crates/proc-macro-srv-cli",
941            extra_features: vec!["in-rust-tree".to_owned()],
942            source_type: SourceType::InTree,
943            allow_features: RustAnalyzer::ALLOW_FEATURES,
944            cargo_args: Vec::new(),
945            artifact_kind: ToolArtifactKind::Binary,
946        });
947
948        // Copy `rust-analyzer-proc-macro-srv` to `<sysroot>/libexec/`
949        // so that r-a can use it.
950        let libexec_path = builder.sysroot(self.compiler).join("libexec");
951        t!(fs::create_dir_all(&libexec_path));
952        builder
953            .copy_link(&tool_result.tool_path, &libexec_path.join("rust-analyzer-proc-macro-srv"));
954
955        Some(tool_result)
956    }
957}
958
959#[derive(Debug, Clone, Hash, PartialEq, Eq)]
960pub struct LlvmBitcodeLinker {
961    pub compiler: Compiler,
962    pub target: TargetSelection,
963    pub extra_features: Vec<String>,
964}
965
966impl Step for LlvmBitcodeLinker {
967    type Output = ToolBuildResult;
968    const DEFAULT: bool = true;
969    const ONLY_HOSTS: bool = true;
970
971    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
972        let builder = run.builder;
973        run.path("src/tools/llvm-bitcode-linker")
974            .default_condition(builder.tool_enabled("llvm-bitcode-linker"))
975    }
976
977    fn make_run(run: RunConfig<'_>) {
978        run.builder.ensure(LlvmBitcodeLinker {
979            compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
980            extra_features: Vec::new(),
981            target: run.target,
982        });
983    }
984
985    #[cfg_attr(
986        feature = "tracing",
987        instrument(level = "debug", name = "LlvmBitcodeLinker::run", skip_all)
988    )]
989    fn run(self, builder: &Builder<'_>) -> ToolBuildResult {
990        let tool_result = builder.ensure(ToolBuild {
991            compiler: self.compiler,
992            target: self.target,
993            tool: "llvm-bitcode-linker",
994            mode: Mode::ToolRustc,
995            path: "src/tools/llvm-bitcode-linker",
996            source_type: SourceType::InTree,
997            extra_features: self.extra_features,
998            allow_features: "",
999            cargo_args: Vec::new(),
1000            artifact_kind: ToolArtifactKind::Binary,
1001        });
1002
1003        if tool_result.target_compiler.stage > 0 {
1004            let bindir_self_contained = builder
1005                .sysroot(tool_result.target_compiler)
1006                .join(format!("lib/rustlib/{}/bin/self-contained", self.target.triple));
1007            t!(fs::create_dir_all(&bindir_self_contained));
1008            let bin_destination = bindir_self_contained
1009                .join(exe("llvm-bitcode-linker", tool_result.target_compiler.host));
1010            builder.copy_link(&tool_result.tool_path, &bin_destination);
1011            ToolBuildResult {
1012                tool_path: bin_destination,
1013                build_compiler: tool_result.build_compiler,
1014                target_compiler: tool_result.target_compiler,
1015            }
1016        } else {
1017            tool_result
1018        }
1019    }
1020}
1021
1022#[derive(Debug, Clone, Hash, PartialEq, Eq)]
1023pub struct LibcxxVersionTool {
1024    pub target: TargetSelection,
1025}
1026
1027#[expect(dead_code)]
1028#[derive(Debug, Clone)]
1029pub enum LibcxxVersion {
1030    Gnu(usize),
1031    Llvm(usize),
1032}
1033
1034impl Step for LibcxxVersionTool {
1035    type Output = LibcxxVersion;
1036    const DEFAULT: bool = false;
1037    const ONLY_HOSTS: bool = true;
1038
1039    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1040        run.never()
1041    }
1042
1043    fn run(self, builder: &Builder<'_>) -> LibcxxVersion {
1044        let out_dir = builder.out.join(self.target.to_string()).join("libcxx-version");
1045        let executable = out_dir.join(exe("libcxx-version", self.target));
1046
1047        // This is a sanity-check specific step, which means it is frequently called (when using
1048        // CI LLVM), and compiling `src/tools/libcxx-version/main.cpp` at the beginning of the bootstrap
1049        // invocation adds a fair amount of overhead to the process (see https://github.com/rust-lang/rust/issues/126423).
1050        // Therefore, we want to avoid recompiling this file unnecessarily.
1051        if !executable.exists() {
1052            if !out_dir.exists() {
1053                t!(fs::create_dir_all(&out_dir));
1054            }
1055
1056            let compiler = builder.cxx(self.target).unwrap();
1057            let mut cmd = command(compiler);
1058
1059            cmd.arg("-o")
1060                .arg(&executable)
1061                .arg(builder.src.join("src/tools/libcxx-version/main.cpp"));
1062
1063            cmd.run(builder);
1064
1065            if !executable.exists() {
1066                panic!("Something went wrong. {} is not present", executable.display());
1067            }
1068        }
1069
1070        let version_output = command(executable).run_capture_stdout(builder).stdout();
1071
1072        let version_str = version_output.split_once("version:").unwrap().1;
1073        let version = version_str.trim().parse::<usize>().unwrap();
1074
1075        if version_output.starts_with("libstdc++") {
1076            LibcxxVersion::Gnu(version)
1077        } else if version_output.starts_with("libc++") {
1078            LibcxxVersion::Llvm(version)
1079        } else {
1080            panic!("Coudln't recognize the standard library version.");
1081        }
1082    }
1083}
1084
1085macro_rules! tool_extended {
1086    (
1087        $name:ident {
1088            path: $path:expr,
1089            tool_name: $tool_name:expr,
1090            stable: $stable:expr
1091            $( , add_bins_to_sysroot: $add_bins_to_sysroot:expr )?
1092            $( , )?
1093        }
1094    ) => {
1095        #[derive(Debug, Clone, Hash, PartialEq, Eq)]
1096        pub struct $name {
1097            pub compiler: Compiler,
1098            pub target: TargetSelection,
1099        }
1100
1101        impl Step for $name {
1102            type Output = ToolBuildResult;
1103            const DEFAULT: bool = true; // Overridden by `should_run_tool_build_step`
1104            const ONLY_HOSTS: bool = true;
1105
1106            fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1107                should_run_tool_build_step(
1108                    run,
1109                    $tool_name,
1110                    $path,
1111                    $stable,
1112                )
1113            }
1114
1115            fn make_run(run: RunConfig<'_>) {
1116                run.builder.ensure($name {
1117                    compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
1118                    target: run.target,
1119                });
1120            }
1121
1122            fn run(self, builder: &Builder<'_>) -> ToolBuildResult {
1123                let Self { compiler, target } = self;
1124                run_tool_build_step(
1125                    builder,
1126                    compiler,
1127                    target,
1128                    $tool_name,
1129                    $path,
1130                    None $( .or(Some(&$add_bins_to_sysroot)) )?,
1131                )
1132            }
1133        }
1134    }
1135}
1136
1137fn should_run_tool_build_step<'a>(
1138    run: ShouldRun<'a>,
1139    tool_name: &'static str,
1140    path: &'static str,
1141    stable: bool,
1142) -> ShouldRun<'a> {
1143    let builder = run.builder;
1144    run.path(path).default_condition(
1145        builder.config.extended
1146            && builder.config.tools.as_ref().map_or(
1147                // By default, on nightly/dev enable all tools, else only
1148                // build stable tools.
1149                stable || builder.build.unstable_features(),
1150                // If `tools` is set, search list for this tool.
1151                |tools| {
1152                    tools.iter().any(|tool| match tool.as_ref() {
1153                        "clippy" => tool_name == "clippy-driver",
1154                        x => tool_name == x,
1155                    })
1156                },
1157            ),
1158    )
1159}
1160
1161fn run_tool_build_step(
1162    builder: &Builder<'_>,
1163    compiler: Compiler,
1164    target: TargetSelection,
1165    tool_name: &'static str,
1166    path: &'static str,
1167    add_bins_to_sysroot: Option<&[&str]>,
1168) -> ToolBuildResult {
1169    let ToolBuildResult { tool_path, build_compiler, target_compiler } =
1170        builder.ensure(ToolBuild {
1171            compiler,
1172            target,
1173            tool: tool_name,
1174            mode: Mode::ToolRustc,
1175            path,
1176            extra_features: vec![],
1177            source_type: SourceType::InTree,
1178            allow_features: "",
1179            cargo_args: vec![],
1180            artifact_kind: ToolArtifactKind::Binary,
1181        });
1182
1183    // FIXME: This should just be an if-let-chain, but those are unstable.
1184    if let Some(add_bins_to_sysroot) =
1185        add_bins_to_sysroot.filter(|bins| !bins.is_empty() && target_compiler.stage > 0)
1186    {
1187        let bindir = builder.sysroot(target_compiler).join("bin");
1188        t!(fs::create_dir_all(&bindir));
1189
1190        for add_bin in add_bins_to_sysroot {
1191            let bin_destination = bindir.join(exe(add_bin, target_compiler.host));
1192            builder.copy_link(&tool_path, &bin_destination);
1193        }
1194
1195        // Return a path into the bin dir.
1196        let path = bindir.join(exe(tool_name, target_compiler.host));
1197        ToolBuildResult { tool_path: path, build_compiler, target_compiler }
1198    } else {
1199        ToolBuildResult { tool_path, build_compiler, target_compiler }
1200    }
1201}
1202
1203tool_extended!(Cargofmt {
1204    path: "src/tools/rustfmt",
1205    tool_name: "cargo-fmt",
1206    stable: true,
1207    add_bins_to_sysroot: ["cargo-fmt"]
1208});
1209tool_extended!(CargoClippy {
1210    path: "src/tools/clippy",
1211    tool_name: "cargo-clippy",
1212    stable: true,
1213    add_bins_to_sysroot: ["cargo-clippy"]
1214});
1215tool_extended!(Clippy {
1216    path: "src/tools/clippy",
1217    tool_name: "clippy-driver",
1218    stable: true,
1219    add_bins_to_sysroot: ["clippy-driver"]
1220});
1221tool_extended!(Miri {
1222    path: "src/tools/miri",
1223    tool_name: "miri",
1224    stable: false,
1225    add_bins_to_sysroot: ["miri"]
1226});
1227tool_extended!(CargoMiri {
1228    path: "src/tools/miri/cargo-miri",
1229    tool_name: "cargo-miri",
1230    stable: false,
1231    add_bins_to_sysroot: ["cargo-miri"]
1232});
1233tool_extended!(Rustfmt {
1234    path: "src/tools/rustfmt",
1235    tool_name: "rustfmt",
1236    stable: true,
1237    add_bins_to_sysroot: ["rustfmt"]
1238});
1239
1240#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1241pub struct TestFloatParse {
1242    pub host: TargetSelection,
1243}
1244
1245impl Step for TestFloatParse {
1246    type Output = ToolBuildResult;
1247    const ONLY_HOSTS: bool = true;
1248    const DEFAULT: bool = false;
1249
1250    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1251        run.path("src/etc/test-float-parse")
1252    }
1253
1254    fn run(self, builder: &Builder<'_>) -> ToolBuildResult {
1255        let bootstrap_host = builder.config.build;
1256        let compiler = builder.compiler(builder.top_stage, bootstrap_host);
1257
1258        builder.ensure(ToolBuild {
1259            compiler,
1260            target: bootstrap_host,
1261            tool: "test-float-parse",
1262            mode: Mode::ToolStd,
1263            path: "src/etc/test-float-parse",
1264            source_type: SourceType::InTree,
1265            extra_features: Vec::new(),
1266            allow_features: "",
1267            cargo_args: Vec::new(),
1268            artifact_kind: ToolArtifactKind::Binary,
1269        })
1270    }
1271}
1272
1273impl Builder<'_> {
1274    /// Gets a `BootstrapCommand` which is ready to run `tool` in `stage` built for
1275    /// `host`.
1276    pub fn tool_cmd(&self, tool: Tool) -> BootstrapCommand {
1277        let mut cmd = command(self.tool_exe(tool));
1278        let compiler = self.compiler(0, self.config.build);
1279        let host = &compiler.host;
1280        // Prepares the `cmd` provided to be able to run the `compiler` provided.
1281        //
1282        // Notably this munges the dynamic library lookup path to point to the
1283        // right location to run `compiler`.
1284        let mut lib_paths: Vec<PathBuf> = vec![
1285            self.build.rustc_snapshot_libdir(),
1286            self.cargo_out(compiler, Mode::ToolBootstrap, *host).join("deps"),
1287        ];
1288
1289        // On MSVC a tool may invoke a C compiler (e.g., compiletest in run-make
1290        // mode) and that C compiler may need some extra PATH modification. Do
1291        // so here.
1292        if compiler.host.is_msvc() {
1293            let curpaths = env::var_os("PATH").unwrap_or_default();
1294            let curpaths = env::split_paths(&curpaths).collect::<Vec<_>>();
1295            for (k, v) in self.cc.borrow()[&compiler.host].env() {
1296                if k != "PATH" {
1297                    continue;
1298                }
1299                for path in env::split_paths(v) {
1300                    if !curpaths.contains(&path) {
1301                        lib_paths.push(path);
1302                    }
1303                }
1304            }
1305        }
1306
1307        add_dylib_path(lib_paths, &mut cmd);
1308
1309        // Provide a RUSTC for this command to use.
1310        cmd.env("RUSTC", &self.initial_rustc);
1311
1312        cmd
1313    }
1314}