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};
22 use compile::{self, libtest_stamp, libstd_stamp, librustc_stamp};
26 use toolstate::ToolState;
28 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
29 pub struct CleanTools {
30 pub compiler: Compiler,
31 pub target: Interned<String>,
35 impl Step for CleanTools {
38 fn should_run(run: ShouldRun) -> ShouldRun {
42 fn run(self, builder: &Builder) {
43 let compiler = self.compiler;
44 let target = self.target;
45 let cause = self.cause;
47 // This is for the original compiler, but if we're forced to use stage 1, then
48 // std/test/rustc stamps won't exist in stage 2, so we need to get those from stage 1, since
49 // we copy the libs forward.
50 let tools_dir = builder.stage_out(compiler, Mode::ToolRustc);
51 let compiler = if builder.force_use_stage1(compiler, target) {
52 builder.compiler(1, compiler.host)
57 for &cur_mode in &[Mode::Std, Mode::Test, Mode::Rustc] {
58 let stamp = match cur_mode {
59 Mode::Std => libstd_stamp(builder, compiler, target),
60 Mode::Test => libtest_stamp(builder, compiler, target),
61 Mode::Rustc => librustc_stamp(builder, compiler, target),
65 if builder.clear_if_dirty(&tools_dir, &stamp) {
69 // If we are a rustc tool, and std changed, we also need to clear ourselves out -- our
70 // dependencies depend on std. Therefore, we iterate up until our own mode.
71 if cause == cur_mode {
78 #[derive(Debug, Clone, Hash, PartialEq, Eq)]
84 #[derive(Debug, Clone, Hash, PartialEq, Eq)]
87 target: Interned<String>,
91 is_optional_tool: bool,
92 source_type: SourceType,
93 extra_features: Vec<String>,
96 impl Step for ToolBuild {
97 type Output = Option<PathBuf>;
99 fn should_run(run: ShouldRun) -> ShouldRun {
103 /// Build a tool in `src/tools`
105 /// This will build the specified tool with the specified `host` compiler in
106 /// `stage` into the normal cargo output directory.
107 fn run(self, builder: &Builder) -> Option<PathBuf> {
108 let compiler = self.compiler;
109 let target = self.target;
110 let tool = self.tool;
111 let path = self.path;
112 let is_optional_tool = self.is_optional_tool;
116 builder.ensure(compile::Rustc { compiler, target })
119 builder.ensure(compile::Std { compiler, target })
121 Mode::ToolBootstrap => {} // uses downloaded stage0 compiler libs
122 _ => panic!("unexpected Mode for tool build")
125 let mut cargo = prepare_tool_cargo(
134 cargo.arg("--features").arg(self.extra_features.join(" "));
136 let _folder = builder.fold_output(|| format!("stage{}-{}", compiler.stage, tool));
137 builder.info(&format!("Building stage{} tool {} ({})", compiler.stage, tool, target));
138 let mut duplicates = Vec::new();
139 let is_expected = compile::stream_cargo(builder, &mut cargo, &mut |msg| {
140 // Only care about big things like the RLS/Cargo for now
149 let (id, features, filenames) = match msg {
150 compile::CargoMessage::CompilerArtifact {
155 (package_id, features, filenames)
159 let features = features.iter().map(|s| s.to_string()).collect::<Vec<_>>();
161 for path in filenames {
162 let val = (tool, PathBuf::from(&*path), features.clone());
163 // we're only interested in deduplicating rlibs for now
164 if val.1.extension().and_then(|s| s.to_str()) != Some("rlib") {
168 // Don't worry about libs that turn out to be host dependencies
169 // or build scripts, we only care about target dependencies that
171 if let Some(maybe_target) = val.1
172 .parent() // chop off file name
173 .and_then(|p| p.parent()) // chop off `deps`
174 .and_then(|p| p.parent()) // chop off `release`
175 .and_then(|p| p.file_name())
176 .and_then(|p| p.to_str())
178 if maybe_target != &*target {
183 let mut artifacts = builder.tool_artifacts.borrow_mut();
184 let prev_artifacts = artifacts
186 .or_insert_with(Default::default);
187 if let Some(prev) = prev_artifacts.get(&*id) {
197 prev_artifacts.insert(id.to_string(), val);
201 if is_expected && duplicates.len() != 0 {
202 println!("duplicate artfacts found when compiling a tool, this \
203 typically means that something was recompiled because \
204 a transitive dependency has different features activated \
205 than in a previous build:\n");
206 println!("the following dependencies are duplicated although they \
207 have the same features enabled:");
208 for (id, cur, prev) in duplicates.drain_filter(|(_, cur, prev)| cur.2 == prev.2) {
211 println!(" `{}` ({:?})\n `{}` ({:?})", cur.0, cur.1, prev.0, prev.1);
213 println!("the following dependencies have different features:");
214 for (id, cur, prev) in duplicates {
216 let cur_features: HashSet<_> = cur.2.into_iter().collect();
217 let prev_features: HashSet<_> = prev.2.into_iter().collect();
218 println!(" `{}` additionally enabled features {:?} at {:?}",
219 cur.0, &cur_features - &prev_features, cur.1);
220 println!(" `{}` additionally enabled features {:?} at {:?}",
221 prev.0, &prev_features - &cur_features, prev.1);
224 println!("to fix this you will probably want to edit the local \
225 src/tools/rustc-workspace-hack/Cargo.toml crate, as \
226 that will update the dependency graph to ensure that \
227 these crates all share the same feature set");
228 panic!("tools should not compile multiple copies of the same crate");
231 builder.save_toolstate(tool, if is_expected {
238 if !is_optional_tool {
244 let cargo_out = builder.cargo_out(compiler, self.mode, target)
245 .join(exe(tool, &compiler.host));
246 let bin = builder.tools_dir(compiler).join(exe(tool, &compiler.host));
247 builder.copy(&cargo_out, &bin);
253 pub fn prepare_tool_cargo(
257 target: Interned<String>,
258 command: &'static str,
260 source_type: SourceType,
262 let mut cargo = builder.cargo(compiler, mode, target, command);
263 let dir = builder.src.join(path);
264 cargo.arg("--manifest-path").arg(dir.join("Cargo.toml"));
266 // We don't want to build tools dynamically as they'll be running across
267 // stages and such and it's just easier if they're not dynamically linked.
268 cargo.env("RUSTC_NO_PREFER_DYNAMIC", "1");
270 if source_type == SourceType::Submodule {
271 cargo.env("RUSTC_EXTERNAL_TOOL", "1");
274 if let Some(dir) = builder.openssl_install_dir(target) {
275 cargo.env("OPENSSL_STATIC", "1");
276 cargo.env("OPENSSL_DIR", dir);
277 cargo.env("LIBZ_SYS_STATIC", "1");
280 // if tools are using lzma we want to force the build script to build its
282 cargo.env("LZMA_API_STATIC", "1");
284 cargo.env("CFG_RELEASE_CHANNEL", &builder.config.channel);
285 cargo.env("CFG_VERSION", builder.rust_version());
287 let info = GitInfo::new(&builder.config, &dir);
288 if let Some(sha) = info.sha() {
289 cargo.env("CFG_COMMIT_HASH", sha);
291 if let Some(sha_short) = info.sha_short() {
292 cargo.env("CFG_SHORT_COMMIT_HASH", sha_short);
294 if let Some(date) = info.commit_date() {
295 cargo.env("CFG_COMMIT_DATE", date);
301 ($($name:ident, $path:expr, $tool_name:expr, $mode:expr
302 $(,llvm_tools = $llvm:expr)* $(,is_external_tool = $external:expr)*;)+) => {
303 #[derive(Copy, PartialEq, Eq, Clone)]
311 pub fn get_mode(&self) -> Mode {
312 let mode = match self {
313 $(Tool::$name => $mode,)+
318 /// Whether this tool requires LLVM to run
319 pub fn uses_llvm_tools(&self) -> bool {
321 $(Tool::$name => false $(|| $llvm)*,)+
326 impl<'a> Builder<'a> {
327 pub fn tool_exe(&self, tool: Tool) -> PathBuf {
328 let stage = self.tool_default_stage(tool);
332 compiler: self.compiler(stage, self.config.build),
333 target: self.config.build,
339 pub fn tool_default_stage(&self, tool: Tool) -> u32 {
340 // Compile the error-index in the same stage as rustdoc to avoid
341 // recompiling rustdoc twice if we can. Otherwise compile
342 // everything else in stage0 as there's no need to rebootstrap
345 Tool::ErrorIndex if self.top_stage >= 2 => self.top_stage,
352 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
354 pub compiler: Compiler,
355 pub target: Interned<String>,
358 impl Step for $name {
359 type Output = PathBuf;
361 fn should_run(run: ShouldRun) -> ShouldRun {
365 fn make_run(run: RunConfig) {
366 run.builder.ensure($name {
367 compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
372 fn run(self, builder: &Builder) -> PathBuf {
373 builder.ensure(ToolBuild {
374 compiler: self.compiler,
379 is_optional_tool: false,
380 source_type: if false $(|| $external)* {
381 SourceType::Submodule
385 extra_features: Vec::new(),
386 }).expect("expected to build -- essential tool")
394 Rustbook, "src/tools/rustbook", "rustbook", Mode::ToolBootstrap;
395 ErrorIndex, "src/tools/error_index_generator", "error_index_generator", Mode::ToolRustc;
396 UnstableBookGen, "src/tools/unstable-book-gen", "unstable-book-gen", Mode::ToolBootstrap;
397 Tidy, "src/tools/tidy", "tidy", Mode::ToolBootstrap;
398 Linkchecker, "src/tools/linkchecker", "linkchecker", Mode::ToolBootstrap;
399 CargoTest, "src/tools/cargotest", "cargotest", Mode::ToolBootstrap;
400 Compiletest, "src/tools/compiletest", "compiletest", Mode::ToolBootstrap, llvm_tools = true;
401 BuildManifest, "src/tools/build-manifest", "build-manifest", Mode::ToolBootstrap;
402 RemoteTestClient, "src/tools/remote-test-client", "remote-test-client", Mode::ToolBootstrap;
403 RustInstaller, "src/tools/rust-installer", "fabricate", Mode::ToolBootstrap,
404 is_external_tool = true;
405 RustdocTheme, "src/tools/rustdoc-themes", "rustdoc-themes", Mode::ToolBootstrap;
408 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
409 pub struct RemoteTestServer {
410 pub compiler: Compiler,
411 pub target: Interned<String>,
414 impl Step for RemoteTestServer {
415 type Output = PathBuf;
417 fn should_run(run: ShouldRun) -> ShouldRun {
418 run.path("src/tools/remote-test-server")
421 fn make_run(run: RunConfig) {
422 run.builder.ensure(RemoteTestServer {
423 compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
428 fn run(self, builder: &Builder) -> PathBuf {
429 builder.ensure(ToolBuild {
430 compiler: self.compiler,
432 tool: "remote-test-server",
434 path: "src/tools/remote-test-server",
435 is_optional_tool: false,
436 source_type: SourceType::InTree,
437 extra_features: Vec::new(),
438 }).expect("expected to build -- essential tool")
442 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
444 pub host: Interned<String>,
447 impl Step for Rustdoc {
448 type Output = PathBuf;
449 const DEFAULT: bool = true;
450 const ONLY_HOSTS: bool = true;
452 fn should_run(run: ShouldRun) -> ShouldRun {
453 run.path("src/tools/rustdoc")
456 fn make_run(run: RunConfig) {
457 run.builder.ensure(Rustdoc {
462 fn run(self, builder: &Builder) -> PathBuf {
463 let target_compiler = builder.compiler(builder.top_stage, self.host);
464 let target = target_compiler.host;
465 let build_compiler = if target_compiler.stage == 0 {
466 builder.compiler(0, builder.config.build)
467 } else if target_compiler.stage >= 2 {
468 // Past stage 2, we consider the compiler to be ABI-compatible and hence capable of
469 // building rustdoc itself.
470 builder.compiler(target_compiler.stage, builder.config.build)
472 // Similar to `compile::Assemble`, build with the previous stage's compiler. Otherwise
473 // we'd have stageN/bin/rustc and stageN/bin/rustdoc be effectively different stage
474 // compilers, which isn't what we want.
475 builder.compiler(target_compiler.stage - 1, builder.config.build)
478 builder.ensure(compile::Rustc { compiler: build_compiler, target });
479 builder.ensure(compile::Rustc {
480 compiler: build_compiler,
481 target: builder.config.build,
484 let mut cargo = prepare_tool_cargo(
494 // Most tools don't get debuginfo, but rustdoc should.
495 cargo.env("RUSTC_DEBUGINFO", builder.config.rust_debuginfo.to_string())
496 .env("RUSTC_DEBUGINFO_LINES", builder.config.rust_debuginfo_lines.to_string());
498 let _folder = builder.fold_output(|| format!("stage{}-rustdoc", target_compiler.stage));
499 builder.info(&format!("Building rustdoc for stage{} ({})",
500 target_compiler.stage, target_compiler.host));
501 builder.run(&mut cargo);
503 // Cargo adds a number of paths to the dylib search path on windows, which results in
504 // the wrong rustdoc being executed. To avoid the conflicting rustdocs, we name the "tool"
505 // rustdoc a different name.
506 let tool_rustdoc = builder.cargo_out(build_compiler, Mode::ToolRustc, target)
507 .join(exe("rustdoc_tool_binary", &target_compiler.host));
509 // don't create a stage0-sysroot/bin directory.
510 if target_compiler.stage > 0 {
511 let sysroot = builder.sysroot(target_compiler);
512 let bindir = sysroot.join("bin");
513 t!(fs::create_dir_all(&bindir));
514 let bin_rustdoc = bindir.join(exe("rustdoc", &*target_compiler.host));
515 let _ = fs::remove_file(&bin_rustdoc);
516 builder.copy(&tool_rustdoc, &bin_rustdoc);
524 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
526 pub compiler: Compiler,
527 pub target: Interned<String>,
530 impl Step for Cargo {
531 type Output = PathBuf;
532 const DEFAULT: bool = true;
533 const ONLY_HOSTS: bool = true;
535 fn should_run(run: ShouldRun) -> ShouldRun {
536 let builder = run.builder;
537 run.path("src/tools/cargo").default_condition(builder.config.extended)
540 fn make_run(run: RunConfig) {
541 run.builder.ensure(Cargo {
542 compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
547 fn run(self, builder: &Builder) -> PathBuf {
548 builder.ensure(native::Openssl {
551 // Cargo depends on procedural macros, which requires a full host
552 // compiler to be available, so we need to depend on that.
553 builder.ensure(compile::Rustc {
554 compiler: self.compiler,
555 target: builder.config.build,
557 builder.ensure(ToolBuild {
558 compiler: self.compiler,
561 mode: Mode::ToolRustc,
562 path: "src/tools/cargo",
563 is_optional_tool: false,
564 source_type: SourceType::Submodule,
565 extra_features: Vec::new(),
566 }).expect("expected to build -- essential tool")
570 macro_rules! tool_extended {
571 (($sel:ident, $builder:ident),
576 $extra_deps:block;)+) => {
578 #[derive(Debug, Clone, Hash, PartialEq, Eq)]
580 pub compiler: Compiler,
581 pub target: Interned<String>,
582 pub extra_features: Vec<String>,
585 impl Step for $name {
586 type Output = Option<PathBuf>;
587 const DEFAULT: bool = true;
588 const ONLY_HOSTS: bool = true;
590 fn should_run(run: ShouldRun) -> ShouldRun {
591 let builder = run.builder;
592 run.path($path).default_condition(builder.config.extended)
595 fn make_run(run: RunConfig) {
596 run.builder.ensure($name {
597 compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
599 extra_features: Vec::new(),
604 fn run(mut $sel, $builder: &Builder) -> Option<PathBuf> {
606 $builder.ensure(ToolBuild {
607 compiler: $sel.compiler,
610 mode: Mode::ToolRustc,
612 extra_features: $sel.extra_features,
613 is_optional_tool: true,
614 source_type: SourceType::Submodule,
622 tool_extended!((self, builder),
623 Cargofmt, rustfmt, "src/tools/rustfmt", "cargo-fmt", {};
624 CargoClippy, clippy, "src/tools/clippy", "cargo-clippy", {
625 // Clippy depends on procedural macros (serde), which requires a full host
626 // compiler to be available, so we need to depend on that.
627 builder.ensure(compile::Rustc {
628 compiler: self.compiler,
629 target: builder.config.build,
632 Clippy, clippy, "src/tools/clippy", "clippy-driver", {
633 // Clippy 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 Miri, miri, "src/tools/miri", "miri", {};
641 Rls, rls, "src/tools/rls", "rls", {
642 let clippy = builder.ensure(Clippy {
643 compiler: self.compiler,
645 extra_features: Vec::new(),
647 if clippy.is_some() {
648 self.extra_features.push("clippy".to_owned());
650 builder.ensure(native::Openssl {
653 // RLS depends on procedural macros, which requires a full host
654 // compiler to be available, so we need to depend on that.
655 builder.ensure(compile::Rustc {
656 compiler: self.compiler,
657 target: builder.config.build,
660 Rustfmt, rustfmt, "src/tools/rustfmt", "rustfmt", {};
663 impl<'a> Builder<'a> {
664 /// Get a `Command` which is ready to run `tool` in `stage` built for
666 pub fn tool_cmd(&self, tool: Tool) -> Command {
667 let mut cmd = Command::new(self.tool_exe(tool));
668 let compiler = self.compiler(self.tool_default_stage(tool), self.config.build);
669 self.prepare_tool_cmd(compiler, tool, &mut cmd);
673 /// Prepares the `cmd` provided to be able to run the `compiler` provided.
675 /// Notably this munges the dynamic library lookup path to point to the
676 /// right location to run `compiler`.
677 fn prepare_tool_cmd(&self, compiler: Compiler, tool: Tool, cmd: &mut Command) {
678 let host = &compiler.host;
679 let mut lib_paths: Vec<PathBuf> = vec![
680 if compiler.stage == 0 && tool != Tool::ErrorIndex {
681 self.build.rustc_snapshot_libdir()
683 PathBuf::from(&self.sysroot_libdir(compiler, compiler.host))
685 self.cargo_out(compiler, tool.get_mode(), *host).join("deps"),
688 // On MSVC a tool may invoke a C compiler (e.g. compiletest in run-make
689 // mode) and that C compiler may need some extra PATH modification. Do
691 if compiler.host.contains("msvc") {
692 let curpaths = env::var_os("PATH").unwrap_or_default();
693 let curpaths = env::split_paths(&curpaths).collect::<Vec<_>>();
694 for &(ref k, ref v) in self.cc[&compiler.host].env() {
698 for path in env::split_paths(v) {
699 if !curpaths.contains(&path) {
700 lib_paths.push(path);
706 // Add the llvm/bin directory to PATH since it contains lots of
707 // useful, platform-independent tools
708 if tool.uses_llvm_tools() {
709 if let Some(llvm_bin_path) = self.llvm_bin_path() {
710 if host.contains("windows") {
711 // On Windows, PATH and the dynamic library path are the same,
712 // so we just add the LLVM bin path to lib_path
713 lib_paths.push(llvm_bin_path);
715 let old_path = env::var_os("PATH").unwrap_or_default();
716 let new_path = env::join_paths(iter::once(llvm_bin_path)
717 .chain(env::split_paths(&old_path)))
718 .expect("Could not add LLVM bin path to PATH");
719 cmd.env("PATH", new_path);
724 add_lib_path(lib_paths, cmd);
727 fn llvm_bin_path(&self) -> Option<PathBuf> {
728 if self.config.llvm_enabled && !self.config.dry_run {
729 let llvm_config = self.ensure(native::Llvm {
730 target: self.config.build,
734 // Add the llvm/bin directory to PATH since it contains lots of
735 // useful, platform-independent tools
736 let llvm_bin_path = llvm_config.parent()
737 .expect("Expected llvm-config to be contained in directory");
738 assert!(llvm_bin_path.is_dir());
739 Some(llvm_bin_path.to_path_buf())