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 panic!("tools should not compile multiple copies of the same crate");
227 builder.save_toolstate(tool, if is_expected {
234 if !is_optional_tool {
240 let cargo_out = builder.cargo_out(compiler, self.mode, target)
241 .join(exe(tool, &compiler.host));
242 let bin = builder.tools_dir(compiler).join(exe(tool, &compiler.host));
243 builder.copy(&cargo_out, &bin);
249 pub fn prepare_tool_cargo(
253 target: Interned<String>,
254 command: &'static str,
256 source_type: SourceType,
258 let mut cargo = builder.cargo(compiler, mode, target, command);
259 let dir = builder.src.join(path);
260 cargo.arg("--manifest-path").arg(dir.join("Cargo.toml"));
262 // We don't want to build tools dynamically as they'll be running across
263 // stages and such and it's just easier if they're not dynamically linked.
264 cargo.env("RUSTC_NO_PREFER_DYNAMIC", "1");
266 if source_type == SourceType::Submodule {
267 cargo.env("RUSTC_EXTERNAL_TOOL", "1");
270 if let Some(dir) = builder.openssl_install_dir(target) {
271 cargo.env("OPENSSL_STATIC", "1");
272 cargo.env("OPENSSL_DIR", dir);
273 cargo.env("LIBZ_SYS_STATIC", "1");
276 // if tools are using lzma we want to force the build script to build its
278 cargo.env("LZMA_API_STATIC", "1");
280 cargo.env("CFG_RELEASE_CHANNEL", &builder.config.channel);
281 cargo.env("CFG_VERSION", builder.rust_version());
283 let info = GitInfo::new(&builder.config, &dir);
284 if let Some(sha) = info.sha() {
285 cargo.env("CFG_COMMIT_HASH", sha);
287 if let Some(sha_short) = info.sha_short() {
288 cargo.env("CFG_SHORT_COMMIT_HASH", sha_short);
290 if let Some(date) = info.commit_date() {
291 cargo.env("CFG_COMMIT_DATE", date);
297 ($($name:ident, $path:expr, $tool_name:expr, $mode:expr
298 $(,llvm_tools = $llvm:expr)* $(,is_external_tool = $external:expr)*;)+) => {
299 #[derive(Copy, PartialEq, Eq, Clone)]
307 pub fn get_mode(&self) -> Mode {
308 let mode = match self {
309 $(Tool::$name => $mode,)+
314 /// Whether this tool requires LLVM to run
315 pub fn uses_llvm_tools(&self) -> bool {
317 $(Tool::$name => false $(|| $llvm)*,)+
322 impl<'a> Builder<'a> {
323 pub fn tool_exe(&self, tool: Tool) -> PathBuf {
324 let stage = self.tool_default_stage(tool);
328 compiler: self.compiler(stage, self.config.build),
329 target: self.config.build,
335 pub fn tool_default_stage(&self, tool: Tool) -> u32 {
336 // Compile the error-index in the same stage as rustdoc to avoid
337 // recompiling rustdoc twice if we can. Otherwise compile
338 // everything else in stage0 as there's no need to rebootstrap
341 Tool::ErrorIndex if self.top_stage >= 2 => self.top_stage,
348 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
350 pub compiler: Compiler,
351 pub target: Interned<String>,
354 impl Step for $name {
355 type Output = PathBuf;
357 fn should_run(run: ShouldRun) -> ShouldRun {
361 fn make_run(run: RunConfig) {
362 run.builder.ensure($name {
363 compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
368 fn run(self, builder: &Builder) -> PathBuf {
369 builder.ensure(ToolBuild {
370 compiler: self.compiler,
375 is_optional_tool: false,
376 source_type: if false $(|| $external)* {
377 SourceType::Submodule
381 extra_features: Vec::new(),
382 }).expect("expected to build -- essential tool")
390 Rustbook, "src/tools/rustbook", "rustbook", Mode::ToolBootstrap;
391 ErrorIndex, "src/tools/error_index_generator", "error_index_generator", Mode::ToolRustc;
392 UnstableBookGen, "src/tools/unstable-book-gen", "unstable-book-gen", Mode::ToolBootstrap;
393 Tidy, "src/tools/tidy", "tidy", Mode::ToolBootstrap;
394 Linkchecker, "src/tools/linkchecker", "linkchecker", Mode::ToolBootstrap;
395 CargoTest, "src/tools/cargotest", "cargotest", Mode::ToolBootstrap;
396 Compiletest, "src/tools/compiletest", "compiletest", Mode::ToolBootstrap, llvm_tools = true;
397 BuildManifest, "src/tools/build-manifest", "build-manifest", Mode::ToolBootstrap;
398 RemoteTestClient, "src/tools/remote-test-client", "remote-test-client", Mode::ToolBootstrap;
399 RustInstaller, "src/tools/rust-installer", "fabricate", Mode::ToolBootstrap,
400 is_external_tool = true;
401 RustdocTheme, "src/tools/rustdoc-themes", "rustdoc-themes", Mode::ToolBootstrap;
404 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
405 pub struct RemoteTestServer {
406 pub compiler: Compiler,
407 pub target: Interned<String>,
410 impl Step for RemoteTestServer {
411 type Output = PathBuf;
413 fn should_run(run: ShouldRun) -> ShouldRun {
414 run.path("src/tools/remote-test-server")
417 fn make_run(run: RunConfig) {
418 run.builder.ensure(RemoteTestServer {
419 compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
424 fn run(self, builder: &Builder) -> PathBuf {
425 builder.ensure(ToolBuild {
426 compiler: self.compiler,
428 tool: "remote-test-server",
430 path: "src/tools/remote-test-server",
431 is_optional_tool: false,
432 source_type: SourceType::InTree,
433 extra_features: Vec::new(),
434 }).expect("expected to build -- essential tool")
438 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
440 pub host: Interned<String>,
443 impl Step for Rustdoc {
444 type Output = PathBuf;
445 const DEFAULT: bool = true;
446 const ONLY_HOSTS: bool = true;
448 fn should_run(run: ShouldRun) -> ShouldRun {
449 run.path("src/tools/rustdoc")
452 fn make_run(run: RunConfig) {
453 run.builder.ensure(Rustdoc {
458 fn run(self, builder: &Builder) -> PathBuf {
459 let target_compiler = builder.compiler(builder.top_stage, self.host);
460 let target = target_compiler.host;
461 let build_compiler = if target_compiler.stage == 0 {
462 builder.compiler(0, builder.config.build)
463 } else if target_compiler.stage >= 2 {
464 // Past stage 2, we consider the compiler to be ABI-compatible and hence capable of
465 // building rustdoc itself.
466 builder.compiler(target_compiler.stage, builder.config.build)
468 // Similar to `compile::Assemble`, build with the previous stage's compiler. Otherwise
469 // we'd have stageN/bin/rustc and stageN/bin/rustdoc be effectively different stage
470 // compilers, which isn't what we want.
471 builder.compiler(target_compiler.stage - 1, builder.config.build)
474 builder.ensure(compile::Rustc { compiler: build_compiler, target });
475 builder.ensure(compile::Rustc {
476 compiler: build_compiler,
477 target: builder.config.build,
480 let mut cargo = prepare_tool_cargo(
490 // Most tools don't get debuginfo, but rustdoc should.
491 cargo.env("RUSTC_DEBUGINFO", builder.config.rust_debuginfo.to_string())
492 .env("RUSTC_DEBUGINFO_LINES", builder.config.rust_debuginfo_lines.to_string());
494 let _folder = builder.fold_output(|| format!("stage{}-rustdoc", target_compiler.stage));
495 builder.info(&format!("Building rustdoc for stage{} ({})",
496 target_compiler.stage, target_compiler.host));
497 builder.run(&mut cargo);
499 // Cargo adds a number of paths to the dylib search path on windows, which results in
500 // the wrong rustdoc being executed. To avoid the conflicting rustdocs, we name the "tool"
501 // rustdoc a different name.
502 let tool_rustdoc = builder.cargo_out(build_compiler, Mode::ToolRustc, target)
503 .join(exe("rustdoc_tool_binary", &target_compiler.host));
505 // don't create a stage0-sysroot/bin directory.
506 if target_compiler.stage > 0 {
507 let sysroot = builder.sysroot(target_compiler);
508 let bindir = sysroot.join("bin");
509 t!(fs::create_dir_all(&bindir));
510 let bin_rustdoc = bindir.join(exe("rustdoc", &*target_compiler.host));
511 let _ = fs::remove_file(&bin_rustdoc);
512 builder.copy(&tool_rustdoc, &bin_rustdoc);
520 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
522 pub compiler: Compiler,
523 pub target: Interned<String>,
526 impl Step for Cargo {
527 type Output = PathBuf;
528 const DEFAULT: bool = true;
529 const ONLY_HOSTS: bool = true;
531 fn should_run(run: ShouldRun) -> ShouldRun {
532 let builder = run.builder;
533 run.path("src/tools/cargo").default_condition(builder.config.extended)
536 fn make_run(run: RunConfig) {
537 run.builder.ensure(Cargo {
538 compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
543 fn run(self, builder: &Builder) -> PathBuf {
544 builder.ensure(native::Openssl {
547 // Cargo depends on procedural macros, which requires a full host
548 // compiler to be available, so we need to depend on that.
549 builder.ensure(compile::Rustc {
550 compiler: self.compiler,
551 target: builder.config.build,
553 builder.ensure(ToolBuild {
554 compiler: self.compiler,
557 mode: Mode::ToolRustc,
558 path: "src/tools/cargo",
559 is_optional_tool: false,
560 source_type: SourceType::Submodule,
561 extra_features: Vec::new(),
562 }).expect("expected to build -- essential tool")
566 macro_rules! tool_extended {
567 (($sel:ident, $builder:ident),
572 $extra_deps:block;)+) => {
574 #[derive(Debug, Clone, Hash, PartialEq, Eq)]
576 pub compiler: Compiler,
577 pub target: Interned<String>,
578 pub extra_features: Vec<String>,
581 impl Step for $name {
582 type Output = Option<PathBuf>;
583 const DEFAULT: bool = true;
584 const ONLY_HOSTS: bool = true;
586 fn should_run(run: ShouldRun) -> ShouldRun {
587 let builder = run.builder;
588 run.path($path).default_condition(builder.config.extended)
591 fn make_run(run: RunConfig) {
592 run.builder.ensure($name {
593 compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
595 extra_features: Vec::new(),
600 fn run(mut $sel, $builder: &Builder) -> Option<PathBuf> {
602 $builder.ensure(ToolBuild {
603 compiler: $sel.compiler,
606 mode: Mode::ToolRustc,
608 extra_features: $sel.extra_features,
609 is_optional_tool: true,
610 source_type: SourceType::Submodule,
618 tool_extended!((self, builder),
619 Cargofmt, rustfmt, "src/tools/rustfmt", "cargo-fmt", {};
620 CargoClippy, clippy, "src/tools/clippy", "cargo-clippy", {
621 // Clippy depends on procedural macros (serde), which requires a full host
622 // compiler to be available, so we need to depend on that.
623 builder.ensure(compile::Rustc {
624 compiler: self.compiler,
625 target: builder.config.build,
628 Clippy, clippy, "src/tools/clippy", "clippy-driver", {
629 // Clippy depends on procedural macros (serde), which requires a full host
630 // compiler to be available, so we need to depend on that.
631 builder.ensure(compile::Rustc {
632 compiler: self.compiler,
633 target: builder.config.build,
636 Miri, miri, "src/tools/miri", "miri", {};
637 Rls, rls, "src/tools/rls", "rls", {
638 let clippy = builder.ensure(Clippy {
639 compiler: self.compiler,
641 extra_features: Vec::new(),
643 if clippy.is_some() {
644 self.extra_features.push("clippy".to_owned());
646 builder.ensure(native::Openssl {
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 /// Get 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(self.tool_default_stage(tool), 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 && tool != Tool::ErrorIndex {
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 the llvm/bin directory to PATH since it contains lots of
703 // useful, platform-independent tools
704 if tool.uses_llvm_tools() {
705 if let Some(llvm_bin_path) = self.llvm_bin_path() {
706 if host.contains("windows") {
707 // On Windows, PATH and the dynamic library path are the same,
708 // so we just add the LLVM bin path to lib_path
709 lib_paths.push(llvm_bin_path);
711 let old_path = env::var_os("PATH").unwrap_or_default();
712 let new_path = env::join_paths(iter::once(llvm_bin_path)
713 .chain(env::split_paths(&old_path)))
714 .expect("Could not add LLVM bin path to PATH");
715 cmd.env("PATH", new_path);
720 add_lib_path(lib_paths, cmd);
723 fn llvm_bin_path(&self) -> Option<PathBuf> {
724 if self.config.llvm_enabled && !self.config.dry_run {
725 let llvm_config = self.ensure(native::Llvm {
726 target: self.config.build,
730 // Add the llvm/bin directory to PATH since it contains lots of
731 // useful, platform-independent tools
732 let llvm_bin_path = llvm_config.parent()
733 .expect("Expected llvm-config to be contained in directory");
734 assert!(llvm_bin_path.is_dir());
735 Some(llvm_bin_path.to_path_buf())