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)]
81 target: Interned<String>,
86 extra_features: Vec<String>,
89 impl Step for ToolBuild {
90 type Output = Option<PathBuf>;
92 fn should_run(run: ShouldRun) -> ShouldRun {
96 /// Build a tool in `src/tools`
98 /// This will build the specified tool with the specified `host` compiler in
99 /// `stage` into the normal cargo output directory.
100 fn run(self, builder: &Builder) -> Option<PathBuf> {
101 let compiler = self.compiler;
102 let target = self.target;
103 let tool = self.tool;
104 let path = self.path;
105 let is_ext_tool = self.is_ext_tool;
109 builder.ensure(compile::Rustc { compiler, target })
112 builder.ensure(compile::Std { compiler, target })
114 Mode::ToolBootstrap => {} // uses downloaded stage0 compiler libs
115 _ => panic!("unexpected Mode for tool build")
118 let mut cargo = prepare_tool_cargo(builder, compiler, self.mode, target, "build", path);
119 cargo.arg("--features").arg(self.extra_features.join(" "));
121 let _folder = builder.fold_output(|| format!("stage{}-{}", compiler.stage, tool));
122 builder.info(&format!("Building stage{} tool {} ({})", compiler.stage, tool, target));
123 let mut duplicates = Vec::new();
124 let is_expected = compile::stream_cargo(builder, &mut cargo, &mut |msg| {
125 // Only care about big things like the RLS/Cargo for now
134 let (id, features, filenames) = match msg {
135 compile::CargoMessage::CompilerArtifact {
140 (package_id, features, filenames)
144 let features = features.iter().map(|s| s.to_string()).collect::<Vec<_>>();
146 for path in filenames {
147 let val = (tool, PathBuf::from(&*path), features.clone());
148 // we're only interested in deduplicating rlibs for now
149 if val.1.extension().and_then(|s| s.to_str()) != Some("rlib") {
153 // Don't worry about libs that turn out to be host dependencies
154 // or build scripts, we only care about target dependencies that
156 if let Some(maybe_target) = val.1
157 .parent() // chop off file name
158 .and_then(|p| p.parent()) // chop off `deps`
159 .and_then(|p| p.parent()) // chop off `release`
160 .and_then(|p| p.file_name())
161 .and_then(|p| p.to_str())
163 if maybe_target != &*target {
168 let mut artifacts = builder.tool_artifacts.borrow_mut();
169 let prev_artifacts = artifacts
171 .or_insert_with(Default::default);
172 if let Some(prev) = prev_artifacts.get(&*id) {
182 prev_artifacts.insert(id.to_string(), val);
186 if is_expected && duplicates.len() != 0 {
187 println!("duplicate artfacts found when compiling a tool, this \
188 typically means that something was recompiled because \
189 a transitive dependency has different features activated \
190 than in a previous build:\n");
191 println!("the following dependencies are duplicated although they \
192 have the same features enabled:");
193 for (id, cur, prev) in duplicates.drain_filter(|(_, cur, prev)| cur.2 == prev.2) {
196 println!(" `{}` ({:?})\n `{}` ({:?})", cur.0, cur.1, prev.0, prev.1);
198 println!("the following dependencies have different features:");
199 for (id, cur, prev) in duplicates {
201 let cur_features: HashSet<_> = cur.2.into_iter().collect();
202 let prev_features: HashSet<_> = prev.2.into_iter().collect();
203 println!(" `{}` additionally enabled features {:?} at {:?}",
204 cur.0, &cur_features - &prev_features, cur.1);
205 println!(" `{}` additionally enabled features {:?} at {:?}",
206 prev.0, &prev_features - &cur_features, prev.1);
209 panic!("tools should not compile multiple copies of the same crate");
212 builder.save_toolstate(tool, if is_expected {
225 let cargo_out = builder.cargo_out(compiler, self.mode, target)
226 .join(exe(tool, &compiler.host));
227 let bin = builder.tools_dir(compiler).join(exe(tool, &compiler.host));
228 builder.copy(&cargo_out, &bin);
234 pub fn prepare_tool_cargo(
238 target: Interned<String>,
239 command: &'static str,
242 let mut cargo = builder.cargo(compiler, mode, target, command);
243 let dir = builder.src.join(path);
244 cargo.arg("--manifest-path").arg(dir.join("Cargo.toml"));
246 // We don't want to build tools dynamically as they'll be running across
247 // stages and such and it's just easier if they're not dynamically linked.
248 cargo.env("RUSTC_NO_PREFER_DYNAMIC", "1");
250 if let Some(dir) = builder.openssl_install_dir(target) {
251 cargo.env("OPENSSL_STATIC", "1");
252 cargo.env("OPENSSL_DIR", dir);
253 cargo.env("LIBZ_SYS_STATIC", "1");
256 // if tools are using lzma we want to force the build script to build its
258 cargo.env("LZMA_API_STATIC", "1");
260 cargo.env("CFG_RELEASE_CHANNEL", &builder.config.channel);
261 cargo.env("CFG_VERSION", builder.rust_version());
263 let info = GitInfo::new(&builder.config, &dir);
264 if let Some(sha) = info.sha() {
265 cargo.env("CFG_COMMIT_HASH", sha);
267 if let Some(sha_short) = info.sha_short() {
268 cargo.env("CFG_SHORT_COMMIT_HASH", sha_short);
270 if let Some(date) = info.commit_date() {
271 cargo.env("CFG_COMMIT_DATE", date);
277 ($($name:ident, $path:expr, $tool_name:expr, $mode:expr $(,llvm_tools = $llvm:expr)*;)+) => {
278 #[derive(Copy, Clone)]
286 pub fn get_mode(&self) -> Mode {
287 let mode = match self {
288 $(Tool::$name => $mode,)+
293 /// Whether this tool requires LLVM to run
294 pub fn uses_llvm_tools(&self) -> bool {
296 $(Tool::$name => false $(|| $llvm)*,)+
301 impl<'a> Builder<'a> {
302 pub fn tool_exe(&self, tool: Tool) -> PathBuf {
303 let stage = self.tool_default_stage(tool);
307 compiler: self.compiler(stage, self.config.build),
308 target: self.config.build,
314 pub fn tool_default_stage(&self, tool: Tool) -> u32 {
315 // Compile the error-index in the same stage as rustdoc to avoid
316 // recompiling rustdoc twice if we can. Otherwise compile
317 // everything else in stage0 as there's no need to rebootstrap
320 Tool::ErrorIndex if self.top_stage >= 2 => self.top_stage,
327 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
329 pub compiler: Compiler,
330 pub target: Interned<String>,
333 impl Step for $name {
334 type Output = PathBuf;
336 fn should_run(run: ShouldRun) -> ShouldRun {
340 fn make_run(run: RunConfig) {
341 run.builder.ensure($name {
342 compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
347 fn run(self, builder: &Builder) -> PathBuf {
348 builder.ensure(ToolBuild {
349 compiler: self.compiler,
355 extra_features: Vec::new(),
356 }).expect("expected to build -- essential tool")
364 Rustbook, "src/tools/rustbook", "rustbook", Mode::ToolBootstrap;
365 ErrorIndex, "src/tools/error_index_generator", "error_index_generator", Mode::ToolRustc;
366 UnstableBookGen, "src/tools/unstable-book-gen", "unstable-book-gen", Mode::ToolBootstrap;
367 Tidy, "src/tools/tidy", "tidy", Mode::ToolBootstrap;
368 Linkchecker, "src/tools/linkchecker", "linkchecker", Mode::ToolBootstrap;
369 CargoTest, "src/tools/cargotest", "cargotest", Mode::ToolBootstrap;
370 Compiletest, "src/tools/compiletest", "compiletest", Mode::ToolBootstrap, llvm_tools = true;
371 BuildManifest, "src/tools/build-manifest", "build-manifest", Mode::ToolBootstrap;
372 RemoteTestClient, "src/tools/remote-test-client", "remote-test-client", Mode::ToolBootstrap;
373 RustInstaller, "src/tools/rust-installer", "fabricate", Mode::ToolBootstrap;
374 RustdocTheme, "src/tools/rustdoc-themes", "rustdoc-themes", Mode::ToolBootstrap;
377 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
378 pub struct RemoteTestServer {
379 pub compiler: Compiler,
380 pub target: Interned<String>,
383 impl Step for RemoteTestServer {
384 type Output = PathBuf;
386 fn should_run(run: ShouldRun) -> ShouldRun {
387 run.path("src/tools/remote-test-server")
390 fn make_run(run: RunConfig) {
391 run.builder.ensure(RemoteTestServer {
392 compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
397 fn run(self, builder: &Builder) -> PathBuf {
398 builder.ensure(ToolBuild {
399 compiler: self.compiler,
401 tool: "remote-test-server",
403 path: "src/tools/remote-test-server",
405 extra_features: Vec::new(),
406 }).expect("expected to build -- essential tool")
410 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
412 pub host: Interned<String>,
415 impl Step for Rustdoc {
416 type Output = PathBuf;
417 const DEFAULT: bool = true;
418 const ONLY_HOSTS: bool = true;
420 fn should_run(run: ShouldRun) -> ShouldRun {
421 run.path("src/tools/rustdoc")
424 fn make_run(run: RunConfig) {
425 run.builder.ensure(Rustdoc {
430 fn run(self, builder: &Builder) -> PathBuf {
431 let target_compiler = builder.compiler(builder.top_stage, self.host);
432 let target = target_compiler.host;
433 let build_compiler = if target_compiler.stage == 0 {
434 builder.compiler(0, builder.config.build)
435 } else if target_compiler.stage >= 2 {
436 // Past stage 2, we consider the compiler to be ABI-compatible and hence capable of
437 // building rustdoc itself.
438 builder.compiler(target_compiler.stage, builder.config.build)
440 // Similar to `compile::Assemble`, build with the previous stage's compiler. Otherwise
441 // we'd have stageN/bin/rustc and stageN/bin/rustdoc be effectively different stage
442 // compilers, which isn't what we want.
443 builder.compiler(target_compiler.stage - 1, builder.config.build)
446 builder.ensure(compile::Rustc { compiler: build_compiler, target });
447 builder.ensure(compile::Rustc {
448 compiler: build_compiler,
449 target: builder.config.build,
452 let mut cargo = prepare_tool_cargo(builder,
457 "src/tools/rustdoc");
459 // Most tools don't get debuginfo, but rustdoc should.
460 cargo.env("RUSTC_DEBUGINFO", builder.config.rust_debuginfo.to_string())
461 .env("RUSTC_DEBUGINFO_LINES", builder.config.rust_debuginfo_lines.to_string());
463 let _folder = builder.fold_output(|| format!("stage{}-rustdoc", target_compiler.stage));
464 builder.info(&format!("Building rustdoc for stage{} ({})",
465 target_compiler.stage, target_compiler.host));
466 builder.run(&mut cargo);
468 // Cargo adds a number of paths to the dylib search path on windows, which results in
469 // the wrong rustdoc being executed. To avoid the conflicting rustdocs, we name the "tool"
470 // rustdoc a different name.
471 let tool_rustdoc = builder.cargo_out(build_compiler, Mode::ToolRustc, target)
472 .join(exe("rustdoc_tool_binary", &target_compiler.host));
474 // don't create a stage0-sysroot/bin directory.
475 if target_compiler.stage > 0 {
476 let sysroot = builder.sysroot(target_compiler);
477 let bindir = sysroot.join("bin");
478 t!(fs::create_dir_all(&bindir));
479 let bin_rustdoc = bindir.join(exe("rustdoc", &*target_compiler.host));
480 let _ = fs::remove_file(&bin_rustdoc);
481 builder.copy(&tool_rustdoc, &bin_rustdoc);
489 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
491 pub compiler: Compiler,
492 pub target: Interned<String>,
495 impl Step for Cargo {
496 type Output = PathBuf;
497 const DEFAULT: bool = true;
498 const ONLY_HOSTS: bool = true;
500 fn should_run(run: ShouldRun) -> ShouldRun {
501 let builder = run.builder;
502 run.path("src/tools/cargo").default_condition(builder.config.extended)
505 fn make_run(run: RunConfig) {
506 run.builder.ensure(Cargo {
507 compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
512 fn run(self, builder: &Builder) -> PathBuf {
513 builder.ensure(native::Openssl {
516 // Cargo depends on procedural macros, which requires a full host
517 // compiler to be available, so we need to depend on that.
518 builder.ensure(compile::Rustc {
519 compiler: self.compiler,
520 target: builder.config.build,
522 builder.ensure(ToolBuild {
523 compiler: self.compiler,
526 mode: Mode::ToolRustc,
527 path: "src/tools/cargo",
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,
585 tool_extended!((self, builder),
586 Cargofmt, rustfmt, "src/tools/rustfmt", "cargo-fmt", {};
587 CargoClippy, clippy, "src/tools/clippy", "cargo-clippy", {
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 Clippy, clippy, "src/tools/clippy", "clippy-driver", {
596 // Clippy depends on procedural macros (serde), which requires a full host
597 // compiler to be available, so we need to depend on that.
598 builder.ensure(compile::Rustc {
599 compiler: self.compiler,
600 target: builder.config.build,
603 Miri, miri, "src/tools/miri", "miri", {};
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 builder.ensure(native::Openssl {
616 // RLS depends on procedural macros, which requires a full host
617 // compiler to be available, so we need to depend on that.
618 builder.ensure(compile::Rustc {
619 compiler: self.compiler,
620 target: builder.config.build,
623 Rustfmt, rustfmt, "src/tools/rustfmt", "rustfmt", {};
626 impl<'a> Builder<'a> {
627 /// Get a `Command` which is ready to run `tool` in `stage` built for
629 pub fn tool_cmd(&self, tool: Tool) -> Command {
630 let mut cmd = Command::new(self.tool_exe(tool));
631 let compiler = self.compiler(self.tool_default_stage(tool), self.config.build);
632 self.prepare_tool_cmd(compiler, tool, &mut cmd);
636 /// Prepares the `cmd` provided to be able to run the `compiler` provided.
638 /// Notably this munges the dynamic library lookup path to point to the
639 /// right location to run `compiler`.
640 fn prepare_tool_cmd(&self, compiler: Compiler, tool: Tool, cmd: &mut Command) {
641 let host = &compiler.host;
642 let mut lib_paths: Vec<PathBuf> = vec![
643 if compiler.stage == 0 {
644 self.build.rustc_snapshot_libdir()
646 PathBuf::from(&self.sysroot_libdir(compiler, compiler.host))
648 self.cargo_out(compiler, tool.get_mode(), *host).join("deps"),
651 // On MSVC a tool may invoke a C compiler (e.g. compiletest in run-make
652 // mode) and that C compiler may need some extra PATH modification. Do
654 if compiler.host.contains("msvc") {
655 let curpaths = env::var_os("PATH").unwrap_or_default();
656 let curpaths = env::split_paths(&curpaths).collect::<Vec<_>>();
657 for &(ref k, ref v) in self.cc[&compiler.host].env() {
661 for path in env::split_paths(v) {
662 if !curpaths.contains(&path) {
663 lib_paths.push(path);
669 // Add the llvm/bin directory to PATH since it contains lots of
670 // useful, platform-independent tools
671 if tool.uses_llvm_tools() {
672 if let Some(llvm_bin_path) = self.llvm_bin_path() {
673 if host.contains("windows") {
674 // On Windows, PATH and the dynamic library path are the same,
675 // so we just add the LLVM bin path to lib_path
676 lib_paths.push(llvm_bin_path);
678 let old_path = env::var_os("PATH").unwrap_or_default();
679 let new_path = env::join_paths(iter::once(llvm_bin_path)
680 .chain(env::split_paths(&old_path)))
681 .expect("Could not add LLVM bin path to PATH");
682 cmd.env("PATH", new_path);
687 add_lib_path(lib_paths, cmd);
690 fn llvm_bin_path(&self) -> Option<PathBuf> {
691 if self.config.llvm_enabled && !self.config.dry_run {
692 let llvm_config = self.ensure(native::Llvm {
693 target: self.config.build,
697 // Add the llvm/bin directory to PATH since it contains lots of
698 // useful, platform-independent tools
699 let llvm_bin_path = llvm_config.parent()
700 .expect("Expected llvm-config to be contained in directory");
701 assert!(llvm_bin_path.is_dir());
702 Some(llvm_bin_path.to_path_buf())