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};
13 use crate::channel::GitInfo;
15 use crate::cache::Interned;
16 use crate::toolstate::ToolState;
18 #[derive(Debug, Clone, Hash, PartialEq, Eq)]
24 #[derive(Debug, Clone, Hash, PartialEq, Eq)]
27 target: Interned<String>,
31 is_optional_tool: bool,
32 source_type: SourceType,
33 extra_features: Vec<String>,
36 impl Step for ToolBuild {
37 type Output = Option<PathBuf>;
39 fn should_run(run: ShouldRun) -> ShouldRun {
43 /// Builds a tool in `src/tools`
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;
52 let is_optional_tool = self.is_optional_tool;
56 builder.ensure(compile::Rustc { compiler, target })
59 builder.ensure(compile::Std { compiler, target })
61 Mode::ToolBootstrap => {} // uses downloaded stage0 compiler libs
62 _ => panic!("unexpected Mode for tool build")
65 let mut cargo = prepare_tool_cargo(
76 let _folder = builder.fold_output(|| format!("stage{}-{}", compiler.stage, tool));
77 builder.info(&format!("Building stage{} tool {} ({})", compiler.stage, tool, target));
78 let mut duplicates = Vec::new();
79 let is_expected = compile::stream_cargo(builder, &mut cargo, &mut |msg| {
80 // Only care about big things like the RLS/Cargo for now
90 let (id, features, filenames) = match msg {
91 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(
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, &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(", "));
255 $name:ident, $path:expr, $tool_name:expr, $mode: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 {
269 let mode = match self {
270 $(Tool::$name => $mode,)+
275 /// Whether this tool requires LLVM to run
276 pub fn uses_llvm_tools(&self) -> bool {
278 $(Tool::$name => false $(|| $llvm)*,)+
283 impl<'a> Builder<'a> {
284 pub fn tool_exe(&self, tool: Tool) -> PathBuf {
285 let stage = self.tool_default_stage(tool);
289 compiler: self.compiler(stage, self.config.build),
290 target: self.config.build,
296 pub fn tool_default_stage(&self, tool: Tool) -> u32 {
297 // Compile the error-index in the same stage as rustdoc to avoid
298 // recompiling rustdoc twice if we can. Otherwise compile
299 // everything else in stage0 as there's no need to rebootstrap
302 Tool::ErrorIndex if self.top_stage >= 2 => self.top_stage,
309 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
311 pub compiler: Compiler,
312 pub target: Interned<String>,
315 impl Step for $name {
316 type Output = PathBuf;
318 fn should_run(run: ShouldRun) -> ShouldRun {
322 fn make_run(run: RunConfig) {
323 run.builder.ensure($name {
324 compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
329 fn run(self, builder: &Builder) -> PathBuf {
330 builder.ensure(ToolBuild {
331 compiler: self.compiler,
336 is_optional_tool: false,
337 source_type: if false $(|| $external)* {
338 SourceType::Submodule
342 extra_features: Vec::new(),
343 }).expect("expected to build -- essential tool")
351 Rustbook, "src/tools/rustbook", "rustbook", Mode::ToolBootstrap;
352 ErrorIndex, "src/tools/error_index_generator", "error_index_generator", Mode::ToolRustc;
353 UnstableBookGen, "src/tools/unstable-book-gen", "unstable-book-gen", Mode::ToolBootstrap;
354 Tidy, "src/tools/tidy", "tidy", Mode::ToolBootstrap;
355 Linkchecker, "src/tools/linkchecker", "linkchecker", Mode::ToolBootstrap;
356 CargoTest, "src/tools/cargotest", "cargotest", Mode::ToolBootstrap;
357 Compiletest, "src/tools/compiletest", "compiletest", Mode::ToolBootstrap, llvm_tools = true;
358 BuildManifest, "src/tools/build-manifest", "build-manifest", Mode::ToolBootstrap;
359 RemoteTestClient, "src/tools/remote-test-client", "remote-test-client", Mode::ToolBootstrap;
360 RustInstaller, "src/tools/rust-installer", "fabricate", Mode::ToolBootstrap,
361 is_external_tool = true;
362 RustdocTheme, "src/tools/rustdoc-themes", "rustdoc-themes", Mode::ToolBootstrap;
365 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
366 pub struct RemoteTestServer {
367 pub compiler: Compiler,
368 pub target: Interned<String>,
371 impl Step for RemoteTestServer {
372 type Output = PathBuf;
374 fn should_run(run: ShouldRun) -> ShouldRun {
375 run.path("src/tools/remote-test-server")
378 fn make_run(run: RunConfig) {
379 run.builder.ensure(RemoteTestServer {
380 compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
385 fn run(self, builder: &Builder) -> PathBuf {
386 builder.ensure(ToolBuild {
387 compiler: self.compiler,
389 tool: "remote-test-server",
391 path: "src/tools/remote-test-server",
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)]
401 pub host: Interned<String>,
404 impl Step for Rustdoc {
405 type Output = PathBuf;
406 const DEFAULT: bool = true;
407 const ONLY_HOSTS: bool = true;
409 fn should_run(run: ShouldRun) -> ShouldRun {
410 run.path("src/tools/rustdoc")
413 fn make_run(run: RunConfig) {
414 run.builder.ensure(Rustdoc {
419 fn run(self, builder: &Builder) -> PathBuf {
420 let target_compiler = builder.compiler(builder.top_stage, self.host);
421 if target_compiler.stage == 0 {
422 if !target_compiler.is_snapshot(builder) {
423 panic!("rustdoc in stage 0 must be snapshot rustdoc");
425 return builder.initial_rustc.with_file_name(exe("rustdoc", &target_compiler.host));
427 let target = target_compiler.host;
428 // Similar to `compile::Assemble`, build with the previous stage's compiler. Otherwise
429 // we'd have stageN/bin/rustc and stageN/bin/rustdoc be effectively different stage
430 // compilers, which isn't what we want. Rustdoc should be linked in the same way as the
431 // rustc compiler it's paired with, so it must be built with the previous stage compiler.
432 let build_compiler = builder.compiler(target_compiler.stage - 1, builder.config.build);
434 // The presence of `target_compiler` ensures that the necessary libraries (codegen backends,
435 // compiler libraries, ...) are built. Rustdoc does not require the presence of any
436 // libraries within sysroot_libdir (i.e., rustlib), though doctests may want it (since
437 // they'll be linked to those libraries). As such, don't explicitly `ensure` any additional
438 // libraries here. The intuition here is that If we've built a compiler, we should be able
441 let mut cargo = prepare_tool_cargo(
452 // Most tools don't get debuginfo, but rustdoc should.
453 cargo.env("RUSTC_DEBUGINFO", builder.config.rust_debuginfo.to_string())
454 .env("RUSTC_DEBUGINFO_LINES", builder.config.rust_debuginfo_lines.to_string());
456 let _folder = builder.fold_output(|| format!("stage{}-rustdoc", target_compiler.stage));
457 builder.info(&format!("Building rustdoc for stage{} ({})",
458 target_compiler.stage, target_compiler.host));
459 builder.run(&mut cargo);
461 // Cargo adds a number of paths to the dylib search path on windows, which results in
462 // the wrong rustdoc being executed. To avoid the conflicting rustdocs, we name the "tool"
463 // rustdoc a different name.
464 let tool_rustdoc = builder.cargo_out(build_compiler, Mode::ToolRustc, target)
465 .join(exe("rustdoc_tool_binary", &target_compiler.host));
467 // don't create a stage0-sysroot/bin directory.
468 if target_compiler.stage > 0 {
469 let sysroot = builder.sysroot(target_compiler);
470 let bindir = sysroot.join("bin");
471 t!(fs::create_dir_all(&bindir));
472 let bin_rustdoc = bindir.join(exe("rustdoc", &*target_compiler.host));
473 let _ = fs::remove_file(&bin_rustdoc);
474 builder.copy(&tool_rustdoc, &bin_rustdoc);
482 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
484 pub compiler: Compiler,
485 pub target: Interned<String>,
488 impl Step for Cargo {
489 type Output = PathBuf;
490 const DEFAULT: bool = true;
491 const ONLY_HOSTS: bool = true;
493 fn should_run(run: ShouldRun) -> ShouldRun {
494 let builder = run.builder;
495 run.path("src/tools/cargo").default_condition(builder.config.extended)
498 fn make_run(run: RunConfig) {
499 run.builder.ensure(Cargo {
500 compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
505 fn run(self, builder: &Builder) -> PathBuf {
506 // Cargo depends on procedural macros, which requires a full host
507 // compiler to be available, so we need to depend on that.
508 builder.ensure(compile::Rustc {
509 compiler: self.compiler,
510 target: builder.config.build,
512 builder.ensure(ToolBuild {
513 compiler: self.compiler,
516 mode: Mode::ToolRustc,
517 path: "src/tools/cargo",
518 is_optional_tool: false,
519 source_type: SourceType::Submodule,
520 extra_features: Vec::new(),
521 }).expect("expected to build -- essential tool")
525 macro_rules! tool_extended {
526 (($sel:ident, $builder:ident),
531 $extra_deps:block;)+) => {
533 #[derive(Debug, Clone, Hash, PartialEq, Eq)]
535 pub compiler: Compiler,
536 pub target: Interned<String>,
537 pub extra_features: Vec<String>,
540 impl Step for $name {
541 type Output = Option<PathBuf>;
542 const DEFAULT: bool = true;
543 const ONLY_HOSTS: bool = true;
545 fn should_run(run: ShouldRun) -> ShouldRun {
546 let builder = run.builder;
547 run.path($path).default_condition(builder.config.extended)
550 fn make_run(run: RunConfig) {
551 run.builder.ensure($name {
552 compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
554 extra_features: Vec::new(),
559 fn run(mut $sel, $builder: &Builder) -> Option<PathBuf> {
561 $builder.ensure(ToolBuild {
562 compiler: $sel.compiler,
565 mode: Mode::ToolRustc,
567 extra_features: $sel.extra_features,
568 is_optional_tool: true,
569 source_type: SourceType::Submodule,
577 tool_extended!((self, builder),
578 Cargofmt, rustfmt, "src/tools/rustfmt", "cargo-fmt", {};
579 CargoClippy, clippy, "src/tools/clippy", "cargo-clippy", {
580 // Clippy depends on procedural macros (serde), which requires a full host
581 // compiler to be available, so we need to depend on that.
582 builder.ensure(compile::Rustc {
583 compiler: self.compiler,
584 target: builder.config.build,
587 Clippy, clippy, "src/tools/clippy", "clippy-driver", {
588 // Clippy depends on procedural macros (serde), which requires a full host
589 // compiler to be available, so we need to depend on that.
590 builder.ensure(compile::Rustc {
591 compiler: self.compiler,
592 target: builder.config.build,
595 Miri, miri, "src/tools/miri", "miri", {};
596 CargoMiri, miri, "src/tools/miri", "cargo-miri", {
597 // Miri depends on procedural macros (serde), which requires a full host
598 // compiler to be available, so we need to depend on that.
599 builder.ensure(compile::Rustc {
600 compiler: self.compiler,
601 target: builder.config.build,
604 Rls, rls, "src/tools/rls", "rls", {
605 let clippy = builder.ensure(Clippy {
606 compiler: self.compiler,
608 extra_features: Vec::new(),
610 if clippy.is_some() {
611 self.extra_features.push("clippy".to_owned());
613 // RLS depends on procedural macros, which requires a full host
614 // compiler to be available, so we need to depend on that.
615 builder.ensure(compile::Rustc {
616 compiler: self.compiler,
617 target: builder.config.build,
620 Rustfmt, rustfmt, "src/tools/rustfmt", "rustfmt", {};
623 impl<'a> Builder<'a> {
624 /// Gets a `Command` which is ready to run `tool` in `stage` built for
626 pub fn tool_cmd(&self, tool: Tool) -> Command {
627 let mut cmd = Command::new(self.tool_exe(tool));
628 let compiler = self.compiler(self.tool_default_stage(tool), self.config.build);
629 self.prepare_tool_cmd(compiler, tool, &mut cmd);
633 /// Prepares the `cmd` provided to be able to run the `compiler` provided.
635 /// Notably this munges the dynamic library lookup path to point to the
636 /// right location to run `compiler`.
637 fn prepare_tool_cmd(&self, compiler: Compiler, tool: Tool, cmd: &mut Command) {
638 let host = &compiler.host;
639 let mut lib_paths: Vec<PathBuf> = vec![
640 if compiler.stage == 0 && tool != Tool::ErrorIndex {
641 self.build.rustc_snapshot_libdir()
643 PathBuf::from(&self.sysroot_libdir(compiler, compiler.host))
645 self.cargo_out(compiler, tool.get_mode(), *host).join("deps"),
648 // On MSVC a tool may invoke a C compiler (e.g., compiletest in run-make
649 // mode) and that C compiler may need some extra PATH modification. Do
651 if compiler.host.contains("msvc") {
652 let curpaths = env::var_os("PATH").unwrap_or_default();
653 let curpaths = env::split_paths(&curpaths).collect::<Vec<_>>();
654 for &(ref k, ref v) in self.cc[&compiler.host].env() {
658 for path in env::split_paths(v) {
659 if !curpaths.contains(&path) {
660 lib_paths.push(path);
666 // Add the llvm/bin directory to PATH since it contains lots of
667 // useful, platform-independent tools
668 if tool.uses_llvm_tools() && !self.config.dry_run {
669 let mut additional_paths = vec![];
671 if let Some(llvm_bin_path) = self.llvm_bin_path() {
672 additional_paths.push(llvm_bin_path);
675 // If LLD is available, add that too.
676 if self.config.lld_enabled {
677 let lld_install_root = self.ensure(native::Lld {
678 target: self.config.build,
681 let lld_bin_path = lld_install_root.join("bin");
682 additional_paths.push(lld_bin_path);
685 if host.contains("windows") {
686 // On Windows, PATH and the dynamic library path are the same,
687 // so we just add the LLVM bin path to lib_path
688 lib_paths.extend(additional_paths);
690 let old_path = env::var_os("PATH").unwrap_or_default();
691 let new_path = env::join_paths(additional_paths.into_iter()
692 .chain(env::split_paths(&old_path)))
693 .expect("Could not add LLVM bin path to PATH");
694 cmd.env("PATH", new_path);
698 add_lib_path(lib_paths, cmd);
701 fn llvm_bin_path(&self) -> Option<PathBuf> {
702 if self.config.llvm_enabled {
703 let llvm_config = self.ensure(native::Llvm {
704 target: self.config.build,
708 // Add the llvm/bin directory to PATH since it contains lots of
709 // useful, platform-independent tools
710 let llvm_bin_path = llvm_config.parent()
711 .expect("Expected llvm-config to be contained in directory");
712 assert!(llvm_bin_path.is_dir());
713 Some(llvm_bin_path.to_path_buf())