1 // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
14 use std::path::PathBuf;
15 use std::process::{Command, exit};
16 use std::collections::HashSet;
20 use builder::{Step, RunConfig, ShouldRun, Builder};
21 use util::{exe, add_lib_path};
27 use toolstate::ToolState;
29 #[derive(Debug, Clone, Hash, PartialEq, Eq)]
35 #[derive(Debug, Clone, Hash, PartialEq, Eq)]
38 target: Interned<String>,
42 is_optional_tool: bool,
43 source_type: SourceType,
44 extra_features: Vec<String>,
47 impl Step for ToolBuild {
48 type Output = Option<PathBuf>;
50 fn should_run(run: ShouldRun) -> ShouldRun {
54 /// Build a tool in `src/tools`
56 /// This will build the specified tool with the specified `host` compiler in
57 /// `stage` into the normal cargo output directory.
58 fn run(self, builder: &Builder) -> Option<PathBuf> {
59 let compiler = self.compiler;
60 let target = self.target;
63 let is_optional_tool = self.is_optional_tool;
67 builder.ensure(compile::Rustc { compiler, target })
70 builder.ensure(compile::Std { compiler, target })
72 Mode::ToolBootstrap => {} // uses downloaded stage0 compiler libs
73 _ => panic!("unexpected Mode for tool build")
76 let mut cargo = prepare_tool_cargo(
87 let _folder = builder.fold_output(|| format!("stage{}-{}", compiler.stage, tool));
88 builder.info(&format!("Building stage{} tool {} ({})", compiler.stage, tool, target));
89 let mut duplicates = Vec::new();
90 let is_expected = compile::stream_cargo(builder, &mut cargo, vec![], &mut |msg| {
91 // Only care about big things like the RLS/Cargo for now
100 let (id, features, filenames) = match msg {
101 compile::CargoMessage::CompilerArtifact {
106 (package_id, features, filenames)
110 let features = features.iter().map(|s| s.to_string()).collect::<Vec<_>>();
112 for path in filenames {
113 let val = (tool, PathBuf::from(&*path), features.clone());
114 // we're only interested in deduplicating rlibs for now
115 if val.1.extension().and_then(|s| s.to_str()) != Some("rlib") {
119 // Don't worry about libs that turn out to be host dependencies
120 // or build scripts, we only care about target dependencies that
122 if let Some(maybe_target) = val.1
123 .parent() // chop off file name
124 .and_then(|p| p.parent()) // chop off `deps`
125 .and_then(|p| p.parent()) // chop off `release`
126 .and_then(|p| p.file_name())
127 .and_then(|p| p.to_str())
129 if maybe_target != &*target {
134 let mut artifacts = builder.tool_artifacts.borrow_mut();
135 let prev_artifacts = artifacts
138 if let Some(prev) = prev_artifacts.get(&*id) {
148 prev_artifacts.insert(id.to_string(), val);
152 if is_expected && !duplicates.is_empty() {
153 println!("duplicate artfacts found when compiling a tool, this \
154 typically means that something was recompiled because \
155 a transitive dependency has different features activated \
156 than in a previous build:\n");
157 println!("the following dependencies are duplicated although they \
158 have the same features enabled:");
159 for (id, cur, prev) in duplicates.drain_filter(|(_, cur, prev)| cur.2 == prev.2) {
162 println!(" `{}` ({:?})\n `{}` ({:?})", cur.0, cur.1, prev.0, prev.1);
164 println!("the following dependencies have different features:");
165 for (id, cur, prev) in duplicates {
167 let cur_features: HashSet<_> = cur.2.into_iter().collect();
168 let prev_features: HashSet<_> = prev.2.into_iter().collect();
169 println!(" `{}` additionally enabled features {:?} at {:?}",
170 cur.0, &cur_features - &prev_features, cur.1);
171 println!(" `{}` additionally enabled features {:?} at {:?}",
172 prev.0, &prev_features - &cur_features, prev.1);
175 println!("to fix this you will probably want to edit the local \
176 src/tools/rustc-workspace-hack/Cargo.toml crate, as \
177 that will update the dependency graph to ensure that \
178 these crates all share the same feature set");
179 panic!("tools should not compile multiple copies of the same crate");
182 builder.save_toolstate(tool, if is_expected {
189 if !is_optional_tool {
195 let cargo_out = builder.cargo_out(compiler, self.mode, target)
196 .join(exe(tool, &compiler.host));
197 let bin = builder.tools_dir(compiler).join(exe(tool, &compiler.host));
198 builder.copy(&cargo_out, &bin);
204 pub fn prepare_tool_cargo(
208 target: Interned<String>,
209 command: &'static str,
211 source_type: SourceType,
212 extra_features: &[String],
214 let mut cargo = builder.cargo(compiler, mode, target, command);
215 let dir = builder.src.join(path);
216 cargo.arg("--manifest-path").arg(dir.join("Cargo.toml"));
218 // We don't want to build tools dynamically as they'll be running across
219 // stages and such and it's just easier if they're not dynamically linked.
220 cargo.env("RUSTC_NO_PREFER_DYNAMIC", "1");
222 if source_type == SourceType::Submodule {
223 cargo.env("RUSTC_EXTERNAL_TOOL", "1");
226 let mut features = extra_features.iter().cloned().collect::<Vec<_>>();
227 if builder.build.config.cargo_native_static {
228 if path.ends_with("cargo") ||
229 path.ends_with("rls") ||
230 path.ends_with("clippy") ||
231 path.ends_with("rustfmt")
233 cargo.env("LIBZ_SYS_STATIC", "1");
234 features.push("rustc-workspace-hack/all-static".to_string());
238 // if tools are using lzma we want to force the build script to build its
240 cargo.env("LZMA_API_STATIC", "1");
242 cargo.env("CFG_RELEASE_CHANNEL", &builder.config.channel);
243 cargo.env("CFG_VERSION", builder.rust_version());
244 cargo.env("CFG_RELEASE_NUM", channel::CFG_RELEASE_NUM);
246 let info = GitInfo::new(&builder.config, &dir);
247 if let Some(sha) = info.sha() {
248 cargo.env("CFG_COMMIT_HASH", sha);
250 if let Some(sha_short) = info.sha_short() {
251 cargo.env("CFG_SHORT_COMMIT_HASH", sha_short);
253 if let Some(date) = info.commit_date() {
254 cargo.env("CFG_COMMIT_DATE", date);
256 if !features.is_empty() {
257 cargo.arg("--features").arg(&features.join(", "));
264 $name:ident, $path:expr, $tool_name:expr, $mode:expr
265 $(,llvm_tools = $llvm:expr)*
266 $(,is_external_tool = $external:expr)*
269 #[derive(Copy, PartialEq, Eq, Clone)]
277 pub fn get_mode(&self) -> Mode {
278 let mode = match self {
279 $(Tool::$name => $mode,)+
284 /// Whether this tool requires LLVM to run
285 pub fn uses_llvm_tools(&self) -> bool {
287 $(Tool::$name => false $(|| $llvm)*,)+
292 impl<'a> Builder<'a> {
293 pub fn tool_exe(&self, tool: Tool) -> PathBuf {
294 let stage = self.tool_default_stage(tool);
298 compiler: self.compiler(stage, self.config.build),
299 target: self.config.build,
305 pub fn tool_default_stage(&self, tool: Tool) -> u32 {
306 // Compile the error-index in the same stage as rustdoc to avoid
307 // recompiling rustdoc twice if we can. Otherwise compile
308 // everything else in stage0 as there's no need to rebootstrap
311 Tool::ErrorIndex if self.top_stage >= 2 => self.top_stage,
318 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
320 pub compiler: Compiler,
321 pub target: Interned<String>,
324 impl Step for $name {
325 type Output = PathBuf;
327 fn should_run(run: ShouldRun) -> ShouldRun {
331 fn make_run(run: RunConfig) {
332 run.builder.ensure($name {
333 compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
338 fn run(self, builder: &Builder) -> PathBuf {
339 builder.ensure(ToolBuild {
340 compiler: self.compiler,
345 is_optional_tool: false,
346 source_type: if false $(|| $external)* {
347 SourceType::Submodule
351 extra_features: Vec::new(),
352 }).expect("expected to build -- essential tool")
360 Rustbook, "src/tools/rustbook", "rustbook", Mode::ToolBootstrap;
361 ErrorIndex, "src/tools/error_index_generator", "error_index_generator", Mode::ToolRustc;
362 UnstableBookGen, "src/tools/unstable-book-gen", "unstable-book-gen", Mode::ToolBootstrap;
363 Tidy, "src/tools/tidy", "tidy", Mode::ToolBootstrap;
364 Linkchecker, "src/tools/linkchecker", "linkchecker", Mode::ToolBootstrap;
365 CargoTest, "src/tools/cargotest", "cargotest", Mode::ToolBootstrap;
366 Compiletest, "src/tools/compiletest", "compiletest", Mode::ToolBootstrap, llvm_tools = true;
367 BuildManifest, "src/tools/build-manifest", "build-manifest", Mode::ToolBootstrap;
368 RemoteTestClient, "src/tools/remote-test-client", "remote-test-client", Mode::ToolBootstrap;
369 RustInstaller, "src/tools/rust-installer", "fabricate", Mode::ToolBootstrap,
370 is_external_tool = true;
371 RustdocTheme, "src/tools/rustdoc-themes", "rustdoc-themes", Mode::ToolBootstrap;
374 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
375 pub struct RemoteTestServer {
376 pub compiler: Compiler,
377 pub target: Interned<String>,
380 impl Step for RemoteTestServer {
381 type Output = PathBuf;
383 fn should_run(run: ShouldRun) -> ShouldRun {
384 run.path("src/tools/remote-test-server")
387 fn make_run(run: RunConfig) {
388 run.builder.ensure(RemoteTestServer {
389 compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
394 fn run(self, builder: &Builder) -> PathBuf {
395 builder.ensure(ToolBuild {
396 compiler: self.compiler,
398 tool: "remote-test-server",
400 path: "src/tools/remote-test-server",
401 is_optional_tool: false,
402 source_type: SourceType::InTree,
403 extra_features: Vec::new(),
404 }).expect("expected to build -- essential tool")
408 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
410 pub host: Interned<String>,
413 impl Step for Rustdoc {
414 type Output = PathBuf;
415 const DEFAULT: bool = true;
416 const ONLY_HOSTS: bool = true;
418 fn should_run(run: ShouldRun) -> ShouldRun {
419 run.path("src/tools/rustdoc")
422 fn make_run(run: RunConfig) {
423 run.builder.ensure(Rustdoc {
428 fn run(self, builder: &Builder) -> PathBuf {
429 let target_compiler = builder.compiler(builder.top_stage, self.host);
430 let target = target_compiler.host;
431 let build_compiler = if target_compiler.stage == 0 {
432 builder.compiler(0, builder.config.build)
433 } else if target_compiler.stage >= 2 {
434 // Past stage 2, we consider the compiler to be ABI-compatible and hence capable of
435 // building rustdoc itself.
436 builder.compiler(target_compiler.stage, builder.config.build)
438 // Similar to `compile::Assemble`, build with the previous stage's compiler. Otherwise
439 // we'd have stageN/bin/rustc and stageN/bin/rustdoc be effectively different stage
440 // compilers, which isn't what we want.
441 builder.compiler(target_compiler.stage - 1, builder.config.build)
444 builder.ensure(compile::Rustc { compiler: build_compiler, target });
445 builder.ensure(compile::Rustc {
446 compiler: build_compiler,
447 target: builder.config.build,
450 let mut cargo = prepare_tool_cargo(
461 // Most tools don't get debuginfo, but rustdoc should.
462 cargo.env("RUSTC_DEBUGINFO", builder.config.rust_debuginfo.to_string())
463 .env("RUSTC_DEBUGINFO_LINES", builder.config.rust_debuginfo_lines.to_string());
465 let _folder = builder.fold_output(|| format!("stage{}-rustdoc", target_compiler.stage));
466 builder.info(&format!("Building rustdoc for stage{} ({})",
467 target_compiler.stage, target_compiler.host));
468 builder.run(&mut cargo);
470 // Cargo adds a number of paths to the dylib search path on windows, which results in
471 // the wrong rustdoc being executed. To avoid the conflicting rustdocs, we name the "tool"
472 // rustdoc a different name.
473 let tool_rustdoc = builder.cargo_out(build_compiler, Mode::ToolRustc, target)
474 .join(exe("rustdoc_tool_binary", &target_compiler.host));
476 // don't create a stage0-sysroot/bin directory.
477 if target_compiler.stage > 0 {
478 let sysroot = builder.sysroot(target_compiler);
479 let bindir = sysroot.join("bin");
480 t!(fs::create_dir_all(&bindir));
481 let bin_rustdoc = bindir.join(exe("rustdoc", &*target_compiler.host));
482 let _ = fs::remove_file(&bin_rustdoc);
483 builder.copy(&tool_rustdoc, &bin_rustdoc);
491 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
493 pub compiler: Compiler,
494 pub target: Interned<String>,
497 impl Step for Cargo {
498 type Output = PathBuf;
499 const DEFAULT: bool = true;
500 const ONLY_HOSTS: bool = true;
502 fn should_run(run: ShouldRun) -> ShouldRun {
503 let builder = run.builder;
504 run.path("src/tools/cargo").default_condition(builder.config.extended)
507 fn make_run(run: RunConfig) {
508 run.builder.ensure(Cargo {
509 compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
514 fn run(self, builder: &Builder) -> PathBuf {
515 // Cargo depends on procedural macros, which requires a full host
516 // compiler to be available, so we need to depend on that.
517 builder.ensure(compile::Rustc {
518 compiler: self.compiler,
519 target: builder.config.build,
521 builder.ensure(ToolBuild {
522 compiler: self.compiler,
525 mode: Mode::ToolRustc,
526 path: "src/tools/cargo",
527 is_optional_tool: false,
528 source_type: SourceType::Submodule,
529 extra_features: Vec::new(),
530 }).expect("expected to build -- essential tool")
534 macro_rules! tool_extended {
535 (($sel:ident, $builder:ident),
540 $extra_deps:block;)+) => {
542 #[derive(Debug, Clone, Hash, PartialEq, Eq)]
544 pub compiler: Compiler,
545 pub target: Interned<String>,
546 pub extra_features: Vec<String>,
549 impl Step for $name {
550 type Output = Option<PathBuf>;
551 const DEFAULT: bool = true;
552 const ONLY_HOSTS: bool = true;
554 fn should_run(run: ShouldRun) -> ShouldRun {
555 let builder = run.builder;
556 run.path($path).default_condition(builder.config.extended)
559 fn make_run(run: RunConfig) {
560 run.builder.ensure($name {
561 compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
563 extra_features: Vec::new(),
568 fn run(mut $sel, $builder: &Builder) -> Option<PathBuf> {
570 $builder.ensure(ToolBuild {
571 compiler: $sel.compiler,
574 mode: Mode::ToolRustc,
576 extra_features: $sel.extra_features,
577 is_optional_tool: true,
578 source_type: SourceType::Submodule,
586 tool_extended!((self, builder),
587 Cargofmt, rustfmt, "src/tools/rustfmt", "cargo-fmt", {};
588 CargoClippy, clippy, "src/tools/clippy", "cargo-clippy", {
589 // Clippy depends on procedural macros (serde), which requires a full host
590 // compiler to be available, so we need to depend on that.
591 builder.ensure(compile::Rustc {
592 compiler: self.compiler,
593 target: builder.config.build,
596 Clippy, clippy, "src/tools/clippy", "clippy-driver", {
597 // Clippy 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 Miri, miri, "src/tools/miri", "miri", {};
605 Rls, rls, "src/tools/rls", "rls", {
606 let clippy = builder.ensure(Clippy {
607 compiler: self.compiler,
609 extra_features: Vec::new(),
611 if clippy.is_some() {
612 self.extra_features.push("clippy".to_owned());
614 // RLS depends on procedural macros, 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 Rustfmt, rustfmt, "src/tools/rustfmt", "rustfmt", {};
624 impl<'a> Builder<'a> {
625 /// Get a `Command` which is ready to run `tool` in `stage` built for
627 pub fn tool_cmd(&self, tool: Tool) -> Command {
628 let mut cmd = Command::new(self.tool_exe(tool));
629 let compiler = self.compiler(self.tool_default_stage(tool), self.config.build);
630 self.prepare_tool_cmd(compiler, tool, &mut cmd);
634 /// Prepares the `cmd` provided to be able to run the `compiler` provided.
636 /// Notably this munges the dynamic library lookup path to point to the
637 /// right location to run `compiler`.
638 fn prepare_tool_cmd(&self, compiler: Compiler, tool: Tool, cmd: &mut Command) {
639 let host = &compiler.host;
640 let mut lib_paths: Vec<PathBuf> = vec![
641 if compiler.stage == 0 && tool != Tool::ErrorIndex {
642 self.build.rustc_snapshot_libdir()
644 PathBuf::from(&self.sysroot_libdir(compiler, compiler.host))
646 self.cargo_out(compiler, tool.get_mode(), *host).join("deps"),
649 // On MSVC a tool may invoke a C compiler (e.g. compiletest in run-make
650 // mode) and that C compiler may need some extra PATH modification. Do
652 if compiler.host.contains("msvc") {
653 let curpaths = env::var_os("PATH").unwrap_or_default();
654 let curpaths = env::split_paths(&curpaths).collect::<Vec<_>>();
655 for &(ref k, ref v) in self.cc[&compiler.host].env() {
659 for path in env::split_paths(v) {
660 if !curpaths.contains(&path) {
661 lib_paths.push(path);
667 // Add the llvm/bin directory to PATH since it contains lots of
668 // useful, platform-independent tools
669 if tool.uses_llvm_tools() {
670 if let Some(llvm_bin_path) = self.llvm_bin_path() {
671 if host.contains("windows") {
672 // On Windows, PATH and the dynamic library path are the same,
673 // so we just add the LLVM bin path to lib_path
674 lib_paths.push(llvm_bin_path);
676 let old_path = env::var_os("PATH").unwrap_or_default();
677 let new_path = env::join_paths(iter::once(llvm_bin_path)
678 .chain(env::split_paths(&old_path)))
679 .expect("Could not add LLVM bin path to PATH");
680 cmd.env("PATH", new_path);
685 add_lib_path(lib_paths, cmd);
688 fn llvm_bin_path(&self) -> Option<PathBuf> {
689 if self.config.llvm_enabled && !self.config.dry_run {
690 let llvm_config = self.ensure(native::Llvm {
691 target: self.config.build,
695 // Add the llvm/bin directory to PATH since it contains lots of
696 // useful, platform-independent tools
697 let llvm_bin_path = llvm_config.parent()
698 .expect("Expected llvm-config to be contained in directory");
699 assert!(llvm_bin_path.is_dir());
700 Some(llvm_bin_path.to_path_buf())