3 use std::path::PathBuf;
4 use std::process::{Command, exit};
5 use std::collections::HashSet;
9 use crate::builder::{Step, RunConfig, ShouldRun, Builder};
10 use crate::util::{exe, add_lib_path};
12 use crate::channel::GitInfo;
14 use crate::cache::Interned;
15 use crate::toolstate::ToolState;
17 #[derive(Debug, Clone, Hash, PartialEq, Eq)]
23 #[derive(Debug, Clone, Hash, PartialEq, Eq)]
26 target: Interned<String>,
30 is_optional_tool: bool,
31 source_type: SourceType,
32 extra_features: Vec<String>,
35 impl Step for ToolBuild {
36 type Output = Option<PathBuf>;
38 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
42 /// Builds a tool in `src/tools`
44 /// This will build the specified tool with the specified `host` compiler in
45 /// `stage` into the normal cargo output directory.
46 fn run(self, builder: &Builder<'_>) -> Option<PathBuf> {
47 let compiler = self.compiler;
48 let target = self.target;
51 let is_optional_tool = self.is_optional_tool;
55 builder.ensure(compile::Rustc { compiler, target })
58 builder.ensure(compile::Std { compiler, target })
60 Mode::ToolBootstrap => {} // uses downloaded stage0 compiler libs
61 _ => panic!("unexpected Mode for tool build")
64 let mut cargo = prepare_tool_cargo(
75 let _folder = builder.fold_output(|| format!("stage{}-{}", compiler.stage, tool));
76 builder.info(&format!("Building stage{} tool {} ({})", compiler.stage, tool, target));
77 let mut duplicates = Vec::new();
78 let is_expected = compile::stream_cargo(builder, &mut cargo, &mut |msg| {
79 // Only care about big things like the RLS/Cargo for now
89 let (id, features, filenames) = match msg {
90 compile::CargoMessage::CompilerArtifact {
96 (package_id, features, filenames)
100 let features = features.iter().map(|s| s.to_string()).collect::<Vec<_>>();
102 for path in filenames {
103 let val = (tool, PathBuf::from(&*path), features.clone());
104 // we're only interested in deduplicating rlibs for now
105 if val.1.extension().and_then(|s| s.to_str()) != Some("rlib") {
109 // Don't worry about libs that turn out to be host dependencies
110 // or build scripts, we only care about target dependencies that
112 if let Some(maybe_target) = val.1
113 .parent() // chop off file name
114 .and_then(|p| p.parent()) // chop off `deps`
115 .and_then(|p| p.parent()) // chop off `release`
116 .and_then(|p| p.file_name())
117 .and_then(|p| p.to_str())
119 if maybe_target != &*target {
124 let mut artifacts = builder.tool_artifacts.borrow_mut();
125 let prev_artifacts = artifacts
128 if let Some(prev) = prev_artifacts.get(&*id) {
138 prev_artifacts.insert(id.to_string(), val);
142 if is_expected && !duplicates.is_empty() {
143 println!("duplicate artifacts found when compiling a tool, this \
144 typically means that something was recompiled because \
145 a transitive dependency has different features activated \
146 than in a previous build:\n");
147 println!("the following dependencies are duplicated although they \
148 have the same features enabled:");
149 for (id, cur, prev) in duplicates.drain_filter(|(_, cur, prev)| cur.2 == prev.2) {
152 println!(" `{}` ({:?})\n `{}` ({:?})", cur.0, cur.1, prev.0, prev.1);
154 println!("the following dependencies have different features:");
155 for (id, cur, prev) in duplicates {
157 let cur_features: HashSet<_> = cur.2.into_iter().collect();
158 let prev_features: HashSet<_> = prev.2.into_iter().collect();
159 println!(" `{}` additionally enabled features {:?} at {:?}",
160 cur.0, &cur_features - &prev_features, cur.1);
161 println!(" `{}` additionally enabled features {:?} at {:?}",
162 prev.0, &prev_features - &cur_features, prev.1);
165 println!("to fix this you will probably want to edit the local \
166 src/tools/rustc-workspace-hack/Cargo.toml crate, as \
167 that will update the dependency graph to ensure that \
168 these crates all share the same feature set");
169 panic!("tools should not compile multiple copies of the same crate");
172 builder.save_toolstate(tool, if is_expected {
179 if !is_optional_tool {
185 let cargo_out = builder.cargo_out(compiler, self.mode, target)
186 .join(exe(tool, &compiler.host));
187 let bin = builder.tools_dir(compiler).join(exe(tool, &compiler.host));
188 builder.copy(&cargo_out, &bin);
194 pub fn prepare_tool_cargo(
195 builder: &Builder<'_>,
198 target: Interned<String>,
199 command: &'static str,
201 source_type: SourceType,
202 extra_features: &[String],
204 let mut cargo = builder.cargo(compiler, mode, target, command);
205 let dir = builder.src.join(path);
206 cargo.arg("--manifest-path").arg(dir.join("Cargo.toml"));
208 // We don't want to build tools dynamically as they'll be running across
209 // stages and such and it's just easier if they're not dynamically linked.
210 cargo.env("RUSTC_NO_PREFER_DYNAMIC", "1");
212 if source_type == SourceType::Submodule {
213 cargo.env("RUSTC_EXTERNAL_TOOL", "1");
216 let mut features = extra_features.iter().cloned().collect::<Vec<_>>();
217 if builder.build.config.cargo_native_static {
218 if path.ends_with("cargo") ||
219 path.ends_with("rls") ||
220 path.ends_with("clippy") ||
221 path.ends_with("miri") ||
222 path.ends_with("rustfmt")
224 cargo.env("LIBZ_SYS_STATIC", "1");
225 features.push("rustc-workspace-hack/all-static".to_string());
229 // if tools are using lzma we want to force the build script to build its
231 cargo.env("LZMA_API_STATIC", "1");
233 cargo.env("CFG_RELEASE_CHANNEL", &builder.config.channel);
234 cargo.env("CFG_VERSION", builder.rust_version());
235 cargo.env("CFG_RELEASE_NUM", channel::CFG_RELEASE_NUM);
237 let info = GitInfo::new(builder.config.ignore_git, &dir);
238 if let Some(sha) = info.sha() {
239 cargo.env("CFG_COMMIT_HASH", sha);
241 if let Some(sha_short) = info.sha_short() {
242 cargo.env("CFG_SHORT_COMMIT_HASH", sha_short);
244 if let Some(date) = info.commit_date() {
245 cargo.env("CFG_COMMIT_DATE", date);
247 if !features.is_empty() {
248 cargo.arg("--features").arg(&features.join(", "));
253 macro_rules! bootstrap_tool {
255 $name:ident, $path:expr, $tool_name:expr
256 $(,llvm_tools = $llvm:expr)*
257 $(,is_external_tool = $external:expr)*
260 #[derive(Copy, PartialEq, Eq, Clone)]
268 pub fn get_mode(&self) -> Mode {
272 /// Whether this tool requires LLVM to run
273 pub fn uses_llvm_tools(&self) -> bool {
275 $(Tool::$name => false $(|| $llvm)*,)+
280 impl<'a> Builder<'a> {
281 pub fn tool_exe(&self, tool: Tool) -> PathBuf {
285 compiler: self.compiler(0, self.config.build),
286 target: self.config.build,
294 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
296 pub compiler: Compiler,
297 pub target: Interned<String>,
300 impl Step for $name {
301 type Output = PathBuf;
303 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
307 fn make_run(run: RunConfig<'_>) {
308 run.builder.ensure($name {
310 compiler: run.builder.compiler(0, run.builder.config.build),
315 fn run(self, builder: &Builder<'_>) -> PathBuf {
316 builder.ensure(ToolBuild {
317 compiler: self.compiler,
320 mode: Mode::ToolBootstrap,
322 is_optional_tool: false,
323 source_type: if false $(|| $external)* {
324 SourceType::Submodule
328 extra_features: Vec::new(),
329 }).expect("expected to build -- essential tool")
337 Rustbook, "src/tools/rustbook", "rustbook";
338 UnstableBookGen, "src/tools/unstable-book-gen", "unstable-book-gen";
339 Tidy, "src/tools/tidy", "tidy";
340 Linkchecker, "src/tools/linkchecker", "linkchecker";
341 CargoTest, "src/tools/cargotest", "cargotest";
342 Compiletest, "src/tools/compiletest", "compiletest", llvm_tools = true;
343 BuildManifest, "src/tools/build-manifest", "build-manifest";
344 RemoteTestClient, "src/tools/remote-test-client", "remote-test-client";
345 RustInstaller, "src/tools/rust-installer", "fabricate", is_external_tool = true;
346 RustdocTheme, "src/tools/rustdoc-themes", "rustdoc-themes";
349 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
350 pub struct ErrorIndex {
351 pub compiler: Compiler,
355 pub fn command(builder: &Builder<'_>, compiler: Compiler) -> Command {
356 let mut cmd = Command::new(builder.ensure(ErrorIndex {
360 vec![PathBuf::from(&builder.sysroot_libdir(compiler, compiler.host))],
367 impl Step for ErrorIndex {
368 type Output = PathBuf;
370 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
371 run.path("src/tools/error_index_generator")
374 fn make_run(run: RunConfig<'_>) {
375 // Compile the error-index in the same stage as rustdoc to avoid
376 // recompiling rustdoc twice if we can.
377 let stage = if run.builder.top_stage >= 2 { run.builder.top_stage } else { 0 };
378 run.builder.ensure(ErrorIndex {
379 compiler: run.builder.compiler(stage, run.builder.config.build),
383 fn run(self, builder: &Builder<'_>) -> PathBuf {
384 builder.ensure(ToolBuild {
385 compiler: self.compiler,
386 target: self.compiler.host,
387 tool: "error_index_generator",
388 mode: Mode::ToolRustc,
389 path: "src/tools/error_index_generator",
390 is_optional_tool: false,
391 source_type: SourceType::InTree,
392 extra_features: Vec::new(),
393 }).expect("expected to build -- essential tool")
397 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
398 pub struct RemoteTestServer {
399 pub compiler: Compiler,
400 pub target: Interned<String>,
403 impl Step for RemoteTestServer {
404 type Output = PathBuf;
406 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
407 run.path("src/tools/remote-test-server")
410 fn make_run(run: RunConfig<'_>) {
411 run.builder.ensure(RemoteTestServer {
412 compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
417 fn run(self, builder: &Builder<'_>) -> PathBuf {
418 builder.ensure(ToolBuild {
419 compiler: self.compiler,
421 tool: "remote-test-server",
423 path: "src/tools/remote-test-server",
424 is_optional_tool: false,
425 source_type: SourceType::InTree,
426 extra_features: Vec::new(),
427 }).expect("expected to build -- essential tool")
431 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
433 /// This should only ever be 0 or 2.
434 /// We sometimes want to reference the "bootstrap" rustdoc, which is why this option is here.
435 pub compiler: Compiler,
438 impl Step for Rustdoc {
439 type Output = PathBuf;
440 const DEFAULT: bool = true;
441 const ONLY_HOSTS: bool = true;
443 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
444 run.path("src/tools/rustdoc")
447 fn make_run(run: RunConfig<'_>) {
448 run.builder.ensure(Rustdoc {
449 compiler: run.builder.compiler(run.builder.top_stage, run.host),
453 fn run(self, builder: &Builder<'_>) -> PathBuf {
454 let target_compiler = self.compiler;
455 if target_compiler.stage == 0 {
456 if !target_compiler.is_snapshot(builder) {
457 panic!("rustdoc in stage 0 must be snapshot rustdoc");
459 return builder.initial_rustc.with_file_name(exe("rustdoc", &target_compiler.host));
461 let target = target_compiler.host;
462 // Similar to `compile::Assemble`, build with the previous stage's compiler. Otherwise
463 // we'd have stageN/bin/rustc and stageN/bin/rustdoc be effectively different stage
464 // compilers, which isn't what we want. Rustdoc should be linked in the same way as the
465 // rustc compiler it's paired with, so it must be built with the previous stage compiler.
466 let build_compiler = builder.compiler(target_compiler.stage - 1, builder.config.build);
468 // The presence of `target_compiler` ensures that the necessary libraries (codegen backends,
469 // compiler libraries, ...) are built. Rustdoc does not require the presence of any
470 // libraries within sysroot_libdir (i.e., rustlib), though doctests may want it (since
471 // they'll be linked to those libraries). As such, don't explicitly `ensure` any additional
472 // libraries here. The intuition here is that If we've built a compiler, we should be able
475 let mut cargo = prepare_tool_cargo(
486 // Most tools don't get debuginfo, but rustdoc should.
487 cargo.env("RUSTC_DEBUGINFO", builder.config.rust_debuginfo.to_string())
488 .env("RUSTC_DEBUGINFO_LINES", builder.config.rust_debuginfo_lines.to_string());
490 let _folder = builder.fold_output(|| format!("stage{}-rustdoc", target_compiler.stage));
491 builder.info(&format!("Building rustdoc for stage{} ({})",
492 target_compiler.stage, target_compiler.host));
493 builder.run(&mut cargo);
495 // Cargo adds a number of paths to the dylib search path on windows, which results in
496 // the wrong rustdoc being executed. To avoid the conflicting rustdocs, we name the "tool"
497 // rustdoc a different name.
498 let tool_rustdoc = builder.cargo_out(build_compiler, Mode::ToolRustc, target)
499 .join(exe("rustdoc_tool_binary", &target_compiler.host));
501 // don't create a stage0-sysroot/bin directory.
502 if target_compiler.stage > 0 {
503 let sysroot = builder.sysroot(target_compiler);
504 let bindir = sysroot.join("bin");
505 t!(fs::create_dir_all(&bindir));
506 let bin_rustdoc = bindir.join(exe("rustdoc", &*target_compiler.host));
507 let _ = fs::remove_file(&bin_rustdoc);
508 builder.copy(&tool_rustdoc, &bin_rustdoc);
516 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
518 pub compiler: Compiler,
519 pub target: Interned<String>,
522 impl Step for Cargo {
523 type Output = PathBuf;
524 const DEFAULT: bool = true;
525 const ONLY_HOSTS: bool = true;
527 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
528 let builder = run.builder;
529 run.path("src/tools/cargo").default_condition(builder.config.extended)
532 fn make_run(run: RunConfig<'_>) {
533 run.builder.ensure(Cargo {
534 compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
539 fn run(self, builder: &Builder<'_>) -> PathBuf {
540 // Cargo depends on procedural macros, which requires a full host
541 // compiler to be available, so we need to depend on that.
542 builder.ensure(compile::Rustc {
543 compiler: self.compiler,
544 target: builder.config.build,
546 builder.ensure(ToolBuild {
547 compiler: self.compiler,
550 mode: Mode::ToolRustc,
551 path: "src/tools/cargo",
552 is_optional_tool: false,
553 source_type: SourceType::Submodule,
554 extra_features: Vec::new(),
555 }).expect("expected to build -- essential tool")
559 macro_rules! tool_extended {
560 (($sel:ident, $builder:ident),
565 $extra_deps:block;)+) => {
567 #[derive(Debug, Clone, Hash, PartialEq, Eq)]
569 pub compiler: Compiler,
570 pub target: Interned<String>,
571 pub extra_features: Vec<String>,
574 impl Step for $name {
575 type Output = Option<PathBuf>;
576 const DEFAULT: bool = true;
577 const ONLY_HOSTS: bool = true;
579 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
580 let builder = run.builder;
581 run.path($path).default_condition(builder.config.extended)
584 fn make_run(run: RunConfig<'_>) {
585 run.builder.ensure($name {
586 compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
588 extra_features: Vec::new(),
593 fn run(mut $sel, $builder: &Builder<'_>) -> Option<PathBuf> {
595 $builder.ensure(ToolBuild {
596 compiler: $sel.compiler,
599 mode: Mode::ToolRustc,
601 extra_features: $sel.extra_features,
602 is_optional_tool: true,
603 source_type: SourceType::Submodule,
611 tool_extended!((self, builder),
612 Cargofmt, rustfmt, "src/tools/rustfmt", "cargo-fmt", {};
613 CargoClippy, clippy, "src/tools/clippy", "cargo-clippy", {
614 // Clippy depends on procedural macros (serde), which requires a full host
615 // compiler to be available, so we need to depend on that.
616 builder.ensure(compile::Rustc {
617 compiler: self.compiler,
618 target: builder.config.build,
621 Clippy, clippy, "src/tools/clippy", "clippy-driver", {
622 // Clippy depends on procedural macros (serde), which requires a full host
623 // compiler to be available, so we need to depend on that.
624 builder.ensure(compile::Rustc {
625 compiler: self.compiler,
626 target: builder.config.build,
629 Miri, miri, "src/tools/miri", "miri", {};
630 CargoMiri, miri, "src/tools/miri", "cargo-miri", {
631 // Miri depends on procedural macros (serde), which requires a full host
632 // compiler to be available, so we need to depend on that.
633 builder.ensure(compile::Rustc {
634 compiler: self.compiler,
635 target: builder.config.build,
638 Rls, rls, "src/tools/rls", "rls", {
639 let clippy = builder.ensure(Clippy {
640 compiler: self.compiler,
642 extra_features: Vec::new(),
644 if clippy.is_some() {
645 self.extra_features.push("clippy".to_owned());
647 // RLS depends on procedural macros, which requires a full host
648 // compiler to be available, so we need to depend on that.
649 builder.ensure(compile::Rustc {
650 compiler: self.compiler,
651 target: builder.config.build,
654 Rustfmt, rustfmt, "src/tools/rustfmt", "rustfmt", {};
657 impl<'a> Builder<'a> {
658 /// Gets a `Command` which is ready to run `tool` in `stage` built for
660 pub fn tool_cmd(&self, tool: Tool) -> Command {
661 let mut cmd = Command::new(self.tool_exe(tool));
662 let compiler = self.compiler(0, self.config.build);
663 self.prepare_tool_cmd(compiler, tool, &mut cmd);
667 /// Prepares the `cmd` provided to be able to run the `compiler` provided.
669 /// Notably this munges the dynamic library lookup path to point to the
670 /// right location to run `compiler`.
671 fn prepare_tool_cmd(&self, compiler: Compiler, tool: Tool, cmd: &mut Command) {
672 let host = &compiler.host;
673 let mut lib_paths: Vec<PathBuf> = vec![
674 if compiler.stage == 0 {
675 self.build.rustc_snapshot_libdir()
677 PathBuf::from(&self.sysroot_libdir(compiler, compiler.host))
679 self.cargo_out(compiler, tool.get_mode(), *host).join("deps"),
682 // On MSVC a tool may invoke a C compiler (e.g., compiletest in run-make
683 // mode) and that C compiler may need some extra PATH modification. Do
685 if compiler.host.contains("msvc") {
686 let curpaths = env::var_os("PATH").unwrap_or_default();
687 let curpaths = env::split_paths(&curpaths).collect::<Vec<_>>();
688 for &(ref k, ref v) in self.cc[&compiler.host].env() {
692 for path in env::split_paths(v) {
693 if !curpaths.contains(&path) {
694 lib_paths.push(path);
700 add_lib_path(lib_paths, cmd);