]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/tool.rs
Rollup merge of #107740 - oli-obk:lock_tcx, r=petrochenkov
[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::Command;
6
7 use crate::builder::{Builder, Cargo as CargoCommand, RunConfig, ShouldRun, Step};
8 use crate::channel::GitInfo;
9 use crate::compile;
10 use crate::config::TargetSelection;
11 use crate::toolstate::ToolState;
12 use crate::util::{add_dylib_path, exe, t};
13 use crate::Compiler;
14 use crate::Mode;
15
16 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
17 pub enum SourceType {
18     InTree,
19     Submodule,
20 }
21
22 #[derive(Debug, Clone, Hash, PartialEq, Eq)]
23 struct ToolBuild {
24     compiler: Compiler,
25     target: TargetSelection,
26     tool: &'static str,
27     path: &'static str,
28     mode: Mode,
29     is_optional_tool: bool,
30     source_type: SourceType,
31     extra_features: Vec<String>,
32     /// Nightly-only features that are allowed (comma-separated list).
33     allow_features: &'static str,
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 mut 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 => {
56                 builder.ensure(compile::Std::new(compiler, compiler.host));
57                 builder.ensure(compile::Rustc::new(compiler, target));
58             }
59             Mode::ToolStd => builder.ensure(compile::Std::new(compiler, target)),
60             Mode::ToolBootstrap => {} // uses downloaded stage0 compiler libs
61             _ => panic!("unexpected Mode for tool build"),
62         }
63
64         let mut cargo = prepare_tool_cargo(
65             builder,
66             compiler,
67             self.mode,
68             target,
69             "build",
70             path,
71             self.source_type,
72             &self.extra_features,
73         );
74         if !self.allow_features.is_empty() {
75             cargo.allow_features(self.allow_features);
76         }
77
78         builder.info(&format!("Building stage{} tool {} ({})", compiler.stage, tool, target));
79         let mut duplicates = Vec::new();
80         let is_expected = compile::stream_cargo(builder, cargo, vec![], &mut |msg| {
81             // Only care about big things like the RLS/Cargo for now
82             match tool {
83                 "rls" | "cargo" | "clippy-driver" | "miri" | "rustfmt" => {}
84
85                 _ => return,
86             }
87             let (id, features, filenames) = match msg {
88                 compile::CargoMessage::CompilerArtifact {
89                     package_id,
90                     features,
91                     filenames,
92                     target: _,
93                 } => (package_id, features, filenames),
94                 _ => return,
95             };
96             let features = features.iter().map(|s| s.to_string()).collect::<Vec<_>>();
97
98             for path in filenames {
99                 let val = (tool, PathBuf::from(&*path), features.clone());
100                 // we're only interested in deduplicating rlibs for now
101                 if val.1.extension().and_then(|s| s.to_str()) != Some("rlib") {
102                     continue;
103                 }
104
105                 // Don't worry about compiles that turn out to be host
106                 // dependencies or build scripts. To skip these we look for
107                 // anything that goes in `.../release/deps` but *doesn't* go in
108                 // `$target/release/deps`. This ensure that outputs in
109                 // `$target/release` are still considered candidates for
110                 // deduplication.
111                 if let Some(parent) = val.1.parent() {
112                     if parent.ends_with("release/deps") {
113                         let maybe_target = parent
114                             .parent()
115                             .and_then(|p| p.parent())
116                             .and_then(|p| p.file_name())
117                             .and_then(|p| p.to_str())
118                             .unwrap();
119                         if maybe_target != &*target.triple {
120                             continue;
121                         }
122                     }
123                 }
124
125                 // Record that we've built an artifact for `id`, and if one was
126                 // already listed then we need to see if we reused the same
127                 // artifact or produced a duplicate.
128                 let mut artifacts = builder.tool_artifacts.borrow_mut();
129                 let prev_artifacts = artifacts.entry(target).or_default();
130                 let prev = match prev_artifacts.get(&*id) {
131                     Some(prev) => prev,
132                     None => {
133                         prev_artifacts.insert(id.to_string(), val);
134                         continue;
135                     }
136                 };
137                 if prev.1 == val.1 {
138                     return; // same path, same artifact
139                 }
140
141                 // If the paths are different and one of them *isn't* inside of
142                 // `release/deps`, then it means it's probably in
143                 // `$target/release`, or it's some final artifact like
144                 // `libcargo.rlib`. In these situations Cargo probably just
145                 // copied it up from `$target/release/deps/libcargo-xxxx.rlib`,
146                 // so if the features are equal we can just skip it.
147                 let prev_no_hash = prev.1.parent().unwrap().ends_with("release/deps");
148                 let val_no_hash = val.1.parent().unwrap().ends_with("release/deps");
149                 if prev.2 == val.2 || !prev_no_hash || !val_no_hash {
150                     return;
151                 }
152
153                 // ... and otherwise this looks like we duplicated some sort of
154                 // compilation, so record it to generate an error later.
155                 duplicates.push((id.to_string(), val, prev.clone()));
156             }
157         });
158
159         if is_expected && !duplicates.is_empty() {
160             eprintln!(
161                 "duplicate artifacts found when compiling a tool, this \
162                       typically means that something was recompiled because \
163                       a transitive dependency has different features activated \
164                       than in a previous build:\n"
165             );
166             let (same, different): (Vec<_>, Vec<_>) =
167                 duplicates.into_iter().partition(|(_, cur, prev)| cur.2 == prev.2);
168             if !same.is_empty() {
169                 eprintln!(
170                     "the following dependencies are duplicated although they \
171                       have the same features enabled:"
172                 );
173                 for (id, cur, prev) in same {
174                     eprintln!("  {}", id);
175                     // same features
176                     eprintln!("    `{}` ({:?})\n    `{}` ({:?})", cur.0, cur.1, prev.0, prev.1);
177                 }
178             }
179             if !different.is_empty() {
180                 eprintln!("the following dependencies have different features:");
181                 for (id, cur, prev) in different {
182                     eprintln!("  {}", id);
183                     let cur_features: HashSet<_> = cur.2.into_iter().collect();
184                     let prev_features: HashSet<_> = prev.2.into_iter().collect();
185                     eprintln!(
186                         "    `{}` additionally enabled features {:?} at {:?}",
187                         cur.0,
188                         &cur_features - &prev_features,
189                         cur.1
190                     );
191                     eprintln!(
192                         "    `{}` additionally enabled features {:?} at {:?}",
193                         prev.0,
194                         &prev_features - &cur_features,
195                         prev.1
196                     );
197                 }
198             }
199             eprintln!();
200             eprintln!(
201                 "to fix this you will probably want to edit the local \
202                       src/tools/rustc-workspace-hack/Cargo.toml crate, as \
203                       that will update the dependency graph to ensure that \
204                       these crates all share the same feature set"
205             );
206             panic!("tools should not compile multiple copies of the same crate");
207         }
208
209         builder.save_toolstate(
210             tool,
211             if is_expected { ToolState::TestFail } else { ToolState::BuildFail },
212         );
213
214         if !is_expected {
215             if !is_optional_tool {
216                 crate::detail_exit(1);
217             } else {
218                 None
219             }
220         } else {
221             // HACK(#82501): on Windows, the tools directory gets added to PATH when running tests, and
222             // compiletest confuses HTML tidy with the in-tree tidy. Name the in-tree tidy something
223             // different so the problem doesn't come up.
224             if tool == "tidy" {
225                 tool = "rust-tidy";
226             }
227             let cargo_out = builder.cargo_out(compiler, self.mode, target).join(exe(tool, target));
228             let bin = builder.tools_dir(compiler).join(exe(tool, target));
229             builder.copy(&cargo_out, &bin);
230             Some(bin)
231         }
232     }
233 }
234
235 pub fn prepare_tool_cargo(
236     builder: &Builder<'_>,
237     compiler: Compiler,
238     mode: Mode,
239     target: TargetSelection,
240     command: &'static str,
241     path: &'static str,
242     source_type: SourceType,
243     extra_features: &[String],
244 ) -> CargoCommand {
245     let mut cargo = builder.cargo(compiler, mode, source_type, target, command);
246     let dir = builder.src.join(path);
247     cargo.arg("--manifest-path").arg(dir.join("Cargo.toml"));
248
249     let mut features = extra_features.to_vec();
250     if builder.build.config.cargo_native_static {
251         if path.ends_with("cargo")
252             || path.ends_with("rls")
253             || path.ends_with("clippy")
254             || path.ends_with("miri")
255             || path.ends_with("rustfmt")
256         {
257             cargo.env("LIBZ_SYS_STATIC", "1");
258             features.push("rustc-workspace-hack/all-static".to_string());
259         }
260     }
261
262     // clippy tests need to know about the stage sysroot. Set them consistently while building to
263     // avoid rebuilding when running tests.
264     cargo.env("SYSROOT", builder.sysroot(compiler));
265
266     // if tools are using lzma we want to force the build script to build its
267     // own copy
268     cargo.env("LZMA_API_STATIC", "1");
269
270     // CFG_RELEASE is needed by rustfmt (and possibly other tools) which
271     // import rustc-ap-rustc_attr which requires this to be set for the
272     // `#[cfg(version(...))]` attribute.
273     cargo.env("CFG_RELEASE", builder.rust_release());
274     cargo.env("CFG_RELEASE_CHANNEL", &builder.config.channel);
275     cargo.env("CFG_VERSION", builder.rust_version());
276     cargo.env("CFG_RELEASE_NUM", &builder.version);
277     cargo.env("DOC_RUST_LANG_ORG_CHANNEL", builder.doc_rust_lang_org_channel());
278
279     let info = GitInfo::new(builder.config.ignore_git, &dir);
280     if let Some(sha) = info.sha() {
281         cargo.env("CFG_COMMIT_HASH", sha);
282     }
283     if let Some(sha_short) = info.sha_short() {
284         cargo.env("CFG_SHORT_COMMIT_HASH", sha_short);
285     }
286     if let Some(date) = info.commit_date() {
287         cargo.env("CFG_COMMIT_DATE", date);
288     }
289     if !features.is_empty() {
290         cargo.arg("--features").arg(&features.join(", "));
291     }
292     cargo
293 }
294
295 macro_rules! bootstrap_tool {
296     ($(
297         $name:ident, $path:expr, $tool_name:expr
298         $(,is_external_tool = $external:expr)*
299         $(,is_unstable_tool = $unstable:expr)*
300         $(,allow_features = $allow_features:expr)?
301         ;
302     )+) => {
303         #[derive(Copy, PartialEq, Eq, Clone)]
304         pub enum Tool {
305             $(
306                 $name,
307             )+
308         }
309
310         impl<'a> Builder<'a> {
311             pub fn tool_exe(&self, tool: Tool) -> PathBuf {
312                 match tool {
313                     $(Tool::$name =>
314                         self.ensure($name {
315                             compiler: self.compiler(0, self.config.build),
316                             target: self.config.build,
317                         }),
318                     )+
319                 }
320             }
321         }
322
323         $(
324             #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
325         pub struct $name {
326             pub compiler: Compiler,
327             pub target: TargetSelection,
328         }
329
330         impl Step for $name {
331             type Output = PathBuf;
332
333             fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
334                 run.path($path)
335             }
336
337             fn make_run(run: RunConfig<'_>) {
338                 run.builder.ensure($name {
339                     // snapshot compiler
340                     compiler: run.builder.compiler(0, run.builder.config.build),
341                     target: run.target,
342                 });
343             }
344
345             fn run(self, builder: &Builder<'_>) -> PathBuf {
346                 builder.ensure(ToolBuild {
347                     compiler: self.compiler,
348                     target: self.target,
349                     tool: $tool_name,
350                     mode: if false $(|| $unstable)* {
351                         // use in-tree libraries for unstable features
352                         Mode::ToolStd
353                     } else {
354                         Mode::ToolBootstrap
355                     },
356                     path: $path,
357                     is_optional_tool: false,
358                     source_type: if false $(|| $external)* {
359                         SourceType::Submodule
360                     } else {
361                         SourceType::InTree
362                     },
363                     extra_features: vec![],
364                     allow_features: concat!($($allow_features)*),
365                 }).expect("expected to build -- essential tool")
366             }
367         }
368         )+
369     }
370 }
371
372 bootstrap_tool!(
373     Rustbook, "src/tools/rustbook", "rustbook";
374     UnstableBookGen, "src/tools/unstable-book-gen", "unstable-book-gen";
375     Tidy, "src/tools/tidy", "tidy";
376     Linkchecker, "src/tools/linkchecker", "linkchecker";
377     CargoTest, "src/tools/cargotest", "cargotest";
378     Compiletest, "src/tools/compiletest", "compiletest", is_unstable_tool = true, allow_features = "test";
379     BuildManifest, "src/tools/build-manifest", "build-manifest";
380     RemoteTestClient, "src/tools/remote-test-client", "remote-test-client";
381     RustInstaller, "src/tools/rust-installer", "rust-installer", is_external_tool = true;
382     RustdocTheme, "src/tools/rustdoc-themes", "rustdoc-themes";
383     ExpandYamlAnchors, "src/tools/expand-yaml-anchors", "expand-yaml-anchors";
384     LintDocs, "src/tools/lint-docs", "lint-docs";
385     JsonDocCk, "src/tools/jsondocck", "jsondocck";
386     JsonDocLint, "src/tools/jsondoclint", "jsondoclint";
387     HtmlChecker, "src/tools/html-checker", "html-checker";
388     BumpStage0, "src/tools/bump-stage0", "bump-stage0";
389     ReplaceVersionPlaceholder, "src/tools/replace-version-placeholder", "replace-version-placeholder";
390     CollectLicenseMetadata, "src/tools/collect-license-metadata", "collect-license-metadata";
391     GenerateCopyright, "src/tools/generate-copyright", "generate-copyright";
392 );
393
394 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq, Ord, PartialOrd)]
395 pub struct ErrorIndex {
396     pub compiler: Compiler,
397 }
398
399 impl ErrorIndex {
400     pub fn command(builder: &Builder<'_>) -> Command {
401         // Error-index-generator links with the rustdoc library, so we need to add `rustc_lib_paths`
402         // for rustc_private and libLLVM.so, and `sysroot_lib` for libstd, etc.
403         let host = builder.config.build;
404         let compiler = builder.compiler_for(builder.top_stage, host, host);
405         let mut cmd = Command::new(builder.ensure(ErrorIndex { compiler }));
406         let mut dylib_paths = builder.rustc_lib_paths(compiler);
407         dylib_paths.push(PathBuf::from(&builder.sysroot_libdir(compiler, compiler.host)));
408         add_dylib_path(dylib_paths, &mut cmd);
409         cmd
410     }
411 }
412
413 impl Step for ErrorIndex {
414     type Output = PathBuf;
415
416     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
417         run.path("src/tools/error_index_generator")
418     }
419
420     fn make_run(run: RunConfig<'_>) {
421         // Compile the error-index in the same stage as rustdoc to avoid
422         // recompiling rustdoc twice if we can.
423         //
424         // NOTE: This `make_run` isn't used in normal situations, only if you
425         // manually build the tool with `x.py build
426         // src/tools/error-index-generator` which almost nobody does.
427         // Normally, `x.py test` or `x.py doc` will use the
428         // `ErrorIndex::command` function instead.
429         let compiler =
430             run.builder.compiler(run.builder.top_stage.saturating_sub(1), run.builder.config.build);
431         run.builder.ensure(ErrorIndex { compiler });
432     }
433
434     fn run(self, builder: &Builder<'_>) -> PathBuf {
435         builder
436             .ensure(ToolBuild {
437                 compiler: self.compiler,
438                 target: self.compiler.host,
439                 tool: "error_index_generator",
440                 mode: Mode::ToolRustc,
441                 path: "src/tools/error_index_generator",
442                 is_optional_tool: false,
443                 source_type: SourceType::InTree,
444                 extra_features: Vec::new(),
445                 allow_features: "",
446             })
447             .expect("expected to build -- essential tool")
448     }
449 }
450
451 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
452 pub struct RemoteTestServer {
453     pub compiler: Compiler,
454     pub target: TargetSelection,
455 }
456
457 impl Step for RemoteTestServer {
458     type Output = PathBuf;
459
460     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
461         run.path("src/tools/remote-test-server")
462     }
463
464     fn make_run(run: RunConfig<'_>) {
465         run.builder.ensure(RemoteTestServer {
466             compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
467             target: run.target,
468         });
469     }
470
471     fn run(self, builder: &Builder<'_>) -> PathBuf {
472         builder
473             .ensure(ToolBuild {
474                 compiler: self.compiler,
475                 target: self.target,
476                 tool: "remote-test-server",
477                 mode: Mode::ToolStd,
478                 path: "src/tools/remote-test-server",
479                 is_optional_tool: false,
480                 source_type: SourceType::InTree,
481                 extra_features: Vec::new(),
482                 allow_features: "",
483             })
484             .expect("expected to build -- essential tool")
485     }
486 }
487
488 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq, Ord, PartialOrd)]
489 pub struct Rustdoc {
490     /// This should only ever be 0 or 2.
491     /// We sometimes want to reference the "bootstrap" rustdoc, which is why this option is here.
492     pub compiler: Compiler,
493 }
494
495 impl Step for Rustdoc {
496     type Output = PathBuf;
497     const DEFAULT: bool = true;
498     const ONLY_HOSTS: bool = true;
499
500     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
501         run.path("src/tools/rustdoc").path("src/librustdoc")
502     }
503
504     fn make_run(run: RunConfig<'_>) {
505         run.builder.ensure(Rustdoc {
506             // Note: this is somewhat unique in that we actually want a *target*
507             // compiler here, because rustdoc *is* a compiler. We won't be using
508             // this as the compiler to build with, but rather this is "what
509             // compiler are we producing"?
510             compiler: run.builder.compiler(run.builder.top_stage, run.target),
511         });
512     }
513
514     fn run(self, builder: &Builder<'_>) -> PathBuf {
515         let target_compiler = self.compiler;
516         if target_compiler.stage == 0 {
517             if !target_compiler.is_snapshot(builder) {
518                 panic!("rustdoc in stage 0 must be snapshot rustdoc");
519             }
520             return builder.initial_rustc.with_file_name(exe("rustdoc", target_compiler.host));
521         }
522         let target = target_compiler.host;
523         // Similar to `compile::Assemble`, build with the previous stage's compiler. Otherwise
524         // we'd have stageN/bin/rustc and stageN/bin/rustdoc be effectively different stage
525         // compilers, which isn't what we want. Rustdoc should be linked in the same way as the
526         // rustc compiler it's paired with, so it must be built with the previous stage compiler.
527         let build_compiler = builder.compiler(target_compiler.stage - 1, builder.config.build);
528
529         // When using `download-rustc` and a stage0 build_compiler, copying rustc doesn't actually
530         // build stage0 libstd (because the libstd in sysroot has the wrong ABI). Explicitly build
531         // it.
532         builder.ensure(compile::Std::new(build_compiler, target_compiler.host));
533         builder.ensure(compile::Rustc::new(build_compiler, target_compiler.host));
534         // NOTE: this implies that `download-rustc` is pretty useless when compiling with the stage0
535         // compiler, since you do just as much work.
536         if !builder.config.dry_run() && builder.download_rustc() && build_compiler.stage == 0 {
537             println!(
538                 "warning: `download-rustc` does nothing when building stage1 tools; consider using `--stage 2` instead"
539             );
540         }
541
542         // The presence of `target_compiler` ensures that the necessary libraries (codegen backends,
543         // compiler libraries, ...) are built. Rustdoc does not require the presence of any
544         // libraries within sysroot_libdir (i.e., rustlib), though doctests may want it (since
545         // they'll be linked to those libraries). As such, don't explicitly `ensure` any additional
546         // libraries here. The intuition here is that If we've built a compiler, we should be able
547         // to build rustdoc.
548         //
549         let mut features = Vec::new();
550         if builder.config.jemalloc {
551             features.push("jemalloc".to_string());
552         }
553
554         let cargo = prepare_tool_cargo(
555             builder,
556             build_compiler,
557             Mode::ToolRustc,
558             target,
559             "build",
560             "src/tools/rustdoc",
561             SourceType::InTree,
562             features.as_slice(),
563         );
564
565         builder.info(&format!(
566             "Building rustdoc for stage{} ({})",
567             target_compiler.stage, target_compiler.host
568         ));
569         builder.run(&mut cargo.into());
570
571         // Cargo adds a number of paths to the dylib search path on windows, which results in
572         // the wrong rustdoc being executed. To avoid the conflicting rustdocs, we name the "tool"
573         // rustdoc a different name.
574         let tool_rustdoc = builder
575             .cargo_out(build_compiler, Mode::ToolRustc, target)
576             .join(exe("rustdoc_tool_binary", target_compiler.host));
577
578         // don't create a stage0-sysroot/bin directory.
579         if target_compiler.stage > 0 {
580             let sysroot = builder.sysroot(target_compiler);
581             let bindir = sysroot.join("bin");
582             t!(fs::create_dir_all(&bindir));
583             let bin_rustdoc = bindir.join(exe("rustdoc", target_compiler.host));
584             let _ = fs::remove_file(&bin_rustdoc);
585             builder.copy(&tool_rustdoc, &bin_rustdoc);
586             bin_rustdoc
587         } else {
588             tool_rustdoc
589         }
590     }
591 }
592
593 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
594 pub struct Cargo {
595     pub compiler: Compiler,
596     pub target: TargetSelection,
597 }
598
599 impl Step for Cargo {
600     type Output = PathBuf;
601     const DEFAULT: bool = true;
602     const ONLY_HOSTS: bool = true;
603
604     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
605         let builder = run.builder;
606         run.path("src/tools/cargo").default_condition(
607             builder.config.extended
608                 && builder.config.tools.as_ref().map_or(
609                     true,
610                     // If `tools` is set, search list for this tool.
611                     |tools| tools.iter().any(|tool| tool == "cargo"),
612                 ),
613         )
614     }
615
616     fn make_run(run: RunConfig<'_>) {
617         run.builder.ensure(Cargo {
618             compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
619             target: run.target,
620         });
621     }
622
623     fn run(self, builder: &Builder<'_>) -> PathBuf {
624         let cargo_bin_path = builder
625             .ensure(ToolBuild {
626                 compiler: self.compiler,
627                 target: self.target,
628                 tool: "cargo",
629                 mode: Mode::ToolRustc,
630                 path: "src/tools/cargo",
631                 is_optional_tool: false,
632                 source_type: SourceType::Submodule,
633                 extra_features: Vec::new(),
634                 allow_features: "",
635             })
636             .expect("expected to build -- essential tool");
637
638         let build_cred = |name, path| {
639             // These credential helpers are currently experimental.
640             // Any build failures will be ignored.
641             let _ = builder.ensure(ToolBuild {
642                 compiler: self.compiler,
643                 target: self.target,
644                 tool: name,
645                 mode: Mode::ToolRustc,
646                 path,
647                 is_optional_tool: true,
648                 source_type: SourceType::Submodule,
649                 extra_features: Vec::new(),
650                 allow_features: "",
651             });
652         };
653
654         if self.target.contains("windows") {
655             build_cred(
656                 "cargo-credential-wincred",
657                 "src/tools/cargo/crates/credential/cargo-credential-wincred",
658             );
659         }
660         if self.target.contains("apple-darwin") {
661             build_cred(
662                 "cargo-credential-macos-keychain",
663                 "src/tools/cargo/crates/credential/cargo-credential-macos-keychain",
664             );
665         }
666         build_cred(
667             "cargo-credential-1password",
668             "src/tools/cargo/crates/credential/cargo-credential-1password",
669         );
670         cargo_bin_path
671     }
672 }
673
674 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
675 pub struct LldWrapper {
676     pub compiler: Compiler,
677     pub target: TargetSelection,
678 }
679
680 impl Step for LldWrapper {
681     type Output = PathBuf;
682
683     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
684         run.never()
685     }
686
687     fn run(self, builder: &Builder<'_>) -> PathBuf {
688         let src_exe = builder
689             .ensure(ToolBuild {
690                 compiler: self.compiler,
691                 target: self.target,
692                 tool: "lld-wrapper",
693                 mode: Mode::ToolStd,
694                 path: "src/tools/lld-wrapper",
695                 is_optional_tool: false,
696                 source_type: SourceType::InTree,
697                 extra_features: Vec::new(),
698                 allow_features: "",
699             })
700             .expect("expected to build -- essential tool");
701
702         src_exe
703     }
704 }
705
706 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
707 pub struct RustAnalyzer {
708     pub compiler: Compiler,
709     pub target: TargetSelection,
710 }
711
712 impl RustAnalyzer {
713     pub const ALLOW_FEATURES: &str =
714         "proc_macro_internals,proc_macro_diagnostic,proc_macro_span,proc_macro_span_shrink";
715 }
716
717 impl Step for RustAnalyzer {
718     type Output = Option<PathBuf>;
719     const DEFAULT: bool = true;
720     const ONLY_HOSTS: bool = true;
721
722     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
723         let builder = run.builder;
724         run.path("src/tools/rust-analyzer").default_condition(
725             builder.config.extended
726                 && builder
727                     .config
728                     .tools
729                     .as_ref()
730                     .map_or(true, |tools| tools.iter().any(|tool| tool == "rust-analyzer")),
731         )
732     }
733
734     fn make_run(run: RunConfig<'_>) {
735         run.builder.ensure(RustAnalyzer {
736             compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
737             target: run.target,
738         });
739     }
740
741     fn run(self, builder: &Builder<'_>) -> Option<PathBuf> {
742         builder.ensure(ToolBuild {
743             compiler: self.compiler,
744             target: self.target,
745             tool: "rust-analyzer",
746             mode: Mode::ToolStd,
747             path: "src/tools/rust-analyzer",
748             extra_features: vec!["rust-analyzer/in-rust-tree".to_owned()],
749             is_optional_tool: false,
750             source_type: SourceType::InTree,
751             allow_features: RustAnalyzer::ALLOW_FEATURES,
752         })
753     }
754 }
755
756 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
757 pub struct RustAnalyzerProcMacroSrv {
758     pub compiler: Compiler,
759     pub target: TargetSelection,
760 }
761
762 impl Step for RustAnalyzerProcMacroSrv {
763     type Output = Option<PathBuf>;
764     const DEFAULT: bool = true;
765     const ONLY_HOSTS: bool = true;
766
767     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
768         let builder = run.builder;
769         // Allow building `rust-analyzer-proc-macro-srv` both as part of the `rust-analyzer` and as a stand-alone tool.
770         run.path("src/tools/rust-analyzer")
771             .path("src/tools/rust-analyzer/crates/proc-macro-srv-cli")
772             .default_condition(builder.config.tools.as_ref().map_or(true, |tools| {
773                 tools
774                     .iter()
775                     .any(|tool| tool == "rust-analyzer" || tool == "rust-analyzer-proc-macro-srv")
776             }))
777     }
778
779     fn make_run(run: RunConfig<'_>) {
780         run.builder.ensure(RustAnalyzerProcMacroSrv {
781             compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
782             target: run.target,
783         });
784     }
785
786     fn run(self, builder: &Builder<'_>) -> Option<PathBuf> {
787         let path = builder.ensure(ToolBuild {
788             compiler: self.compiler,
789             target: self.target,
790             tool: "rust-analyzer-proc-macro-srv",
791             mode: Mode::ToolStd,
792             path: "src/tools/rust-analyzer/crates/proc-macro-srv-cli",
793             extra_features: vec!["proc-macro-srv/sysroot-abi".to_owned()],
794             is_optional_tool: false,
795             source_type: SourceType::InTree,
796             allow_features: RustAnalyzer::ALLOW_FEATURES,
797         })?;
798
799         // Copy `rust-analyzer-proc-macro-srv` to `<sysroot>/libexec/`
800         // so that r-a can use it.
801         let libexec_path = builder.sysroot(self.compiler).join("libexec");
802         t!(fs::create_dir_all(&libexec_path));
803         builder.copy(&path, &libexec_path.join("rust-analyzer-proc-macro-srv"));
804
805         Some(path)
806     }
807 }
808
809 macro_rules! tool_extended {
810     (($sel:ident, $builder:ident),
811        $($name:ident,
812        $path:expr,
813        $tool_name:expr,
814        stable = $stable:expr
815        $(,tool_std = $tool_std:literal)?
816        $(,allow_features = $allow_features:expr)?
817        ;)+) => {
818         $(
819             #[derive(Debug, Clone, Hash, PartialEq, Eq)]
820         pub struct $name {
821             pub compiler: Compiler,
822             pub target: TargetSelection,
823             pub extra_features: Vec<String>,
824         }
825
826         impl Step for $name {
827             type Output = Option<PathBuf>;
828             const DEFAULT: bool = true; // Overwritten below
829             const ONLY_HOSTS: bool = true;
830
831             fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
832                 let builder = run.builder;
833                 run.path($path).default_condition(
834                     builder.config.extended
835                         && builder.config.tools.as_ref().map_or(
836                             // By default, on nightly/dev enable all tools, else only
837                             // build stable tools.
838                             $stable || builder.build.unstable_features(),
839                             // If `tools` is set, search list for this tool.
840                             |tools| {
841                                 tools.iter().any(|tool| match tool.as_ref() {
842                                     "clippy" => $tool_name == "clippy-driver",
843                                     x => $tool_name == x,
844                             })
845                         }),
846                 )
847             }
848
849             fn make_run(run: RunConfig<'_>) {
850                 run.builder.ensure($name {
851                     compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
852                     target: run.target,
853                     extra_features: Vec::new(),
854                 });
855             }
856
857             #[allow(unused_mut)]
858             fn run(mut $sel, $builder: &Builder<'_>) -> Option<PathBuf> {
859                 $builder.ensure(ToolBuild {
860                     compiler: $sel.compiler,
861                     target: $sel.target,
862                     tool: $tool_name,
863                     mode: if false $(|| $tool_std)? { Mode::ToolStd } else { Mode::ToolRustc },
864                     path: $path,
865                     extra_features: $sel.extra_features,
866                     is_optional_tool: true,
867                     source_type: SourceType::InTree,
868                     allow_features: concat!($($allow_features)*),
869                 })
870             }
871         }
872         )+
873     }
874 }
875
876 // Note: tools need to be also added to `Builder::get_step_descriptions` in `builder.rs`
877 // to make `./x.py build <tool>` work.
878 // Note: Most submodule updates for tools are handled by bootstrap.py, since they're needed just to
879 // invoke Cargo to build bootstrap. See the comment there for more details.
880 tool_extended!((self, builder),
881     Cargofmt, "src/tools/rustfmt", "cargo-fmt", stable=true;
882     CargoClippy, "src/tools/clippy", "cargo-clippy", stable=true;
883     Clippy, "src/tools/clippy", "clippy-driver", stable=true;
884     Miri, "src/tools/miri", "miri", stable=false;
885     CargoMiri, "src/tools/miri/cargo-miri", "cargo-miri", stable=true;
886     // FIXME: tool_std is not quite right, we shouldn't allow nightly features.
887     // But `builder.cargo` doesn't know how to handle ToolBootstrap in stages other than 0,
888     // and this is close enough for now.
889     Rls, "src/tools/rls", "rls", stable=true, tool_std=true;
890     RustDemangler, "src/tools/rust-demangler", "rust-demangler", stable=false, tool_std=true;
891     Rustfmt, "src/tools/rustfmt", "rustfmt", stable=true;
892 );
893
894 impl<'a> Builder<'a> {
895     /// Gets a `Command` which is ready to run `tool` in `stage` built for
896     /// `host`.
897     pub fn tool_cmd(&self, tool: Tool) -> Command {
898         let mut cmd = Command::new(self.tool_exe(tool));
899         let compiler = self.compiler(0, self.config.build);
900         let host = &compiler.host;
901         // Prepares the `cmd` provided to be able to run the `compiler` provided.
902         //
903         // Notably this munges the dynamic library lookup path to point to the
904         // right location to run `compiler`.
905         let mut lib_paths: Vec<PathBuf> = vec![
906             self.build.rustc_snapshot_libdir(),
907             self.cargo_out(compiler, Mode::ToolBootstrap, *host).join("deps"),
908         ];
909
910         // On MSVC a tool may invoke a C compiler (e.g., compiletest in run-make
911         // mode) and that C compiler may need some extra PATH modification. Do
912         // so here.
913         if compiler.host.contains("msvc") {
914             let curpaths = env::var_os("PATH").unwrap_or_default();
915             let curpaths = env::split_paths(&curpaths).collect::<Vec<_>>();
916             for &(ref k, ref v) in self.cc[&compiler.host].env() {
917                 if k != "PATH" {
918                     continue;
919                 }
920                 for path in env::split_paths(v) {
921                     if !curpaths.contains(&path) {
922                         lib_paths.push(path);
923                     }
924                 }
925             }
926         }
927
928         add_dylib_path(lib_paths, &mut cmd);
929
930         // Provide a RUSTC for this command to use.
931         cmd.env("RUSTC", &self.initial_rustc);
932
933         cmd
934     }
935 }