]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/tool.rs
bootstrap: convert reproducible-artifacts to use Tarball
[rust.git] / src / bootstrap / tool.rs
1 use std::collections::HashSet;
2 use std::env;
3 use std::fs;
4 use std::path::PathBuf;
5 use std::process::{exit, Command};
6
7 use build_helper::t;
8
9 use crate::builder::{Builder, Cargo as CargoCommand, RunConfig, ShouldRun, Step};
10 use crate::channel::GitInfo;
11 use crate::compile;
12 use crate::config::TargetSelection;
13 use crate::toolstate::ToolState;
14 use crate::util::{add_dylib_path, exe};
15 use crate::Compiler;
16 use crate::Mode;
17
18 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
19 pub enum SourceType {
20     InTree,
21     Submodule,
22 }
23
24 #[derive(Debug, Clone, Hash, PartialEq, Eq)]
25 struct ToolBuild {
26     compiler: Compiler,
27     target: TargetSelection,
28     tool: &'static str,
29     path: &'static str,
30     mode: Mode,
31     is_optional_tool: bool,
32     source_type: SourceType,
33     extra_features: Vec<String>,
34 }
35
36 impl Step for ToolBuild {
37     type Output = Option<PathBuf>;
38
39     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
40         run.never()
41     }
42
43     /// Builds a tool in `src/tools`
44     ///
45     /// This will build the specified tool with the specified `host` compiler in
46     /// `stage` into the normal cargo output directory.
47     fn run(self, builder: &Builder<'_>) -> Option<PathBuf> {
48         let compiler = self.compiler;
49         let target = self.target;
50         let tool = self.tool;
51         let path = self.path;
52         let is_optional_tool = self.is_optional_tool;
53
54         match self.mode {
55             Mode::ToolRustc => builder.ensure(compile::Rustc { compiler, target }),
56             Mode::ToolStd => builder.ensure(compile::Std { compiler, target }),
57             Mode::ToolBootstrap => {} // uses downloaded stage0 compiler libs
58             _ => panic!("unexpected Mode for tool build"),
59         }
60
61         let cargo = prepare_tool_cargo(
62             builder,
63             compiler,
64             self.mode,
65             target,
66             "build",
67             path,
68             self.source_type,
69             &self.extra_features,
70         );
71
72         builder.info(&format!("Building stage{} tool {} ({})", compiler.stage, tool, target));
73         let mut duplicates = Vec::new();
74         let is_expected = compile::stream_cargo(builder, cargo, vec![], &mut |msg| {
75             // Only care about big things like the RLS/Cargo for now
76             match tool {
77                 "rls" | "cargo" | "clippy-driver" | "miri" | "rustfmt" => {}
78
79                 _ => return,
80             }
81             let (id, features, filenames) = match msg {
82                 compile::CargoMessage::CompilerArtifact {
83                     package_id,
84                     features,
85                     filenames,
86                     target: _,
87                 } => (package_id, features, filenames),
88                 _ => return,
89             };
90             let features = features.iter().map(|s| s.to_string()).collect::<Vec<_>>();
91
92             for path in filenames {
93                 let val = (tool, PathBuf::from(&*path), features.clone());
94                 // we're only interested in deduplicating rlibs for now
95                 if val.1.extension().and_then(|s| s.to_str()) != Some("rlib") {
96                     continue;
97                 }
98
99                 // Don't worry about compiles that turn out to be host
100                 // dependencies or build scripts. To skip these we look for
101                 // anything that goes in `.../release/deps` but *doesn't* go in
102                 // `$target/release/deps`. This ensure that outputs in
103                 // `$target/release` are still considered candidates for
104                 // deduplication.
105                 if let Some(parent) = val.1.parent() {
106                     if parent.ends_with("release/deps") {
107                         let maybe_target = parent
108                             .parent()
109                             .and_then(|p| p.parent())
110                             .and_then(|p| p.file_name())
111                             .and_then(|p| p.to_str())
112                             .unwrap();
113                         if maybe_target != &*target.triple {
114                             continue;
115                         }
116                     }
117                 }
118
119                 // Record that we've built an artifact for `id`, and if one was
120                 // already listed then we need to see if we reused the same
121                 // artifact or produced a duplicate.
122                 let mut artifacts = builder.tool_artifacts.borrow_mut();
123                 let prev_artifacts = artifacts.entry(target).or_default();
124                 let prev = match prev_artifacts.get(&*id) {
125                     Some(prev) => prev,
126                     None => {
127                         prev_artifacts.insert(id.to_string(), val);
128                         continue;
129                     }
130                 };
131                 if prev.1 == val.1 {
132                     return; // same path, same artifact
133                 }
134
135                 // If the paths are different and one of them *isn't* inside of
136                 // `release/deps`, then it means it's probably in
137                 // `$target/release`, or it's some final artifact like
138                 // `libcargo.rlib`. In these situations Cargo probably just
139                 // copied it up from `$target/release/deps/libcargo-xxxx.rlib`,
140                 // so if the features are equal we can just skip it.
141                 let prev_no_hash = prev.1.parent().unwrap().ends_with("release/deps");
142                 let val_no_hash = val.1.parent().unwrap().ends_with("release/deps");
143                 if prev.2 == val.2 || !prev_no_hash || !val_no_hash {
144                     return;
145                 }
146
147                 // ... and otherwise this looks like we duplicated some sort of
148                 // compilation, so record it to generate an error later.
149                 duplicates.push((id.to_string(), val, prev.clone()));
150             }
151         });
152
153         if is_expected && !duplicates.is_empty() {
154             println!(
155                 "duplicate artifacts found when compiling a tool, this \
156                       typically means that something was recompiled because \
157                       a transitive dependency has different features activated \
158                       than in a previous build:\n"
159             );
160             println!(
161                 "the following dependencies are duplicated although they \
162                       have the same features enabled:"
163             );
164             let (same, different): (Vec<_>, Vec<_>) =
165                 duplicates.into_iter().partition(|(_, cur, prev)| cur.2 == prev.2);
166             for (id, cur, prev) in same {
167                 println!("  {}", id);
168                 // same features
169                 println!("    `{}` ({:?})\n    `{}` ({:?})", cur.0, cur.1, prev.0, prev.1);
170             }
171             println!("the following dependencies have different features:");
172             for (id, cur, prev) in different {
173                 println!("  {}", id);
174                 let cur_features: HashSet<_> = cur.2.into_iter().collect();
175                 let prev_features: HashSet<_> = prev.2.into_iter().collect();
176                 println!(
177                     "    `{}` additionally enabled features {:?} at {:?}",
178                     cur.0,
179                     &cur_features - &prev_features,
180                     cur.1
181                 );
182                 println!(
183                     "    `{}` additionally enabled features {:?} at {:?}",
184                     prev.0,
185                     &prev_features - &cur_features,
186                     prev.1
187                 );
188             }
189             println!();
190             println!(
191                 "to fix this you will probably want to edit the local \
192                       src/tools/rustc-workspace-hack/Cargo.toml crate, as \
193                       that will update the dependency graph to ensure that \
194                       these crates all share the same feature set"
195             );
196             panic!("tools should not compile multiple copies of the same crate");
197         }
198
199         builder.save_toolstate(
200             tool,
201             if is_expected { ToolState::TestFail } else { ToolState::BuildFail },
202         );
203
204         if !is_expected {
205             if !is_optional_tool {
206                 exit(1);
207             } else {
208                 None
209             }
210         } else {
211             let cargo_out =
212                 builder.cargo_out(compiler, self.mode, target).join(exe(tool, compiler.host));
213             let bin = builder.tools_dir(compiler).join(exe(tool, compiler.host));
214             builder.copy(&cargo_out, &bin);
215             Some(bin)
216         }
217     }
218 }
219
220 pub fn prepare_tool_cargo(
221     builder: &Builder<'_>,
222     compiler: Compiler,
223     mode: Mode,
224     target: TargetSelection,
225     command: &'static str,
226     path: &'static str,
227     source_type: SourceType,
228     extra_features: &[String],
229 ) -> CargoCommand {
230     let mut cargo = builder.cargo(compiler, mode, source_type, target, command);
231     let dir = builder.src.join(path);
232     cargo.arg("--manifest-path").arg(dir.join("Cargo.toml"));
233
234     let mut features = extra_features.to_vec();
235     if builder.build.config.cargo_native_static {
236         if path.ends_with("cargo")
237             || path.ends_with("rls")
238             || path.ends_with("clippy")
239             || path.ends_with("miri")
240             || path.ends_with("rustfmt")
241         {
242             cargo.env("LIBZ_SYS_STATIC", "1");
243             features.push("rustc-workspace-hack/all-static".to_string());
244         }
245     }
246
247     // if tools are using lzma we want to force the build script to build its
248     // own copy
249     cargo.env("LZMA_API_STATIC", "1");
250
251     // CFG_RELEASE is needed by rustfmt (and possibly other tools) which
252     // import rustc-ap-rustc_attr which requires this to be set for the
253     // `#[cfg(version(...))]` attribute.
254     cargo.env("CFG_RELEASE", builder.rust_release());
255     cargo.env("CFG_RELEASE_CHANNEL", &builder.config.channel);
256     cargo.env("CFG_VERSION", builder.rust_version());
257     cargo.env("CFG_RELEASE_NUM", &builder.version);
258
259     let info = GitInfo::new(builder.config.ignore_git, &dir);
260     if let Some(sha) = info.sha() {
261         cargo.env("CFG_COMMIT_HASH", sha);
262     }
263     if let Some(sha_short) = info.sha_short() {
264         cargo.env("CFG_SHORT_COMMIT_HASH", sha_short);
265     }
266     if let Some(date) = info.commit_date() {
267         cargo.env("CFG_COMMIT_DATE", date);
268     }
269     if !features.is_empty() {
270         cargo.arg("--features").arg(&features.join(", "));
271     }
272     cargo
273 }
274
275 macro_rules! bootstrap_tool {
276     ($(
277         $name:ident, $path:expr, $tool_name:expr
278         $(,is_external_tool = $external:expr)*
279         $(,is_unstable_tool = $unstable:expr)*
280         $(,features = $features:expr)*
281         ;
282     )+) => {
283         #[derive(Copy, PartialEq, Eq, Clone)]
284         pub enum Tool {
285             $(
286                 $name,
287             )+
288         }
289
290         impl<'a> Builder<'a> {
291             pub fn tool_exe(&self, tool: Tool) -> PathBuf {
292                 match tool {
293                     $(Tool::$name =>
294                         self.ensure($name {
295                             compiler: self.compiler(0, self.config.build),
296                             target: self.config.build,
297                         }),
298                     )+
299                 }
300             }
301         }
302
303         $(
304             #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
305         pub struct $name {
306             pub compiler: Compiler,
307             pub target: TargetSelection,
308         }
309
310         impl Step for $name {
311             type Output = PathBuf;
312
313             fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
314                 run.path($path)
315             }
316
317             fn make_run(run: RunConfig<'_>) {
318                 run.builder.ensure($name {
319                     // snapshot compiler
320                     compiler: run.builder.compiler(0, run.builder.config.build),
321                     target: run.target,
322                 });
323             }
324
325             fn run(self, builder: &Builder<'_>) -> PathBuf {
326                 builder.ensure(ToolBuild {
327                     compiler: self.compiler,
328                     target: self.target,
329                     tool: $tool_name,
330                     mode: if false $(|| $unstable)* {
331                         // use in-tree libraries for unstable features
332                         Mode::ToolStd
333                     } else {
334                         Mode::ToolBootstrap
335                     },
336                     path: $path,
337                     is_optional_tool: false,
338                     source_type: if false $(|| $external)* {
339                         SourceType::Submodule
340                     } else {
341                         SourceType::InTree
342                     },
343                     extra_features: {
344                         // FIXME(#60643): avoid this lint by using `_`
345                         let mut _tmp = Vec::new();
346                         $(_tmp.extend($features);)*
347                         _tmp
348                     },
349                 }).expect("expected to build -- essential tool")
350             }
351         }
352         )+
353     }
354 }
355
356 bootstrap_tool!(
357     Rustbook, "src/tools/rustbook", "rustbook";
358     UnstableBookGen, "src/tools/unstable-book-gen", "unstable-book-gen";
359     Tidy, "src/tools/tidy", "tidy";
360     Linkchecker, "src/tools/linkchecker", "linkchecker";
361     CargoTest, "src/tools/cargotest", "cargotest";
362     Compiletest, "src/tools/compiletest", "compiletest", is_unstable_tool = true;
363     BuildManifest, "src/tools/build-manifest", "build-manifest";
364     RemoteTestClient, "src/tools/remote-test-client", "remote-test-client";
365     RustDemangler, "src/tools/rust-demangler", "rust-demangler";
366     RustInstaller, "src/tools/rust-installer", "fabricate", is_external_tool = true;
367     RustdocTheme, "src/tools/rustdoc-themes", "rustdoc-themes";
368     ExpandYamlAnchors, "src/tools/expand-yaml-anchors", "expand-yaml-anchors";
369     LintDocs, "src/tools/lint-docs", "lint-docs";
370 );
371
372 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq, Ord, PartialOrd)]
373 pub struct ErrorIndex {
374     pub compiler: Compiler,
375 }
376
377 impl ErrorIndex {
378     pub fn command(builder: &Builder<'_>, compiler: Compiler) -> Command {
379         let mut cmd = Command::new(builder.ensure(ErrorIndex { compiler }));
380         add_dylib_path(
381             vec![PathBuf::from(&builder.sysroot_libdir(compiler, compiler.host))],
382             &mut cmd,
383         );
384         cmd
385     }
386 }
387
388 impl Step for ErrorIndex {
389     type Output = PathBuf;
390
391     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
392         run.path("src/tools/error_index_generator")
393     }
394
395     fn make_run(run: RunConfig<'_>) {
396         // Compile the error-index in the same stage as rustdoc to avoid
397         // recompiling rustdoc twice if we can.
398         let host = run.builder.config.build;
399         let compiler = run.builder.compiler_for(run.builder.top_stage, host, host);
400         run.builder.ensure(ErrorIndex { compiler });
401     }
402
403     fn run(self, builder: &Builder<'_>) -> PathBuf {
404         builder
405             .ensure(ToolBuild {
406                 compiler: self.compiler,
407                 target: self.compiler.host,
408                 tool: "error_index_generator",
409                 mode: Mode::ToolRustc,
410                 path: "src/tools/error_index_generator",
411                 is_optional_tool: false,
412                 source_type: SourceType::InTree,
413                 extra_features: Vec::new(),
414             })
415             .expect("expected to build -- essential tool")
416     }
417 }
418
419 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
420 pub struct RemoteTestServer {
421     pub compiler: Compiler,
422     pub target: TargetSelection,
423 }
424
425 impl Step for RemoteTestServer {
426     type Output = PathBuf;
427
428     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
429         run.path("src/tools/remote-test-server")
430     }
431
432     fn make_run(run: RunConfig<'_>) {
433         run.builder.ensure(RemoteTestServer {
434             compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
435             target: run.target,
436         });
437     }
438
439     fn run(self, builder: &Builder<'_>) -> PathBuf {
440         builder
441             .ensure(ToolBuild {
442                 compiler: self.compiler,
443                 target: self.target,
444                 tool: "remote-test-server",
445                 mode: Mode::ToolStd,
446                 path: "src/tools/remote-test-server",
447                 is_optional_tool: false,
448                 source_type: SourceType::InTree,
449                 extra_features: Vec::new(),
450             })
451             .expect("expected to build -- essential tool")
452     }
453 }
454
455 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq, Ord, PartialOrd)]
456 pub struct Rustdoc {
457     /// This should only ever be 0 or 2.
458     /// We sometimes want to reference the "bootstrap" rustdoc, which is why this option is here.
459     pub compiler: Compiler,
460 }
461
462 impl Step for Rustdoc {
463     type Output = PathBuf;
464     const DEFAULT: bool = true;
465     const ONLY_HOSTS: bool = true;
466
467     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
468         run.path("src/tools/rustdoc").path("src/librustdoc")
469     }
470
471     fn make_run(run: RunConfig<'_>) {
472         run.builder.ensure(Rustdoc {
473             // Note: this is somewhat unique in that we actually want a *target*
474             // compiler here, because rustdoc *is* a compiler. We won't be using
475             // this as the compiler to build with, but rather this is "what
476             // compiler are we producing"?
477             compiler: run.builder.compiler(run.builder.top_stage, run.target),
478         });
479     }
480
481     fn run(self, builder: &Builder<'_>) -> PathBuf {
482         let target_compiler = self.compiler;
483         if target_compiler.stage == 0 {
484             if !target_compiler.is_snapshot(builder) {
485                 panic!("rustdoc in stage 0 must be snapshot rustdoc");
486             }
487             return builder.initial_rustc.with_file_name(exe("rustdoc", target_compiler.host));
488         }
489         let target = target_compiler.host;
490         // Similar to `compile::Assemble`, build with the previous stage's compiler. Otherwise
491         // we'd have stageN/bin/rustc and stageN/bin/rustdoc be effectively different stage
492         // compilers, which isn't what we want. Rustdoc should be linked in the same way as the
493         // rustc compiler it's paired with, so it must be built with the previous stage compiler.
494         let build_compiler = builder.compiler(target_compiler.stage - 1, builder.config.build);
495
496         // The presence of `target_compiler` ensures that the necessary libraries (codegen backends,
497         // compiler libraries, ...) are built. Rustdoc does not require the presence of any
498         // libraries within sysroot_libdir (i.e., rustlib), though doctests may want it (since
499         // they'll be linked to those libraries). As such, don't explicitly `ensure` any additional
500         // libraries here. The intuition here is that If we've built a compiler, we should be able
501         // to build rustdoc.
502
503         let cargo = prepare_tool_cargo(
504             builder,
505             build_compiler,
506             Mode::ToolRustc,
507             target,
508             "build",
509             "src/tools/rustdoc",
510             SourceType::InTree,
511             &[],
512         );
513
514         builder.info(&format!(
515             "Building rustdoc for stage{} ({})",
516             target_compiler.stage, target_compiler.host
517         ));
518         builder.run(&mut cargo.into());
519
520         // Cargo adds a number of paths to the dylib search path on windows, which results in
521         // the wrong rustdoc being executed. To avoid the conflicting rustdocs, we name the "tool"
522         // rustdoc a different name.
523         let tool_rustdoc = builder
524             .cargo_out(build_compiler, Mode::ToolRustc, target)
525             .join(exe("rustdoc_tool_binary", target_compiler.host));
526
527         // don't create a stage0-sysroot/bin directory.
528         if target_compiler.stage > 0 {
529             let sysroot = builder.sysroot(target_compiler);
530             let bindir = sysroot.join("bin");
531             t!(fs::create_dir_all(&bindir));
532             let bin_rustdoc = bindir.join(exe("rustdoc", target_compiler.host));
533             let _ = fs::remove_file(&bin_rustdoc);
534             builder.copy(&tool_rustdoc, &bin_rustdoc);
535             bin_rustdoc
536         } else {
537             tool_rustdoc
538         }
539     }
540 }
541
542 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
543 pub struct Cargo {
544     pub compiler: Compiler,
545     pub target: TargetSelection,
546 }
547
548 impl Step for Cargo {
549     type Output = PathBuf;
550     const DEFAULT: bool = true;
551     const ONLY_HOSTS: bool = true;
552
553     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
554         let builder = run.builder;
555         run.path("src/tools/cargo").default_condition(builder.config.extended)
556     }
557
558     fn make_run(run: RunConfig<'_>) {
559         run.builder.ensure(Cargo {
560             compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
561             target: run.target,
562         });
563     }
564
565     fn run(self, builder: &Builder<'_>) -> PathBuf {
566         let cargo_bin_path = builder
567             .ensure(ToolBuild {
568                 compiler: self.compiler,
569                 target: self.target,
570                 tool: "cargo",
571                 mode: Mode::ToolRustc,
572                 path: "src/tools/cargo",
573                 is_optional_tool: false,
574                 source_type: SourceType::Submodule,
575                 extra_features: Vec::new(),
576             })
577             .expect("expected to build -- essential tool");
578
579         let build_cred = |name, path| {
580             // These credential helpers are currently experimental.
581             // Any build failures will be ignored.
582             let _ = builder.ensure(ToolBuild {
583                 compiler: self.compiler,
584                 target: self.target,
585                 tool: name,
586                 mode: Mode::ToolRustc,
587                 path,
588                 is_optional_tool: true,
589                 source_type: SourceType::Submodule,
590                 extra_features: Vec::new(),
591             });
592         };
593
594         if self.target.contains("windows") {
595             build_cred(
596                 "cargo-credential-wincred",
597                 "src/tools/cargo/crates/credential/cargo-credential-wincred",
598             );
599         }
600         if self.target.contains("apple-darwin") {
601             build_cred(
602                 "cargo-credential-macos-keychain",
603                 "src/tools/cargo/crates/credential/cargo-credential-macos-keychain",
604             );
605         }
606         build_cred(
607             "cargo-credential-1password",
608             "src/tools/cargo/crates/credential/cargo-credential-1password",
609         );
610         cargo_bin_path
611     }
612 }
613
614 macro_rules! tool_extended {
615     (($sel:ident, $builder:ident),
616        $($name:ident,
617        $toolstate:ident,
618        $path:expr,
619        $tool_name:expr,
620        stable = $stable:expr,
621        $(in_tree = $in_tree:expr,)*
622        $extra_deps:block;)+) => {
623         $(
624             #[derive(Debug, Clone, Hash, PartialEq, Eq)]
625         pub struct $name {
626             pub compiler: Compiler,
627             pub target: TargetSelection,
628             pub extra_features: Vec<String>,
629         }
630
631         impl Step for $name {
632             type Output = Option<PathBuf>;
633             const DEFAULT: bool = true; // Overwritten below
634             const ONLY_HOSTS: bool = true;
635
636             fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
637                 let builder = run.builder;
638                 run.path($path).default_condition(
639                     builder.config.extended
640                         && builder.config.tools.as_ref().map_or(
641                             // By default, on nightly/dev enable all tools, else only
642                             // build stable tools.
643                             $stable || builder.build.unstable_features(),
644                             // If `tools` is set, search list for this tool.
645                             |tools| {
646                                 tools.iter().any(|tool| match tool.as_ref() {
647                                     "clippy" => $tool_name == "clippy-driver",
648                                     x => $tool_name == x,
649                             })
650                         }),
651                 )
652             }
653
654             fn make_run(run: RunConfig<'_>) {
655                 run.builder.ensure($name {
656                     compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
657                     target: run.target,
658                     extra_features: Vec::new(),
659                 });
660             }
661
662             #[allow(unused_mut)]
663             fn run(mut $sel, $builder: &Builder<'_>) -> Option<PathBuf> {
664                 $extra_deps
665                 $builder.ensure(ToolBuild {
666                     compiler: $sel.compiler,
667                     target: $sel.target,
668                     tool: $tool_name,
669                     mode: Mode::ToolRustc,
670                     path: $path,
671                     extra_features: $sel.extra_features,
672                     is_optional_tool: true,
673                     source_type: if false $(|| $in_tree)* {
674                         SourceType::InTree
675                     } else {
676                         SourceType::Submodule
677                     },
678                 })
679             }
680         }
681         )+
682     }
683 }
684
685 // Note: tools need to be also added to `Builder::get_step_descriptions` in `builder.rs`
686 // to make `./x.py build <tool>` work.
687 tool_extended!((self, builder),
688     Cargofmt, rustfmt, "src/tools/rustfmt", "cargo-fmt", stable=true, {};
689     CargoClippy, clippy, "src/tools/clippy", "cargo-clippy", stable=true, in_tree=true, {};
690     Clippy, clippy, "src/tools/clippy", "clippy-driver", stable=true, in_tree=true, {};
691     Miri, miri, "src/tools/miri", "miri", stable=false, {};
692     CargoMiri, miri, "src/tools/miri/cargo-miri", "cargo-miri", stable=false, {};
693     Rls, rls, "src/tools/rls", "rls", stable=true, {
694         builder.ensure(Clippy {
695             compiler: self.compiler,
696             target: self.target,
697             extra_features: Vec::new(),
698         });
699         self.extra_features.push("clippy".to_owned());
700     };
701     Rustfmt, rustfmt, "src/tools/rustfmt", "rustfmt", stable=true, {};
702     RustAnalyzer, rust_analyzer, "src/tools/rust-analyzer/crates/rust-analyzer", "rust-analyzer", stable=false, {};
703 );
704
705 impl<'a> Builder<'a> {
706     /// Gets a `Command` which is ready to run `tool` in `stage` built for
707     /// `host`.
708     pub fn tool_cmd(&self, tool: Tool) -> Command {
709         let mut cmd = Command::new(self.tool_exe(tool));
710         let compiler = self.compiler(0, self.config.build);
711         let host = &compiler.host;
712         // Prepares the `cmd` provided to be able to run the `compiler` provided.
713         //
714         // Notably this munges the dynamic library lookup path to point to the
715         // right location to run `compiler`.
716         let mut lib_paths: Vec<PathBuf> = vec![
717             self.build.rustc_snapshot_libdir(),
718             self.cargo_out(compiler, Mode::ToolBootstrap, *host).join("deps"),
719         ];
720
721         // On MSVC a tool may invoke a C compiler (e.g., compiletest in run-make
722         // mode) and that C compiler may need some extra PATH modification. Do
723         // so here.
724         if compiler.host.contains("msvc") {
725             let curpaths = env::var_os("PATH").unwrap_or_default();
726             let curpaths = env::split_paths(&curpaths).collect::<Vec<_>>();
727             for &(ref k, ref v) in self.cc[&compiler.host].env() {
728                 if k != "PATH" {
729                     continue;
730                 }
731                 for path in env::split_paths(v) {
732                     if !curpaths.contains(&path) {
733                         lib_paths.push(path);
734                     }
735                 }
736             }
737         }
738
739         add_dylib_path(lib_paths, &mut cmd);
740
741         // Provide a RUSTC for this command to use.
742         cmd.env("RUSTC", &self.initial_rustc);
743
744         cmd
745     }
746 }