3 use std::path::PathBuf;
4 use std::process::{Command, exit};
5 use std::collections::HashSet;
11 use crate::builder::{Step, RunConfig, ShouldRun, Builder};
12 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 /// Builds 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, vec![], &mut |msg| {
81 // Only care about big things like the RLS/Cargo for now
92 let (id, features, filenames) = match msg {
93 compile::CargoMessage::CompilerArtifact {
99 (package_id, features, filenames)
103 let features = features.iter().map(|s| s.to_string()).collect::<Vec<_>>();
105 for path in filenames {
106 let val = (tool, PathBuf::from(&*path), features.clone());
107 // we're only interested in deduplicating rlibs for now
108 if val.1.extension().and_then(|s| s.to_str()) != Some("rlib") {
112 // Don't worry about libs that turn out to be host dependencies
113 // or build scripts, we only care about target dependencies that
115 if let Some(maybe_target) = val.1
116 .parent() // chop off file name
117 .and_then(|p| p.parent()) // chop off `deps`
118 .and_then(|p| p.parent()) // chop off `release`
119 .and_then(|p| p.file_name())
120 .and_then(|p| p.to_str())
122 if maybe_target != &*target {
127 let mut artifacts = builder.tool_artifacts.borrow_mut();
128 let prev_artifacts = artifacts
131 if let Some(prev) = prev_artifacts.get(&*id) {
141 prev_artifacts.insert(id.to_string(), val);
145 if is_expected && !duplicates.is_empty() {
146 println!("duplicate artifacts found when compiling a tool, this \
147 typically means that something was recompiled because \
148 a transitive dependency has different features activated \
149 than in a previous build:\n");
150 println!("the following dependencies are duplicated although they \
151 have the same features enabled:");
152 for (id, cur, prev) in duplicates.drain_filter(|(_, cur, prev)| cur.2 == prev.2) {
155 println!(" `{}` ({:?})\n `{}` ({:?})", cur.0, cur.1, prev.0, prev.1);
157 println!("the following dependencies have different features:");
158 for (id, cur, prev) in duplicates {
160 let cur_features: HashSet<_> = cur.2.into_iter().collect();
161 let prev_features: HashSet<_> = prev.2.into_iter().collect();
162 println!(" `{}` additionally enabled features {:?} at {:?}",
163 cur.0, &cur_features - &prev_features, cur.1);
164 println!(" `{}` additionally enabled features {:?} at {:?}",
165 prev.0, &prev_features - &cur_features, prev.1);
168 println!("to fix this you will probably want to edit the local \
169 src/tools/rustc-workspace-hack/Cargo.toml crate, as \
170 that will update the dependency graph to ensure that \
171 these crates all share the same feature set");
172 panic!("tools should not compile multiple copies of the same crate");
175 builder.save_toolstate(tool, if is_expected {
182 if !is_optional_tool {
188 let cargo_out = builder.cargo_out(compiler, self.mode, target)
189 .join(exe(tool, &compiler.host));
190 let bin = builder.tools_dir(compiler).join(exe(tool, &compiler.host));
191 builder.copy(&cargo_out, &bin);
197 pub fn prepare_tool_cargo(
198 builder: &Builder<'_>,
201 target: Interned<String>,
202 command: &'static str,
204 source_type: SourceType,
205 extra_features: &[String],
207 let mut cargo = builder.cargo(compiler, mode, target, command);
208 let dir = builder.src.join(path);
209 cargo.arg("--manifest-path").arg(dir.join("Cargo.toml"));
211 // We don't want to build tools dynamically as they'll be running across
212 // stages and such and it's just easier if they're not dynamically linked.
213 cargo.env("RUSTC_NO_PREFER_DYNAMIC", "1");
215 if source_type == SourceType::Submodule {
216 cargo.env("RUSTC_EXTERNAL_TOOL", "1");
219 let mut features = extra_features.iter().cloned().collect::<Vec<_>>();
220 if builder.build.config.cargo_native_static {
221 if path.ends_with("cargo") ||
222 path.ends_with("rls") ||
223 path.ends_with("clippy") ||
224 path.ends_with("miri") ||
225 path.ends_with("rustfmt")
227 cargo.env("LIBZ_SYS_STATIC", "1");
228 features.push("rustc-workspace-hack/all-static".to_string());
232 // if tools are using lzma we want to force the build script to build its
234 cargo.env("LZMA_API_STATIC", "1");
236 cargo.env("CFG_RELEASE_CHANNEL", &builder.config.channel);
237 cargo.env("CFG_VERSION", builder.rust_version());
238 cargo.env("CFG_RELEASE_NUM", channel::CFG_RELEASE_NUM);
240 let info = GitInfo::new(builder.config.ignore_git, &dir);
241 if let Some(sha) = info.sha() {
242 cargo.env("CFG_COMMIT_HASH", sha);
244 if let Some(sha_short) = info.sha_short() {
245 cargo.env("CFG_SHORT_COMMIT_HASH", sha_short);
247 if let Some(date) = info.commit_date() {
248 cargo.env("CFG_COMMIT_DATE", date);
250 if !features.is_empty() {
251 cargo.arg("--features").arg(&features.join(", "));
256 macro_rules! bootstrap_tool {
258 $name:ident, $path:expr, $tool_name:expr
259 $(,llvm_tools = $llvm:expr)*
260 $(,is_external_tool = $external:expr)*
263 #[derive(Copy, PartialEq, Eq, Clone)]
271 pub fn get_mode(&self) -> Mode {
275 /// Whether this tool requires LLVM to run
276 pub fn uses_llvm_tools(&self) -> bool {
278 $(Tool::$name => false $(|| $llvm)*,)+
283 impl<'a> Builder<'a> {
284 pub fn tool_exe(&self, tool: Tool) -> PathBuf {
288 compiler: self.compiler(0, self.config.build),
289 target: self.config.build,
297 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
299 pub compiler: Compiler,
300 pub target: Interned<String>,
303 impl Step for $name {
304 type Output = PathBuf;
306 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
310 fn make_run(run: RunConfig<'_>) {
311 run.builder.ensure($name {
313 compiler: run.builder.compiler(0, run.builder.config.build),
318 fn run(self, builder: &Builder<'_>) -> PathBuf {
319 builder.ensure(ToolBuild {
320 compiler: self.compiler,
323 mode: Mode::ToolBootstrap,
325 is_optional_tool: false,
326 source_type: if false $(|| $external)* {
327 SourceType::Submodule
331 extra_features: Vec::new(),
332 }).expect("expected to build -- essential tool")
340 Rustbook, "src/tools/rustbook", "rustbook";
341 UnstableBookGen, "src/tools/unstable-book-gen", "unstable-book-gen";
342 Tidy, "src/tools/tidy", "tidy";
343 Linkchecker, "src/tools/linkchecker", "linkchecker";
344 CargoTest, "src/tools/cargotest", "cargotest";
345 Compiletest, "src/tools/compiletest", "compiletest", llvm_tools = true;
346 BuildManifest, "src/tools/build-manifest", "build-manifest";
347 RemoteTestClient, "src/tools/remote-test-client", "remote-test-client";
348 RustInstaller, "src/tools/rust-installer", "fabricate", is_external_tool = true;
349 RustdocTheme, "src/tools/rustdoc-themes", "rustdoc-themes";
352 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
353 pub struct ErrorIndex {
354 pub compiler: Compiler,
358 pub fn command(builder: &Builder<'_>, compiler: Compiler) -> Command {
359 let mut cmd = Command::new(builder.ensure(ErrorIndex {
363 vec![PathBuf::from(&builder.sysroot_libdir(compiler, compiler.host))],
370 impl Step for ErrorIndex {
371 type Output = PathBuf;
373 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
374 run.path("src/tools/error_index_generator")
377 fn make_run(run: RunConfig<'_>) {
378 // Compile the error-index in the same stage as rustdoc to avoid
379 // recompiling rustdoc twice if we can.
380 let stage = if run.builder.top_stage >= 2 { run.builder.top_stage } else { 0 };
381 run.builder.ensure(ErrorIndex {
382 compiler: run.builder.compiler(stage, run.builder.config.build),
386 fn run(self, builder: &Builder<'_>) -> PathBuf {
387 builder.ensure(ToolBuild {
388 compiler: self.compiler,
389 target: self.compiler.host,
390 tool: "error_index_generator",
391 mode: Mode::ToolRustc,
392 path: "src/tools/error_index_generator",
393 is_optional_tool: false,
394 source_type: SourceType::InTree,
395 extra_features: Vec::new(),
396 }).expect("expected to build -- essential tool")
400 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
401 pub struct RemoteTestServer {
402 pub compiler: Compiler,
403 pub target: Interned<String>,
406 impl Step for RemoteTestServer {
407 type Output = PathBuf;
409 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
410 run.path("src/tools/remote-test-server")
413 fn make_run(run: RunConfig<'_>) {
414 run.builder.ensure(RemoteTestServer {
415 compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
420 fn run(self, builder: &Builder<'_>) -> PathBuf {
421 builder.ensure(ToolBuild {
422 compiler: self.compiler,
424 tool: "remote-test-server",
426 path: "src/tools/remote-test-server",
427 is_optional_tool: false,
428 source_type: SourceType::InTree,
429 extra_features: Vec::new(),
430 }).expect("expected to build -- essential tool")
434 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
436 /// This should only ever be 0 or 2.
437 /// We sometimes want to reference the "bootstrap" rustdoc, which is why this option is here.
438 pub compiler: Compiler,
441 impl Step for Rustdoc {
442 type Output = PathBuf;
443 const DEFAULT: bool = true;
444 const ONLY_HOSTS: bool = true;
446 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
447 run.path("src/tools/rustdoc")
450 fn make_run(run: RunConfig<'_>) {
451 run.builder.ensure(Rustdoc {
452 compiler: run.builder.compiler(run.builder.top_stage, run.host),
456 fn run(self, builder: &Builder<'_>) -> PathBuf {
457 let target_compiler = self.compiler;
458 if target_compiler.stage == 0 {
459 if !target_compiler.is_snapshot(builder) {
460 panic!("rustdoc in stage 0 must be snapshot rustdoc");
462 return builder.initial_rustc.with_file_name(exe("rustdoc", &target_compiler.host));
464 let target = target_compiler.host;
465 // Similar to `compile::Assemble`, build with the previous stage's compiler. Otherwise
466 // we'd have stageN/bin/rustc and stageN/bin/rustdoc be effectively different stage
467 // compilers, which isn't what we want. Rustdoc should be linked in the same way as the
468 // rustc compiler it's paired with, so it must be built with the previous stage compiler.
469 let build_compiler = builder.compiler(target_compiler.stage - 1, builder.config.build);
471 // The presence of `target_compiler` ensures that the necessary libraries (codegen backends,
472 // compiler libraries, ...) are built. Rustdoc does not require the presence of any
473 // libraries within sysroot_libdir (i.e., rustlib), though doctests may want it (since
474 // they'll be linked to those libraries). As such, don't explicitly `ensure` any additional
475 // libraries here. The intuition here is that If we've built a compiler, we should be able
478 let mut cargo = prepare_tool_cargo(
489 let _folder = builder.fold_output(|| format!("stage{}-rustdoc", target_compiler.stage));
490 builder.info(&format!("Building rustdoc for stage{} ({})",
491 target_compiler.stage, target_compiler.host));
492 builder.run(&mut cargo);
494 // Cargo adds a number of paths to the dylib search path on windows, which results in
495 // the wrong rustdoc being executed. To avoid the conflicting rustdocs, we name the "tool"
496 // rustdoc a different name.
497 let tool_rustdoc = builder.cargo_out(build_compiler, Mode::ToolRustc, target)
498 .join(exe("rustdoc_tool_binary", &target_compiler.host));
500 // don't create a stage0-sysroot/bin directory.
501 if target_compiler.stage > 0 {
502 let sysroot = builder.sysroot(target_compiler);
503 let bindir = sysroot.join("bin");
504 t!(fs::create_dir_all(&bindir));
505 let bin_rustdoc = bindir.join(exe("rustdoc", &*target_compiler.host));
506 let _ = fs::remove_file(&bin_rustdoc);
507 builder.copy(&tool_rustdoc, &bin_rustdoc);
515 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
517 pub compiler: Compiler,
518 pub target: Interned<String>,
521 impl Step for Cargo {
522 type Output = PathBuf;
523 const DEFAULT: bool = true;
524 const ONLY_HOSTS: bool = true;
526 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
527 let builder = run.builder;
528 run.path("src/tools/cargo").default_condition(builder.config.extended)
531 fn make_run(run: RunConfig<'_>) {
532 run.builder.ensure(Cargo {
533 compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
538 fn run(self, builder: &Builder<'_>) -> PathBuf {
539 // Cargo depends on procedural macros, so make sure the host
540 // libstd/libproc_macro is available.
541 builder.ensure(compile::Test {
542 compiler: self.compiler,
543 target: builder.config.build,
545 builder.ensure(ToolBuild {
546 compiler: self.compiler,
549 mode: Mode::ToolRustc,
550 path: "src/tools/cargo",
551 is_optional_tool: false,
552 source_type: SourceType::Submodule,
553 extra_features: Vec::new(),
554 }).expect("expected to build -- essential tool")
558 macro_rules! tool_extended {
559 (($sel:ident, $builder:ident),
564 $extra_deps:block;)+) => {
566 #[derive(Debug, Clone, Hash, PartialEq, Eq)]
568 pub compiler: Compiler,
569 pub target: Interned<String>,
570 pub extra_features: Vec<String>,
573 impl Step for $name {
574 type Output = Option<PathBuf>;
575 const DEFAULT: bool = true;
576 const ONLY_HOSTS: bool = true;
578 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
579 let builder = run.builder;
580 run.path($path).default_condition(builder.config.extended)
583 fn make_run(run: RunConfig<'_>) {
584 run.builder.ensure($name {
585 compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
587 extra_features: Vec::new(),
592 fn run(mut $sel, $builder: &Builder<'_>) -> Option<PathBuf> {
594 $builder.ensure(ToolBuild {
595 compiler: $sel.compiler,
598 mode: Mode::ToolRustc,
600 extra_features: $sel.extra_features,
601 is_optional_tool: true,
602 source_type: SourceType::Submodule,
610 tool_extended!((self, builder),
611 Cargofmt, rustfmt, "src/tools/rustfmt", "cargo-fmt", {};
612 CargoClippy, clippy, "src/tools/clippy", "cargo-clippy", {
613 // Clippy depends on procedural macros, so make sure that's built for
614 // the compiler itself.
615 builder.ensure(compile::Test {
616 compiler: self.compiler,
617 target: builder.config.build,
620 Clippy, clippy, "src/tools/clippy", "clippy-driver", {
621 // Clippy depends on procedural macros, so make sure that's built for
622 // the compiler itself.
623 builder.ensure(compile::Test {
624 compiler: self.compiler,
625 target: builder.config.build,
628 Miri, miri, "src/tools/miri", "miri", {};
629 CargoMiri, miri, "src/tools/miri", "cargo-miri", {
630 // Miri depends on procedural macros, so make sure that's built for
631 // the compiler itself.
632 builder.ensure(compile::Test {
633 compiler: self.compiler,
634 target: builder.config.build,
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 // RLS depends on procedural macros, so make sure that's built for
647 // the compiler itself.
648 builder.ensure(compile::Test {
649 compiler: self.compiler,
650 target: builder.config.build,
653 Rustfmt, rustfmt, "src/tools/rustfmt", "rustfmt", {};
656 impl<'a> Builder<'a> {
657 /// Gets a `Command` which is ready to run `tool` in `stage` built for
659 pub fn tool_cmd(&self, tool: Tool) -> Command {
660 let mut cmd = Command::new(self.tool_exe(tool));
661 let compiler = self.compiler(0, self.config.build);
662 self.prepare_tool_cmd(compiler, tool, &mut cmd);
666 /// Prepares the `cmd` provided to be able to run the `compiler` provided.
668 /// Notably this munges the dynamic library lookup path to point to the
669 /// right location to run `compiler`.
670 fn prepare_tool_cmd(&self, compiler: Compiler, tool: Tool, cmd: &mut Command) {
671 let host = &compiler.host;
672 let mut lib_paths: Vec<PathBuf> = vec![
673 if compiler.stage == 0 {
674 self.build.rustc_snapshot_libdir()
676 PathBuf::from(&self.sysroot_libdir(compiler, compiler.host))
678 self.cargo_out(compiler, tool.get_mode(), *host).join("deps"),
681 // On MSVC a tool may invoke a C compiler (e.g., compiletest in run-make
682 // mode) and that C compiler may need some extra PATH modification. Do
684 if compiler.host.contains("msvc") {
685 let curpaths = env::var_os("PATH").unwrap_or_default();
686 let curpaths = env::split_paths(&curpaths).collect::<Vec<_>>();
687 for &(ref k, ref v) in self.cc[&compiler.host].env() {
691 for path in env::split_paths(v) {
692 if !curpaths.contains(&path) {
693 lib_paths.push(path);
699 add_lib_path(lib_paths, cmd);