3 use std::path::PathBuf;
4 use std::process::{Command, exit};
5 use std::collections::HashSet;
11 use crate::builder::{Step, RunConfig, ShouldRun, Builder};
12 use crate::util::{exe, add_lib_path};
14 use crate::channel::GitInfo;
16 use crate::cache::Interned;
17 use crate::toolstate::ToolState;
19 #[derive(Debug, Clone, Hash, PartialEq, Eq)]
25 #[derive(Debug, Clone, Hash, PartialEq, Eq)]
28 target: Interned<String>,
32 is_optional_tool: bool,
33 source_type: SourceType,
34 extra_features: Vec<String>,
37 impl Step for ToolBuild {
38 type Output = Option<PathBuf>;
40 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
44 /// Builds a tool in `src/tools`
46 /// This will build the specified tool with the specified `host` compiler in
47 /// `stage` into the normal cargo output directory.
48 fn run(self, builder: &Builder<'_>) -> Option<PathBuf> {
49 let compiler = self.compiler;
50 let target = self.target;
53 let is_optional_tool = self.is_optional_tool;
57 builder.ensure(compile::Rustc { compiler, target })
60 builder.ensure(compile::Std { compiler, target })
62 Mode::ToolBootstrap => {} // uses downloaded stage0 compiler libs
63 _ => panic!("unexpected Mode for tool build")
66 let mut cargo = prepare_tool_cargo(
77 let _folder = builder.fold_output(|| format!("stage{}-{}", compiler.stage, tool));
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, &mut cargo, &mut |msg| {
81 // Only care about big things like the RLS/Cargo for now
91 let (id, features, filenames) = match msg {
92 compile::CargoMessage::CompilerArtifact {
98 (package_id, features, filenames)
102 let features = features.iter().map(|s| s.to_string()).collect::<Vec<_>>();
104 for path in filenames {
105 let val = (tool, PathBuf::from(&*path), features.clone());
106 // we're only interested in deduplicating rlibs for now
107 if val.1.extension().and_then(|s| s.to_str()) != Some("rlib") {
111 // Don't worry about libs that turn out to be host dependencies
112 // or build scripts, we only care about target dependencies that
114 if let Some(maybe_target) = val.1
115 .parent() // chop off file name
116 .and_then(|p| p.parent()) // chop off `deps`
117 .and_then(|p| p.parent()) // chop off `release`
118 .and_then(|p| p.file_name())
119 .and_then(|p| p.to_str())
121 if maybe_target != &*target {
126 let mut artifacts = builder.tool_artifacts.borrow_mut();
127 let prev_artifacts = artifacts
130 if let Some(prev) = prev_artifacts.get(&*id) {
140 prev_artifacts.insert(id.to_string(), val);
144 if is_expected && !duplicates.is_empty() {
145 println!("duplicate artifacts found when compiling a tool, this \
146 typically means that something was recompiled because \
147 a transitive dependency has different features activated \
148 than in a previous build:\n");
149 println!("the following dependencies are duplicated although they \
150 have the same features enabled:");
151 for (id, cur, prev) in duplicates.drain_filter(|(_, cur, prev)| cur.2 == prev.2) {
154 println!(" `{}` ({:?})\n `{}` ({:?})", cur.0, cur.1, prev.0, prev.1);
156 println!("the following dependencies have different features:");
157 for (id, cur, prev) in duplicates {
159 let cur_features: HashSet<_> = cur.2.into_iter().collect();
160 let prev_features: HashSet<_> = prev.2.into_iter().collect();
161 println!(" `{}` additionally enabled features {:?} at {:?}",
162 cur.0, &cur_features - &prev_features, cur.1);
163 println!(" `{}` additionally enabled features {:?} at {:?}",
164 prev.0, &prev_features - &cur_features, prev.1);
167 println!("to fix this you will probably want to edit the local \
168 src/tools/rustc-workspace-hack/Cargo.toml crate, as \
169 that will update the dependency graph to ensure that \
170 these crates all share the same feature set");
171 panic!("tools should not compile multiple copies of the same crate");
174 builder.save_toolstate(tool, if is_expected {
181 if !is_optional_tool {
187 let cargo_out = builder.cargo_out(compiler, self.mode, target)
188 .join(exe(tool, &compiler.host));
189 let bin = builder.tools_dir(compiler).join(exe(tool, &compiler.host));
190 builder.copy(&cargo_out, &bin);
196 pub fn prepare_tool_cargo(
197 builder: &Builder<'_>,
200 target: Interned<String>,
201 command: &'static str,
203 source_type: SourceType,
204 extra_features: &[String],
206 let mut cargo = builder.cargo(compiler, mode, target, command);
207 let dir = builder.src.join(path);
208 cargo.arg("--manifest-path").arg(dir.join("Cargo.toml"));
210 // We don't want to build tools dynamically as they'll be running across
211 // stages and such and it's just easier if they're not dynamically linked.
212 cargo.env("RUSTC_NO_PREFER_DYNAMIC", "1");
214 if source_type == SourceType::Submodule {
215 cargo.env("RUSTC_EXTERNAL_TOOL", "1");
218 let mut features = extra_features.iter().cloned().collect::<Vec<_>>();
219 if builder.build.config.cargo_native_static {
220 if path.ends_with("cargo") ||
221 path.ends_with("rls") ||
222 path.ends_with("clippy") ||
223 path.ends_with("miri") ||
224 path.ends_with("rustfmt")
226 cargo.env("LIBZ_SYS_STATIC", "1");
227 features.push("rustc-workspace-hack/all-static".to_string());
231 // if tools are using lzma we want to force the build script to build its
233 cargo.env("LZMA_API_STATIC", "1");
235 cargo.env("CFG_RELEASE_CHANNEL", &builder.config.channel);
236 cargo.env("CFG_VERSION", builder.rust_version());
237 cargo.env("CFG_RELEASE_NUM", channel::CFG_RELEASE_NUM);
239 let info = GitInfo::new(builder.config.ignore_git, &dir);
240 if let Some(sha) = info.sha() {
241 cargo.env("CFG_COMMIT_HASH", sha);
243 if let Some(sha_short) = info.sha_short() {
244 cargo.env("CFG_SHORT_COMMIT_HASH", sha_short);
246 if let Some(date) = info.commit_date() {
247 cargo.env("CFG_COMMIT_DATE", date);
249 if !features.is_empty() {
250 cargo.arg("--features").arg(&features.join(", "));
255 macro_rules! bootstrap_tool {
257 $name:ident, $path:expr, $tool_name:expr
258 $(,llvm_tools = $llvm:expr)*
259 $(,is_external_tool = $external:expr)*
262 #[derive(Copy, PartialEq, Eq, Clone)]
270 pub fn get_mode(&self) -> Mode {
274 /// Whether this tool requires LLVM to run
275 pub fn uses_llvm_tools(&self) -> bool {
277 $(Tool::$name => false $(|| $llvm)*,)+
282 impl<'a> Builder<'a> {
283 pub fn tool_exe(&self, tool: Tool) -> PathBuf {
287 compiler: self.compiler(0, self.config.build),
288 target: self.config.build,
296 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
298 pub compiler: Compiler,
299 pub target: Interned<String>,
302 impl Step for $name {
303 type Output = PathBuf;
305 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
309 fn make_run(run: RunConfig<'_>) {
310 run.builder.ensure($name {
312 compiler: run.builder.compiler(0, run.builder.config.build),
317 fn run(self, builder: &Builder<'_>) -> PathBuf {
318 builder.ensure(ToolBuild {
319 compiler: self.compiler,
322 mode: Mode::ToolBootstrap,
324 is_optional_tool: false,
325 source_type: if false $(|| $external)* {
326 SourceType::Submodule
330 extra_features: Vec::new(),
331 }).expect("expected to build -- essential tool")
339 Rustbook, "src/tools/rustbook", "rustbook";
340 UnstableBookGen, "src/tools/unstable-book-gen", "unstable-book-gen";
341 Tidy, "src/tools/tidy", "tidy";
342 Linkchecker, "src/tools/linkchecker", "linkchecker";
343 CargoTest, "src/tools/cargotest", "cargotest";
344 Compiletest, "src/tools/compiletest", "compiletest", llvm_tools = true;
345 BuildManifest, "src/tools/build-manifest", "build-manifest";
346 RemoteTestClient, "src/tools/remote-test-client", "remote-test-client";
347 RustInstaller, "src/tools/rust-installer", "fabricate", is_external_tool = true;
348 RustdocTheme, "src/tools/rustdoc-themes", "rustdoc-themes";
351 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
352 pub struct ErrorIndex {
353 pub compiler: Compiler,
357 pub fn command(builder: &Builder<'_>, compiler: Compiler) -> Command {
358 let mut cmd = Command::new(builder.ensure(ErrorIndex {
362 vec![PathBuf::from(&builder.sysroot_libdir(compiler, compiler.host))],
369 impl Step for ErrorIndex {
370 type Output = PathBuf;
372 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
373 run.path("src/tools/error_index_generator")
376 fn make_run(run: RunConfig<'_>) {
377 // Compile the error-index in the same stage as rustdoc to avoid
378 // recompiling rustdoc twice if we can.
379 let stage = if run.builder.top_stage >= 2 { run.builder.top_stage } else { 0 };
380 run.builder.ensure(ErrorIndex {
381 compiler: run.builder.compiler(stage, run.builder.config.build),
385 fn run(self, builder: &Builder<'_>) -> PathBuf {
386 builder.ensure(ToolBuild {
387 compiler: self.compiler,
388 target: self.compiler.host,
389 tool: "error_index_generator",
390 mode: Mode::ToolRustc,
391 path: "src/tools/error_index_generator",
392 is_optional_tool: false,
393 source_type: SourceType::InTree,
394 extra_features: Vec::new(),
395 }).expect("expected to build -- essential tool")
399 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
400 pub struct RemoteTestServer {
401 pub compiler: Compiler,
402 pub target: Interned<String>,
405 impl Step for RemoteTestServer {
406 type Output = PathBuf;
408 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
409 run.path("src/tools/remote-test-server")
412 fn make_run(run: RunConfig<'_>) {
413 run.builder.ensure(RemoteTestServer {
414 compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
419 fn run(self, builder: &Builder<'_>) -> PathBuf {
420 builder.ensure(ToolBuild {
421 compiler: self.compiler,
423 tool: "remote-test-server",
425 path: "src/tools/remote-test-server",
426 is_optional_tool: false,
427 source_type: SourceType::InTree,
428 extra_features: Vec::new(),
429 }).expect("expected to build -- essential tool")
433 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
435 /// This should only ever be 0 or 2.
436 /// We sometimes want to reference the "bootstrap" rustdoc, which is why this option is here.
437 pub compiler: Compiler,
440 impl Step for Rustdoc {
441 type Output = PathBuf;
442 const DEFAULT: bool = true;
443 const ONLY_HOSTS: bool = true;
445 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
446 run.path("src/tools/rustdoc")
449 fn make_run(run: RunConfig<'_>) {
450 run.builder.ensure(Rustdoc {
451 compiler: run.builder.compiler(run.builder.top_stage, run.host),
455 fn run(self, builder: &Builder<'_>) -> PathBuf {
456 let target_compiler = self.compiler;
457 if target_compiler.stage == 0 {
458 if !target_compiler.is_snapshot(builder) {
459 panic!("rustdoc in stage 0 must be snapshot rustdoc");
461 return builder.initial_rustc.with_file_name(exe("rustdoc", &target_compiler.host));
463 let target = target_compiler.host;
464 // Similar to `compile::Assemble`, build with the previous stage's compiler. Otherwise
465 // we'd have stageN/bin/rustc and stageN/bin/rustdoc be effectively different stage
466 // compilers, which isn't what we want. Rustdoc should be linked in the same way as the
467 // rustc compiler it's paired with, so it must be built with the previous stage compiler.
468 let build_compiler = builder.compiler(target_compiler.stage - 1, builder.config.build);
470 // The presence of `target_compiler` ensures that the necessary libraries (codegen backends,
471 // compiler libraries, ...) are built. Rustdoc does not require the presence of any
472 // libraries within sysroot_libdir (i.e., rustlib), though doctests may want it (since
473 // they'll be linked to those libraries). As such, don't explicitly `ensure` any additional
474 // libraries here. The intuition here is that If we've built a compiler, we should be able
477 let mut cargo = prepare_tool_cargo(
488 // Most tools don't get debuginfo, but rustdoc should.
489 cargo.env("RUSTC_DEBUGINFO", builder.config.rust_debuginfo.to_string())
490 .env("RUSTC_DEBUGINFO_LINES", builder.config.rust_debuginfo_lines.to_string());
492 let _folder = builder.fold_output(|| format!("stage{}-rustdoc", target_compiler.stage));
493 builder.info(&format!("Building rustdoc for stage{} ({})",
494 target_compiler.stage, target_compiler.host));
495 builder.run(&mut cargo);
497 // Cargo adds a number of paths to the dylib search path on windows, which results in
498 // the wrong rustdoc being executed. To avoid the conflicting rustdocs, we name the "tool"
499 // rustdoc a different name.
500 let tool_rustdoc = builder.cargo_out(build_compiler, Mode::ToolRustc, target)
501 .join(exe("rustdoc_tool_binary", &target_compiler.host));
503 // don't create a stage0-sysroot/bin directory.
504 if target_compiler.stage > 0 {
505 let sysroot = builder.sysroot(target_compiler);
506 let bindir = sysroot.join("bin");
507 t!(fs::create_dir_all(&bindir));
508 let bin_rustdoc = bindir.join(exe("rustdoc", &*target_compiler.host));
509 let _ = fs::remove_file(&bin_rustdoc);
510 builder.copy(&tool_rustdoc, &bin_rustdoc);
518 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
520 pub compiler: Compiler,
521 pub target: Interned<String>,
524 impl Step for Cargo {
525 type Output = PathBuf;
526 const DEFAULT: bool = true;
527 const ONLY_HOSTS: bool = true;
529 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
530 let builder = run.builder;
531 run.path("src/tools/cargo").default_condition(builder.config.extended)
534 fn make_run(run: RunConfig<'_>) {
535 run.builder.ensure(Cargo {
536 compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
541 fn run(self, builder: &Builder<'_>) -> PathBuf {
542 // Cargo depends on procedural macros, which requires a full host
543 // compiler to be available, so we need to depend on that.
544 builder.ensure(compile::Rustc {
545 compiler: self.compiler,
546 target: builder.config.build,
548 builder.ensure(ToolBuild {
549 compiler: self.compiler,
552 mode: Mode::ToolRustc,
553 path: "src/tools/cargo",
554 is_optional_tool: false,
555 source_type: SourceType::Submodule,
556 extra_features: Vec::new(),
557 }).expect("expected to build -- essential tool")
561 macro_rules! tool_extended {
562 (($sel:ident, $builder:ident),
567 $extra_deps:block;)+) => {
569 #[derive(Debug, Clone, Hash, PartialEq, Eq)]
571 pub compiler: Compiler,
572 pub target: Interned<String>,
573 pub extra_features: Vec<String>,
576 impl Step for $name {
577 type Output = Option<PathBuf>;
578 const DEFAULT: bool = true;
579 const ONLY_HOSTS: bool = true;
581 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
582 let builder = run.builder;
583 run.path($path).default_condition(builder.config.extended)
586 fn make_run(run: RunConfig<'_>) {
587 run.builder.ensure($name {
588 compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
590 extra_features: Vec::new(),
595 fn run(mut $sel, $builder: &Builder<'_>) -> Option<PathBuf> {
597 $builder.ensure(ToolBuild {
598 compiler: $sel.compiler,
601 mode: Mode::ToolRustc,
603 extra_features: $sel.extra_features,
604 is_optional_tool: true,
605 source_type: SourceType::Submodule,
613 tool_extended!((self, builder),
614 Cargofmt, rustfmt, "src/tools/rustfmt", "cargo-fmt", {};
615 CargoClippy, clippy, "src/tools/clippy", "cargo-clippy", {
616 // Clippy depends on procedural macros (serde), which requires a full host
617 // compiler to be available, so we need to depend on that.
618 builder.ensure(compile::Rustc {
619 compiler: self.compiler,
620 target: builder.config.build,
623 Clippy, clippy, "src/tools/clippy", "clippy-driver", {
624 // Clippy depends on procedural macros (serde), which requires a full host
625 // compiler to be available, so we need to depend on that.
626 builder.ensure(compile::Rustc {
627 compiler: self.compiler,
628 target: builder.config.build,
631 Miri, miri, "src/tools/miri", "miri", {};
632 CargoMiri, miri, "src/tools/miri", "cargo-miri", {
633 // Miri depends on procedural macros (serde), which requires a full host
634 // compiler to be available, so we need to depend on that.
635 builder.ensure(compile::Rustc {
636 compiler: self.compiler,
637 target: builder.config.build,
640 Rls, rls, "src/tools/rls", "rls", {
641 let clippy = builder.ensure(Clippy {
642 compiler: self.compiler,
644 extra_features: Vec::new(),
646 if clippy.is_some() {
647 self.extra_features.push("clippy".to_owned());
649 // RLS depends on procedural macros, which requires a full host
650 // compiler to be available, so we need to depend on that.
651 builder.ensure(compile::Rustc {
652 compiler: self.compiler,
653 target: builder.config.build,
656 Rustfmt, rustfmt, "src/tools/rustfmt", "rustfmt", {};
659 impl<'a> Builder<'a> {
660 /// Gets a `Command` which is ready to run `tool` in `stage` built for
662 pub fn tool_cmd(&self, tool: Tool) -> Command {
663 let mut cmd = Command::new(self.tool_exe(tool));
664 let compiler = self.compiler(0, self.config.build);
665 self.prepare_tool_cmd(compiler, tool, &mut cmd);
669 /// Prepares the `cmd` provided to be able to run the `compiler` provided.
671 /// Notably this munges the dynamic library lookup path to point to the
672 /// right location to run `compiler`.
673 fn prepare_tool_cmd(&self, compiler: Compiler, tool: Tool, cmd: &mut Command) {
674 let host = &compiler.host;
675 let mut lib_paths: Vec<PathBuf> = vec![
676 if compiler.stage == 0 {
677 self.build.rustc_snapshot_libdir()
679 PathBuf::from(&self.sysroot_libdir(compiler, compiler.host))
681 self.cargo_out(compiler, tool.get_mode(), *host).join("deps"),
684 // On MSVC a tool may invoke a C compiler (e.g., compiletest in run-make
685 // mode) and that C compiler may need some extra PATH modification. Do
687 if compiler.host.contains("msvc") {
688 let curpaths = env::var_os("PATH").unwrap_or_default();
689 let curpaths = env::split_paths(&curpaths).collect::<Vec<_>>();
690 for &(ref k, ref v) in self.cc[&compiler.host].env() {
694 for path in env::split_paths(v) {
695 if !curpaths.contains(&path) {
696 lib_paths.push(path);
702 add_lib_path(lib_paths, cmd);