4 use std::path::PathBuf;
5 use std::process::{Command, exit};
6 use std::collections::HashSet;
10 use crate::builder::{Step, RunConfig, ShouldRun, Builder};
11 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 /// Build 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
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("rustfmt")
223 cargo.env("LIBZ_SYS_STATIC", "1");
224 features.push("rustc-workspace-hack/all-static".to_string());
228 // if tools are using lzma we want to force the build script to build its
230 cargo.env("LZMA_API_STATIC", "1");
232 cargo.env("CFG_RELEASE_CHANNEL", &builder.config.channel);
233 cargo.env("CFG_VERSION", builder.rust_version());
234 cargo.env("CFG_RELEASE_NUM", channel::CFG_RELEASE_NUM);
236 let info = GitInfo::new(&builder.config, &dir);
237 if let Some(sha) = info.sha() {
238 cargo.env("CFG_COMMIT_HASH", sha);
240 if let Some(sha_short) = info.sha_short() {
241 cargo.env("CFG_SHORT_COMMIT_HASH", sha_short);
243 if let Some(date) = info.commit_date() {
244 cargo.env("CFG_COMMIT_DATE", date);
246 if !features.is_empty() {
247 cargo.arg("--features").arg(&features.join(", "));
254 $name:ident, $path:expr, $tool_name:expr, $mode:expr
255 $(,llvm_tools = $llvm:expr)*
256 $(,is_external_tool = $external:expr)*
259 #[derive(Copy, PartialEq, Eq, Clone)]
267 pub fn get_mode(&self) -> Mode {
268 let mode = match self {
269 $(Tool::$name => $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 {
284 let stage = self.tool_default_stage(tool);
288 compiler: self.compiler(stage, self.config.build),
289 target: self.config.build,
295 pub fn tool_default_stage(&self, tool: Tool) -> u32 {
296 // Compile the error-index in the same stage as rustdoc to avoid
297 // recompiling rustdoc twice if we can. Otherwise compile
298 // everything else in stage0 as there's no need to rebootstrap
301 Tool::ErrorIndex if self.top_stage >= 2 => self.top_stage,
308 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
310 pub compiler: Compiler,
311 pub target: Interned<String>,
314 impl Step for $name {
315 type Output = PathBuf;
317 fn should_run(run: ShouldRun) -> ShouldRun {
321 fn make_run(run: RunConfig) {
322 run.builder.ensure($name {
323 compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
328 fn run(self, builder: &Builder) -> PathBuf {
329 builder.ensure(ToolBuild {
330 compiler: self.compiler,
335 is_optional_tool: false,
336 source_type: if false $(|| $external)* {
337 SourceType::Submodule
341 extra_features: Vec::new(),
342 }).expect("expected to build -- essential tool")
350 Rustbook, "src/tools/rustbook", "rustbook", Mode::ToolBootstrap;
351 ErrorIndex, "src/tools/error_index_generator", "error_index_generator", Mode::ToolRustc;
352 UnstableBookGen, "src/tools/unstable-book-gen", "unstable-book-gen", Mode::ToolBootstrap;
353 Tidy, "src/tools/tidy", "tidy", Mode::ToolBootstrap;
354 Linkchecker, "src/tools/linkchecker", "linkchecker", Mode::ToolBootstrap;
355 CargoTest, "src/tools/cargotest", "cargotest", Mode::ToolBootstrap;
356 Compiletest, "src/tools/compiletest", "compiletest", Mode::ToolBootstrap, llvm_tools = true;
357 BuildManifest, "src/tools/build-manifest", "build-manifest", Mode::ToolBootstrap;
358 RemoteTestClient, "src/tools/remote-test-client", "remote-test-client", Mode::ToolBootstrap;
359 RustInstaller, "src/tools/rust-installer", "fabricate", Mode::ToolBootstrap,
360 is_external_tool = true;
361 RustdocTheme, "src/tools/rustdoc-themes", "rustdoc-themes", Mode::ToolBootstrap;
364 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
365 pub struct RemoteTestServer {
366 pub compiler: Compiler,
367 pub target: Interned<String>,
370 impl Step for RemoteTestServer {
371 type Output = PathBuf;
373 fn should_run(run: ShouldRun) -> ShouldRun {
374 run.path("src/tools/remote-test-server")
377 fn make_run(run: RunConfig) {
378 run.builder.ensure(RemoteTestServer {
379 compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
384 fn run(self, builder: &Builder) -> PathBuf {
385 builder.ensure(ToolBuild {
386 compiler: self.compiler,
388 tool: "remote-test-server",
390 path: "src/tools/remote-test-server",
391 is_optional_tool: false,
392 source_type: SourceType::InTree,
393 extra_features: Vec::new(),
394 }).expect("expected to build -- essential tool")
398 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
400 pub host: Interned<String>,
403 impl Step for Rustdoc {
404 type Output = PathBuf;
405 const DEFAULT: bool = true;
406 const ONLY_HOSTS: bool = true;
408 fn should_run(run: ShouldRun) -> ShouldRun {
409 run.path("src/tools/rustdoc")
412 fn make_run(run: RunConfig) {
413 run.builder.ensure(Rustdoc {
418 fn run(self, builder: &Builder) -> PathBuf {
419 let target_compiler = builder.compiler(builder.top_stage, self.host);
420 let target = target_compiler.host;
421 let build_compiler = if target_compiler.stage == 0 {
422 builder.compiler(0, builder.config.build)
423 } else if target_compiler.stage >= 2 {
424 // Past stage 2, we consider the compiler to be ABI-compatible and hence capable of
425 // building rustdoc itself.
426 builder.compiler(target_compiler.stage, builder.config.build)
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.
431 builder.compiler(target_compiler.stage - 1, builder.config.build)
434 builder.ensure(compile::Rustc { compiler: build_compiler, target });
435 builder.ensure(compile::Rustc {
436 compiler: build_compiler,
437 target: builder.config.build,
440 let mut cargo = prepare_tool_cargo(
451 // Most tools don't get debuginfo, but rustdoc should.
452 cargo.env("RUSTC_DEBUGINFO", builder.config.rust_debuginfo.to_string())
453 .env("RUSTC_DEBUGINFO_LINES", builder.config.rust_debuginfo_lines.to_string());
455 let _folder = builder.fold_output(|| format!("stage{}-rustdoc", target_compiler.stage));
456 builder.info(&format!("Building rustdoc for stage{} ({})",
457 target_compiler.stage, target_compiler.host));
458 builder.run(&mut cargo);
460 // Cargo adds a number of paths to the dylib search path on windows, which results in
461 // the wrong rustdoc being executed. To avoid the conflicting rustdocs, we name the "tool"
462 // rustdoc a different name.
463 let tool_rustdoc = builder.cargo_out(build_compiler, Mode::ToolRustc, target)
464 .join(exe("rustdoc_tool_binary", &target_compiler.host));
466 // don't create a stage0-sysroot/bin directory.
467 if target_compiler.stage > 0 {
468 let sysroot = builder.sysroot(target_compiler);
469 let bindir = sysroot.join("bin");
470 t!(fs::create_dir_all(&bindir));
471 let bin_rustdoc = bindir.join(exe("rustdoc", &*target_compiler.host));
472 let _ = fs::remove_file(&bin_rustdoc);
473 builder.copy(&tool_rustdoc, &bin_rustdoc);
481 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
483 pub compiler: Compiler,
484 pub target: Interned<String>,
487 impl Step for Cargo {
488 type Output = PathBuf;
489 const DEFAULT: bool = true;
490 const ONLY_HOSTS: bool = true;
492 fn should_run(run: ShouldRun) -> ShouldRun {
493 let builder = run.builder;
494 run.path("src/tools/cargo").default_condition(builder.config.extended)
497 fn make_run(run: RunConfig) {
498 run.builder.ensure(Cargo {
499 compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
504 fn run(self, builder: &Builder) -> PathBuf {
505 // Cargo depends on procedural macros, which requires a full host
506 // compiler to be available, so we need to depend on that.
507 builder.ensure(compile::Rustc {
508 compiler: self.compiler,
509 target: builder.config.build,
511 builder.ensure(ToolBuild {
512 compiler: self.compiler,
515 mode: Mode::ToolRustc,
516 path: "src/tools/cargo",
517 is_optional_tool: false,
518 source_type: SourceType::Submodule,
519 extra_features: Vec::new(),
520 }).expect("expected to build -- essential tool")
524 macro_rules! tool_extended {
525 (($sel:ident, $builder:ident),
530 $extra_deps:block;)+) => {
532 #[derive(Debug, Clone, Hash, PartialEq, Eq)]
534 pub compiler: Compiler,
535 pub target: Interned<String>,
536 pub extra_features: Vec<String>,
539 impl Step for $name {
540 type Output = Option<PathBuf>;
541 const DEFAULT: bool = true;
542 const ONLY_HOSTS: bool = true;
544 fn should_run(run: ShouldRun) -> ShouldRun {
545 let builder = run.builder;
546 run.path($path).default_condition(builder.config.extended)
549 fn make_run(run: RunConfig) {
550 run.builder.ensure($name {
551 compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
553 extra_features: Vec::new(),
558 fn run(mut $sel, $builder: &Builder) -> Option<PathBuf> {
560 $builder.ensure(ToolBuild {
561 compiler: $sel.compiler,
564 mode: Mode::ToolRustc,
566 extra_features: $sel.extra_features,
567 is_optional_tool: true,
568 source_type: SourceType::Submodule,
576 tool_extended!((self, builder),
577 Cargofmt, rustfmt, "src/tools/rustfmt", "cargo-fmt", {};
578 CargoClippy, clippy, "src/tools/clippy", "cargo-clippy", {
579 // Clippy depends on procedural macros (serde), which requires a full host
580 // compiler to be available, so we need to depend on that.
581 builder.ensure(compile::Rustc {
582 compiler: self.compiler,
583 target: builder.config.build,
586 Clippy, clippy, "src/tools/clippy", "clippy-driver", {
587 // Clippy depends on procedural macros (serde), which requires a full host
588 // compiler to be available, so we need to depend on that.
589 builder.ensure(compile::Rustc {
590 compiler: self.compiler,
591 target: builder.config.build,
594 Miri, miri, "src/tools/miri", "miri", {};
595 Rls, rls, "src/tools/rls", "rls", {
596 let clippy = builder.ensure(Clippy {
597 compiler: self.compiler,
599 extra_features: Vec::new(),
601 if clippy.is_some() {
602 self.extra_features.push("clippy".to_owned());
604 // RLS depends on procedural macros, which requires a full host
605 // compiler to be available, so we need to depend on that.
606 builder.ensure(compile::Rustc {
607 compiler: self.compiler,
608 target: builder.config.build,
611 Rustfmt, rustfmt, "src/tools/rustfmt", "rustfmt", {};
614 impl<'a> Builder<'a> {
615 /// Get a `Command` which is ready to run `tool` in `stage` built for
617 pub fn tool_cmd(&self, tool: Tool) -> Command {
618 let mut cmd = Command::new(self.tool_exe(tool));
619 let compiler = self.compiler(self.tool_default_stage(tool), self.config.build);
620 self.prepare_tool_cmd(compiler, tool, &mut cmd);
624 /// Prepares the `cmd` provided to be able to run the `compiler` provided.
626 /// Notably this munges the dynamic library lookup path to point to the
627 /// right location to run `compiler`.
628 fn prepare_tool_cmd(&self, compiler: Compiler, tool: Tool, cmd: &mut Command) {
629 let host = &compiler.host;
630 let mut lib_paths: Vec<PathBuf> = vec![
631 if compiler.stage == 0 && tool != Tool::ErrorIndex {
632 self.build.rustc_snapshot_libdir()
634 PathBuf::from(&self.sysroot_libdir(compiler, compiler.host))
636 self.cargo_out(compiler, tool.get_mode(), *host).join("deps"),
639 // On MSVC a tool may invoke a C compiler (e.g., compiletest in run-make
640 // mode) and that C compiler may need some extra PATH modification. Do
642 if compiler.host.contains("msvc") {
643 let curpaths = env::var_os("PATH").unwrap_or_default();
644 let curpaths = env::split_paths(&curpaths).collect::<Vec<_>>();
645 for &(ref k, ref v) in self.cc[&compiler.host].env() {
649 for path in env::split_paths(v) {
650 if !curpaths.contains(&path) {
651 lib_paths.push(path);
657 // Add the llvm/bin directory to PATH since it contains lots of
658 // useful, platform-independent tools
659 if tool.uses_llvm_tools() {
660 if let Some(llvm_bin_path) = self.llvm_bin_path() {
661 if host.contains("windows") {
662 // On Windows, PATH and the dynamic library path are the same,
663 // so we just add the LLVM bin path to lib_path
664 lib_paths.push(llvm_bin_path);
666 let old_path = env::var_os("PATH").unwrap_or_default();
667 let new_path = env::join_paths(iter::once(llvm_bin_path)
668 .chain(env::split_paths(&old_path)))
669 .expect("Could not add LLVM bin path to PATH");
670 cmd.env("PATH", new_path);
675 add_lib_path(lib_paths, cmd);
678 fn llvm_bin_path(&self) -> Option<PathBuf> {
679 if self.config.llvm_enabled && !self.config.dry_run {
680 let llvm_config = self.ensure(native::Llvm {
681 target: self.config.build,
685 // Add the llvm/bin directory to PATH since it contains lots of
686 // useful, platform-independent tools
687 let llvm_bin_path = llvm_config.parent()
688 .expect("Expected llvm-config to be contained in directory");
689 assert!(llvm_bin_path.is_dir());
690 Some(llvm_bin_path.to_path_buf())